mirror of
https://github.com/LeCoupa/awesome-cheatsheets.git
synced 2026-01-26 05:08:03 -08:00
Merge branch 'LeCoupa:master' into master
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -3,3 +3,6 @@
|
||||
|
||||
# Editors
|
||||
.vscode/
|
||||
|
||||
# Vim
|
||||
*.swp
|
||||
|
||||
28
README.md
28
README.md
@@ -8,7 +8,7 @@
|
||||
|
||||
## 🤔 Why Awesome-Cheatsheets?
|
||||
|
||||
I usually make a cheatsheet when I want to improve my skills on a programming language, a framework or a development tool. [I started doing these kind of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I reorganized all of them into this single repository. Most of the content is coming from official documentations and some books I have read.
|
||||
I usually make a cheat sheet when I want to improve my skills in a programming language, a framework or a development tool. [I started doing these kinds of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I reorganized all of them into this single repository. Most of the content is coming from official documentation and some books I have read.
|
||||
|
||||
Feel free to take a look. You might learn new things. They have been designed to provide a quick way to assess your knowledge and to save you time.
|
||||
|
||||
@@ -27,7 +27,10 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
|
||||
- [C](languages/C.txt)
|
||||
- [C#](languages/C%23.txt)
|
||||
- [Go](languages/golang.md)
|
||||
- [Java](languages/java.md)
|
||||
- [PHP](languages/php.php)
|
||||
- [Python](languages/python.md)
|
||||
|
||||
#### Functional
|
||||
|
||||
@@ -50,6 +53,7 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
|
||||
#### Javascript
|
||||
|
||||
- [Adonis.js](backend/adonis.js)
|
||||
- [Feathers.js](backend/feathers.js)
|
||||
- [Moleculer](backend/moleculer.js)
|
||||
- [Node.js](backend/node.js)
|
||||
@@ -69,6 +73,7 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
|
||||
- [React.js](frontend/react.js)
|
||||
- [Vue.js](frontend/vue.js)
|
||||
- [Tailwind.css](frontend/tailwind.css)
|
||||
- [Ember.js](frontend/ember.js)
|
||||
- [Angular (2+)](frontend/angular.js)
|
||||
- [AngularJS](frontend/angularjs.js)
|
||||
@@ -79,6 +84,10 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
<details>
|
||||
<summary>View cheatsheets</summary>
|
||||
|
||||
#### SQL
|
||||
|
||||
- [MySQL](databases/mysql.sh)
|
||||
|
||||
#### NoSQL
|
||||
|
||||
- [Redis](databases/redis.sh)
|
||||
@@ -91,17 +100,30 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
|
||||
#### Development
|
||||
|
||||
- [cURL](tools/curl.sh)
|
||||
- [Drush](tools/drush.sh)
|
||||
- [Elasticsearch](tools/elasticsearch.js)
|
||||
- [Emmet](tools/emmet.md)
|
||||
- [Git](tools/git.sh)
|
||||
- [Puppeteer](tools/puppeteer.js)
|
||||
- [Sublime Text](tools/sublime_text.md)
|
||||
- [VIM](tools/vim.txt)
|
||||
- [Visual Studio Code](tools/vscode.md)
|
||||
- [Xcode](tools/xcode.txt)
|
||||
|
||||
#### Infrastructure
|
||||
|
||||
- [AWS CLI](tools/aws.sh)
|
||||
- [Docker](tools/docker.sh)
|
||||
- [Kubernetes](tools/kubernetes.sh)
|
||||
- [Heroku CLI](tools/heroku.sh)
|
||||
- [Kubernetes](tools/kubernetes.md)
|
||||
- [Nanobox Boxfile](tools/nanobox_boxfile.yml)
|
||||
- [Nanobox CLI](tools/nanobox_cli.sh)
|
||||
- [Nginx](tools/nginx.sh)
|
||||
- [PM2](tools/pm2.sh)
|
||||
- [Ubuntu](tools/ubuntu.sh)
|
||||
</details>
|
||||
|
||||
## 🙌🏼 How to Contribute?
|
||||
|
||||
You are more than welcome to contribute and build your own cheatsheet for your favorite programming language, framework or development tool. Just submit changes via pull request and I will review them before merging.
|
||||
You are more than welcome to contribute and build your own cheat sheet for your favorite programming language, framework or development tool. Just submit changes via pull request and I will review them before merging.
|
||||
|
||||
474
backend/adonis.js
Normal file
474
backend/adonis.js
Normal file
@@ -0,0 +1,474 @@
|
||||
/********************************************************************************************
|
||||
* ADONIS CHEATSHEET
|
||||
* https://adonisjs.com/
|
||||
********************************************************************************************/
|
||||
|
||||
/********************************************************************************************
|
||||
* AVAILABLE CLI COMMANDS
|
||||
* https://adonisjs.com/docs/ace
|
||||
********************************************************************************************/
|
||||
|
||||
build // Compile typescript code to Javascript. Optionally watch for file changes.
|
||||
invoke // Invoke post install instructions on a given AdonisJs package.
|
||||
serve // Compile typescript code to Javascript and start the HTTP server.
|
||||
|
||||
// Dump
|
||||
|
||||
dump:rcfile // Dump contents of .adonisrc.json file along with defaults.
|
||||
|
||||
// Generate
|
||||
|
||||
generate:key // Generate a new APP_KEY secret.
|
||||
generate:manifest // Generate manifest file to execute ace commands.
|
||||
|
||||
// List
|
||||
|
||||
list:routes // List application routes.
|
||||
|
||||
// Make
|
||||
|
||||
make:command // Make a new ace command.
|
||||
make:controller // Make a new HTTP controller.
|
||||
make:middleware // Make a new middleware.
|
||||
make:migration // Make a new migration.
|
||||
make:provider // Make a new IoC container provider.
|
||||
make:validator // Make a new validator.
|
||||
make:view // Make a new view template.
|
||||
|
||||
// Migrations
|
||||
|
||||
migration:run // Run all pending migrations.
|
||||
migration:rollback // Rollback last set of migrations.
|
||||
migration:refresh // Rollback all migrations to the 0 batch then re-run them from the start.
|
||||
migration:reset // Rollback all migrations to the 0 batch.
|
||||
migration:status // Get the status of all the migrations.
|
||||
|
||||
/********************************************************************************************
|
||||
* REQUEST
|
||||
* https://adonisjs.com/docs/request
|
||||
********************************************************************************************/
|
||||
|
||||
request.all() // Returns an object containing all request data (merges query params and request body data).
|
||||
request.get() // Returns an object containing query params data.
|
||||
request.post() // Returns an object containing request body data.
|
||||
request.raw() // Returns raw body data as a string.
|
||||
request.only(['username', 'age']) // Returns an object with only the specified keys.
|
||||
request.collect(['username', 'age']) // Formats so it’s ready to save to the database.
|
||||
request.except(['csrf_token', 'submit']) // Returns an object with everything except the specified keys (opposite of only).
|
||||
request.input('drink', 'coffee') // Get the value of a given key (if it doesn’t exist, return the default value).
|
||||
|
||||
request.headers() // Returns an object of all header data.
|
||||
request.header('some-other-header', 'default') // The header value for a given key (optionally with default value).
|
||||
|
||||
request.cookies() // Returns an object of all cookie data.
|
||||
request.cookie('cart_total', 0) // Returns the cookie value for a given key (optionally with default value).
|
||||
request.plainCookies() // Returns an object of all raw cookie data.
|
||||
request.plainCookie('cart_total', 0) // Returns the raw cookie value for a given key (optionally with default value).
|
||||
|
||||
request.accepts(['json', 'html']) // Reads the Accept header to help determine the response format.
|
||||
request.language(['en', 'fr']) // Language can also be negotiated based upon the Accept-Language header.
|
||||
|
||||
request.url() // Returns the current request url.
|
||||
request.originalUrl() // Returns the full current request url with query strings.
|
||||
request.method() // Returns the HTTP request method.
|
||||
request.intended() // Returns the intended request HTTP method.
|
||||
request.ip() // Returns the most trusted ip address for the user.
|
||||
request.ips() // Returns an array of ips from most to the least trusted (removes the default ip address, which can be accessed via the ip method).
|
||||
request.subdomains() // Returns a list of request subdomains (removes www from the list).
|
||||
request.ajax() // Checks for X-Requested-With header to determine if the request is ajax or not.
|
||||
request.pjax() // This methods looks for the X-PJAX header to identify if a request is pjax or not.
|
||||
request.hostname() // Returns the request hostname.
|
||||
request.protocol() // Return the request protocol.
|
||||
request.match(['posts/:id']) // Returns whether the passed set of expressions match the current request URL.
|
||||
request.hasBody() // A boolean indicating if the request has a post body (mainly used by the BodyParser to determine whether or not to parse the body).
|
||||
request.is(['json', 'html']) // The is method returns the best matching content type for the current request. The check is entirely based upon the content-type header.
|
||||
|
||||
/********************************************************************************************
|
||||
* RESPONSE
|
||||
* https://adonisjs.com/docs/response
|
||||
********************************************************************************************/
|
||||
|
||||
response.header("Content-type", "application/json"); // Set a header value.
|
||||
response.safeHeader("Content-type", "application/json"); // Only set a header value if it does not already exist.
|
||||
response.removeHeader("Content-type"); // Remove an existing header.
|
||||
response.type("application/json"); // Set the Content-Type header.
|
||||
|
||||
response.cookie("cartTotal", 20); // Set a cookie value.
|
||||
response.clearCookie("cartTotal"); // Remove an existing cookie value (by setting its expiry in the past).
|
||||
response.plainCookie("cartTotal", 20); // Set a plain cookie.
|
||||
|
||||
response.redirect(url, [(sendParams = false)], [(status = 302)]); // Redirect request to a different url (by default it will set the status as 302).
|
||||
response.route(route, [data], [domain], [(sendParams = false)], [(status = 302)]); // Redirect to a route (via route name or controller method).
|
||||
|
||||
response.download(filePath); // Stream the file to the client.
|
||||
response.attachment(filePath, [name], [disposition]); // Force download the file.
|
||||
|
||||
response.continue(); // 100 status code
|
||||
response.switchingProtocols(); // 101 status code
|
||||
response.ok(); // 200 status code
|
||||
response.created(); // 201 status code
|
||||
response.accepted(); // 202 status code
|
||||
response.nonAuthoritativeInformation(); // 203 status code
|
||||
response.noContent(); // 204 status code
|
||||
response.resetContent(); // 205 status code
|
||||
response.partialContent(); // 206 status code
|
||||
response.multipleChoices(); // 300 status code
|
||||
response.movedPermanently(); // 301 status code
|
||||
response.found(); // 302 status code
|
||||
response.seeOther(); // 303 status code
|
||||
response.notModified(); // 304 status code
|
||||
response.useProxy(); // 305 status code
|
||||
response.temporaryRedirect(); // 307 status code
|
||||
response.badRequest(); // 400 status code
|
||||
response.unauthorized(); // 401 status code
|
||||
response.paymentRequired(); // 402 status code
|
||||
response.forbidden(); // 403 status code
|
||||
response.notFound(); // 404 status code
|
||||
response.methodNotAllowed(); // 405 status code
|
||||
response.notAcceptable(); // 406 status code
|
||||
response.proxyAuthenticationRequired(); // 407 status code
|
||||
response.requestTimeout(); // 408 status code
|
||||
response.conflict(); // 409 status code
|
||||
response.gone(); // 410 status code
|
||||
response.lengthRequired(); // 411 status code
|
||||
response.preconditionFailed(); // 412 status code
|
||||
response.requestEntityTooLarge(); // 413 status code
|
||||
response.requestUriTooLong(); // 414 status code
|
||||
response.unsupportedMediaType(); // 415 status code
|
||||
response.requestedRangeNotSatisfiable(); // 416 status code
|
||||
response.expectationFailed(); // 417 status code
|
||||
response.unprocessableEntity(); // 422 status code
|
||||
response.tooManyRequests(); // 429 status code
|
||||
response.internalServerError(); // 500 status code
|
||||
response.notImplemented(); // 501 status code
|
||||
response.badGateway(); // 502 status code
|
||||
response.serviceUnavailable(); // 503 status code
|
||||
response.gatewayTimeout(); // 504 status code
|
||||
response.httpVersionNotSupported(); // 505 status code
|
||||
|
||||
/********************************************************************************************
|
||||
* ROUTING
|
||||
* https://adonisjs.com/docs/routing
|
||||
********************************************************************************************/
|
||||
|
||||
Route.get(url, closure) // Register route for GET verb.
|
||||
Route.post(url, closure) // Register route for POST verb.
|
||||
Route.put(url, closure) // Register route for PUT verb.
|
||||
Route.patch(url, closure) // Register route for PATCH verb.
|
||||
Route.delete(url, closure) // Register route for DELETED verb.
|
||||
Route.any(url, closure) // Register route for all HTTP verbs.
|
||||
|
||||
Route.on('/').render('welcome') // Render a view directly.
|
||||
|
||||
Route.route('/', () => {}, ['GET', 'POST', 'PUT']) // Register route for multiple verbs.
|
||||
Route.get('users', closure).as('users.index') // Assign a unique name to the route.
|
||||
Route.get('users', closure).formats(['json', 'html'], true) // Force client to define the route format.
|
||||
|
||||
Route.resource('users', 'UserController') // Define a resource route for CRUD operations.
|
||||
Route.resource('users', 'UserController').apiOnly() // Remove create and edit routes.
|
||||
Route.resource('users', 'UserController').only(['index']) // Keeps only the passed routes.
|
||||
Route.resource('users', 'UserController').except(['index']) //Keeps all routes except the passed routes.
|
||||
|
||||
Route.group(() => {}) // Define a group of routes.
|
||||
Route.group(() => {}).middleware(['auth']) // Attach a middleware.
|
||||
Route.group(() => {}).formats(['json']) // Define response formats.
|
||||
Route.group(() => {}).prefix('api/v1') // Define a prefix for a group of routes.
|
||||
Route.group(() => {}).namespace('Admin') // Prefix the namespace of the bound controller.
|
||||
Route.group(() => {}).domain('blog.sthg.com') // Specify which domain goup routes belong to.
|
||||
|
||||
/********************************************************************************************
|
||||
* VALIDATOR
|
||||
* https://indicative-v5.adonisjs.com/
|
||||
********************************************************************************************/
|
||||
|
||||
const indicative = require("indicative");
|
||||
|
||||
const rules = {
|
||||
email: "required|email|unique:users",
|
||||
password: "required|min:6|max:30",
|
||||
};
|
||||
|
||||
// Indivative methods
|
||||
|
||||
indicative.validate(data, rules); // Validate data with defined rules.
|
||||
indicative.validateAll(data, rules); // Same as validate but continues to validate all fields, whereas the validate method stops on first error.
|
||||
indicative.is.email(emailAddress); // Raw validator.
|
||||
indicative.extend("exists", existsFn); // Add your own rules.
|
||||
indicative.sanitize(data, rules); // Returns a new object with sanitized data:.
|
||||
indicative.sanitizor.normalizeEmail(emailAddress); // Raw sanitizor.
|
||||
|
||||
// Validations
|
||||
|
||||
above // Makes sure the value provided by the end user is above the expected value.
|
||||
accepted // Ensures that the field under validation is accepted.
|
||||
after // Ensures the value of the field is after the expected date.
|
||||
afterOffsetOf // Ensures the date is after a given offset of a given time period.
|
||||
alpha // Makes sure the field under validation is alpha only.
|
||||
alphaNumeric // Makes sure the field under validation is alpha numeric only.
|
||||
array // Ensure the value is a valid array. Also this validation will never validate the size of array.
|
||||
before // Ensures the value of field under validation is before a given date.
|
||||
beforeOffsetOf // Ensures the date is before a given offset of a given time period.
|
||||
boolean // Ensures the value of a field is a boolean.
|
||||
confirmed // Ensures a field value as confirmed using a _confirmation convention. This is mainly used for password confirmation field.
|
||||
date // Ensures the field under validation is a valid date. The value can be a date object or a valid date string.
|
||||
dateFormat // Ensures the date or date time is valid as the one of the defined formats.
|
||||
different // Ensures the value of the field under validation is always different from the targeted field value.
|
||||
email // Ensures the field under validation is a valid email format.
|
||||
endsWith // Ensure the value of field under validation ends with a certain substr. This validation will also trim whitespaces before making the check.
|
||||
equals // Ensures 2 values are lossely same. This validation will not check for the same type, but instead checks for the same value.
|
||||
in // Ensures the value of a given field matches one of expected values.
|
||||
includes // Ensures the value of field under validation contains a given substring.
|
||||
integer // Ensures the value is a valid integer. Also string representation of a number will return true.
|
||||
ip // Ensures the value is a valid ip address as per ipv4 and ipv6 specs.
|
||||
ipv4 // Ensures the value is a valid ip address as per ipv4 spec only.
|
||||
ipv6 // Ensures the value is a valid ip address as per ipv6 spec only.
|
||||
json // Ensures the value of field under validation is safe to be parsed using JSON.parse method.
|
||||
max // Ensures the length of a string or array is not greater than the defined length.
|
||||
min // Ensures the length of a string or array is not is not less than the expected length
|
||||
notEquals // Makes sure that the value of field under validation is not same as the defined value.
|
||||
notIn // Makes sure that the value of field under validation is not from one of the defined values.
|
||||
number // Makes sure that the value of field under validation is a valid number. The validation will pass for floats too, since it uses typeof internally.
|
||||
object // Ensures the value of field under validation is a valid Javascript object. The validation will fail for Arrays, though they are objects too in Javascript.
|
||||
range // Ensures the value of field under validation is under a given range. The values will be cased to Number automatically.
|
||||
regex // Ensures the value of field under validation, passes the regex test. The regex can be defined as a string or a RegExp object.
|
||||
required // Ensures the value of field under validation is not empty (i.e. not an empty object, empty array, empty string, null or undefined).
|
||||
requiredIf // The field is checked for required validation, when expected field exists.
|
||||
requiredWhen // The field is checked for required validation, when expected field value is same as the expected value.
|
||||
requiredWithAll // Ensures the field is required when all other fields have non-empty values.
|
||||
requiredWithAny // Ensures the field is required when any of the other fields have non-empty values.
|
||||
requiredWithoutAll // Ensures the field is required when all of the other fields has empty values.
|
||||
requiredWithoutAny // Ensures the field is required when any of the other fields has empty values.
|
||||
same // Ensures the value of 2 fields are same.
|
||||
startsWith // Ensure the value of field under validation starts with a certain substr. This validation will also trim whitespaces before making the check.
|
||||
string // Ensures the value is a string.
|
||||
under // Ensures the value of a field is under a certain value. All values will be casted to Number.
|
||||
url // Ensures the value is a valid URL format.
|
||||
|
||||
/********************************************************************************************
|
||||
* LUCID
|
||||
* https://adonisjs.com/docs/lucid
|
||||
********************************************************************************************/
|
||||
|
||||
Model.find() // Find a record using the primary key (always returns one record).
|
||||
Model.findOrFail() // Similar to find, but instead throws a ModelNotFoundException when unable to find a record.
|
||||
Model.findBy() // Find a record using a key/value pair (returns the first matching record).
|
||||
Model.findByOrFail() // Similar to findBy, but instead throws a ModelNotFoundException when unable to find a record.
|
||||
Model.first() // Find the first row from the database.
|
||||
Model.firstOrFail() // Similar to first, but instead throws a ModelNotFoundException when unable to find a record.
|
||||
Model.last() // Find the latest row from the database.
|
||||
Model.findOrCreate(whereAttributes, values) // Find a record, if not found a new record will be created and returned.
|
||||
Model.pick(rows = 1) // Pick x number of rows from the database table (defaults to 1 row).
|
||||
Model.pickInverse(rows = 1) // Pick x number of rows from the database table from last (defaults to 1 row).
|
||||
Model.ids() // Return an array of primary keys.
|
||||
Model.pair(lhs, rhs) // Returns an object of key/value pairs (lhs is the key, rhs is the value).
|
||||
Model.all() // Select all rows.
|
||||
Model.truncate() // Delete all rows (truncate table).
|
||||
Model.getCount() // Return a count of records in a given result set.
|
||||
Model.create(jsonAttributes) // Return model instance after saving it into the database.
|
||||
Model.createMany(arrayAttributes) // Return an array of model instances after saving them into the database.
|
||||
Model.toJSON() // Converts a serializable instance to a plain array/object.
|
||||
|
||||
Model.query().setHidden(['password']) // Define hidden fields.
|
||||
Model.query().setVisible(['title', 'body']) // Define visible fields.
|
||||
Model.query().paginate() // Returns an object with metadata and data property that has a list of model results.
|
||||
|
||||
instance.fill(jsonAttributes) // Remove all existing values, only set the specified attributes.
|
||||
instance.merge(jsonAttributes) // Modifies the specified attributes.
|
||||
instance.save() // Save the instance to the database.
|
||||
instance.delete() // Delete model instance from the database.
|
||||
|
||||
instance.associate(id) // Exclusive to belongsTo relationship, where it associates two model instances together.
|
||||
instance.dissociate(id) // The opposite of associate, where you just drop the relationship
|
||||
instance.attach(arrayOfIds, callback) // Works with the belongsToMany relationship to attach a relationship inside the pivot table. The attach method accepts an optional callback receiving the pivotModel instance, allowing you to set extra properties on a pivot table if required:
|
||||
instance.detach(arrayOfIds) // The opposite of the attach method, and it removes the relationship from the pivot table only.
|
||||
|
||||
/********************************************************************************************
|
||||
* QUERY BUILDER
|
||||
* https://adonisjs.com/docs/query-builder
|
||||
* http://knexjs.org/
|
||||
********************************************************************************************/
|
||||
|
||||
const Database = use('Database')
|
||||
|
||||
// Available where clauses
|
||||
|
||||
where(~mixed~)
|
||||
orWhere(~mixed~)
|
||||
whereNot(~mixed~)
|
||||
orWhereNot(~mixed~)
|
||||
whereIn(column|columns, array|callback|builder)
|
||||
orWhereIn(column | columns, array | callback | builder)
|
||||
whereNotIn(column, array|callback|builder)
|
||||
orWhereNotIn(column, array | callback | builder)
|
||||
whereNull(column)
|
||||
orWhereNull(column)
|
||||
whereNotNull(column)
|
||||
orWhereNotNull(column)
|
||||
whereExists(builder | callback)
|
||||
orWhereExists(builder | callback)
|
||||
whereNotExists(builder | callback)
|
||||
orWhereNotExists(builder | callback)
|
||||
whereBetween(column, range)
|
||||
orWhereBetween(column, range)
|
||||
whereNotBetween(column, range)
|
||||
orWhereNotBetween(column, range)
|
||||
whereRaw(query, [bindings])
|
||||
|
||||
/********************************************************************************************
|
||||
* DATABASE HOOKS
|
||||
* https://adonisjs.com/docs/database-hooks
|
||||
********************************************************************************************/
|
||||
|
||||
beforeCreate // Before creating a new record.
|
||||
afterCreate // After a new record is created.
|
||||
beforeUpdate // Before updating a record.
|
||||
afterUpdate // After a record has been updated.
|
||||
beforeSave // Before creating or updating a new record.
|
||||
afterSave // After a new record has been created or updated.
|
||||
beforeDelete // Before removing a record.
|
||||
afterDelete // After a record is removed.
|
||||
afterFind // After a single record is fetched from the database.
|
||||
afterFetch // After the fetch method is executed.The hook method receives an array of model instances.
|
||||
afterPaginate // After the paginate method is executed.The hook method receives two arguments: an array of model instances and the pagination metadata.
|
||||
|
||||
/********************************************************************************************
|
||||
* EVENTS
|
||||
* https://adonisjs.com/docs/events
|
||||
********************************************************************************************/
|
||||
|
||||
Event.on(event, listener) // Bind single or multiple listeners for a given event. The listener can be a closure function or reference to one (or many) IoC container bindings.
|
||||
Event.when(event, listener) // The when method aliases the on method.
|
||||
Event.once(event, listener) // Same as on, but only called one time.
|
||||
Event.onAny(listener) // Bind listener for any event
|
||||
Event.times(number) // The times method is chained with on or when to limit the number of times the listener should be fired.
|
||||
Event.emit(event, data) // Emit an event with optional data.
|
||||
Event.fire(event, data) // The fire method aliases the emit method.
|
||||
Event.removeListener(event, listener) // Remove listener(s) for a given event.
|
||||
Event.off(event, listener) // The off method aliases the removeListener method.
|
||||
Event.removeAllListeners(event) // Remove all listeners for a given event.
|
||||
Event.listenersCount(event) // Return the number of listeners for a given event.
|
||||
Event.getListeners(event) // Return an array of listeners for a given event.
|
||||
Event.hasListeners(event) // Return a boolean indicating whether there are any listeners for a given event.
|
||||
|
||||
/********************************************************************************************
|
||||
* LOGGER
|
||||
* https://adonisjs.com/docs/sessions
|
||||
********************************************************************************************/
|
||||
|
||||
const Logger = use('Logger')
|
||||
|
||||
Logger.level = 'debug' // Sed default config level
|
||||
|
||||
Logger.emerg(msg[, …data]) // Print an emergency log (level 0).
|
||||
Logger.alert(msg[, …data]) // Print an alert log (level 1).
|
||||
Logger.crit(msg[, …data]) // Print a critical log (level 2).
|
||||
Logger.error(msg[, …data]) // Print an error log (level 3).
|
||||
Logger.warning(msg[, …data]) // Print a warning log (level 4).
|
||||
Logger.notice(msg[, …data]) // Print a notice log (level 5).
|
||||
Logger.info(msg[, …data]) // Print an info log (level 6).
|
||||
Logger.debug(msg[, …data]) // Print a debug log (level 7).
|
||||
|
||||
Logger.transport(transport) // Switch transport on the fly.
|
||||
|
||||
/********************************************************************************************
|
||||
* ENCRYPTION AND HASHING
|
||||
* https://adonisjs.com/docs/encryption-and-hashing
|
||||
********************************************************************************************/
|
||||
|
||||
const Encryption = use('Encryption')
|
||||
|
||||
Encryption.encrypt(string) // Encrypt a given value.
|
||||
Encryption.decrypt(string) // Decrypt an encrypted value.
|
||||
|
||||
const Hash = use('Hash')
|
||||
|
||||
await Hash.make(string[, config]) // Hash a plain string value.
|
||||
await Hash.verify(string, hashedString) // Since you cannot decrypt a hash, you can verify the user input against the previously hashed value.
|
||||
|
||||
/********************************************************************************************
|
||||
* SESSIONS
|
||||
* https://adonisjs.com/docs/sessions
|
||||
********************************************************************************************/
|
||||
|
||||
session.put(key, value); // Add a key/value pair to the session store.
|
||||
session.get(key, [defaultValue]); // Return the value for a given key (accepts an optional default value).
|
||||
session.all(); // Get everything back as an object from the session store.
|
||||
session.increment(key, [steps]); // Increment the value for a given key (ensure the previous value is a number).
|
||||
session.decrement(key, [steps]); // Decrement the value for a given key (ensure the previous value is a number).
|
||||
session.forget(key); // Remove a key/value pair from the session store.
|
||||
session.pull(key, [defaultValue]); // Return (and then remove) a key/value pair from the session store.
|
||||
session.clear(); // Empty the session store.
|
||||
|
||||
session.flashAll() // Flash the request form data.
|
||||
session.flashOnly() // Flash only the selected fields.
|
||||
session.flashExcept() // Flash the request form data except the selected fields.
|
||||
session.withErrors() // Flash with an array of errors.
|
||||
session.flash() // Flash a custom object.
|
||||
|
||||
/********************************************************************************************
|
||||
* FILE STORAGE
|
||||
* https://adonisjs.com/docs/file-system
|
||||
********************************************************************************************/
|
||||
|
||||
const Drive = use('Drive')
|
||||
|
||||
Drive.exists(relativePath) // Find if a file/directory exists or not.
|
||||
Drive.get(relativePath, encoding = utf-8) // Get file contents as a buffer or string.
|
||||
Drive.getStream(relativePath) // Get file as a stream.
|
||||
Drive.put(relativePath, content, options = {}) // Create a new file with given contents (creates any missing directories).
|
||||
Drive.prepend(relativePath, content, options = {}) // Prepend content to a file (creates a new file if path doesn’t exist).
|
||||
Drive.append(relativePath, content, options = {}) // Append content to a file (creates a new file if path doesn’t exist).
|
||||
Drive.delete(relativePath) // Remove existing file.
|
||||
Drive.move(src, dest, options = {}) // Move file from one directory to another.
|
||||
Drive.copy(src, dest, options = {}) // Copy file from one directory to another.
|
||||
|
||||
// For S3 & Spaces drivers
|
||||
|
||||
Drive.getObject(location, params) // Get S3 object for a given file (for params info, see S3 params).
|
||||
Drive.getUrl(location, [bucket]) // Get url for a given file (accepts optional alternative bucket param).
|
||||
Drive.getSignedUrl(location, expiry = 900, params) // Get signed url for a given file (expiry set to 15mins by default).
|
||||
|
||||
/********************************************************************************************
|
||||
* HELPERS
|
||||
* https://adonisjs.com/docs/helpers
|
||||
********************************************************************************************/
|
||||
|
||||
const Helpers = use('Helpers')
|
||||
|
||||
Helpers.appRoot() // Returns path to the application root.
|
||||
Helpers.publicPath([toFile]) // Returns path to the public directory or file inside the directory.
|
||||
Helpers.configPath([toFile]) // Returns path to the config directory or file inside the directory.
|
||||
Helpers.resourcesPath([toFile]) // Returns path to the resources directory or file inside the directory.
|
||||
Helpers.migrationsPath([toFile]) // Returns path to the migrations directory or file inside the directory.
|
||||
Helpers.seedsPath([toFile]) // Returns path to the seeds directory or file inside the directory.
|
||||
Helpers.databasePath([toFile]) // Returns path to the database directory or file inside the directory.
|
||||
Helpers.viewsPath([toFile]) // Returns path to the views directory or file inside the directory.
|
||||
Helpers.tmpPath([toFile]) // Returns path to the tmp directory or file inside the directory.
|
||||
|
||||
Helpers.promisify() // Returns promisified callback functions.
|
||||
Helpers.isAceCommand() // Returns whether the process was started as the ace command or not.
|
||||
|
||||
/********************************************************************************************
|
||||
* SOCIAL AUTHENTICATION
|
||||
* https://adonisjs.com/docs/social-auth
|
||||
********************************************************************************************/
|
||||
|
||||
// Drivers: Facebook, Github, Google, Instagram, Linkedin, Twitter, Foursquare.
|
||||
|
||||
ally.redirect() // Redirect user to the 3rd party website.
|
||||
ally.getRedirectUrl() // Get redirect URL back as a string.
|
||||
ally.scope(scopesArray) // Define runtime scopes before redirecting the user.
|
||||
ally.fields(fieldsArray) // Fields to be fetched when getting the authenticated user profile.
|
||||
ally.getUser() // Get the user profile of an authenticated user (returns an AllyUser instance).
|
||||
ally.getUserByToken(accessToken, [accessSecret]) // Returns the user details using the accessToken.
|
||||
|
||||
user.getId() // Returns the user id.
|
||||
user.getName() // Returns the user name.
|
||||
user.getEmail() // Returns the user email.
|
||||
user.getNickname() // Returns the nickname / display name of the user.
|
||||
user.getAvatar() // Returns public URL to the user’s profile picture.
|
||||
user.getAccessToken() // Returns the access token which may be used later to update the user profile.
|
||||
user.getRefreshToken() // Refresh token to be used when access token expires.
|
||||
user.getExpires() // Access token expiry data.
|
||||
user.getTokenSecret() // Returns token secret.
|
||||
user.getOriginal() // Original payload returned by the 3rd party provider.
|
||||
@@ -38,15 +38,74 @@
|
||||
# Use underscores in URL pattern names rather than dashes.
|
||||
|
||||
|
||||
# *****************************************************************************
|
||||
# Deployment
|
||||
# *****************************************************************************
|
||||
|
||||
|
||||
# add your media, database, venv, __pycache__ to the .gitignore (there is a compelete list that you can find here: https://github.com/jpadilla/django-project-template/blob/master/.gitignore)
|
||||
# keep migration files in the git (you will need to migrate them in target server)
|
||||
# don't run "makemigrations" in the target server (you will need to just run "migrate")
|
||||
# $ pip freeze > requirements.txt
|
||||
# make appropriate changes in your project settings.py file (change DEBUG to False and etc)
|
||||
# push your code to your git-server
|
||||
# pull your code in your target server
|
||||
# give right permissions to the web-server (e.g. $ chown www-data:www-data -R /var/www/myproject)
|
||||
# make a new venv in the target server and activate it
|
||||
# $ sudo pip install -r requirements.txt
|
||||
# sudo ./venv/bin/python3 manage.py migrate
|
||||
# restart your web-server (in case of apache: $ sudo service apache2 restart)
|
||||
|
||||
|
||||
# *****************************************************************************
|
||||
# DJANGO-ADMIN
|
||||
# *****************************************************************************
|
||||
|
||||
|
||||
django-admin startproject <ProjectName> # create a new project directory structure
|
||||
django-admin startapp <Appname> # create a new django application with the specified name
|
||||
django-admin migrate # synchronize the database state with your current state project models and migrations
|
||||
django-admin makemigrations # create new migrations to the database based on the changes detected in the models
|
||||
django-admin runserver # start the development webserver at 127.0.0.1 with the port 8000
|
||||
django-admin check # Checks the entire django project for potential problems
|
||||
django-admin changepassword <username> # Allows changing a user’s password. It prompts you to enter a new password twice for the given user.
|
||||
django-admin clearsessions # Can be run as a cron job or directly to clean out expired sessions.
|
||||
django-admin collectstatic # Helps to collect all the static files in the one mentioned directory
|
||||
django-admin createsuperuser # Creates a superuser account (a user who has all permissions).
|
||||
django-admin compilemessages # Compiles .po files to .mo files for use with builtin gettext support
|
||||
django-admin createcachetable # Creates the tables needed to use the SQL cache backend.
|
||||
django-admin dbshell # Runs the command-line client for specified database, or the default database if none is provided.
|
||||
django-admin diffsettings # Displays differences between the current settings.py and Django's default settings.
|
||||
django-admin dumpdata # Output the contents of the database as a fixture of the given format (using each model's default manager unless --all is specified).
|
||||
django-admin flush # Removes ALL DATA from the database, including data added during migrations. Does not achieve a "fresh install" state.
|
||||
django-admin inspectdb # Introspects the database tables in the given database and outputs a Django model module.
|
||||
django-admin loaddata # Installs the named fixture(s) in the database.
|
||||
django-admin makemessages # Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the django tree) or locale (for projects and applications) directory. You must run this command with one of either the --locale, --exclude, or --all options.
|
||||
django-admin help # display usage information and a list of the commands provided by each application
|
||||
django-admin makemigrations # create new migrations to the database based on the changes detected in the models
|
||||
django-admin migrate # synchronize the database state with your current state project models and migrations
|
||||
django-admin remove_stale_contenttypes # Deletes stale content types (from deleted models) in your database.y.
|
||||
django-admin runserver <port> # start the development webserver at 127.0.0.1 with the port <port> default 8000
|
||||
django-admin sendtestemail # Sends a test email to the email addresses specified as arguments.
|
||||
django-admin shell # Runs a Python interactive interpreter. Tries to use IPython or bpython, if one of them is available. Any standard input is executed as code.
|
||||
django-admin showmigrations # Shows all available migrations for the current project.
|
||||
django-admin sqlflush # Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed.
|
||||
django-admin sqlmigrate # Prints the SQL statements for the named migration.
|
||||
django-admin sqlsequencereset # Prints the SQL statements for resetting sequences for the given app name(s).
|
||||
django-admin squashmigrations # Squashes an existing set of migrations (from first until specified) into a single new one.
|
||||
django-admin startapp <Appname> # create a new django application with the specified name
|
||||
django-admin startproject <ProjectName> # create a new project directory structure
|
||||
django-admin testserver # Runs a development server with data from the given fixture(s).
|
||||
django-admin version # display the current django version
|
||||
|
||||
|
||||
# *****************************************************************************
|
||||
# Starting a django project in python3
|
||||
# *****************************************************************************
|
||||
|
||||
|
||||
# 1. $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py; python3 get-pip.py
|
||||
# 2. $ pip install virtualenv
|
||||
# 3. $ mkdir django-projects
|
||||
# 4. $ cd django-projects
|
||||
# 5. $ virtualenv venv
|
||||
# 6. $ source venv/bin/activate
|
||||
# 7. $ pip install django
|
||||
# 8. $ django-admin startproject myproject
|
||||
# 9. $ django-admin startapp myapp
|
||||
# 10. $ python manage.py runserver
|
||||
|
||||
@@ -113,13 +113,13 @@ app.service('my-service').hooks({
|
||||
before: {
|
||||
all: [
|
||||
// Use normal functions
|
||||
function(context) { console.log('before all hook ran'); }
|
||||
async function(context) { console.log('before all hook ran'); }
|
||||
],
|
||||
|
||||
find: [
|
||||
// Use ES6 arrow functions
|
||||
context => console.log('before find hook 1 ran'),
|
||||
context => console.log('before find hook 2 ran')
|
||||
async context => console.log('before find hook 2 ran')
|
||||
],
|
||||
|
||||
async create (context) {
|
||||
@@ -177,7 +177,8 @@ service.publish([event,] fn) // registers a publishing function for a specific
|
||||
app.publish([event,] fn) // registers an event publishing callback
|
||||
|
||||
app.on('connection', connection => {}) // fired every time a new real-time connection is established
|
||||
app.on('login', (payload, info) => {}) // sent by the authentication module and also contains the connection in the info object that is passed as the second parameter
|
||||
app.on('disconnection', connection => {})
|
||||
app.on('login', (authenticationResult, params, context) => {}) // sent by the authentication module and also contains the connection in the info object that is passed as the second parameter
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
@@ -233,13 +234,6 @@ app.configure(socketio(callback)) // sets up the Socket.io t
|
||||
app.configure(socketio(options [, callback])) // sets up the Socket.io transport with the given Socket.io options object and optionally calls the callback
|
||||
app.configure(socketio(port, [options], [callback])) // creates a new Socket.io server on a separate port. Options and a callback are optional
|
||||
|
||||
// The options can also be used to initialize uWebSocket which is a WebSocket server
|
||||
// implementation that provides better performace and reduced latency.
|
||||
// npm install uws --save
|
||||
app.configure(socketio({
|
||||
wsEngine: 'uws'
|
||||
}));
|
||||
|
||||
// --> PRIMUS <--
|
||||
// https://docs.feathersjs.com/api/client/primus.html
|
||||
|
||||
@@ -306,55 +300,65 @@ npm install @feathersjs/authentication --save
|
||||
# Wraps the passport-local authentication strategy (username and password)
|
||||
npm install @feathersjs/authentication-local --save
|
||||
|
||||
# Wraps the passport-jwt authentication strategy (JSON Web Token access token)
|
||||
npm install @feathersjs/authentication-jwt --save
|
||||
|
||||
# Allows you to use any Passport OAuth1 authentication strategy (most notably Twitter)
|
||||
npm install @feathersjs/authentication-oauth1 --save
|
||||
|
||||
# Allows you to use any Passport OAuth2 authentication strategy (FB, Instagram, Github, Google...)
|
||||
npm install @feathersjs/authentication-oauth2 --save
|
||||
# Allows to use 180+ oAuth providers (Facebook, Google, Twitter etc.)
|
||||
npm install @feathersjs/authentication-oauth --save
|
||||
```
|
||||
|
||||
// --> SERVER <--
|
||||
// https://docs.feathersjs.com/api/authentication/server.html
|
||||
|
||||
const options = {
|
||||
path: '/authentication', // the authentication service path
|
||||
header: 'Authorization', // the header to use when using JWT auth
|
||||
entity: 'user', // the entity that will be added to the request, socket, and context.params. (ie. req.user, socket.user, context.params.user)
|
||||
service: 'users', // the service to look up the entity
|
||||
passReqToCallback: true, // whether the request object should be passed to the strategies `verify` function
|
||||
session: false, // whether to use sessions
|
||||
cookie: {
|
||||
enabled: false, // whether cookie creation is enabled
|
||||
name: 'feathers-jwt', // the cookie name
|
||||
httpOnly: false, // when enabled, prevents the client from reading the cookie.
|
||||
secure: true // whether cookies should only be available over HTTPS
|
||||
},
|
||||
jwt: {
|
||||
header: { typ: 'access' }, // by default is an access token but can be any type
|
||||
audience: 'https://yourdomain.com', // The resource server where the token is processed
|
||||
subject: 'anonymous', // Typically the entity id associated with the JWT
|
||||
issuer: 'feathers', // The issuing server, application or resource
|
||||
algorithm: 'HS256', // the algorithm to use
|
||||
expiresIn: '1d' // the access token expiry
|
||||
"authentication": {
|
||||
"secret": "CHANGE_ME", // The token signing secret
|
||||
"entity": "user", // the entity that will be added to the request, socket, and context.params. (ie. req.user, socket.user, context.params.user)
|
||||
"service": "users", // the service to look up the entity
|
||||
"authStrategies": [ "jwt", "local" ], // The authentication strategies to allow to create a token
|
||||
"jwtOptions": {
|
||||
"header": { "typ": "access" }, // by default is an access token but can be any type
|
||||
"audience": "https://yourdomain.com", // The resource server where the token is processed
|
||||
"issuer": "feathers", // The issuing server, application or resource
|
||||
"algorithm": "HS256", // the algorithm to use
|
||||
"expiresIn": "1d" // the access token expiry
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app.configure(auth(options)) // configure the authentication plugin with the given options
|
||||
const { AuthenticationService, JWTStrategy } = require('@feathersjs/authentication');
|
||||
|
||||
service = app.service('authentication') // service for creating JWT (implements only the create and remove methods)
|
||||
let authService = new AuthenticationService(app);
|
||||
|
||||
service.create(data) // creates a JWT based on the jwt options configured on the plugin
|
||||
service.remove(data) // removes the JWT token (mostly exists for the logout process)
|
||||
service.hooks({ before }) // registers hooks for this service
|
||||
service.hooks({ after }) // registers hooks for this service
|
||||
service.register('jwt', new JWTStrategy());
|
||||
|
||||
app.passport.createJWT(payload, options) // used by the authentication service to generate JSON Web Tokens
|
||||
app.passport.verifyJWT(token, options) // verifies the signature and payload of the passed in JWT token using the options
|
||||
app.use('/authentication', authService);
|
||||
app.configure(expressOauth());
|
||||
|
||||
app.get('defaultAuthentication') // The name of the default authentication service
|
||||
|
||||
authService = app.service('authentication') // service for creating JWT (implements only the create and remove methods)
|
||||
|
||||
authService.hooks({ before }) // registers hooks for this service
|
||||
authService.hooks({ after }) // registers hooks for this service
|
||||
|
||||
new AuthenticationService(app) // Create a new authentication service
|
||||
|
||||
class MyAuthenticationService extends AuthenticationService {} // Customize the authentication service
|
||||
|
||||
authService.authenticate(data, params, ...strategies) // Authenticate with strategies
|
||||
authService.create(data, params) // Authenticate with data and params
|
||||
authService.create({ // Authenticate and create a JWT using the local strategy email/password
|
||||
strategy: 'local',
|
||||
email: 'hello@feathersjs.com',
|
||||
password: 'supersecret'
|
||||
});
|
||||
authService.remove(id, params) // removes the JWT token (mostly exists for the logout process)
|
||||
authService.configuration // The current configuration
|
||||
authService.register(name, strategy) // Register a new authentication strategy
|
||||
authService.createAccessToken(payload) // Create a new access token with payload
|
||||
authService.verifyAccessToken(accessToken) // Verify an existing access token
|
||||
authService.getTokenOptions(authResult, params) // Get the options for a token
|
||||
authService.getPayload(authResult, params) // Return the payload for an authentication result
|
||||
authService.parse(req, res, ...strategies) // Parse an HTTP request and response with using a list of strategies
|
||||
|
||||
auth.hooks.authenticate(strategies) // registers an array of authentication strategies on a service method
|
||||
|
||||
app.on('login', callback)) // emits an event whenever a client successfully authenticates
|
||||
app.on('logout', callback)) // emits an event whenever a client successfully logout
|
||||
@@ -363,198 +367,77 @@ app.on('logout', callback)) // emits an event whenever a client successfully lo
|
||||
// https://docs.feathersjs.com/api/authentication/client.html
|
||||
|
||||
const options = {
|
||||
path: '/authentication', // the server-side authentication service path
|
||||
header: 'Authorization', // the default authorization header for REST
|
||||
jwtStrategy: 'jwt', // the name of the JWT authentication strategy
|
||||
entity: 'user', // the entity you are authenticating (ie. a users)
|
||||
service: 'users', // the service to look up the entity
|
||||
cookie: 'feathers-jwt', // the name of the cookie to parse the JWT from when cookies are enabled server side
|
||||
storageKey: 'feathers-jwt', // the key to store the accessToken in localstorage or AsyncStorage on React Native
|
||||
storage: undefined // Passing a WebStorage-compatible object to enable automatic storage on the client.
|
||||
storage: window.localStorage, // The storage to store the access token
|
||||
path: '/authentication', // The path of the authentication service
|
||||
locationKey: 'access_token', // The name of the window hash parameter to parse for an access token from the window.location. Usually used by the oAuth flow.
|
||||
locationErrorKey: 'error', // The name of the window hash parameter to parse for authentication errors. Usually used by the oAuth flow.
|
||||
jwtStrategy: 'jwt', // The access token authentication strategy
|
||||
storageKey: 'feathers-jwt', // Key for storing the token in e.g. localStorage
|
||||
header: 'Authorization', // Name of the accessToken header
|
||||
scheme: 'Bearer', // The HTTP header scheme
|
||||
Authentication: AuthenticationClient // Allows to provide a customized authentication client class
|
||||
}
|
||||
|
||||
app.configure(auth(options)) // configure the authentication plugin with the given options
|
||||
|
||||
app.authenticate() // authenticates using the JWT from the storage
|
||||
app.reAuthenticate() // authenticates using the JWT from the storage
|
||||
app.authenticate(options) // authenticate with a Feathers server by passing a strategy and other properties as credentials
|
||||
app.logout() // removes the JWT accessToken from storage on the client
|
||||
|
||||
app.passport.getJWT() // pulls the JWT from storage or the cookie
|
||||
app.passport.verifyJWT(token) // verifies that a JWT is not expired and decode it to get the payload
|
||||
app.passport.payloadIsValid(token) // synchronously verify that a token has not expired
|
||||
const authenticationInfo = await app.get('authentication'); // The authenticatoin information (like the user)
|
||||
|
||||
app.on('authenticated', callback)) // emits an event whenever the client successfully authenticates
|
||||
app.on('logout', callback)) // emits an event whenever the client successfully authenticates
|
||||
app.on('reauthentication-error', errorHandler) // will automatically handle attempting to re-authenticate the socket when the client regains connectivity with the server
|
||||
app.on('login', callback) // emits an event whenever the client successfully authenticates
|
||||
app.on('logout', callback) // emits an event whenever the client successfully authenticates
|
||||
|
||||
// --> LOCAL (EMAIL & PASSWORD) <--
|
||||
// https://docs.feathersjs.com/api/authentication/local.html
|
||||
|
||||
const feathers = require('@feathersjs/feathers');
|
||||
const authentication = require('@feathersjs/authentication');
|
||||
const local = require('@feathersjs/authentication-local');
|
||||
const app = feathers();
|
||||
const { LocalStrategy } = require('@feathersjs/authentication-local');
|
||||
|
||||
const options = {
|
||||
name: 'local', // the name to use when invoking the authentication Strategy
|
||||
entity: 'user', // the entity that you're comparing username/password against
|
||||
service: 'users', // the service to look up the entity
|
||||
usernameField: 'email', // key name of username field
|
||||
passwordField: 'password', // key name of password field
|
||||
passReqToCallback: true, // whether the request object should be passed to `verify`
|
||||
session: false, // whether to use sessions
|
||||
Verifier: Verifier // A Verifier class. Defaults to the built-in one but can be a custom one
|
||||
usernameField: 'email', // Name of the username field in the (e.g. 'email')
|
||||
passwordField: 'password', // Name of the password field (e.g. 'password')
|
||||
hashSize: 10, // The BCrypt hash size
|
||||
errorMessage: 'Invalid login', // The error message to return on errors
|
||||
entityUsernameField: usernameField, // Name of the username field on the entity if authentication request data and entity field names are different
|
||||
entityPasswordField: passwordField // Name of the password field on the entity if authentication request data and entity field names are different
|
||||
}
|
||||
|
||||
app.configure(authentication(options));
|
||||
app.configure(local());
|
||||
|
||||
// Setup a hook to only allow valid JWTs or successful
|
||||
// local auth to authenticate and get new JWT access tokens
|
||||
app.service('authentication').hooks({
|
||||
before: {
|
||||
create: [
|
||||
authentication.hooks.authenticate(['local', 'jwt'])
|
||||
]
|
||||
}
|
||||
});
|
||||
authService.register('local', new LocalStrategy());
|
||||
|
||||
local.hooks.hashPassword() // hashes plain text passwords before they are saved to the database
|
||||
local.hooks.protect('password') // makes sure that protected fields don't get sent to a client
|
||||
|
||||
// --> JWT <--
|
||||
// https://docs.feathersjs.com/api/authentication/jwt.html
|
||||
// --> OAUTH <--
|
||||
// https://docs.feathersjs.com/api/authentication/oauth.html
|
||||
const { expressOauth, OAuthStrategy } = require('@feathersjs/authentication-oauth');
|
||||
|
||||
const feathers = require('@feathersjs/feathers');
|
||||
const authentication = require('@feathersjs/authentication');
|
||||
const jwt = require('@feathersjs/authentication-jwt');
|
||||
const app = feathers();
|
||||
class GitHubStrategy extends OAuthStrategy {
|
||||
async getEntityData(profile) {
|
||||
const baseData = await super.getEntityData(profile);
|
||||
|
||||
const options = {
|
||||
name: 'jwt', // the name to use when invoking the authentication Strategy
|
||||
entity: 'user', // the entity that you pull from if an 'id' is present in the payload
|
||||
service: 'users', // the service to look up the entity
|
||||
passReqToCallback: true, // whether the request object should be passed to `verify`
|
||||
jwtFromRequest: [ // a passport-jwt option determining where to parse the JWT
|
||||
ExtractJwt.fromHeader, // From "Authorization" header
|
||||
ExtractJwt.fromAuthHeaderWithScheme('Bearer'), // Allowing "Bearer" prefix
|
||||
ExtractJwt.fromBodyField('body') // from request body
|
||||
],
|
||||
secretOrKey: auth.secret, // Your main secret provided to passport-jwt
|
||||
session: false, // whether to use sessions,
|
||||
Verifier: Verifier // A Verifier class. Defaults to the built-in one but can be a custom one. See below for details.
|
||||
return {
|
||||
...baseData,
|
||||
email: profile.email
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
app.configure(authentication(options));
|
||||
app.configure(jwt());
|
||||
|
||||
// Setup a hook to only allow valid JWTs to authenticate
|
||||
// and get new JWT access tokens
|
||||
app.service('authentication').hooks({
|
||||
before: {
|
||||
create: [
|
||||
authentication.hooks.authenticate(['jwt'])
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// --> OAUTH1 <--
|
||||
// https://docs.feathersjs.com/api/authentication/oauth1.html
|
||||
|
||||
const feathers = require('@feathersjs/feathers');
|
||||
const authentication = require('@feathersjs/authentication');
|
||||
const jwt = require('@feathersjs/authentication-jwt');
|
||||
const oauth1 = require('@feathersjs/authentication-oauth1');
|
||||
|
||||
const session = require('express-session');
|
||||
const TwitterStrategy = require('passport-twitter').Strategy;
|
||||
const app = feathers();
|
||||
|
||||
// Setup in memory session
|
||||
app.use(session({
|
||||
secret: 'super secret',
|
||||
resave: true,
|
||||
saveUninitialized: true
|
||||
}));
|
||||
authService.register('github', new MyGitHubStrategy());
|
||||
|
||||
const options = {
|
||||
idField: '<provider>Id', // The field to look up the entity by when logging in with the provider. Defaults to '<provider>Id' (ie. 'twitterId').
|
||||
path: '/auth/<provider>', // The route to register the middleware
|
||||
callbackURL: 'http(s)://hostame[:port]/auth/<provider>/callback', // The callback url. Will automatically take into account your host and port and whether you are in production based on your app environment to construct the url. (ie. in development http://localhost:3030/auth/twitter/callback)
|
||||
entity: 'user', // the entity that you are looking up
|
||||
service: 'users', // the service to look up the entity
|
||||
passReqToCallback: true, // whether the request object should be passed to `verify`
|
||||
session: true, // whether to use sessions,
|
||||
handler: fn, // Express middleware for handling the oauth callback. Defaults to the built in middleware.
|
||||
formatter: fn, // The response formatter. Defaults the the built in feathers-rest formatter, which returns JSON.
|
||||
Verifier: Verifier // A Verifier class. Defaults to the built-in one but can be a custom one. See below for details.
|
||||
authentication: {
|
||||
oauth: {
|
||||
redirect: '/', // The redirect after a successful login
|
||||
github: { // The per-strategy configuration
|
||||
key: '<Client ID>',
|
||||
secret: '<Client secret>'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Setup authentication
|
||||
app.configure(authentication(options));
|
||||
app.configure(jwt());
|
||||
app.configure(oauth1({
|
||||
name: 'twitter',
|
||||
Strategy: TwitterStrategy,
|
||||
consumerKey: '<your consumer key>',
|
||||
consumerSecret: '<your consumer secret>'
|
||||
}));
|
||||
|
||||
// Setup a hook to only allow valid JWTs to authenticate
|
||||
// and get new JWT access tokens
|
||||
app.service('authentication').hooks({
|
||||
before: {
|
||||
create: [
|
||||
authentication.hooks.authenticate(['jwt'])
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// --> OAUTH 2 <--
|
||||
// https://docs.feathersjs.com/api/authentication/oauth2.html
|
||||
|
||||
const feathers = require('@feathersjs/feathers');
|
||||
const authentication = require('@feathersjs/authentication');
|
||||
const jwt = require('@feathersjs/authentication-jwt');
|
||||
const oauth2 = require('@feathersjs/authentication-oauth2');
|
||||
const FacebookStrategy = require('passport-facebook').Strategy;
|
||||
const app = feathers();
|
||||
|
||||
const options = {
|
||||
idField: '<provider>Id', // The field to look up the entity by when logging in with the provider. Defaults to '<provider>Id' (ie. 'facebookId').
|
||||
path: '/auth/<provider>', // The route to register the middleware
|
||||
callbackURL: 'http(s)://hostname[:port]/auth/<provider>/callback', // The callback url. Will automatically take into account your host and port and whether you are in production based on your app environment to construct the url. (ie. in development http://localhost:3030/auth/facebook/callback)
|
||||
successRedirect: undefined,
|
||||
failureRedirect: undefined,
|
||||
entity: 'user', // the entity that you are looking up
|
||||
service: 'users', // the service to look up the entity
|
||||
passReqToCallback: true, // whether the request object should be passed to `verify`
|
||||
session: false, // whether to use sessions,
|
||||
handler: fn, // Express middleware for handling the oauth callback. Defaults to the built in middleware.
|
||||
formatter: fn, // The response formatter. Defaults the the built in feathers-rest formatter, which returns JSON.
|
||||
Verifier: Verifier // A Verifier class. Defaults to the built-in one but can be a custom one. See below for details.
|
||||
}
|
||||
|
||||
// Setup authentication
|
||||
app.configure(authentication({ secret: 'super secret' }));
|
||||
app.configure(jwt());
|
||||
app.configure(oauth2({
|
||||
name: 'facebook',
|
||||
Strategy: FacebookStrategy,
|
||||
clientID: '<your client id>',
|
||||
clientSecret: '<your client secret>',
|
||||
scope: ['public_profile', 'email']
|
||||
}));
|
||||
|
||||
// Setup a hook to only allow valid JWTs to authenticate
|
||||
// and get new JWT access tokens
|
||||
app.service('authentication').hooks({
|
||||
before: {
|
||||
create: [
|
||||
authentication.hooks.authenticate(['jwt'])
|
||||
]
|
||||
}
|
||||
});
|
||||
app.configure(expressOauth(options));
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
@@ -602,7 +485,9 @@ app.use('/messages', service({
|
||||
paginate: { // (optional) a pagination object containing a default and max page size
|
||||
default: undefined, // sets the default number of items when $limit is not set
|
||||
max: undefined // sets the maximum allowed number of items per page (even if the $limit query parameter is set higher)
|
||||
}
|
||||
},
|
||||
whitelist: [], // A list of additional non-standard query parameters to allow (e.g [ '$regex', '$populate' ])
|
||||
multi: true // Allow create with arrays and update and remove with id null to change multiple items
|
||||
}));
|
||||
|
||||
adapter.find() // returns a list of all records matching the query in params.query using the common querying mechanism
|
||||
@@ -612,6 +497,14 @@ adapter.update(id, data, params) // completely replaces a single record identif
|
||||
adapter.patch(id, data, params) // merges a record identified by id with data. id can be null to allow replacing multiple records (all records that match params.query the same as in .find). id can not be changed
|
||||
adapter.remove(id, params) // removes a record identified by id. id can be null to allow removing multiple records (all records that match params.query the same as in .find)
|
||||
|
||||
// Hook-less
|
||||
adapter._find()
|
||||
adapter._get(id, params)
|
||||
adapter._create(data, params)
|
||||
adapter._update(id, data, params)
|
||||
adapter._patch(id, data, params)
|
||||
adapter._remove(id, params)
|
||||
|
||||
// --> QUERYING <--
|
||||
// https://docs.feathersjs.com/api/databases/querying.html
|
||||
|
||||
@@ -673,14 +566,13 @@ app.service('messages').find({
|
||||
// │ │ └── ...
|
||||
// │ ├── services/ # contains our services
|
||||
// │ │ └── ...
|
||||
// │ ├── tests/ # contains Mocha test files for the app, hooks and services
|
||||
// │ │ └── ...
|
||||
// │ │
|
||||
// │ ├── index.js # is used to load and start the application
|
||||
// │ ├── app.js # configures our Feathers application
|
||||
// │ ├── app.hooks.js # contains hooks which that run for all services
|
||||
// │ └── channels.js # set up Feathers event channels
|
||||
// │
|
||||
// ├── tests/ # contains Mocha test files for the app, hooks and services
|
||||
// │ └── ...
|
||||
// ├── .editorconfig # helps developers define and maintain consistent coding styles
|
||||
// ├── .eslintrc.json # eslint configuration
|
||||
// └── package.json # express server for production
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<?php
|
||||
|
||||
/********************************************************************************************
|
||||
* 1. CLI AVAILABLE COMMANDS FOR ARTISAN
|
||||
* CLI AVAILABLE COMMANDS FOR ARTISAN
|
||||
* https://laravel.com/docs/5.8/artisan
|
||||
********************************************************************************************/
|
||||
|
||||
// 1.1. MAIN.
|
||||
// MAIN.
|
||||
|
||||
php artisan clear-compiled // Remove the compiled class file
|
||||
php artisan down // Put the application into maintenance mode
|
||||
@@ -21,38 +21,38 @@ php artisan serve // Serve the application on the PHP development
|
||||
php artisan tinker // Interact with your application
|
||||
php artisan up // Bring the application out of maintenance mode
|
||||
|
||||
// 1.2. APP.
|
||||
// APP.
|
||||
|
||||
php artisan app:name // Set the application namespace
|
||||
|
||||
// 1.3. AUTH
|
||||
// AUTH
|
||||
|
||||
php artisan auth:clear-resets // Flush expired password reset tokens
|
||||
|
||||
// 1.4. CACHE
|
||||
// CACHE
|
||||
|
||||
php artisan cache:clear // Flush the application cache
|
||||
php artisan cache:forget // Remove an item from the cache
|
||||
php artisan cache:table // Create a migration for the cache database table
|
||||
|
||||
// 1.5. CONFIG
|
||||
// CONFIG
|
||||
|
||||
php artisan config:cache // Create a cache file for faster configuration loading
|
||||
php artisan config:clear // Remove the configuration cache file
|
||||
|
||||
// 1.6. DB
|
||||
// DB
|
||||
|
||||
php artisan db:seed // Seed the database with records
|
||||
|
||||
// 1.7. EVENT
|
||||
// EVENT
|
||||
|
||||
php artisan event:generate // Generate the missing events and listeners based on registration
|
||||
|
||||
// 1.8. KEY
|
||||
// KEY
|
||||
|
||||
php artisan key:generate // Set the application key
|
||||
|
||||
// 1.9. MAKE
|
||||
// MAKE
|
||||
|
||||
php artisan make:auth // Scaffold basic login and registration views and routes
|
||||
php artisan make:channel // Create a new channel class
|
||||
@@ -77,7 +77,7 @@ php artisan make:rule // Create a new validation rule
|
||||
php artisan make:seeder // Create a new seeder class
|
||||
php artisan make:test // Create a new test class
|
||||
|
||||
// 1.10. MIGRATE
|
||||
// MIGRATE
|
||||
|
||||
php artisan migrate:fresh // Drop all tables and re-run all migrations
|
||||
php artisan migrate:install // Create the migration repository
|
||||
@@ -86,19 +86,19 @@ php artisan migrate:reset // Rollback all database migrations
|
||||
php artisan migrate:rollback // Rollback the last database migration
|
||||
php artisan migrate:status // Show the status of each migration
|
||||
|
||||
// 1.11. NOTIFICATIONS
|
||||
// NOTIFICATIONS
|
||||
|
||||
php artisan notifications:table // Create a migration for the notifications table
|
||||
|
||||
// 1.12. OPTIMIZE
|
||||
// OPTIMIZE
|
||||
|
||||
php artisan optimize:clear // Remove the cached bootstrap files
|
||||
|
||||
// 1.13. PACKAGE
|
||||
// PACKAGE
|
||||
|
||||
php artisan package:discover // Rebuild the cached package manifest
|
||||
|
||||
// 1.14. QUEUE
|
||||
// QUEUE
|
||||
|
||||
php artisan queue:failed // List all of the failed queue jobs
|
||||
php artisan queue:failed-table // Create a migration for the failed queue jobs database table
|
||||
@@ -110,35 +110,35 @@ php artisan queue:retry // Retry a failed queue job
|
||||
php artisan queue:table // Create a migration for the queue jobs database table
|
||||
php artisan queue:work // Start processing jobs on the queue as a daemon
|
||||
|
||||
// 1.15. ROUTE
|
||||
// ROUTE
|
||||
|
||||
php artisan route:cache // Create a route cache file for faster route registration
|
||||
php artisan route:clear // Remove the route cache file
|
||||
php artisan route:list // List all registered routes
|
||||
|
||||
// 1.16. SCHEDULE
|
||||
// SCHEDULE
|
||||
|
||||
php artisan schedule:run // Run the scheduled commands
|
||||
|
||||
// 1.17. SESSION
|
||||
// SESSION
|
||||
|
||||
php artisan session:table // Create a migration for the session database table
|
||||
|
||||
// 1.18. STORAGE
|
||||
// STORAGE
|
||||
|
||||
php artisan storage:link // Create a symbolic link from "public/storage" to "storage/app/public"
|
||||
|
||||
// 1.19. VENDOR
|
||||
// VENDOR
|
||||
|
||||
php artisan vendor:publish // Publish any publishable assets from vendor packages
|
||||
|
||||
// 1.20. VIEW
|
||||
// VIEW
|
||||
|
||||
php artisan view:cache // Compile all of the application's Blade templates
|
||||
php artisan view:clear // Clear all compiled view files
|
||||
|
||||
/********************************************************************************************
|
||||
* 2. REQUEST
|
||||
* REQUEST
|
||||
* https://laravel.com/api/5.8/Illuminate/Http/Request.html
|
||||
* https://laravel.com/docs/5.8/requests
|
||||
********************************************************************************************/
|
||||
@@ -146,7 +146,7 @@ php artisan view:clear // Clear all compiled view files
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 3. RESPONSE
|
||||
* RESPONSE
|
||||
* https://laravel.com/api/5.8/Illuminate/Http/Response.html
|
||||
* https://laravel.com/docs/5.8/responses
|
||||
********************************************************************************************/
|
||||
@@ -154,65 +154,243 @@ php artisan view:clear // Clear all compiled view files
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 4. ROUTING
|
||||
* ROUTING
|
||||
* https://laravel.com/docs/5.8/routing
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 5. MIDDLEWARE
|
||||
* MIDDLEWARE
|
||||
* https://laravel.com/docs/5.8/middleware
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 6. CONTROLLERS
|
||||
* CONTROLLERS
|
||||
* https://laravel.com/docs/5.8/controllers
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 7. SESSION
|
||||
* SESSION
|
||||
* https://laravel.com/docs/5.8/session
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 8. URL GENERATION
|
||||
* URL GENERATION
|
||||
* https://laravel.com/docs/5.8/urls
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 9. VALIDATION
|
||||
* VALIDATION
|
||||
* https://laravel.com/docs/5.8/validation
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
accepted // The field under validation must be yes, on, 1, or true.
|
||||
active_url // The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.
|
||||
after:date // The field under validation must be a value after a given date.
|
||||
after_or_equal:date // The field under validation must be a value after or equal to the given date.
|
||||
alpha // The field under validation must be entirely alphabetic characters.
|
||||
alpha_dash // The field under validation may have alpha-numeric characters, as well as dashes and underscores.
|
||||
alpha_num // The field under validation must be entirely alpha-numeric characters.
|
||||
array // The field under validation must be a PHP array.
|
||||
bail // Stop running validation rules after the first validation failure.
|
||||
before:date // The field under validation must be a value preceding the given date.
|
||||
before_or_equal:date // The field under validation must be a value preceding or equal to the given date.
|
||||
between:min,max // The field under validation must have a size between the given min and max.
|
||||
boolean // The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".
|
||||
confirmed // The field under validation must have a matching field of foo_confirmation.
|
||||
date // The field under validation must be a valid, non-relative date according to the strtotime PHP function.
|
||||
date_equals:date // The field under validation must be equal to the given date.
|
||||
date_format:format // The field under validation must match the given format.
|
||||
different:field // The field under validation must have a different value than field.
|
||||
digits:value // The field under validation must be numeric and must have an exact length of value.
|
||||
digits_between:min,max // The field under validation must have a length between the given min and max.
|
||||
dimensions // The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters.
|
||||
distinct // When working with arrays, the field under validation must not have any duplicate values.
|
||||
email // The field under validation must be formatted as an e-mail address.
|
||||
ends_with:foo,bar,... // The field under validation must end with one of the given values.
|
||||
exists:table,column // The field under validation must exist on a given database table.
|
||||
file // The field under validation must be a successfully uploaded file.
|
||||
filled // The field under validation must not be empty when it is present.
|
||||
gt:field // The field under validation must be greater than the given field.
|
||||
gte:field // The field under validation must be greater than or equal to the given field.
|
||||
image // The file under validation must be an image (jpeg, png, bmp, gif, svg, or webp)
|
||||
in:foo,bar,... // The field under validation must be included in the given list of values.
|
||||
in_array:anotherfield.* // The field under validation must exist in anotherfield's values.
|
||||
integer // The field under validation must be an integer.
|
||||
ip // The field under validation must be an IP address.
|
||||
ipv4 // The field under validation must be an IPv4 address.
|
||||
ipv6 // The field under validation must be an IPv6 address.
|
||||
json // The field under validation must be a valid JSON string.
|
||||
lt:field // The field under validation must be less than the given field.
|
||||
lte:field // The field under validation must be less than or equal to the given field.
|
||||
max:value // The field under validation must be less than or equal to a maximum value.
|
||||
mimetypes:text/plain,... // The file under validation must match one of the given MIME types:
|
||||
mimes:foo,bar,... // The file under validation must have a MIME type corresponding to one of the listed extensions.
|
||||
min:value // The field under validation must have a minimum value.
|
||||
not_in:foo,bar,... // The field under validation must not be included in the given list of values.
|
||||
not_regex:pattern // The field under validation must not match the given regular expression.
|
||||
nullable // The field under validation may be null.
|
||||
numeric // The field under validation must be numeric.
|
||||
present // The field under validation must be present in the input data but can be empty.
|
||||
regex:pattern // The field under validation must match the given regular expression.
|
||||
required // The field under validation must be present in the input data and not empty.
|
||||
required_if:anotherfield,value,... // The field under validation must be present and not empty if the anotherfield field is equal to any value.
|
||||
required_unless:anotherfield,value,... // The field under validation must be present and not empty unless the anotherfield field is equal to any value.
|
||||
required_with:foo,bar,... // The field under validation must be present and not empty only if any of the other specified fields are present.
|
||||
required_with_all:foo,bar,... // The field under validation must be present and not empty only if all of the other specified fields are present.
|
||||
required_without:foo,bar,... // The field under validation must be present and not empty only when any of the other specified fields are not present.
|
||||
required_without_all:foo,bar,... // The field under validation must be present and not empty only when all of the other specified fields are not present.
|
||||
same:field // The given field must match the field under validation.
|
||||
size:value // The field under validation must have a size matching the given value.
|
||||
starts_with:foo,bar,... // The field under validation must start with one of the given values.
|
||||
string // The field under validation must be a string.
|
||||
timezone // The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.
|
||||
unique:table,column,except,idColumn // The field under validation must not exist within the given database table.
|
||||
url // The field under validation must be a valid URL.
|
||||
uuid // The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).
|
||||
|
||||
/********************************************************************************************
|
||||
* 10. ERROR HANDLING
|
||||
* ERROR HANDLING
|
||||
* https://laravel.com/docs/5.8/errors
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 11. LOGGING
|
||||
* https://laravel.com/docs/5.8/logging
|
||||
* MIGRATION COMMANDS
|
||||
* https://laravel.com/docs/5.8/migrations
|
||||
********************************************************************************************/
|
||||
|
||||
// TABLE OPTIONS
|
||||
|
||||
$table->engine = 'InnoDB'; // Specify the table storage engine (MySQL).
|
||||
$table->charset = 'utf8'; // Specify a default character set for the table (MySQL).
|
||||
$table->collation = 'utf8_unicode_ci'; // Specify a default collation for the table (MySQL).
|
||||
$table->temporary(); // Create a temporary table (except SQL Server).
|
||||
|
||||
// COLUMN TYPES
|
||||
|
||||
$table->bigIncrements('id'); // Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.
|
||||
$table->bigInteger('votes'); // BIGINT equivalent column.
|
||||
$table->binary('data'); // BLOB equivalent column.
|
||||
$table->boolean('confirmed'); // BOOLEAN equivalent column.
|
||||
$table->char('name', 100); // CHAR equivalent column with an optional length.
|
||||
$table->date('created_at'); // DATE equivalent column.
|
||||
$table->dateTime('created_at'); // DATETIME equivalent column.
|
||||
$table->dateTimeTz('created_at'); // DATETIME (with timezone) equivalent column.
|
||||
$table->decimal('amount', 8, 2); // DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
|
||||
$table->double('amount', 8, 2); // DOUBLE equivalent column with a precision (total digits) and scale (decimal digits).
|
||||
$table->enum('level', ['easy', 'hard']); // ENUM equivalent column.
|
||||
$table->float('amount', 8, 2); // FLOAT equivalent column with a precision (total digits) and scale (decimal digits).
|
||||
$table->geometry('positions'); // GEOMETRY equivalent column.
|
||||
$table->geometryCollection('positions'); // GEOMETRYCOLLECTION equivalent column.
|
||||
$table->increments('id'); // Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
|
||||
$table->integer('votes'); // INTEGER equivalent column.
|
||||
$table->ipAddress('visitor'); // IP address equivalent column.
|
||||
$table->json('options'); // JSON equivalent column.
|
||||
$table->jsonb('options'); // JSONB equivalent column.
|
||||
$table->lineString('positions'); // LINESTRING equivalent column.
|
||||
$table->longText('description'); // LONGTEXT equivalent column.
|
||||
$table->macAddress('device'); // MAC address equivalent column.
|
||||
$table->mediumIncrements('id'); // Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column.
|
||||
$table->mediumInteger('votes'); // MEDIUMINT equivalent column.
|
||||
$table->mediumText('description'); // MEDIUMTEXT equivalent column.
|
||||
$table->morphs('taggable'); // Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.
|
||||
$table->uuidMorphs('taggable'); // Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns.
|
||||
$table->multiLineString('positions'); // MULTILINESTRING equivalent column.
|
||||
$table->multiPoint('positions'); // MULTIPOINT equivalent column.
|
||||
$table->multiPolygon('positions'); // MULTIPOLYGON equivalent column.
|
||||
$table->nullableMorphs('taggable'); // Adds nullable versions of morphs() columns.
|
||||
$table->nullableUuidMorphs('taggable'); // Adds nullable versions of uuidMorphs() columns.
|
||||
$table->nullableTimestamps(); // Alias of timestamps() method.
|
||||
$table->point('position'); // POINT equivalent column.
|
||||
$table->polygon('positions'); // POLYGON equivalent column.
|
||||
$table->rememberToken(); // Adds a nullable remember_token VARCHAR(100) equivalent column.
|
||||
$table->set('flavors', ['strawberry', 'vanilla']); // SET equivalent column.
|
||||
$table->smallIncrements('id'); // Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column.
|
||||
$table->smallInteger('votes'); // SMALLINT equivalent column.
|
||||
$table->softDeletes(); // Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes.
|
||||
$table->softDeletesTz(); // Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes.
|
||||
$table->string('name', 100); // VARCHAR equivalent column with a optional length.
|
||||
$table->text('description'); // TEXT equivalent column.
|
||||
$table->time('sunrise'); // TIME equivalent column.
|
||||
$table->timeTz('sunrise'); // TIME (with timezone) equivalent column.
|
||||
$table->timestamp('added_on'); // TIMESTAMP equivalent column.
|
||||
$table->timestampTz('added_on'); // TIMESTAMP (with timezone) equivalent column.
|
||||
$table->timestamps(); // Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
|
||||
$table->timestampsTz(); // Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
|
||||
$table->tinyIncrements('id'); // Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
|
||||
$table->tinyInteger('votes'); // TINYINT equivalent column.
|
||||
$table->unsignedBigInteger('votes'); // UNSIGNED BIGINT equivalent column.
|
||||
$table->unsignedDecimal('amount', 8, 2); // UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
|
||||
$table->unsignedInteger('votes'); // UNSIGNED INTEGER equivalent column.
|
||||
$table->unsignedMediumInteger('votes'); // UNSIGNED MEDIUMINT equivalent column.
|
||||
$table->unsignedSmallInteger('votes'); // UNSIGNED SMALLINT equivalent column.
|
||||
$table->unsignedTinyInteger('votes'); // UNSIGNED TINYINT equivalent column.
|
||||
$table->uuid('id'); // UUID equivalent column.
|
||||
$table->year('birth_year'); // YEAR equivalent column.
|
||||
|
||||
// COLUMN MODIFIERS
|
||||
|
||||
$table->someType()->after('column'); // Place the column "after" another column (MySQL)
|
||||
$table->someType()->autoIncrement(); // Set INTEGER columns as auto-increment (primary key)
|
||||
$table->someType()->charset('utf8'); // Specify a character set for the column (MySQL)
|
||||
$table->someType()->collation('utf8_unicode_ci'); // Specify a collation for the column (MySQL/SQL Server)
|
||||
$table->someType()->comment('my comment'); // Add a comment to a column (MySQL/PostgreSQL)
|
||||
$table->someType()->default($value); // Specify a "default" value for the column
|
||||
$table->someType()->first(); // Place the column "first" in the table (MySQL)
|
||||
$table->someType()->nullable($value = true); // Allows (by default) NULL values to be inserted into the column
|
||||
$table->someType()->storedAs($expression); // Create a stored generated column (MySQL)
|
||||
$table->someType()->unsigned(); // Set INTEGER columns as UNSIGNED (MySQL)
|
||||
$table->someType()->useCurrent(); // Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value
|
||||
$table->someType()->virtualAs($expression); // Create a virtual generated column (MySQL)
|
||||
$table->someType()->generatedAs($expression); // Create an identity column with specified sequence options (PostgreSQL)
|
||||
$table->someType()->always(); // Defines the precedence of sequence values over input for an identity column (PostgreSQL)
|
||||
|
||||
// UPDATING COLUMNS
|
||||
|
||||
$table->someType()->change(); // Allows you to modify some existing column types to a new type or modify the column's attributes.
|
||||
$table->renameColumn('from', 'to'); // Rename a column
|
||||
|
||||
$table->dropColumn('column'); // Drop a given column (accepts an array of columns).
|
||||
$table->dropRememberToken(); // Drop the remember_token column.
|
||||
$table->dropSoftDeletes(); // Drop the deleted_at column.
|
||||
$table->dropSoftDeletesTz(); // Alias of dropSoftDeletes() method.
|
||||
$table->dropTimestamps(); // Drop the created_at and updated_at columns.
|
||||
$table->dropTimestampsTz(); // Alias of dropTimestamps() method.
|
||||
|
||||
// INDEXES
|
||||
|
||||
$table->primary('id'); // Adds a primary key.
|
||||
$table->primary(['id', 'parent_id']); // Adds composite keys.
|
||||
$table->unique('email'); // Adds a unique index.
|
||||
$table->index('state'); // Adds a plain index.
|
||||
$table->spatialIndex('location'); // Adds a spatial index. (except SQLite)
|
||||
|
||||
$table->dropPrimary('users_id_primary'); // Drop a primary key from the "users" table.
|
||||
$table->dropUnique('users_email_unique'); // Drop a unique index from the "users" table.
|
||||
$table->dropIndex('geo_state_index'); // Drop a basic index from the "geo" table.
|
||||
$table->dropSpatialIndex('geo_location_spatialindex'); // Drop a spatial index from the "geo" table (except SQLite).
|
||||
|
||||
// FOREIGN KEY CONSTRAINTS
|
||||
|
||||
$table->foreign('user_id')->references('id')->on('users'); // Create foreign key constraints.
|
||||
$table->dropForeign('posts_user_id_foreign'); // Drop foreign key (accepts an array of strings).
|
||||
|
||||
Schema::enableForeignKeyConstraints(); // Enable foreign key constraints within your migrations.
|
||||
Schema::disableForeignKeyConstraints(); // Disable foreign key constraints within your migrations.
|
||||
|
||||
/********************************************************************************************
|
||||
* 12. COLLECTIONS
|
||||
* COLLECTION ELOQUENT METHODS
|
||||
* https://laravel.com/docs/5.7/collections
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
all
|
||||
average
|
||||
avg
|
||||
@@ -321,13 +499,11 @@ whereNotInStrict
|
||||
wrap
|
||||
zip
|
||||
|
||||
|
||||
/********************************************************************************************
|
||||
* 13. HTTP TESTS
|
||||
* HTTP TESTS
|
||||
* https://laravel.com/docs/5.7/http-tests
|
||||
********************************************************************************************/
|
||||
|
||||
|
||||
$response->assertStatus($code); // Assert that the response has a given code.
|
||||
$response->assertForbidden(); // Assert that the response has a forbidden status code.
|
||||
$response->assertNotFound(); // Assert that the response has a not found status code.
|
||||
@@ -379,3 +555,32 @@ $this->assertGuest($guard = null); // Assert t
|
||||
$this->assertAuthenticatedAs($user, $guard = null); // Assert that the given user is authenticated.
|
||||
$this->assertCredentials(array $credentials, $guard = null); // $this->assertCredentials(array $credentials, $guard = null).
|
||||
$this->assertInvalidCredentials(array $credentials, $guard = null); // Assert that the given credentials are invalid.
|
||||
|
||||
/********************************************************************************************
|
||||
* LARAVEL VALET COMMANDS
|
||||
* https://laravel.com/docs/6.0/valet
|
||||
********************************************************************************************/
|
||||
|
||||
valet install // Install the Valet daemon.
|
||||
valet uninstall // Uninstall the Valet daemon.
|
||||
valet use php@7.2 // Allows you to switch between php versions.
|
||||
|
||||
valet start // Start the Valet daemon.
|
||||
valet stop // Stop the Valet daemon.
|
||||
valet restart // Restart the Valet daemon.
|
||||
|
||||
valet park // Register your current working directory as a path which Valet should search for sites.
|
||||
valet forget // Run this command from a "parked" directory to remove it from the parked directory list.
|
||||
valet paths // View all of your "parked" paths.
|
||||
|
||||
valet link <name> // Link a single site in the current directory and not the entire directory.
|
||||
valet unlink <name> // Unlink a single site in the current directory
|
||||
valet links // View all of your "linked" paths.
|
||||
|
||||
valet secure // Serve site into https
|
||||
valet unsecure // Revert back to http
|
||||
|
||||
valet log // View a list of logs which are written by Valet's services.
|
||||
valet trust // Add sudoers files for Brew and Valet to allow Valet commands to be run without prompting for passwords.
|
||||
valet tld <suffix> // Update tld for your domains (default to test).
|
||||
valet share // Share your site with the world.
|
||||
|
||||
12
databases/mysql.sh
Normal file
12
databases/mysql.sh
Normal file
@@ -0,0 +1,12 @@
|
||||
# *****************************************************************************
|
||||
# BASICS
|
||||
# *****************************************************************************
|
||||
|
||||
mysqldump -h hostname -u username -p database_name -P port > file.sql # Export database
|
||||
mysql -u username -p database_name < file.sql # Import database
|
||||
|
||||
SHOW PROCESSLIST; # Show you any queries that are currently running or in the queue to run
|
||||
|
||||
GRANT ALL PRIVILEGES ON prospectwith.* TO 'power'@'localhost' WITH GRANT OPTION; # Grant all privileges on database
|
||||
|
||||
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; # Create user
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
redis-server /path/redis.conf # start redis with the related configuration file
|
||||
redis-cli # opens a redis prompt
|
||||
|
||||
sudo systemctl restart redis.service # Restart Redis
|
||||
sudo systemctl status redis # Check Redis status
|
||||
|
||||
# *****************************************************************************
|
||||
# STRINGS
|
||||
@@ -41,8 +42,9 @@ TTL key # returns the number of seconds until a key is
|
||||
|
||||
|
||||
RPUSH key value [value ...] # put the new value at the end of the list
|
||||
RPUSHX key value # append a value to a list, only if the exists
|
||||
RPUSHX key value # append a value at the end of the list, only if it exists
|
||||
LPUSH key value [value ...] # put the new value at the start of the list
|
||||
LPUSHX key value # append a value at the start of the list, only if it exists
|
||||
LRANGE key start stop # give a subset of the list
|
||||
LINDEX key index # get an element from a list by its index
|
||||
LINSERT key BEFORE|AFTER pivot value # insert an element before or after another element in a list
|
||||
@@ -115,7 +117,7 @@ HINCRBY key field increment # increment value in hash by X
|
||||
HDEL key field [field ...] # delete one or more hash fields
|
||||
HEXISTS key field # determine if a hash field exists
|
||||
HKEYS key # get all the fields in a hash
|
||||
HLEN key # get all the fields in a hash
|
||||
HLEN key # get the number of fields in a hash
|
||||
HSTRLEN key field # get the length of the value of a hash field
|
||||
HVALS key # get all the values in a hash
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
|
||||
<h1></h1> ... <h6></h6> <!-- All six levels of heading with 1 being the most promiment and 6 being the least prominent -->
|
||||
<p></p> <!-- Used to organize paragraph text -->
|
||||
<div></div> <!-- A generic ontainerused to denote a page section -->
|
||||
<div></div> <!-- A generic container used to denote a page section -->
|
||||
<span></span> <!-- Inline section or block container used for creating inline style elements -->
|
||||
<br/> <!-- Creates a line-break -->
|
||||
<hr> <!-- Creates a sectional break into HTML -->
|
||||
@@ -39,12 +39,17 @@
|
||||
|
||||
<strong></strong> and <b></b> <!-- Makes text contained in the tag as bold -->
|
||||
<em></em> and <i></i> <!-- Alternative way to make the text contained in the tag as italic -->
|
||||
<strike></strike> <!-- creates a strike through the text element -->
|
||||
<strike></strike> <!-- Creates a strike through the text element -->
|
||||
<pre></pre> <!-- Preformatted monospace text block with some spacing intact -->
|
||||
<blockquote></blockquote> <!-- Contains long paragraphs of quotations often cited -->
|
||||
<abbr></abbr> <!-- Contains abbreviations while also making the full form avaialable -->
|
||||
<address></address> <!-- Used to display contact information -->
|
||||
<code></code> <!-- Used to display inline code snippets -->
|
||||
<q></q> <!-- Defines a short inline quotation -->
|
||||
<sub></sub> <!-- Defines subscripted text -->
|
||||
<sup></sup> <!-- Defines superscripted text -->
|
||||
<kbd></kbd> <!-- Specifies text as keyboard input -->
|
||||
<small></small> <!-- Specifies small text -->
|
||||
|
||||
|
||||
<!-- Links Formatting -->
|
||||
@@ -54,13 +59,13 @@
|
||||
<a href="mailto:email@example.com"></a> <!-- Used to link to an email address -->
|
||||
<a href="name"></a> <!-- Used to link to a document element -->
|
||||
<a href="#name"></a> <!-- Used to link to specific div element -->
|
||||
<a href="tel://####-####-##"></a> <!-- Used to display phone numbers and make them as clickable -->
|
||||
<a href="tel://####-####-##"></a> <!-- Used to display phone numbers and make them clickable -->
|
||||
|
||||
|
||||
<!-- Image Formatting -->
|
||||
|
||||
|
||||
<img src="url" alt="text"> <!-- Used to display images in a webpage wehre src="url" contains the link to the image source and alt="" contains an alternative text to display wehn the image is not displayed -->
|
||||
<img src="url" alt="text"> <!-- Used to display images in a webpage where src="url" contains the link to the image source and alt="" contains an alternative text to display when the image is not displayed -->
|
||||
|
||||
|
||||
<!-- List Formatting -->
|
||||
@@ -70,7 +75,7 @@
|
||||
<ul></ul> <!-- Used to display unordered lists with numbers in the items -->
|
||||
<li></li> <!-- Contains list items inside ordered and unordered lists -->
|
||||
<dl></dl> <!-- Contains list item definitions -->
|
||||
<dt></dt> <!-- definition of single term inline with body content -->
|
||||
<dt></dt> <!-- Definition of single term inline with body content -->
|
||||
<dd></dd> <!-- The descrpition of the defined term -->
|
||||
|
||||
|
||||
@@ -85,7 +90,7 @@ enctype="" <!-- Dictates how the data is
|
||||
autocomplete="" <!-- Specifies if the autocomplete functionality is enabled or not -->
|
||||
novalidate <!-- Dictates if the form will be validated or not -->
|
||||
accept-charset="" <!-- Identifies the character encoding upon form submission -->
|
||||
target="" <!-- Tell where to display the information upon form submission. POssible values: '_blank', '_self', '_parent', '_top' -->
|
||||
target="" <!-- Tell where to display the information upon form submission. Possible values: '_blank', '_self', '_parent', '_top' -->
|
||||
|
||||
<fieldset disabled="disabled"></fieldset> <!-- Identifies the group of all fields in the form -->
|
||||
<label for=""></label> <!-- A simple field label telling the user what to type in the field -->
|
||||
@@ -105,7 +110,7 @@ step="" <!-- Identifies the legal numb
|
||||
<textarea name="" id="" cols="30" rows="10"> <!-- Specifies a large input text field for longer messages -->
|
||||
</textarea>
|
||||
|
||||
<select name=""></select> <!-- Describes a dropdown box for users to select from variety of ochoices-->
|
||||
<select name=""></select> <!-- Describes a dropdown box for users to select from variety of choices -->
|
||||
|
||||
<!-- Supported attributes -->
|
||||
name="" <!-- The name for a dropdown combination box -->
|
||||
@@ -114,7 +119,7 @@ multiple <!-- Allows for multiple optio
|
||||
required <!-- Requires that a value is selected before submitting the form -->
|
||||
autofocus <!-- Specifies that the dropdown automatically comes to focus once the page loads -->
|
||||
<optgroup></optgroup> <!-- Specifies the entire grouping of available options -->
|
||||
<option value=""></option> <!-- Defines one of the avaialble option from the dorpdown list-->
|
||||
<option value=""></option> <!-- Defines one of the avaialble option from the dropdown list -->
|
||||
<button></button> <!-- A clickable button to submit the form -->
|
||||
|
||||
|
||||
@@ -136,7 +141,7 @@ autofocus <!-- Specifies that the dropd
|
||||
<!-- Objects and iFrames -->
|
||||
|
||||
|
||||
<object data=""></object> <!-- Describes and embed file type including audio, video, PDf's, images -->
|
||||
<object data=""></object> <!-- Describes and embed file type including audio, video, PDF's, images -->
|
||||
|
||||
<!-- Supported attributes -->
|
||||
type="" <!-- Describes the type of media embedded -->
|
||||
@@ -146,7 +151,7 @@ usemap="" <!-- This is the name of the c
|
||||
|
||||
<iframe src="" frameborder="0"></iframe> <!-- Contains an inline frame that allows to embed external information -->
|
||||
<embed src="" type=""> <!-- Acts as a container for external application or plug-in -->
|
||||
scr="" <!-- The source of the external file you're embedding -->
|
||||
src="" <!-- The source of the external file you're embedding -->
|
||||
width="" <!-- Describes the width of the iframe in pixels -->
|
||||
|
||||
|
||||
@@ -155,7 +160,7 @@ width="" <!-- Describes the width of th
|
||||
|
||||
<header></header> <!-- Defines the header block for a document or a section -->
|
||||
<footer></footer> <!-- Defines the footer block for a document or a section -->
|
||||
<main></main> <!-- Describes the main content of a document-->
|
||||
<main></main> <!-- Describes the main content of a document -->
|
||||
<article></article> <!-- Identifies an article inside a document -->
|
||||
<aside></aside> <!-- Specifies content contained in a document sidebar -->
|
||||
<section></section> <!-- Defines a section of a document -->
|
||||
@@ -165,7 +170,7 @@ width="" <!-- Describes the width of th
|
||||
<figcaption></figcaption> <!-- Caption that describe a figure -->
|
||||
<mark></mark> <!-- Displays a portion of highlighted text with in a page content -->
|
||||
<nav></nav> <!-- Navigation links for the user in a document -->
|
||||
<menuitem></menuitem> <!-- The specific menu item that a usrr can raise from a pop up menu -->
|
||||
<menuitem></menuitem> <!-- The specific menu item that a user can raise from a pop up menu -->
|
||||
<meter></meter> <!-- Describes the scalar measurement with in a known array -->
|
||||
<progress></progress> <!-- Displays the progress of a task usually a progress bar -->
|
||||
<rp></rp> <!-- Describes text within the browsers that do not support ruby notations -->
|
||||
@@ -176,8 +181,13 @@ width="" <!-- Describes the width of th
|
||||
<time></time> <!-- Identifies the time and date -->
|
||||
<wbr> <!-- A line break within the content -->
|
||||
|
||||
<!-- Some other useful tags -->
|
||||
|
||||
<!-- Collective CHaracter Obejcts -->
|
||||
<canvas></canvas> <!-- Allows to draw 2D shapes on the web page with the help of javascript -->
|
||||
<keygen> <!-- Represents a control for generating a public-private key pair -->
|
||||
<map></map> <!-- Specifies an image map -->
|
||||
|
||||
<!-- Collective Character Obejcts -->
|
||||
|
||||
|
||||
" " Quotation Marks - "
|
||||
|
||||
2278
frontend/tailwind.css
Normal file
2278
frontend/tailwind.css
Normal file
File diff suppressed because it is too large
Load Diff
@@ -45,7 +45,7 @@ break used to exit loop and used to exit switch
|
||||
case choice in a switch
|
||||
char basic declaration of a type character
|
||||
const prefix declaration meaning variable can not be changed
|
||||
continuego to bottom of loop in for, while and do loops
|
||||
continue go to bottom of loop in for, while and do loops
|
||||
default optional last case of a switch
|
||||
do executable statement, do-while loop
|
||||
double basic declaration double precision floating point
|
||||
|
||||
62
languages/XML.md
Normal file
62
languages/XML.md
Normal file
@@ -0,0 +1,62 @@
|
||||
> announcement: this doc is a quiz-, interview-oriented cheatsheet, which desigend for those who want to have an overview of XML, when preparing for interviews.
|
||||
|
||||
# What is XML
|
||||
XML stands for eXtensible Markup Language, XML was designed to store and transport data. XML is often used for distributing data over the Internet(especial in web development).
|
||||
|
||||
# Then how can XML store data
|
||||
XML uses a DTD to describe the data.
|
||||
|
||||
# The relation with HTML
|
||||
* XML: is used to store or transport data.
|
||||
So the XML is a **Complement** to HTML.
|
||||
* HTML: is used to format and display the same data.
|
||||
|
||||
|
||||
XML does not carry any information about how to be displayed. The same XML data can be used in many different presentation scenarios.
|
||||
Because of this, with XML, there is a full separation between data and presentation.
|
||||
|
||||
# What is XML Schema/DTD
|
||||
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements:
|
||||
|
||||
|
||||
# When Not to Use a XML DTD/Sschema
|
||||
XML does not require a DTD/Schema.
|
||||
|
||||
When you are experimenting with XML, or when you are working with small XML files, creating DTDs may be a waste of time.
|
||||
|
||||
If you develop applications, wait until the specification is stable before you add a document definition. Otherwise, your software might stop working because of validation errors.
|
||||
|
||||
|
||||
# XML Syntax
|
||||
The XML language has no predefined tags, but the syntax is rather logic and easy to learn. XML documents must contain one root element that is the parent of all other elements.
|
||||
|
||||
```
|
||||
<bookstore>
|
||||
<book category="children">
|
||||
<title>Harry Potter</title>
|
||||
<author>J K. Rowling</author>
|
||||
<year>2005</year>
|
||||
<price>29.99</price>
|
||||
</book>
|
||||
<book category="web">
|
||||
<title>Learning XML</title>
|
||||
<author>Erik T. Ray</author>
|
||||
<year>2003</year>
|
||||
<price>39.95</price>
|
||||
</book>
|
||||
</bookstore>
|
||||
```
|
||||
|
||||
1. XML Tags are Case Sensitive
|
||||
2. All XML Elements Must Have a Closeing Tag
|
||||
|
||||
```
|
||||
<p>This is a paragraph.</p>
|
||||
<br /> <!-- This is a self closing -->
|
||||
```
|
||||
3. XML Attribute Values Must Always be Quoted
|
||||
4. Pay attention to the name rules.
|
||||
|
||||
# Reference
|
||||
1. (W3School) [https://www.w3schools.com/xml/]
|
||||
2. [cheat sheet in German](https://www.i-d-e.de/wp-content/uploads/2015/02/ide-xml-kurzreferenz.pdf)
|
||||
@@ -1,9 +1,8 @@
|
||||
#!/bin/bash
|
||||
##############################################################################
|
||||
# SHORTCUTS
|
||||
# SHORTCUTS and HISTORY
|
||||
##############################################################################
|
||||
|
||||
|
||||
CTRL+A # move to beginning of line
|
||||
CTRL+B # moves backward one character
|
||||
CTRL+C # halts the current command
|
||||
@@ -11,6 +10,7 @@ CTRL+D # deletes one character backward or logs out of current session, similar
|
||||
CTRL+E # moves to end of line
|
||||
CTRL+F # moves forward one character
|
||||
CTRL+G # aborts the current editing command and ring the terminal bell
|
||||
CTRL+H # deletes one character under cursor (same as DELETE)
|
||||
CTRL+J # same as RETURN
|
||||
CTRL+K # deletes (kill) forward to end of line
|
||||
CTRL+L # clears screen and redisplay the line
|
||||
@@ -18,8 +18,9 @@ CTRL+M # same as RETURN
|
||||
CTRL+N # next line in command history
|
||||
CTRL+O # same as RETURN, then displays next line in history file
|
||||
CTRL+P # previous line in command history
|
||||
CTRL+Q # resumes suspended shell output
|
||||
CTRL+R # searches backward
|
||||
CTRL+S # searches forward
|
||||
CTRL+S # searches forward or suspends shell output
|
||||
CTRL+T # transposes two characters
|
||||
CTRL+U # kills backward from point to the beginning of line
|
||||
CTRL+V # makes the next character typed verbatim
|
||||
@@ -31,9 +32,29 @@ CTRL+Z # stops the current command, resume with fg in the foreground or bg in t
|
||||
ALT+B # moves backward one word
|
||||
ALT+D # deletes next word
|
||||
ALT+F # moves forward one word
|
||||
ALT+H # deletes one character backward
|
||||
ALT+T # transposes two words
|
||||
ALT+. # pastes last word from the last command. Pressing it repeatedly traverses through command history.
|
||||
ALT+U # capitalizes every character from the current cursor position to the end of the word
|
||||
ALT+L # uncapitalizes every character from the current cursor position to the end of the word
|
||||
ALT+C # capitalizes the letter under the cursor. The cursor then moves to the end of the word.
|
||||
ALT+R # reverts any changes to a command you’ve pulled from your history if you’ve edited it.
|
||||
ALT+? # list possible completions to what is typed
|
||||
ALT+^ # expand line to most recent match from history
|
||||
|
||||
DELETE # deletes one character backward
|
||||
CTRL+X then ( # start recording a keyboard macro
|
||||
CTRL+X then ) # finish recording keyboard macro
|
||||
CTRL+X then E # recall last recorded keyboard macro
|
||||
CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands
|
||||
|
||||
BACKSPACE # deletes one character backward
|
||||
DELETE # deletes one character under cursor
|
||||
|
||||
history # shows command line history
|
||||
!! # repeats the last command
|
||||
!<n> # refers to command line 'n'
|
||||
!<string> # refers to command starting with 'string'
|
||||
|
||||
exit # logs out of current session
|
||||
|
||||
|
||||
@@ -47,7 +68,7 @@ echo $SHELL # displays the shell you're using
|
||||
echo $BASH_VERSION # displays bash version
|
||||
|
||||
bash # if you want to use bash (type exit to go back to your previously opened shell)
|
||||
whereis bash # finds out where bash is on your system
|
||||
whereis bash # locates the binary, source and manual-page for a command
|
||||
which bash # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments)
|
||||
|
||||
clear # clears content on window (hide displayed lines)
|
||||
@@ -60,9 +81,13 @@ clear # clears content on window (hide displayed lines)
|
||||
|
||||
ls # lists your files in current directory, ls <dir> to print files in a specific directory
|
||||
ls -l # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified
|
||||
ls -a # lists all files, including hidden files (name beginning with '.')
|
||||
ls -a # lists all files in 'long format', including hidden files (name beginning with '.')
|
||||
ln -s <filename> <link> # creates symbolic link to file
|
||||
readlink <filename> # shows where a symbolic links points to
|
||||
tree # show directories and subdirectories in easilly readable file tree
|
||||
mc # terminal file explorer (alternative to ncdu)
|
||||
touch <filename> # creates or updates (edit) your file
|
||||
mktemp -t <filename> # make a temp file in /tmp/ which is deleted at next boot (-d to make directory)
|
||||
cat <filename> # prints file raw content (will not be interpreted)
|
||||
any_command > <filename> # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout)
|
||||
more <filename> # shows the first part of a file (move with space and type q to quit)
|
||||
@@ -72,8 +97,12 @@ vim <filename> # opens a file in VIM (VI iMproved) text editor, w
|
||||
mv <filename1> <dest> # moves a file to destination, behavior will change based on 'dest' type (dir: file is placed into dir; file: file will replace dest (tip: useful for renaming))
|
||||
cp <filename1> <dest> # copies a file
|
||||
rm <filename> # removes a file
|
||||
find . -name <name> <type> # searches for a file or a directory in the current directory and all its sub-directories by its name
|
||||
diff <filename1> <filename2> # compares files, and shows where they differ
|
||||
wc <filename> # tells you how many lines, words and characters there are in a file. Use -lwc (lines, word, character) to ouput only 1 of those informations
|
||||
sort <filename> # sorts the contents of a text file line by line in alphabetical order, use -n for numeric sort and -r for reversing order.
|
||||
sort -t -k <filename> # sorts the contents on specific sort key field starting from 1, using the field separator t.
|
||||
rev # reverse string characters (hello becomes olleh)
|
||||
chmod -options <filename> # lets you change the read, write, and execute permissions on your files (more infos: SUID, GUID)
|
||||
gzip <filename> # compresses files using gzip algorithm
|
||||
gunzip <filename> # uncompresses files compressed by gzip
|
||||
@@ -85,6 +114,8 @@ genscript # converts plain text files into postscript for pr
|
||||
dvips <filename> # prints .dvi files (i.e. files produced by LaTeX)
|
||||
grep <pattern> <filenames> # looks for the string in the files
|
||||
grep -r <pattern> <dir> # search recursively for pattern in directory
|
||||
head -n file_name | tail +n # Print nth line from file.
|
||||
head -y lines.txt | tail +x # want to display all the lines from x to y. This includes the xth and yth lines.
|
||||
|
||||
|
||||
##############################################################################
|
||||
@@ -93,10 +124,16 @@ grep -r <pattern> <dir> # search recursively for pattern in directory
|
||||
|
||||
|
||||
mkdir <dirname> # makes a new directory
|
||||
rmdir <dirname> # remove an empty directory
|
||||
rmdir -rf <dirname> # remove a non-empty directory
|
||||
mv <dir1> <dir2> # rename a directory from <dir1> to <dir2>
|
||||
cd # changes to home
|
||||
cd .. # changes to the parent directory
|
||||
cd <dirname> # changes directory
|
||||
cp -r <dir1> <dir2> # copy <dir1> into <dir2> including sub-directories
|
||||
pwd # tells you where you currently are
|
||||
|
||||
cd ~ # changes to home.
|
||||
cd - # changes to previous working directory
|
||||
|
||||
##############################################################################
|
||||
# SSH, SYSTEM INFO & NETWORK COMMANDS
|
||||
@@ -124,6 +161,7 @@ ps -u yourusername # lists your processes
|
||||
kill <PID> # kills the processes with the ID you gave
|
||||
killall <processname> # kill all processes with the name
|
||||
top # displays your currently active processes
|
||||
lsof # lists open files
|
||||
bg # lists stopped or background jobs ; resume a stopped job in the background
|
||||
fg # brings the most recent job in the foreground
|
||||
fg <job> # brings job to the foreground
|
||||
@@ -134,6 +172,8 @@ dig <domain> # gets DNS information for domain
|
||||
dig -x <host> # reverses lookup host
|
||||
wget <file> # downloads file
|
||||
|
||||
time <command> # report time consumed by command execution
|
||||
|
||||
|
||||
##############################################################################
|
||||
# VARIABLES
|
||||
@@ -146,6 +186,10 @@ echo $varname # checks a variable's value
|
||||
echo $$ # prints process ID of the current shell
|
||||
echo $! # prints process ID of the most recently invoked background job
|
||||
echo $? # displays the exit status of the last command
|
||||
read <varname> # reads a string from the input and assigns it to a variable
|
||||
read -p "prompt" <varname> # same as above but outputs a prompt to ask user for value
|
||||
column -t <filename> # display info in pretty columns (often used with pipe)
|
||||
let <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, %
|
||||
export VARNAME=value # defines an environment variable (will be available in subprocesses)
|
||||
|
||||
array[0]=valA # how to define an array
|
||||
@@ -158,14 +202,15 @@ ${array[i]} # displays array's value for this index. If no inde
|
||||
${#array[i]} # to find out the length of any element in the array
|
||||
${#array[@]} # to find out how many values there are in the array
|
||||
|
||||
declare -a # the variables are treaded as arrays
|
||||
declare -a # the variables are treated as arrays
|
||||
declare -f # uses function names only
|
||||
declare -F # displays function names without definitions
|
||||
declare -i # the variables are treaded as integers
|
||||
declare -i # the variables are treated as integers
|
||||
declare -r # makes the variables read-only
|
||||
declare -x # marks the variables for export via the environment
|
||||
|
||||
${varname:-word} # if varname exists and isn't null, return its value; otherwise return word
|
||||
${varname:word} # if varname exists and isn't null, return its value; otherwise return word
|
||||
${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value
|
||||
${varname:?message} # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script
|
||||
${varname:+word} # if varname exists and isn't null, return word; otherwise return null
|
||||
@@ -223,12 +268,14 @@ str1 == str2 # str1 matches str2
|
||||
str1 != str2 # str1 does not match str2
|
||||
str1 < str2 # str1 is less than str2 (alphabetically)
|
||||
str1 > str2 # str1 is greater than str2 (alphabetically)
|
||||
str1 \> str2 # str1 is sorted after str2
|
||||
str1 \< str2 # str1 is sorted before str2
|
||||
-n str1 # str1 is not null (has length greater than 0)
|
||||
-z str1 # str1 is null (has length 0)
|
||||
|
||||
# FILES
|
||||
|
||||
-a file # file exists
|
||||
-a file # file exists or its compilation is successful
|
||||
-d file # file exists and is a directory
|
||||
-e file # file exists; same -a
|
||||
-f file # file exists and is a regular file (i.e., not a directory or other special type of file)
|
||||
@@ -336,6 +383,8 @@ n<&m # file descriptor n is made to be a copy of the input file descriptor
|
||||
n>&- # closes the ouput from file descriptor n
|
||||
n<&- # closes the input from file descripor n
|
||||
|
||||
|tee <file># output command to both terminal and a file (-a to append to file)
|
||||
|
||||
|
||||
##############################################################################
|
||||
# PROCESS HANDLING
|
||||
@@ -359,6 +408,9 @@ fg %?string # brings job whose command contains string
|
||||
|
||||
kill -l # returns a list of all signals on the system, by name and number
|
||||
kill PID # terminates process with specified PID
|
||||
kill -s SIGKILL 4500 # sends a signal to force or terminate the process
|
||||
kill -15 913 # Ending PID 913 process with signal 15 (TERM)
|
||||
kill %1 # Where %1 is the number of job as read from 'jobs' command.
|
||||
|
||||
ps # prints a line of information about the current running login shell and any processes running under it
|
||||
ps -a # selects all processes with a tty except session leaders
|
||||
@@ -370,6 +422,10 @@ trap - sig1 sig2 # resets the action taken when the signal is received to the
|
||||
disown <PID|JID> # removes the process from the list of jobs
|
||||
|
||||
wait # waits until all background jobs have finished
|
||||
sleep <number> # wait # of seconds before continuing
|
||||
|
||||
pv # display progress bar for data handling commands. often used with pipe like |pv
|
||||
yes # give yes response everytime an input is requested from script/process
|
||||
|
||||
|
||||
##############################################################################
|
||||
@@ -426,3 +482,67 @@ function returntrap {
|
||||
}
|
||||
|
||||
trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing
|
||||
|
||||
##############################################################################
|
||||
# COLORS AND BACKGROUNDS
|
||||
##############################################################################
|
||||
# note: \e or \x1B also work instead of \033
|
||||
# Reset
|
||||
Color_Off='\033[0m' # Text Reset
|
||||
|
||||
# Regular Colors
|
||||
Black='\033[0;30m' # Black
|
||||
Red='\033[0;31m' # Red
|
||||
Green='\033[0;32m' # Green
|
||||
Yellow='\033[0;33m' # Yellow
|
||||
Blue='\033[0;34m' # Blue
|
||||
Purple='\033[0;35m' # Purple
|
||||
Cyan='\033[0;36m' # Cyan
|
||||
White='\033[0;97m' # White
|
||||
|
||||
# Additional colors
|
||||
LGrey='\033[0;37m' # Ligth Gray
|
||||
DGrey='\033[0;90m' # Dark Gray
|
||||
LRed='\033[0;91m' # Ligth Red
|
||||
LGreen='\033[0;92m' # Ligth Green
|
||||
LYellow='\033[0;93m'# Ligth Yellow
|
||||
LBlue='\033[0;94m' # Ligth Blue
|
||||
LPurple='\033[0;95m'# Light Purple
|
||||
LCyan='\033[0;96m' # Ligth Cyan
|
||||
|
||||
|
||||
# Bold
|
||||
BBlack='\033[1;30m' # Black
|
||||
BRed='\033[1;31m' # Red
|
||||
BGreen='\033[1;32m' # Green
|
||||
BYellow='\033[1;33m'# Yellow
|
||||
BBlue='\033[1;34m' # Blue
|
||||
BPurple='\033[1;35m'# Purple
|
||||
BCyan='\033[1;36m' # Cyan
|
||||
BWhite='\033[1;37m' # White
|
||||
|
||||
# Underline
|
||||
UBlack='\033[4;30m' # Black
|
||||
URed='\033[4;31m' # Red
|
||||
UGreen='\033[4;32m' # Green
|
||||
UYellow='\033[4;33m'# Yellow
|
||||
UBlue='\033[4;34m' # Blue
|
||||
UPurple='\033[4;35m'# Purple
|
||||
UCyan='\033[4;36m' # Cyan
|
||||
UWhite='\033[4;37m' # White
|
||||
|
||||
# Background
|
||||
On_Black='\033[40m' # Black
|
||||
On_Red='\033[41m' # Red
|
||||
On_Green='\033[42m' # Green
|
||||
On_Yellow='\033[43m'# Yellow
|
||||
On_Blue='\033[44m' # Blue
|
||||
On_Purple='\033[45m'# Purple
|
||||
On_Cyan='\033[46m' # Cyan
|
||||
On_White='\033[47m' # White
|
||||
|
||||
# Example of usage
|
||||
echo -e "${Green}This is GREEN text${Color_Off} and normal text"
|
||||
echo -e "${Red}${On_White}This is Red test on White background${Color_Off}"
|
||||
# option -e is mandatory, it enable interpretation of backslash escapes
|
||||
printf "${Red} This is red \n"
|
||||
|
||||
820
languages/golang.md
Normal file
820
languages/golang.md
Normal file
@@ -0,0 +1,820 @@
|
||||
# Golang
|
||||
|
||||
## Summary
|
||||
|
||||
- Introduction
|
||||
- [Hello World](#hello-world)
|
||||
- [Go CLI Commands](#go-cli-commands)
|
||||
- [Go Modules](#go-modules)
|
||||
- Basic
|
||||
- [Basic Types](#basic-types)
|
||||
- [Variables](#variables)
|
||||
- [Operators](#operators)
|
||||
- [Conditional Statements](#conditional-statements)
|
||||
- [Loops](#loops)
|
||||
- [Arrays](#arrays)
|
||||
- [Functions](#functions)
|
||||
- Advanced
|
||||
- [Structs](#structs)
|
||||
- [Maps](#maps)
|
||||
- [Pointers](#pointers)
|
||||
- [Methods and Interfaces](#methods-and-interfaces)
|
||||
- [Errors](#errors)
|
||||
- [Testing](#testing)
|
||||
- [Concurrency](#concurrency)
|
||||
- Standard Libs
|
||||
- [Package fmt](#package-fmt)
|
||||
|
||||
## Hello World
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello Gophers!")
|
||||
}
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Go CLI Commands
|
||||
|
||||
```bash
|
||||
# Compile & Run code
|
||||
$ go run [file.go]
|
||||
|
||||
# Compile
|
||||
$ go build [file.go]
|
||||
# Running compiled file
|
||||
$ ./hello
|
||||
|
||||
# Test packages
|
||||
$ go test [folder]
|
||||
|
||||
# Install packages/modules
|
||||
$ go install [package]
|
||||
|
||||
# List installed packages/modules
|
||||
$ go list
|
||||
|
||||
# Update packages/modules
|
||||
$ go fix
|
||||
|
||||
# Format package sources
|
||||
$ go fmt
|
||||
|
||||
# See package documentation
|
||||
$ go doc [package]
|
||||
|
||||
# Add dependencies and install
|
||||
$ go get [module]
|
||||
|
||||
# See Go environment variables
|
||||
$ go env
|
||||
|
||||
# See version
|
||||
$ go version
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Go Modules
|
||||
|
||||
- Go projects are called **modules**
|
||||
- Each module has multiple **packages**
|
||||
- Each package should has a scoped functionality. Packages talk to each other to compose the code
|
||||
- A module needs at least one package, the **main**
|
||||
- The package main needs a entry function called **main**
|
||||
|
||||
```bash
|
||||
# Create Module
|
||||
$ go mod init [name]
|
||||
```
|
||||
|
||||
Tip: By convention, modules names has the follow structure:
|
||||
|
||||
domain.com/user/module/package
|
||||
|
||||
Example: github.com/spf13/cobra
|
||||
|
||||
<hr/>
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
## Basic Types
|
||||
|
||||
| Type | Set of Values | Values |
|
||||
| :--------: | :----------------------------------------: | :-------------------------------------------: |
|
||||
| bool | boolean | true/false |
|
||||
| string | array of characters | needs to be inside "" |
|
||||
| int | integers | 32 or 64 bit integer |
|
||||
| int8 | 8-bit integers | [ -128, 128 ] |
|
||||
| int16 | 16-bit integers | [ -32768, 32767] |
|
||||
| int32 | 32-bit integers | [ -2147483648, 2147483647] |
|
||||
| int64 | 64-bit integers | [ -9223372036854775808, 9223372036854775807 ] |
|
||||
| uint8 | 8-bit unsigned integers | [ 0, 255 ] |
|
||||
| uint16 | 16-bit unsigned integers | [ 0, 65535 ] |
|
||||
| uint32 | 32-bit unsigned integers | [ 0, 4294967295 ] |
|
||||
| uint64 | 64-bit unsigned integers | [ 0, 18446744073709551615 ] |
|
||||
| float32 | 32-bit float | |
|
||||
| float64 | 64-bit float | |
|
||||
| complex64 | 32-bit float with real and imaginary parts | |
|
||||
| complex128 | 64-bit float with real and imaginary parts | |
|
||||
| byte | sets of bits | alias for uint8 |
|
||||
| rune | Unicode characters | alias for int32 |
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Variables
|
||||
|
||||
```go
|
||||
// Declaration
|
||||
var value int
|
||||
|
||||
// Initialization
|
||||
value = 10
|
||||
|
||||
// Declaration + Initialization + Type inference
|
||||
var isActive = true
|
||||
|
||||
// Short declaration (only inside functions)
|
||||
text := "Hello"
|
||||
|
||||
// Multi declaration
|
||||
var i, j, k = 1, 2, 3
|
||||
|
||||
// Variable not initialized = Zero values
|
||||
// Numeric: 0
|
||||
// Boolean: false
|
||||
// String: ""
|
||||
// Special value: nil (same as null)
|
||||
|
||||
var number int // 0
|
||||
var text string // ""
|
||||
var boolean bool // false
|
||||
|
||||
// Type conversions
|
||||
// T(v) converts v to type T
|
||||
|
||||
i := 1.234 // float
|
||||
int(i) // 1
|
||||
|
||||
// Constants
|
||||
const pi = 3.1415
|
||||
```
|
||||
|
||||
<hr/>
|
||||
|
||||
## Operators
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
Arithmetic Operators
|
||||
| Symbol | Operation | Valid Types |
|
||||
|:---------:|:-------------:|:-------------:|
|
||||
| `+` | Sum | integers, floats, complex values, strings |
|
||||
| `-` | Difference | integers, floats, complex values |
|
||||
| `*` | Product | integers, floats, complex values |
|
||||
| `/` | Quotient | integers, floats, complex values |
|
||||
| `%` | Remainder | integers |
|
||||
| `&` | Bitwise AND | integers |
|
||||
| `|` | Bitwise OR | integers |
|
||||
| `^` | Bitwise XOR | integers |
|
||||
| `&^` | Bit clear (AND NOT) | integers |
|
||||
| `<<` | Left shift | integer << unsigned integer |
|
||||
| `>>` | Right shift | integer >> unsigned integer |
|
||||
|
||||
Comparison Operators
|
||||
| Symbol | Operation |
|
||||
|:---------:|:-------------:|
|
||||
| `==` | Equal |
|
||||
| `!=` | Not equal |
|
||||
| `<` | Less |
|
||||
| `<=` | Less or equal |
|
||||
| `>` | Greater |
|
||||
| `>=` | Greater or equal |
|
||||
|
||||
Logical Operators
|
||||
| Symbol | Operation |
|
||||
|:---------:|:-------------:|
|
||||
| `&&` | Conditional AND |
|
||||
| `||` | Conditional OR |
|
||||
| `!` | NOT |
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Conditional Statements
|
||||
|
||||
```go
|
||||
// If / Else
|
||||
i := 1
|
||||
|
||||
if i > 0 {
|
||||
// Condition is True! i is greater than zero
|
||||
} else {
|
||||
// Condition is False! i is lower or equal to zero
|
||||
}
|
||||
|
||||
// Else if
|
||||
i := 1
|
||||
|
||||
if i > 0 {
|
||||
// Condition is True! i is greater than zero
|
||||
} else if i > 0 && i < 2 {
|
||||
// Condition is True! i greater than zero and lower than two
|
||||
} else if i > 1 && i < 4 {
|
||||
// Condition is True! i greater than one and lower than four
|
||||
} else {
|
||||
// None of the above conditions is True, so it falls here
|
||||
}
|
||||
|
||||
// If with short statements
|
||||
i := 2.567
|
||||
|
||||
if j := int(i); j == 2 {
|
||||
// Condition is True! j, the integer value of i, is equal to two
|
||||
} else {
|
||||
// Condition is False! j, the integer value of i, is not equal to two
|
||||
}
|
||||
|
||||
// Switch
|
||||
text := 'hey'
|
||||
|
||||
switch text {
|
||||
case 'hey':
|
||||
// 'Hello!'
|
||||
case 'bye':
|
||||
// 'Byee'
|
||||
default:
|
||||
// 'Ok'
|
||||
}
|
||||
|
||||
// Switch without condition
|
||||
value := 5
|
||||
|
||||
switch {
|
||||
case value < 2:
|
||||
// 'Hello!'
|
||||
case value >= 2 && value < 6:
|
||||
// 'Byee'
|
||||
default:
|
||||
// 'Ok'
|
||||
}
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Loops
|
||||
|
||||
```go
|
||||
// Golang only has the for loop
|
||||
for i := 0; i < 10; i++ {
|
||||
// i
|
||||
}
|
||||
|
||||
// The first and third parameters are ommitable
|
||||
// For as a while
|
||||
i := 0;
|
||||
|
||||
for i < 10 {
|
||||
i++
|
||||
}
|
||||
|
||||
// Forever loop
|
||||
for {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Arrays
|
||||
|
||||
```go
|
||||
// Declaration with specified size
|
||||
var array [3]string
|
||||
array[0] = "Hello"
|
||||
array[1] = "Golang"
|
||||
array[2] = "World"
|
||||
|
||||
// Declaration and Initialization
|
||||
values := [5]int{1, 2, 3, 4, 5}
|
||||
|
||||
// Slices: A subarray that acts as a reference of an array
|
||||
// Determining min and max
|
||||
values[1:3] // {2, 3, 4}
|
||||
|
||||
// Determining only max will use min = 0
|
||||
values[:2] // {1, 2, 3}
|
||||
|
||||
// Determining only min will use max = last element
|
||||
values[3:] // {3, 4}
|
||||
|
||||
// Length: number of elements that a slice contains
|
||||
len(values) // 5
|
||||
|
||||
// Capacity: number of elements that a slice can contain
|
||||
values = values[:1]
|
||||
len(values) // 2
|
||||
cap(values) // 5
|
||||
|
||||
// Slice literal
|
||||
slice := []bool{true, true, false}
|
||||
|
||||
// make function: create a slice with length and capacity
|
||||
slice := make([]int, 5, 6) // make(type, len, cap)
|
||||
|
||||
// Append new element to slice
|
||||
slice := []int{ 1, 2 }
|
||||
slice = append(slice, 3)
|
||||
slice // { 1, 2, 3 }
|
||||
slice = append(slice, 3, 2, 1)
|
||||
slice // { 1, 2, 3, 3, 2, 1 }
|
||||
|
||||
// For range: iterate over a slice
|
||||
slice := string["W", "o", "w"]
|
||||
|
||||
for i, value := range slice {
|
||||
i // 0, then 1, then 2
|
||||
value // "W", then "o", then "w"
|
||||
}
|
||||
|
||||
// Skip index or value
|
||||
|
||||
for i := range slice {
|
||||
i // 0, then 1, then 2
|
||||
}
|
||||
|
||||
for _, value := range slice {
|
||||
value // "W", then "o", then "w"
|
||||
}
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Functions
|
||||
|
||||
```go
|
||||
// Functions acts as a scoped block of code
|
||||
func sayHello() {
|
||||
// Hello World!
|
||||
}
|
||||
sayHello() // Hello World!
|
||||
|
||||
// Functions can take zero or more parameters, as so return zero or more parameters
|
||||
func sum(x int, y int) int {
|
||||
return x + y
|
||||
}
|
||||
sum(3, 7) // 10
|
||||
|
||||
// Returned values can be named and be used inside the function
|
||||
func doubleAndTriple(x int) (double, triple int) {
|
||||
double = x * 2
|
||||
triple = x * 3
|
||||
return
|
||||
}
|
||||
d, t := doubleAndTriple(5)
|
||||
// d = 10
|
||||
// t = 15
|
||||
|
||||
// Skipping one of the returned values
|
||||
_, t := doubleAndTriple(3)
|
||||
// t = 9
|
||||
|
||||
// Functions can defer commands. Defered commands are
|
||||
// runned in a stack order after the execution and
|
||||
// returning of a function
|
||||
var aux = 0
|
||||
|
||||
func switchValuesAndDouble(x, y int) {
|
||||
aux = x
|
||||
defer aux = 0 // cleaning variable to post use
|
||||
x = y * 2
|
||||
y = aux * 2
|
||||
}
|
||||
|
||||
a, b = 2, 5
|
||||
switchValuesAndDouble(2, 5)
|
||||
|
||||
// a = 10
|
||||
// b = 4
|
||||
// aux = 0
|
||||
|
||||
// Functions can be handled as values and be anonymous functions
|
||||
func calc(fn func(int, int) int) int {
|
||||
return fn(2, 6)
|
||||
}
|
||||
|
||||
func sum(x, y int) int {
|
||||
return x + y
|
||||
}
|
||||
|
||||
func mult(x, y int) int {
|
||||
return x * y
|
||||
}
|
||||
|
||||
calc(sum) // 8
|
||||
calc(mult) // 12
|
||||
calc(
|
||||
func(x, y int) int {
|
||||
return x / y
|
||||
}
|
||||
) // 3
|
||||
|
||||
// Function closures: a function that returns a function
|
||||
// that remembers the original context
|
||||
func calc() func(int) int {
|
||||
value := 0
|
||||
return func(x int) int {
|
||||
value += x
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
calculator := calc()
|
||||
calculator(3) // 3
|
||||
calculator(45) // 48
|
||||
calculator(12) // 60
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Structs
|
||||
|
||||
Structs are a way to arrange data in specific formats.
|
||||
|
||||
```go
|
||||
// Declaring a struct
|
||||
type Person struct {
|
||||
Name string
|
||||
Age int
|
||||
}
|
||||
|
||||
// Initializing
|
||||
person := Person{"John", 34}
|
||||
person.Name // "John"
|
||||
person.Age // 34
|
||||
|
||||
person2 := Person{Age: 20}
|
||||
person2.Name // ""
|
||||
person2.Age // 20
|
||||
|
||||
person3 := Person{}
|
||||
person3.Name // ""
|
||||
person3.Age // 0
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Maps
|
||||
|
||||
Maps are data structures that holds values assigneds to a key.
|
||||
|
||||
```go
|
||||
// Declaring a map
|
||||
var cities map[string]string
|
||||
|
||||
// Initializing
|
||||
cities = make(map[string]string)
|
||||
cities // nil
|
||||
|
||||
// Insert
|
||||
cities["NY"] = "EUA"
|
||||
|
||||
// Retrieve
|
||||
newYork = cities["NY"]
|
||||
newYork // "EUA"
|
||||
|
||||
// Delete
|
||||
delete(cities, "NY")
|
||||
|
||||
// Check if a key is setted
|
||||
value, ok := cities["NY"]
|
||||
ok // false
|
||||
value // ""
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Pointers
|
||||
|
||||
Pointers are a direct reference to a memory address that some variable or value is being stored.
|
||||
|
||||
```go
|
||||
// Pointers has *T type
|
||||
var value int
|
||||
var pointer *int
|
||||
|
||||
// Point to a variable memory address with &
|
||||
value = 3
|
||||
pointer = &value
|
||||
|
||||
pointer // 3
|
||||
pointer = 20
|
||||
pointer // 20
|
||||
pointer += 5
|
||||
pointer // 25
|
||||
|
||||
// Pointers to structs can access the attributes
|
||||
type Struct struct {
|
||||
X int
|
||||
}
|
||||
|
||||
s := Struct{3}
|
||||
pointer := &s
|
||||
|
||||
s.X // 3
|
||||
```
|
||||
|
||||
Obs: Unlike C, Go doesn't have pointer arithmetics.
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Methods and Interfaces
|
||||
|
||||
Go doesn't have classes. But you can implement methods, interfaces and almost everything contained in OOP, but in what gophers call "Go Way"
|
||||
|
||||
```go
|
||||
type Dog struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
func (dog *Dog) bark() string {
|
||||
return dog.Name + " is barking!"
|
||||
}
|
||||
|
||||
dog := Dog{"Rex"}
|
||||
dog.bark() // Rex is barking!
|
||||
```
|
||||
|
||||
Interfaces are implicitly implemented. You don't need to inform that your struct are correctly implementing a interface if it already has all methods with the same name of the interface.
|
||||
All structs implement the `interface{}` interface. This empty interface means the same as `any`.
|
||||
|
||||
```go
|
||||
// Car implements Vehicle interface
|
||||
type Vehicle interface {
|
||||
Accelerate()
|
||||
}
|
||||
|
||||
type Car struct {
|
||||
|
||||
}
|
||||
|
||||
func (car *Car) Accelerate() {
|
||||
return "Car is moving on ground"
|
||||
}
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Errors
|
||||
|
||||
Go doesn't support `throw`, `try`, `catch` and other common error handling structures. Here, we use `error` package to build possible errors as a returning parameter in functions
|
||||
|
||||
```go
|
||||
import "errors"
|
||||
|
||||
// Function that contain a logic that can cause a possible exception flow
|
||||
func firstLetter(text string) (string, error) {
|
||||
if len(text) < 1 {
|
||||
return nil, errors.New("Parameter text is empty")
|
||||
}
|
||||
return string(text[0]), nil
|
||||
}
|
||||
|
||||
a, errorA := firstLetter("Wow")
|
||||
a // "W"
|
||||
errorA // nil
|
||||
|
||||
b, errorB := firstLetter("")
|
||||
b // nil
|
||||
errorB // Error("Parameter text is empty")
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Testing
|
||||
|
||||
Go has a built-in library to unit testing. In a separate file you insert tests for functionalities of a file and run `go test package` to run all tests of the actual package or `go test path` to run a specific test file.
|
||||
|
||||
```go
|
||||
// main.go
|
||||
func Sum(x, y int) int {
|
||||
return x + y
|
||||
}
|
||||
|
||||
// main_test.go
|
||||
import (
|
||||
"testing"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func TestSum(t *testing.T) {
|
||||
x, y := 2, 4
|
||||
expected := 2 + 4
|
||||
|
||||
if !reflect.DeepEqual(sum(x, y), expected) {
|
||||
t.Fatalf("Function Sum not working as expected")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Concurrency
|
||||
|
||||
One of the main parts that make Go attractive is its form to handle with concurrency. Different than parallelism, where tasks can be separated in many cores that the machine processor have, in concurrency we have routines that are more lightweight than threads and can run asynchronously, with memory sharing and in a single core.
|
||||
|
||||
```go
|
||||
// Consider a common function, but that function can delay itself because some processing
|
||||
func show(from string) {
|
||||
for i := 0; i < 3; i++ {
|
||||
fmt.Printf("%s : %d\n", from, i)
|
||||
}
|
||||
}
|
||||
|
||||
// In a blocking way...
|
||||
func main() {
|
||||
show("blocking1")
|
||||
show("blocking2")
|
||||
|
||||
fmt.Println("done")
|
||||
}
|
||||
/* blocking1: 0
|
||||
blocking1: 1
|
||||
blocking1: 2
|
||||
blocking2: 0
|
||||
blocking2: 1
|
||||
blocking2: 2
|
||||
done
|
||||
*/
|
||||
|
||||
// Go routines are a function (either declared previously or anonymous) called with the keyword go
|
||||
func main() {
|
||||
go show("routine1")
|
||||
go show("routine2")
|
||||
|
||||
go func() {
|
||||
fmt.Println("going")
|
||||
}()
|
||||
|
||||
time.Sleep(time.Second)
|
||||
|
||||
fmt.Println("done")
|
||||
}
|
||||
|
||||
/* Obs: The result will depends of what processes first
|
||||
routine2: 0
|
||||
routine2: 1
|
||||
routine2: 2
|
||||
going
|
||||
routine1: 0
|
||||
routine1: 1
|
||||
routine1: 2
|
||||
done
|
||||
*/
|
||||
|
||||
// Routines can share data with channels
|
||||
// Channels are queues that store data between multiple routines
|
||||
msgs := make(chan string)
|
||||
|
||||
go func(channel chan string) {
|
||||
channel <- "ping"
|
||||
}(msgs)
|
||||
|
||||
go func(channel chan string) {
|
||||
channel <- "pong"
|
||||
}(msgs)
|
||||
|
||||
fmt.Println(<-msgs) // pong
|
||||
fmt.Println(<-msgs) // ping
|
||||
|
||||
// Channels can be bufferized. Buffered channels will accept a limited number of values and when someone try to put belong their limit, it will throw and error
|
||||
numbers := make(chan int, 2)
|
||||
|
||||
msgs<-0
|
||||
msgs<-1
|
||||
msgs<-2
|
||||
|
||||
// fatal error: all goroutines are asleep - deadlock!
|
||||
|
||||
// Channels can be passed as parameter where the routine can only send or receive
|
||||
numbers := make(chan int)
|
||||
|
||||
go func(sender chan<- int) {
|
||||
sender <- 10
|
||||
}(numbers)
|
||||
|
||||
go func(receiver <-chan int) {
|
||||
fmt.Println(<-receiver) // 10
|
||||
}(numbers)
|
||||
|
||||
time.Sleep(time.Second)
|
||||
|
||||
// When working with multiple channels, the select can provide a control to execute code accordingly of what channel has bring a message
|
||||
c1 := make(chan string)
|
||||
c2 := make(chan string)
|
||||
|
||||
select {
|
||||
case msg1 := <-c1:
|
||||
fmt.Println("received", msg1)
|
||||
case msg2 := <-c2:
|
||||
fmt.Println("received", msg2)
|
||||
default:
|
||||
fmt.Println("no messages")
|
||||
}
|
||||
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
c1 <- "channel1 : one"
|
||||
}()
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
c2 <- "channel2 : one"
|
||||
}()
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
select {
|
||||
case msg1 := <-c1:
|
||||
fmt.Println("received", msg1)
|
||||
case msg2 := <-c2:
|
||||
fmt.Println("received", msg2)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
no messages
|
||||
received channel1: one
|
||||
received channel2: one
|
||||
*/
|
||||
|
||||
// Channels can be closed and iterated
|
||||
channel := make(chan int, 5)
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
channel <- i
|
||||
}
|
||||
|
||||
close(channel)
|
||||
|
||||
for value := range channel {
|
||||
fmt.Println(value)
|
||||
}
|
||||
|
||||
/*
|
||||
0
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
*/
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
|
||||
## Package `fmt`
|
||||
|
||||
```go
|
||||
import "fmt"
|
||||
|
||||
fmt.Print("Hello World") // Print in console
|
||||
fmt.Println("Hello World") // Print and add a new line in end
|
||||
fmt.Printf("%s is %d years old", "John", 32) // Print with formatting
|
||||
fmt.Errorf("User %d not found", 123) // Print a formatted error
|
||||
```
|
||||
|
||||
[Return to Summary](#summary)
|
||||
|
||||
<hr/>
|
||||
619
languages/java.md
Normal file
619
languages/java.md
Normal file
@@ -0,0 +1,619 @@
|
||||
### HELLO WORLD :ghost:
|
||||
|
||||
```java
|
||||
//Text file name HelloWorld.java
|
||||
public class HelloWorld {
|
||||
// main() is the method
|
||||
public static void main (String[] args)
|
||||
//Prints "Hello World" in the terminal window.
|
||||
System.out.println("Hello World");
|
||||
}
|
||||
```
|
||||
|
||||
### COMPILATION & EXECUTING JAVA CODE
|
||||
|
||||
* Goto your program directory in terminal (Assumed JAVA Path is set)
|
||||
* After for compile your code
|
||||
|
||||
> **javac HelloWorld.java (your program file name)**
|
||||
|
||||
* For run program
|
||||
|
||||
> **java HelloWorld (main class name)**
|
||||
|
||||
|
||||
### DATA TYPES
|
||||
|
||||
| Type | Set of values | Values | Operators |
|
||||
|:-------:|:-----------------------:|:----------------------------:|:---------:|
|
||||
| int | integers | between -2^31 and + (2^31)-1 | + - * / % |
|
||||
| double | floating-point numbers | real numbers | + - * / |
|
||||
| boolean | boolean values | true or false | && \|\| ! |
|
||||
| char | characters | | |
|
||||
| String | sequences of characters | | |
|
||||
|
||||
|
||||
### DECLARATION AND ASSIGNMENT STATEMENTS
|
||||
|
||||
```java
|
||||
//Declaration statement
|
||||
int a,b;
|
||||
|
||||
//Assignment statement
|
||||
a = 13212; //a is the variable name; 13212 is the literal which is assign to the variable a
|
||||
|
||||
//Initialization statement
|
||||
int c = a + b;
|
||||
```
|
||||
|
||||
### COMPARISON OPERATORS
|
||||
|
||||
| Operation | Meaning |
|
||||
|:---------:|:---------------------:|
|
||||
| == | equal |
|
||||
| != | not equal |
|
||||
| < | less than |
|
||||
| > | greater than |
|
||||
| <= | less than or equal |
|
||||
| >= | greater than or equal |
|
||||
|
||||
|
||||
### PRINTING
|
||||
```java
|
||||
String s = "Happy Coding Folks!!"
|
||||
void System.out.print(String s) //print s
|
||||
void System.out.println(String s) //print s, followed by a newline
|
||||
void System.out.println() //print a newline
|
||||
```
|
||||
|
||||
### PARSING COMMAND-LINE ARGUMENTS
|
||||
```java
|
||||
String s = "Java is the best!!"
|
||||
int Integer.parseInt(String s) //convert s to an int value
|
||||
double Double.parseDouble(String) //convert s to a double value
|
||||
long Long.parseLong(String s) // convert s to a long value
|
||||
````
|
||||
|
||||
### MATH LIBRARY
|
||||
```java
|
||||
Public Class Math{
|
||||
double abs(double a) // absolute value of a
|
||||
double max(double a, double b) //maximum of a and b
|
||||
double min(double a, dobule a) //minimum of a and b
|
||||
double sin(double theta) //sine of theta
|
||||
double cos(double theta) //cosine of theta
|
||||
double tan(double theta) //tangent of theta
|
||||
double toRadians(double degrees) // convert angle from degrees to radians
|
||||
double toDegrees(double radians) // convert angle from radians to degrees
|
||||
double exp(doube a) // exponential (e^a)
|
||||
double pow(double a, double p) //raise a to the bth power (a^b)
|
||||
double random() //random in [0,1)
|
||||
double sqrt(double a) //square root of a
|
||||
}
|
||||
```
|
||||
|
||||
### EXAMPLES OF TYPE CONVERSION
|
||||
|
||||
| Expression | Expression type | Expression value |
|
||||
|:---------------------:|:---------------:|:----------------:|
|
||||
| (1 + 2 + 3 + 4) / 4.0 | double | 2.5 |
|
||||
| Math.sqrt(4) | double | 2.0 |
|
||||
| "123343" + 99 | String | "12334399" |
|
||||
| 11 * 0.25 | double | 2.75 |
|
||||
| (int) 11 * 0.25 | double | 2.75 |
|
||||
| 11 * (int) 0.25 | int | 0 |
|
||||
| (int) (11 * 0.25) | int | 2 |
|
||||
|
||||
### CONDITIONAL & LOOP STATEMENT
|
||||
#### ANATOMY OF CONDITIONAL STATEMENT
|
||||
> IF Statement
|
||||
```java
|
||||
if (x>y) { // x > y is the boolean expression
|
||||
//Sequence of statements
|
||||
x = y;
|
||||
}
|
||||
```
|
||||
|
||||
> IF-ELSE STATEMENT
|
||||
```java
|
||||
if (BOOLEAN EXPRESSION) {
|
||||
//Sequence of statements
|
||||
} else {
|
||||
//Sequence of statements
|
||||
}
|
||||
```
|
||||
|
||||
> NESTED IF STATEMENT
|
||||
```java
|
||||
if (BOOLEAN EXPRESSION) {
|
||||
//Sequence of statements
|
||||
} else if {
|
||||
//Sequence of statements
|
||||
}
|
||||
.
|
||||
.
|
||||
.
|
||||
else {
|
||||
//Sequence of statements
|
||||
}
|
||||
```
|
||||
|
||||
>SWITCH STATEMENT
|
||||
```java
|
||||
switch (VARIABLE TO EVALUATE ITS VALUE) {
|
||||
case value: Statement; break;
|
||||
...
|
||||
...
|
||||
...
|
||||
default: Statement; break;
|
||||
}
|
||||
```
|
||||
**Example:**
|
||||
```java
|
||||
int month = 8;
|
||||
String monthString;
|
||||
switch (month) {
|
||||
case 1: monthString = "January";
|
||||
break;
|
||||
case 2: monthString = "February";
|
||||
break;
|
||||
case 3: monthString = "March";
|
||||
break;
|
||||
case 4: monthString = "April";
|
||||
break;
|
||||
case 5: monthString = "May";
|
||||
break;
|
||||
case 6: monthString = "June";
|
||||
break;
|
||||
case 7: monthString = "July";
|
||||
break;
|
||||
case 8: monthString = "August";
|
||||
break;
|
||||
case 9: monthString = "September";
|
||||
break;
|
||||
case 10: monthString = "October";
|
||||
break;
|
||||
case 11: monthString = "November";
|
||||
break;
|
||||
case 12: monthString = "December";
|
||||
break;
|
||||
default: monthString = "Invalid month";
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
#### ANATOMY OF A LOOP STATEMENT
|
||||
>FOR LOOP STATEMENT
|
||||
```java
|
||||
for (declare and initialize a loop control variable; loop-continuation condition/s; increment or decrement of the variable of control)
|
||||
{
|
||||
//Statement
|
||||
}
|
||||
```
|
||||
**Example:**
|
||||
```java
|
||||
for (int i = 0; i <= n; i++) {
|
||||
System.out.println(i);
|
||||
}
|
||||
```
|
||||
> WHILE LOOP STATEMENT
|
||||
```java
|
||||
while(condition){ //till condition will be true.
|
||||
//code to be executed
|
||||
}
|
||||
```
|
||||
**Example:**
|
||||
```java
|
||||
//Initialization is a separate statement
|
||||
int power = 1;
|
||||
|
||||
while ( power <= 10/2 ) // power <= n/2 is an example of the loop-continuation condition
|
||||
{
|
||||
System.out.println(power);
|
||||
}
|
||||
```
|
||||
|
||||
> DO-WHILE LOOP STATEMENT
|
||||
|
||||
```java
|
||||
do{ //always run one time even if condition would be false
|
||||
//Statement
|
||||
} while(loop-continuation condition);
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```java
|
||||
int i=1;
|
||||
do{
|
||||
System.out.println(i);
|
||||
i++;
|
||||
}while(i<=10);
|
||||
```
|
||||
|
||||
### ARRAY
|
||||
> ARRAY DECLARATION
|
||||
|
||||
```java
|
||||
int[] ai; // array of int
|
||||
short[][] as; // array of array of short
|
||||
short s, // scalar short
|
||||
aas[][]; // array of array of short
|
||||
Object[] ao; // array of Object
|
||||
Collection<?>[] ca; // array of Collection of unknown type
|
||||
```
|
||||
|
||||
> DECLARATION OF ARRAY VARIABLE
|
||||
|
||||
```java
|
||||
Exception ae[] = new Exception[3];
|
||||
Object aao[][] = new Exception[2][3];
|
||||
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
|
||||
char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
|
||||
'S', 't', 'r', 'i', 'n', 'g' };
|
||||
String[] aas = { "array", "of", "String", };
|
||||
```
|
||||
|
||||
### ACCESS MODIFIERS
|
||||
|
||||
1. defualt(No keyword required)
|
||||
2. private
|
||||
3. public
|
||||
4. protected
|
||||
|
||||
### NON ACCESS MODIFIERS
|
||||
|
||||
1. static
|
||||
2. final
|
||||
3. transient
|
||||
4. abstract
|
||||
5. synchronized
|
||||
6. volatile
|
||||
|
||||
## Object Oriented Programming (OOPs) Concept :clipboard:
|
||||
|
||||
### OBJECT
|
||||
|
||||
```java
|
||||
//Declare a variable, object name
|
||||
String s;
|
||||
|
||||
//Invoke a contructor to create an object
|
||||
s = new String ("Hello World");
|
||||
|
||||
//Invoke an instance method that operates on the object's value
|
||||
char c = s.chartAt(4);
|
||||
```
|
||||
> INSTANCE VARIABLES
|
||||
|
||||
```java
|
||||
public class Charge {
|
||||
//Instance variable declarations
|
||||
private final double rx, ry;
|
||||
private final double q;
|
||||
}
|
||||
```
|
||||
|
||||
### METHODS
|
||||
|
||||
```java
|
||||
public static double sum (int a, int b) { //double is the return type, sum is the method's name, a and b are two arguments of type int;
|
||||
int result; //local variable
|
||||
result = a + b;
|
||||
return result;//return statement;
|
||||
}
|
||||
```
|
||||
|
||||
### CLASS DECLARATION
|
||||
```java
|
||||
class MyClass {
|
||||
// field, constructor, and
|
||||
// method declarations
|
||||
}
|
||||
```
|
||||
**Example:**
|
||||
|
||||
```java
|
||||
public class Bicycle {
|
||||
// the Bicycle class has
|
||||
// three fields
|
||||
public int cadence;
|
||||
public int gear;
|
||||
public int speed;
|
||||
// the Bicycle class has
|
||||
// one constructor
|
||||
public Bicycle(int startCadence, int startSpeed, int startGear) {
|
||||
gear = startGear;
|
||||
cadence = startCadence;
|
||||
speed = startSpeed;
|
||||
}
|
||||
// the Bicycle class has
|
||||
// four methods
|
||||
public void setCadence(int newValue) {
|
||||
cadence = newValue;
|
||||
}
|
||||
public void setGear(int newValue) {
|
||||
gear = newValue;
|
||||
}
|
||||
public void applyBrake(int decrement) {
|
||||
speed -= decrement;
|
||||
}
|
||||
public void speedUp(int increment) {
|
||||
speed += increment;
|
||||
}
|
||||
}
|
||||
```
|
||||
>DECLARING CLASSESS IMPLEMENTATING AN INTERFACE AND EXTENDING PARENT CLASS
|
||||
```java
|
||||
class MyClass extends MySuperClass implements YourInterface {
|
||||
// field, constructor, and
|
||||
// method declarations
|
||||
}
|
||||
```
|
||||
* MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
|
||||
|
||||
> CONSTRUCTORS
|
||||
* A class contains constructors that are invoked to create objects from the class blueprint.
|
||||
* Constructor declarations look like method declarations—except that they use the name of the class and have no return type
|
||||
* Each and every class has defualt No-args constructor.
|
||||
|
||||
|
||||
```java
|
||||
public class Bicycle{
|
||||
|
||||
private int gear;
|
||||
private int cadence;
|
||||
private int speed;
|
||||
|
||||
public Bicycle(int startCadence, int startSpeed, int startGear) { //args-constructor
|
||||
gear = startGear;
|
||||
cadence = startCadence;
|
||||
speed = startSpeed;
|
||||
}
|
||||
|
||||
public Bicycle(){//No-args constructor
|
||||
super();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### POLYMORPHISM
|
||||
* Polymorphism is the concept where an object behaves differently in different situations.
|
||||
* There are two types of polymorphism
|
||||
1. compile time polymorphism
|
||||
2. runtime polymorphism.
|
||||
|
||||
#### 1. Compile Time Polymorphism
|
||||
* Compile-time polymorphism is achieved by method overloading.
|
||||
* method overloading is creating multiple method with methods name is same and arguments are different.
|
||||
```java
|
||||
public class Circle {
|
||||
|
||||
public void draw(){
|
||||
System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
|
||||
}
|
||||
|
||||
public void draw(int diameter){ //method draw() overloaded.
|
||||
System.out.println("Drwaing circle with default color Black and diameter"+diameter+" cm.");
|
||||
}
|
||||
|
||||
public void draw(int diameter, String color){ //method draw() overloaded.
|
||||
System.out.println("Drwaing circle with color"+color+" and diameter"+diameter+" cm.");
|
||||
}
|
||||
}
|
||||
```
|
||||
#### 2. Run Time Polymorphism
|
||||
* Run-time polymorphism is achieved by method overriding.
|
||||
* Runtime polymorphism is implemented when we have an **“IS-A”** relationship between objects.
|
||||
* method overriding is the subclass has to override the superclass method.
|
||||
```java
|
||||
public interface Shape {
|
||||
|
||||
public void draw();
|
||||
}
|
||||
```
|
||||
```java
|
||||
public class Circle implements Shape{
|
||||
|
||||
@Override
|
||||
public void draw(){
|
||||
System.out.println("Drwaing circle");
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
```java
|
||||
public class Square implements Shape {
|
||||
|
||||
@Override
|
||||
public void draw() {
|
||||
System.out.println("Drawing Square");
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
* `Shape` is the superclass and there are two subclasses `Circle` and `Square`
|
||||
* Below is an example of runtime polymorphism.
|
||||
```java
|
||||
Shape sh = new Circle();
|
||||
sh.draw();
|
||||
|
||||
Shape sh1 = getShape(); //some third party logic to determine shape
|
||||
sh1.draw();
|
||||
```
|
||||
|
||||
### INHERITANCE
|
||||
|
||||
* Inheritance is the mechanism of code reuse.
|
||||
* The object that is getting inherited is called the superclass and the object that inherits the superclass is called a subclass.
|
||||
* We use `extends` keyword in java to implement inheritance from class.
|
||||
* We use `implements` keyword in java to implement inheritance from interface.
|
||||
|
||||
```java
|
||||
public class Superclass{
|
||||
// methods and fields
|
||||
}
|
||||
```
|
||||
```java
|
||||
public interface Superinterface{
|
||||
// methods and fields
|
||||
}
|
||||
```
|
||||
```java
|
||||
public class Subclass extends Superclass implements Superinterface{
|
||||
// methods and fields
|
||||
}
|
||||
```
|
||||
|
||||
### Abstraction
|
||||
|
||||
* Abstraction is the concept of hiding the internal details and describing things in simple terms.
|
||||
* Abstraction can be achieved by two ways.
|
||||
1. Abstract Class
|
||||
2. Interface
|
||||
|
||||
#### 1. Abstract Class
|
||||
* An abstract class must be declared with an `abstract` keyword.
|
||||
* It can have abstract and non-abstract methods.
|
||||
* It cannot be instantiated.
|
||||
* It can have constructors and static methods also.
|
||||
* It can have final methods which will force the subclass not to change the body of the method.
|
||||
|
||||
```java
|
||||
abstract class Flower{
|
||||
abstract String Smell(); //abstract method.
|
||||
String Oil(){ // non-abstract method.
|
||||
System.out.println("Flower Oil is good.");
|
||||
}
|
||||
}
|
||||
|
||||
public class Lily extends Flower{
|
||||
private String Smell(){ // implementation of abstarct method.
|
||||
System.out.println("Lily smell's lovender.");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Interface
|
||||
* Interface is a blueprint of a **class**.
|
||||
* It can have only abstract methods. [Except Java 8 and next versions.]
|
||||
* Since Java 8, we can have **default and static** methods in an interface.
|
||||
|
||||
|
||||
```java
|
||||
interface print{
|
||||
void printPaper();
|
||||
}
|
||||
public class A4 implements print{
|
||||
public void printPaper(){
|
||||
System.out.println("A4 Page Printed. ");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Encapsulation
|
||||
|
||||
* Encapsulation is used for access restriction to class members and methods.
|
||||
* Encapsulation is the technique used to implement abstraction in OOP.
|
||||
* As in encapsulation, the data in a class is hidden from other classes, so it is also known as **data-hiding**.
|
||||
* Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
|
||||
* Best example of Encapsulation is POJO (Plain-Java-Object-Class).
|
||||
|
||||
```java
|
||||
public class User {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## ADVANCE DATA TYPE
|
||||
* **STACK DATA TYPE**
|
||||
|
||||
```java
|
||||
public class Stack<Item> implements Iterable <Item>
|
||||
|
||||
Stack() //create an empty stack
|
||||
boolean isEmpty() //return if the stack empty
|
||||
void push(Item item) // push an item onto the stack
|
||||
Item pop() //return and remove the item that was inserted most recently
|
||||
int size() //number of item on stack
|
||||
```
|
||||
|
||||
* **QUEUE DATA TYPE**
|
||||
|
||||
```java
|
||||
public class Queue<Item> implements Iterable<Item>
|
||||
|
||||
Queue() //create an emptyh queue
|
||||
boolean isEmpthy() //return if the queue empthy
|
||||
void enqueue(Item item) // insert an item onto queue
|
||||
Item dequeue() //return and remove the item that was inserted least recently
|
||||
int size() //number of item on queue
|
||||
```
|
||||
|
||||
* **ITERABLE**
|
||||
|
||||
```java
|
||||
//import Iterator
|
||||
import java.util.Iterator;
|
||||
|
||||
public class Queue<Item> implements Iterable <Item> {
|
||||
|
||||
//FIFO queue
|
||||
private Node first;
|
||||
private Node last;
|
||||
private class Node {
|
||||
Item item;
|
||||
Node next;
|
||||
}
|
||||
|
||||
public void enqueue (Item item)
|
||||
...
|
||||
|
||||
public Item dequeue()
|
||||
...
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
* **SYMBOL TABLE DATA TYPE**
|
||||
|
||||
```java
|
||||
public class ST<Key extends Comparable<Key>, Value>
|
||||
|
||||
ST() //create and empty symbol table
|
||||
void put(Key key, Value val) //associate val with key
|
||||
Value get(Key key) //value associated with key
|
||||
void remove(Key key) //remove key (and its associated value)
|
||||
boolean contains (Key key) //return if there is a value associated with key
|
||||
int size() //number of key-value pairs
|
||||
Iterable<Key> keys() // all keys in the symbol table
|
||||
```
|
||||
|
||||
* **SET DATA TYPE**
|
||||
|
||||
```java
|
||||
public class SET<Key extends Comparable<Key>> implements Iterable<Key>
|
||||
SET() //create an empthy set
|
||||
boolean isEmpthy() //return if the set is empthy
|
||||
void add (Key key) //add key to the set
|
||||
void remove(Key key) //remove key from set
|
||||
boolean contains(Key key) //return if the key is in the set
|
||||
int size() //number of elements in set
|
||||
```
|
||||
@@ -11,6 +11,33 @@ echo ""; // Print a string or type that can be made into a string(I.E int, float
|
||||
print_r($arr); // Print anything, with type hints for array's and object's
|
||||
var_dump($arr); // Print anything, with type hints for any value and sizes
|
||||
|
||||
/**
|
||||
* Declaring an Array
|
||||
*/
|
||||
// Indexed Array
|
||||
$arr = array("John", "Doe", "Lorem", "Ipsum");
|
||||
|
||||
// Associative Array
|
||||
$arr = array("John"=>"10", "Doe"=>"200", "Doe"=>"3000", "Ipsum"=>"40000");
|
||||
|
||||
// Multidimensional Arrays
|
||||
$arr = array (
|
||||
array("John",100,180),
|
||||
array("Doe",150,130),
|
||||
array("Lorem",500,200),
|
||||
array("Ipsum",170,150)
|
||||
);
|
||||
|
||||
/**
|
||||
* Sorting an Array
|
||||
*/
|
||||
sort($arr); // Sort arrays in ascending order.
|
||||
rsort($arr); // Sort arrays in descending order.
|
||||
asort($arr); // Sort associative arrays in ascending order, according to the value.
|
||||
ksort($arr); // Sort associative arrays in ascending order, according to the key.
|
||||
arsort($arr); // Sort associative arrays in descending order, according to the value.
|
||||
krsort($arr); // Sort associative arrays in descending order, according to the key.
|
||||
|
||||
/**
|
||||
* Ways of looping
|
||||
*/
|
||||
@@ -24,7 +51,7 @@ foreach($arr as $key => $value) {
|
||||
}
|
||||
|
||||
// For
|
||||
for($i = 0; $i < count($arr) - 1; $i++) {
|
||||
for($i = 0; $i < count($arr); $i++) {
|
||||
$key = $i;
|
||||
$value = $arr[$i];
|
||||
}
|
||||
@@ -303,3 +330,142 @@ abstract class AbstractClassName
|
||||
abstract function abstractFunction(Type $var = null): Type;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Basic Implementation of LoggerAwareInterface.
|
||||
* @see https://github.com/php-fig/log/blob/master/Psr/Log/LoggerAwareTrait.php
|
||||
*/
|
||||
trait LoggerAwareTrait
|
||||
{
|
||||
/**
|
||||
* The logger instance.
|
||||
*
|
||||
* @var LoggerInterface
|
||||
*/
|
||||
protected $logger;
|
||||
/**
|
||||
* Sets a logger.
|
||||
*
|
||||
* @param LoggerInterface $logger
|
||||
*/
|
||||
public function setLogger(LoggerInterface $logger)
|
||||
{
|
||||
$this->logger = $logger;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Example with use of LoggerAwareTrait.
|
||||
*/
|
||||
class ClassWithLogger
|
||||
{
|
||||
/**
|
||||
* Use the LoggerAwareTrait in this class.
|
||||
*/
|
||||
use LoggerAwareTrait;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* PHP Regex.
|
||||
*/
|
||||
|
||||
// Meta Characters.
|
||||
|
||||
^ Start of subject (or line in multiline mode)
|
||||
$ End of subject (or line in multiline mode)
|
||||
[ Start character class definition
|
||||
] End character class definition
|
||||
| Alternates, eg (a|b) matches a or b
|
||||
( Start subpattern
|
||||
) End subpattern
|
||||
\ Escape character
|
||||
|
||||
// Pattern Modifiers.
|
||||
|
||||
i Caseless - ignore case
|
||||
m Multiline mode - ^ and $ match start and end of lines
|
||||
s Dotall - . class includes newline
|
||||
x Extended- comments & whitespace
|
||||
e preg_replace only - enables evaluation of replacement as PHP code
|
||||
S Extra analysis of pattern
|
||||
U Pattern is ungreedy
|
||||
u Pattern is treated as UTF-8
|
||||
|
||||
// Subpattern Modifiers & Assertions.
|
||||
(?:) Non capturing subpattern ((?:foo|fu)bar) matches foobar or fubar without foo or fu appearing as a captured subpattern
|
||||
(?=) Positive look ahead assertion foo(?=bar) matches foo when followed by bar
|
||||
(?!) Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
|
||||
(?<=) Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
|
||||
(?<!) Negative look behind assertion (?<!foo)bar matches bar when not preceded by foo
|
||||
(?>) Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
|
||||
(?(x)) Conditional subpatterns (?(3)foo|fu)bar Matches foo if 3rd subpattern has matched, fu if not
|
||||
(?#) Comment (?# Pattern does x y or z)
|
||||
|
||||
// Base Character Classes
|
||||
\w Any "word" character (a-z 0-9 _)
|
||||
\W Any non "word" character
|
||||
\s Whitespace (space, tab CRLF)
|
||||
\S Any non whitepsace character
|
||||
\d Digits (0-9)
|
||||
\D Any non digit character
|
||||
. (Period) - Any character except newline
|
||||
|
||||
// Multiplicity.
|
||||
n* Zero or more of n
|
||||
n+ One or more of n
|
||||
n? Zero or one occurrences of n
|
||||
{n} n occurrences exactly
|
||||
{n,} At least n occurrences
|
||||
{,m} At most m occurrences
|
||||
{n,m} Between n and m occurrences (inclusive)
|
||||
|
||||
|
||||
// PHP Regular Expression Functions.
|
||||
|
||||
Function Description
|
||||
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
|
||||
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string. Useful for search and replace.
|
||||
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
|
||||
preg_split() Preg Split (preg_split()) operates exactly like the split() function, except that regular expressions are accepted as input parameters.
|
||||
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regex pattern within a string.
|
||||
preg_ quote() Quote regular expression characters
|
||||
|
||||
// Code Snippets.
|
||||
|
||||
//A better solution for validate email syntax is using filter_var.
|
||||
if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) {
|
||||
echo "Your email is ok.";
|
||||
} else {
|
||||
echo "Wrong email address format.";
|
||||
}
|
||||
|
||||
//Validate username, consist of alpha-numeric (a-z, A-Z, 0-9), underscores, and has minimum 5 character and maximum 20 character.
|
||||
//You could change the minimum character and maximum character to any number you like.
|
||||
$username = "user_name12";
|
||||
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
|
||||
echo "Your username is ok.";
|
||||
} else {
|
||||
echo "Wrong username format.";
|
||||
}
|
||||
|
||||
//Validate domain
|
||||
$url = "http://domain-name.com/";
|
||||
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
|
||||
echo "Your url is ok.";
|
||||
} else {
|
||||
echo "Wrong url.";
|
||||
}
|
||||
|
||||
//Extract domain name from certain URL
|
||||
$url = "http://domain-name.com/index.html";
|
||||
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
|
||||
$host = $matches[1];
|
||||
echo $host; // domain-name.com
|
||||
|
||||
//Highlight a word in the content
|
||||
$text = "A regular expression (shortened as regex) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for 'find' or 'find and replace' operations on strings, or for input validation.";
|
||||
$text = preg_replace("/\b(regex)\b/i", 'replaced content', $text);
|
||||
echo $text; /*A regular expression (shortened as replaced content) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for 'find' or 'find and replace' operations on strings, or for input validation.*/
|
||||
|
||||
341
languages/python.md
Normal file
341
languages/python.md
Normal file
@@ -0,0 +1,341 @@
|
||||
# Python
|
||||
|
||||
* Python is an interpreted, high-level and general-purpose, dynamically typed programming language
|
||||
|
||||
* It is also Object oriented, modular oriented and a scripting language.
|
||||
|
||||
* In Python, everything is considered as an Object.
|
||||
|
||||
* A python file has an extension of .py
|
||||
|
||||
* Python follows Indentation to separate code blocks instead of flower brackets({}).
|
||||
|
||||
* We can run a python file by the following command in cmd(Windows) or shell(mac/linux).
|
||||
|
||||
`$ python <filename.py>` or `$ python3 <filename.py>`
|
||||
|
||||
#### By default, python doesn't require any imports to run a python file.
|
||||
|
||||
## Create and execute a program
|
||||
|
||||
1. Open up a terminal/cmd
|
||||
1. Create the program: nano/cat > nameProgram.py
|
||||
1. Write the program and save it
|
||||
1. python nameProgram.py
|
||||
|
||||
<br>
|
||||
|
||||
### Basic Datatypes
|
||||
|
||||
| Data Type | Description |
|
||||
| --------- | ----------- |
|
||||
| int | Integer values [0, 1, -2, 3] |
|
||||
| float | Floating point values [0.1, 4.532, -5.092] |
|
||||
| char | Characters [a, b, @, !, `] |
|
||||
| str | Strings [abc, AbC, A@B, sd!, `asa] |
|
||||
| bool | Boolean Values [True, False] |
|
||||
| complex | Complex numbers [2+3j, 4-1j] |
|
||||
|
||||
<br>
|
||||
|
||||
## Keywords
|
||||
<br>
|
||||
|
||||
- As of python3.8 there are 35 keywords
|
||||
|
||||
| Keyword | Description | Category |
|
||||
|---------- | ---------- | --------- |
|
||||
| True | Boolean value for not False or 1 | Value Keyword|
|
||||
| False | Boolean Value for not True or 0 | Value Keyword |
|
||||
| None | No Value | Value keyword |
|
||||
| and | returns true if both (oprand) are true (other language && ) | Operator keyword |
|
||||
| or | returns true of either operands is true (other language || ) | Operator keyword |
|
||||
| in | returns true if word is in iterator | Operator keyword |
|
||||
| is | returns true if id of variables are same | Operator keyword |
|
||||
| not | returns opposite Boolean value | Operator Keyword |
|
||||
| if | get into block if expression is true | conditional |
|
||||
| elif | for more than 1 if checks | conditional |
|
||||
| else | this block will be executed if condition is false | conditional |
|
||||
| for | used for looping | iteration |
|
||||
| while | used for looping | iteration |
|
||||
| break | get out of loop | iteration |
|
||||
| continue | skip for specific condition | iteration |
|
||||
| def | make user defined function | structure |
|
||||
| class | make user defined classes | structure |
|
||||
| lambda | make anonymous function | structure |
|
||||
| with | execute code within context manager's scope | structure |
|
||||
| as | alias for something | structure |
|
||||
| pass | used for making empty structures(declaration) | structure |
|
||||
| return | get value(s) from function, get out of function | returning keyword |
|
||||
| yield | yields values instead of returning (are called generators) | returning keyword |
|
||||
| import | import libraries/modules/packages | import |
|
||||
| from | import specific function/classes from modules/packages | import |
|
||||
| try | this block will be tried to get executed | execption handling |
|
||||
| execpt | is any execption/error has occured it'll be executed | execption handling |
|
||||
| finally | It'll be executed no matter execption occurs or not | execption handling |
|
||||
| raise | throws any specific error/execption | execption handling |
|
||||
| assert | throws an AssertionError if condition is false | execption handling |
|
||||
| async | used to define asynchronous functions/co-routines | asynchronous programming |
|
||||
| await | used to specify a point when control is taken back | asynchronous programming |
|
||||
| del | deletes/unsets any user defined data | variable handling |
|
||||
| global | used to access variables defined outsied of function | variable handling |
|
||||
| nonlocal | modify variables from different scopes | variable handling |
|
||||
<br>
|
||||
|
||||
## Operators
|
||||
|
||||
<br>
|
||||
|
||||
| Operator | Description |
|
||||
|-|-|
|
||||
| ( ) | grouping parenthesis, function call, tuple declaration |
|
||||
| [ ] | array indexing, also declaring lists etc.|
|
||||
| ! | relational not, complement, ! a yields true or false |
|
||||
| ~ | bitwise not, ones complement, ~a |
|
||||
| \- | unary minus, - a |
|
||||
| \+ | unary plus, + a |
|
||||
| \* | multiply, a * b |
|
||||
| / | divide, a / b |
|
||||
| % | modulo, a % b |
|
||||
| \+ | add, a + b |
|
||||
| \- | subtract, a - b |
|
||||
| << | shift left, left operand is shifted left by right operand bits (multiply by 2) |
|
||||
| \>> | shift right, left operand is shifted right by right operand bits (divide by 2) |
|
||||
| < | less than, result is true or false, a %lt; b
|
||||
| <= | less than or equal, result is true or false, a <= b
|
||||
| \> | greater than, result is true or false, a > b
|
||||
| \>= | greater than or equal, result is true or false, a >= b
|
||||
| == | equal, result is true or false, a == b
|
||||
| != | not equal, result is true or false, a != b
|
||||
| & | bitwise and, a & b
|
||||
| ^ | bitwise exclusive or XOR, a ^ b
|
||||
| \| | bitwise or, a | b
|
||||
| &&, and | relational and, result is true or false, a < b && c >= d
|
||||
| \|\|, or | relational or, result is true or false, a < b \|\| c >= d |
|
||||
| = | store or assignment |
|
||||
| += | add and store |
|
||||
| -= | subtract and store |
|
||||
| *= | multiply and store |
|
||||
| /= | divide and store|
|
||||
| %= | modulo and store|
|
||||
| <<= | shift left and store|
|
||||
| \>>= | shift right and store|
|
||||
| &= | bitwise and and store|
|
||||
| ^= | bitwise exclusive or and store|
|
||||
| \|= | bitwise or and store|
|
||||
| , | separator as in ( y=x,z=++x )|
|
||||
|
||||
### Basic Data Structures
|
||||
|
||||
### List
|
||||
|
||||
- List is a collection which is ordered and changeable. Allows duplicate members.
|
||||
|
||||
|
||||
- Lists are created using square brackets:
|
||||
|
||||
```py
|
||||
thislist = ["apple", "banana", "cherry"]
|
||||
```
|
||||
|
||||
- List items are ordered, changeable, and allow duplicate values.
|
||||
|
||||
- List items are indexed, the first item has index `[0]`, the second item has index `[1]` etc.
|
||||
|
||||
- The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
|
||||
|
||||
- To determine how many items a list has, use the `len()` function.
|
||||
|
||||
- A list can contain different data types:
|
||||
```py
|
||||
list1 = ["abc", 34, True, 40, "male"]
|
||||
```
|
||||
- It is also possible to use the list() constructor when creating a new list
|
||||
```py
|
||||
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
|
||||
```
|
||||
### Tuple
|
||||
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
|
||||
- A tuple is a collection which is ordered and unchangeable.
|
||||
- Tuples are written with round brackets.
|
||||
```py
|
||||
thistuple = ("apple", "banana", "cherry")
|
||||
```
|
||||
- Tuple items are ordered, unchangeable, and allow duplicate values.
|
||||
- Tuple items are indexed, the first item has index `[0]`, the second item has index `[1]` etc.
|
||||
- When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.
|
||||
|
||||
- Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
|
||||
- Since tuple are indexed, tuples can have items with the same value:
|
||||
- Tuples allow duplicate values:
|
||||
```py
|
||||
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
|
||||
```
|
||||
- To determine how many items a tuple has, use the `len()`function:
|
||||
```py
|
||||
thistuple = ("apple", "banana", "cherry")
|
||||
print(len(thistuple))
|
||||
```
|
||||
- To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
|
||||
```py
|
||||
thistuple = ("apple",)
|
||||
print(type(thistuple))
|
||||
|
||||
#NOT a tuple
|
||||
thistuple = ("apple")
|
||||
print(type(thistuple))
|
||||
```
|
||||
- It is also possible to use the tuple() constructor to make a tuple.
|
||||
```py
|
||||
|
||||
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
|
||||
print(thistuple)
|
||||
```
|
||||
|
||||
### Set
|
||||
- Set is a collection which is unordered and unindexed. No duplicate members.
|
||||
- A set is a collection which is both unordered and unindexed.
|
||||
```py
|
||||
thisset = {"apple", "banana", "cherry"}
|
||||
```
|
||||
- Set items are unordered, unchangeable, and do not allow duplicate values.
|
||||
- Unordered means that the items in a set do not have a defined order.
|
||||
|
||||
- Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
|
||||
|
||||
- Sets are unchangeable, meaning that we cannot change the items after the set has been created.
|
||||
- Duplicate values will be ignored.
|
||||
- To determine how many items a set has, use the `len()` method.
|
||||
```py
|
||||
thisset = {"apple", "banana", "cherry"}
|
||||
|
||||
print(len(thisset))
|
||||
```
|
||||
- Set items can be of any data type:
|
||||
```py
|
||||
set1 = {"apple", "banana", "cherry"}
|
||||
set2 = {1, 5, 7, 9, 3}
|
||||
set3 = {True, False, False}
|
||||
set4 = {"abc", 34, True, 40, "male"}
|
||||
```
|
||||
- It is also possible to use the `set()` constructor to make a set.
|
||||
```py
|
||||
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
|
||||
```
|
||||
### Dictionary
|
||||
- Dictionary is a collection which is unordered and changeable. No duplicate members.
|
||||
- Dictionaries are used to store data values in key:value pairs.
|
||||
- Dictionaries are written with curly brackets, and have keys and values:
|
||||
```py
|
||||
thisdict = {
|
||||
"brand": "Ford",
|
||||
"model": "Mustang",
|
||||
"year": 1964
|
||||
}
|
||||
```
|
||||
- Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
|
||||
```py
|
||||
thisdict = {
|
||||
"brand": "Ford",
|
||||
"model": "Mustang",
|
||||
"year": 1964
|
||||
}
|
||||
print(thisdict["brand"])
|
||||
```
|
||||
- Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
|
||||
- Dictionaries cannot have two items with the same key.
|
||||
- Duplicate values will overwrite existing values.
|
||||
- To determine how many items a dictionary has, use the `len()` function.
|
||||
```py
|
||||
print(len(thisdict))
|
||||
```
|
||||
- The values in dictionary items can be of any data type
|
||||
```py
|
||||
thisdict = {
|
||||
"brand": "Ford",
|
||||
"electric": False,
|
||||
"year": 1964,
|
||||
"colors": ["red", "white", "blue"]
|
||||
}
|
||||
```
|
||||
|
||||
### Conditional branching
|
||||
|
||||
```py
|
||||
if condition:
|
||||
pass
|
||||
elif condition2:
|
||||
pass
|
||||
else:
|
||||
pass
|
||||
```
|
||||
### Loops
|
||||
|
||||
Python has two primitive loop commands:
|
||||
1. while loops
|
||||
2. for loops
|
||||
|
||||
#### While loop
|
||||
- With the `while` loop we can execute a set of statements as long as a condition is true.
|
||||
- Example: Print i as long as i is less than 6
|
||||
```py
|
||||
i = 1
|
||||
while i < 6:
|
||||
print(i)
|
||||
i += 1
|
||||
```
|
||||
- The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.
|
||||
- With the `break` statement we can stop the loop even if the while condition is true
|
||||
- With the continue statement we can stop the current iteration, and continue with the next.
|
||||
|
||||
- With the else statement we can run a block of code once when the condition no longer is true.
|
||||
|
||||
#### For loop
|
||||
- A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
|
||||
|
||||
- This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
|
||||
|
||||
- With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
|
||||
```py
|
||||
fruits = ["apple", "banana", "cherry"]
|
||||
for x in fruits:
|
||||
print(x)
|
||||
```
|
||||
- The for loop does not require an indexing variable to set beforehand.
|
||||
- To loop through a set of code a specified number of times, we can use the range() function.
|
||||
- The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
|
||||
- The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3).
|
||||
- The else keyword in a for loop specifies a block of code to be executed when the loop is finished.
|
||||
A nested loop is a loop inside a loop.
|
||||
|
||||
- The "inner loop" will be executed one time for each iteration of the "outer loop":
|
||||
|
||||
```py
|
||||
adj = ["red", "big", "tasty"]
|
||||
fruits = ["apple", "banana", "cherry"]
|
||||
|
||||
for x in adj:
|
||||
for y in fruits:
|
||||
print(x, y)
|
||||
```
|
||||
- for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
|
||||
|
||||
```py
|
||||
for x in [0, 1, 2]:
|
||||
pass
|
||||
```
|
||||
|
||||
### Function definition
|
||||
```py
|
||||
def function_name():
|
||||
return
|
||||
```
|
||||
### Function call
|
||||
|
||||
```py
|
||||
function_name()
|
||||
```
|
||||
|
||||
* We need not to specify the return type of the function.
|
||||
* Functions by default return `None`
|
||||
* We can return any datatype.
|
||||
39
tools/aws.sh
Normal file
39
tools/aws.sh
Normal file
@@ -0,0 +1,39 @@
|
||||
##############################################################################
|
||||
# AWS
|
||||
##############################################################################
|
||||
|
||||
# General
|
||||
aws help
|
||||
aws --version # Show the current AWS CLI version
|
||||
aws configure # Configure your AWS Key ID, AWS Secret, default region and default output format for the AWS CLI
|
||||
aws configure --profile <profile_name> # Configure using the profile name. By default, the list of profile is stored in ~/.aws.credentials (Linux and MacOS)
|
||||
|
||||
# EC2
|
||||
## We need to specify a region to use ec2 commands. We can configure a default region with "aws configure" or set the AWS_DEFAULT_REGION environment variable before the command line
|
||||
## Example: AWS_DEFAULT_REGION=us-east-1 aws ec2 describe-instances
|
||||
|
||||
aws ec2 describe-instances # Desribe all instances in the current region
|
||||
aws ec2 describe-instances --instance-ids <instance_id_1> <instance_id_2> # Describe specific instances by their IDs
|
||||
aws ec2 describe-instances --filters Name=<instance_name> # Filter and describe instances by name
|
||||
|
||||
aws ec2 start-instances --instance-ids <instance_id_1> <instance_id_2> # Start previously stopped instances by their IDs
|
||||
aws ec2 stop-instances --instance-ids <instance_id_1> <instance_id_2> # Stop running instances by their IDs
|
||||
aws ec2 terminate-instances --instance-ids <instance_id_1> <instance_id_2> # Shutdown the specific instances by their IDs
|
||||
|
||||
|
||||
# S3
|
||||
## To specify the root directory of a S3 bucket, use this syntax: s3://<bucket_name>
|
||||
|
||||
aws s3 ls # List S3 objects and common prefixes under a prefix or all S3 buckets
|
||||
aws s3 ls s3://<bucket_name> # List objects and common prefixes under a specified bucket and prefix
|
||||
aws s3 mb s3://<bucket_name> # Create a specific S3 bucket
|
||||
aws s3 rb s3://<bucket_name> # Remove an empty specific S3 bucket by name
|
||||
|
||||
aws s3 mv <local_file_path> s3://<bucket_name>/<destination_file_path> # Move a file in local_file_path to a specific bucket in destination_file_path
|
||||
## Example: aws s3 mv text.txt s3://mybucket/text.txt
|
||||
aws s3 mv s3://<bucket_name_1> s3://<bucket_name_2> --recursive # Move all objects from bucket_name_1 to bucket_name_2
|
||||
|
||||
aws s3 sync <source> <target> # Sync all contents from source to a target directory. This will copy and update all missing or outdated files or objects between source and target
|
||||
## Examples: aws s3 sync . s3://mybucket
|
||||
## aws s3 sync s3://bucket_1 s3://bucket_2
|
||||
aws s3 sync <source> <target> --delete # Sync all contents from source to target, but this will remove all missing files and objects from the target that are not present in source
|
||||
115
tools/curl.sh
Normal file
115
tools/curl.sh
Normal file
@@ -0,0 +1,115 @@
|
||||
#!/bin/bash
|
||||
##############################################################################
|
||||
# BASICS
|
||||
##############################################################################
|
||||
|
||||
# help
|
||||
curl -h # help
|
||||
curl --help # same as -h
|
||||
curl --manual # whole man page
|
||||
|
||||
# verbose
|
||||
curl -v # verbose
|
||||
curl -vv # even more verbose
|
||||
|
||||
# redirect output to the file
|
||||
curl http://url/file > file
|
||||
# write to file instead of stdout
|
||||
curl -o file http://url/file
|
||||
curl --output file http://url/file
|
||||
# write output to a file named as the remote file
|
||||
curl -o file http://url/file
|
||||
curl --output file http://url/file
|
||||
# execute remote script
|
||||
bash <(curl -s http://url/myscript.sh)
|
||||
|
||||
# download headers
|
||||
curl -I url # display header
|
||||
|
||||
# basic authentification
|
||||
curl --user username:password http://example.com/
|
||||
curl -u username:password http://example.com/
|
||||
|
||||
# SSL
|
||||
# -k, --insecure allow insecure server connections when using SSL
|
||||
curl -k https://server_with_self_signed_cert/endpoint
|
||||
curl --insecure https://server_with_self_signed_cert/endpoint
|
||||
|
||||
# HTTP request
|
||||
# -X, --request <command> specify request command to use
|
||||
# example:
|
||||
curl -X GET http://url/endpoint
|
||||
|
||||
# HTTP header
|
||||
# -H, --header <header/@file> pass custom header(s) to server
|
||||
# example:
|
||||
curl -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' http://url/endpoing
|
||||
|
||||
# HTTP POST data
|
||||
# -d, --data <data> HTTP POST data
|
||||
# -d, --data @data HTTP POST data from file
|
||||
# example:
|
||||
curl -d '{json}' -H 'Content-Type: application/json' http://url/endpoint
|
||||
|
||||
# config file
|
||||
curl -K file #
|
||||
#or # Read config from a file
|
||||
curl --config file #
|
||||
$HOME/.curlrc # Default config file in UNIX-like systems
|
||||
|
||||
##############################################################################
|
||||
# WRITE OUT PARAMETERS
|
||||
##############################################################################
|
||||
|
||||
# -w, --write-out <format> Use output FORMAT after completion
|
||||
# example:
|
||||
curl -w %{size_header} --silent -o /dev/null http://gogle.com # print size of header when you accessing google.com
|
||||
|
||||
# FORMAT supported:
|
||||
# %{content_type} # shows the Content-Type of the requested document, if there was any.
|
||||
# %{filename_effective} # shows the ultimate filename that curl writes out to.
|
||||
# This is only meaningful if curl is told to write to a file with
|
||||
# the --remote-name or --output option. It's most useful in combination
|
||||
# with the --remote-header-name option.
|
||||
# %{ftp_entry_path} # shows the initial path curl ended up in when logging on to the remote FTP server.
|
||||
# %{response_code} # shows the numerical response code that was found in the last transfer.
|
||||
# %{http_connect} # shows the numerical code that was found in the last response (from a proxy)
|
||||
# to a curl CONNECT request.
|
||||
# %{local_ip} # shows the IP address of the local end of the most recently done connection—can
|
||||
# be either IPv4 or IPv6
|
||||
# %{local_port} # shows the local port number of the most recently made connection
|
||||
# %{num_connects} # shows the number of new connects made in the recent transfer.
|
||||
# %{num_redirects} # shows the number of redirects that were followed in the request.
|
||||
# %{redirect_url} # shows the actual URL a redirect would take you to when an HTTP request
|
||||
# was made without -L to follow redirects.
|
||||
# %{remote_ip} # shows the remote IP address of the most recently made connection—can be
|
||||
# either IPv4 or IPv6.
|
||||
# %{remote_port} # shows the remote port number of the most recently made connection.
|
||||
# %{size_download} # shows the total number of bytes that were downloaded.
|
||||
# %{size_header} # shows the total number of bytes of the downloaded headers.
|
||||
# %{size_request} # shows the total number of bytes that were sent in the HTTP request.
|
||||
# %{size_upload} # shows the total number of bytes that were uploaded.
|
||||
# %{speed_download} # shows the average download speed that curl measured for the complete download
|
||||
# in bytes per second.
|
||||
# %{speed_upload} # shows the average upload speed that curl measured for the complete upload in
|
||||
# bytes per second.
|
||||
# %{ssl_verify_result} # shows the result of the SSL peer certificate verification that was requested.
|
||||
# 0 means the verification was successful.
|
||||
# %{time_appconnect} # shows the time, in seconds, it took from the start until the SSL/SSH/etc connect/handshake
|
||||
# to the remote host was completed.
|
||||
# %{time_connect} # shows the time, in seconds, it took from the start until the TCP connect to the remote
|
||||
# host (or proxy) was completed.
|
||||
# %{time_namelookup} # shows the time, in seconds, it took from the start until the name resolving was completed.
|
||||
# %{time_pretransfer} # shows the time, in seconds, it took from the start until the file transfer was just about
|
||||
# to begin. This includes all pre-transfer commands and negotiations that are specific to
|
||||
# the particular protocol(s) involved.
|
||||
# %{time_redirect} # shows the time, in seconds, it took for all redirection steps including name lookup, connect,
|
||||
# pre-transfer and transfer before the final transaction was started. time_redirect shows
|
||||
# the complete execution time for multiple redirections.
|
||||
# %{time_starttransfer} # shows the time, in seconds, it took from the start until the first byte was just about to
|
||||
# be transferred. This includes time_pretransfer and also the time the server needed
|
||||
# to calculate the result.
|
||||
# %{time_total} # shows the total time, in seconds, that the full operation lasted. The time will be displayed
|
||||
# with millisecond resolution.
|
||||
# %{url_effective} # shows the URL that was fetched last. This is particularly meaningful if you have told curl
|
||||
# to follow Location: headers (with -L)
|
||||
@@ -16,6 +16,7 @@ docker rm $(docker ps -a -q) # Remove all containers from this ma
|
||||
docker images -a # Show all images on this machine
|
||||
docker rmi <imagename> # Remove the specified image from this machine
|
||||
docker rmi $(docker images -q) # Remove all images from this machine
|
||||
docker logs <container-id> -f # Live tail a container's logs
|
||||
docker login # Log in this CLI session using your Docker credentials
|
||||
docker tag <image> username/repository:tag # Tag <image> for upload to registry
|
||||
docker push username/repository:tag # Upload tagged image to registry
|
||||
|
||||
66
tools/drush.sh
Normal file
66
tools/drush.sh
Normal file
@@ -0,0 +1,66 @@
|
||||
##############################################################################
|
||||
# DRUSH
|
||||
# Install: https://www.drush.org/install/
|
||||
# Usage: https://www.drush.org/usage/
|
||||
##############################################################################
|
||||
|
||||
|
||||
cache clear (cc) # Clear all caches.
|
||||
|
||||
cron # Run all cron hooks.
|
||||
|
||||
disable (dis) # Disable one or more modules.
|
||||
|
||||
download (dl) # Download core Drupal and projects like CCK, Zen, etc.
|
||||
|
||||
enable (en) # Enable one or more modules.
|
||||
|
||||
eval # Evaluate arbitrary php code after bootstrapping Drupal.
|
||||
|
||||
help # Print this help message. Use --filter to limit command list to one command file (e.g. --filter=pm)
|
||||
|
||||
info # Release information for a project
|
||||
|
||||
installcore (ic) # Install Drupal core via the specified install profile. Note that updating core with Drush is not yet available. See http://drupal.org/node/434944.
|
||||
|
||||
refresh (rf) # Refresh update status information script Runs the given php script(s) after a full Drupal bootstrap. NOTE: you can't supply absolute paths to the script e.g. ~/Desktop/script.php won't work Desktop/script.php will
|
||||
|
||||
sql cli (sqlc) # Open a SQL command-line interface using Drupal?s credentials.
|
||||
|
||||
sql conf # Print database connection details.
|
||||
|
||||
sql connect # A string for connecting to the DB.
|
||||
|
||||
sql dump # Exports the Drupal DB as SQL using mysqldump.
|
||||
|
||||
sql load # Copy source database to target database.
|
||||
|
||||
sql query (sqlq) # Execute a query against the site database.
|
||||
|
||||
status (st) # Provides a birds-eye view of the current Drupal installation, if any.
|
||||
|
||||
statusmodules (sm) # Show module enabled/disabled status
|
||||
|
||||
sync # Rsync the Drupal tree to/from another server using ssh.
|
||||
|
||||
test clean # Delete leftover tables and files from prior test runs.
|
||||
|
||||
test mail # Run all tests and mail the results to your team.
|
||||
|
||||
uninstall # Uninstall one or more modules.
|
||||
|
||||
update (up) # Update your project code and apply any database updates required (update.php)
|
||||
|
||||
updatecode (upc) # Update your project code. Moves existing project files to the backup directory specified in the config.
|
||||
|
||||
updatedb (updb) # Execute the update.php process from the command line.
|
||||
|
||||
variable delete (vdel) # Delete a variable.
|
||||
|
||||
variable get (vget) # Get a list of some or all site variables and values.
|
||||
|
||||
variable set (vset) # Set a variable.
|
||||
|
||||
watchdog delete (wd) # Delete all messages or only those of a specified type.
|
||||
|
||||
watchdog show (ws) # Shows recent watchdog log messages. Optionally filter for a specific type.
|
||||
13
tools/elasticsearch.js
Normal file
13
tools/elasticsearch.js
Normal file
@@ -0,0 +1,13 @@
|
||||
/* *******************************************************************************************
|
||||
* ELASTICSEARCH
|
||||
* https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html
|
||||
* https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html
|
||||
* ******************************************************************************************* */
|
||||
|
||||
sudo service elasticsearch status -l // Check elasticsearch status
|
||||
sudo service kibana restart // Restart kibana
|
||||
sudo service elasticsearch restart // Restart elasticsearch
|
||||
brew services elasticsearch-full restart
|
||||
|
||||
sudo /usr/share/elasticsearch/bin/elasticsearch --version // Check ElasticSearch version
|
||||
sudo /usr/share/kibana/bin/kibana --version // Check kibana version
|
||||
282
tools/emmet.md
Normal file
282
tools/emmet.md
Normal file
@@ -0,0 +1,282 @@
|
||||
# EMMET
|
||||
*The essential toolkit for web-developers*
|
||||
|
||||
## Introduction
|
||||
Emmet is a productivity toolkit for web developers that uses expressions to generate HTML snippets.
|
||||
|
||||
## Installation
|
||||
Normally, installation for Emmet should be a straight-forward process from the package-manager, as most of the modern text editors support Emmet. If you have difficulty setting up emmet with your editor and wish to check Emmet is supported by your favourite editor or not, you can check it from here. [Emmet Installation instructions](https://emmet.io/download/)
|
||||
|
||||
## Usage
|
||||
You can use Emmet in two ways:
|
||||
* Tab Expand Way: Type your emmet code and press `Tab` key
|
||||
* Interactive Method: Press `alt + ctrl + Enter` and start typing your expressions. This should automatically generate HTML snippets on the fly.
|
||||
|
||||
__This cheatsheet will assume that you press `Tab` after each expressions.__
|
||||
|
||||
## HTML
|
||||
|
||||
### Generating HTML 5 DOCTYPE
|
||||
`html:5`
|
||||
Will generate
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Child items
|
||||
Child items are created using `>`
|
||||
|
||||
`ul>li>p`
|
||||
|
||||
```html
|
||||
<ul>
|
||||
<li>
|
||||
<p></p>
|
||||
</li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
### Sibling Items
|
||||
Sibling items are created using `+`
|
||||
|
||||
`html>head+body`
|
||||
|
||||
```html
|
||||
<html>
|
||||
<head></head>
|
||||
<body>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Multiplication
|
||||
Items can be multiplied by `*`
|
||||
|
||||
`ul>li*5`
|
||||
|
||||
```html
|
||||
<ul>
|
||||
<li></li>
|
||||
<li></li>
|
||||
<li></li>
|
||||
<li></li>
|
||||
<li></li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
### Grouping
|
||||
Items can be grouped together using `()`
|
||||
|
||||
`table>(tr>th*5)+tr>t*5`
|
||||
|
||||
```html
|
||||
<table>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
<tr>
|
||||
<t></t>
|
||||
<t></t>
|
||||
<t></t>
|
||||
<t></t>
|
||||
<t></t>
|
||||
</tr>
|
||||
</table>
|
||||
```
|
||||
|
||||
### Class and ID
|
||||
Class and Id in Emmet can be done using `.` and `#`
|
||||
|
||||
`div.heading`
|
||||
|
||||
```html
|
||||
<div class="heading"></div>
|
||||
```
|
||||
|
||||
`div#heading`
|
||||
|
||||
```html
|
||||
<div id="heading"></div>
|
||||
```
|
||||
|
||||
ID and Class can also be combined together
|
||||
|
||||
`div#heading.center`
|
||||
|
||||
```html
|
||||
<div id="heading" class="center"></div>
|
||||
```
|
||||
|
||||
### Adding Content inside tags
|
||||
Contents inside tags can be added using `{}`
|
||||
|
||||
`h1{Emmet is awesome}+h2{Every front end developers should use this}+p{This is paragraph}*2`
|
||||
|
||||
```HTML
|
||||
<h1>Emmet is awesome</h1>
|
||||
<h2>Every front end developers should use this</h2>
|
||||
<p>This is paragraph</p>
|
||||
<p>This is paragraph</p>
|
||||
```
|
||||
|
||||
### Attributes inside HTML tags
|
||||
Attributes can be added using `[]`
|
||||
|
||||
`a[href=https://google.com data-toggle=something target=_blank]`
|
||||
|
||||
```HTML
|
||||
<a href="https://google.com" data-toggle="something" target="_blank"></a>
|
||||
```
|
||||
|
||||
### Numbering
|
||||
Numbering can be done using `$`
|
||||
You can use this inside tag or contents.
|
||||
|
||||
`h${This is so awesome $}*6`
|
||||
|
||||
```HTML
|
||||
<h1>This is so awesome 1</h1>
|
||||
<h2>This is so awesome 2</h2>
|
||||
<h3>This is so awesome 3</h3>
|
||||
<h4>This is so awesome 4</h4>
|
||||
<h5>This is so awesome 5</h5>
|
||||
<h6>This is so awesome 6</h6>
|
||||
```
|
||||
|
||||
Use `@-` to reverse the Numbering
|
||||
|
||||
`img[src=image$$@-.jpg]*5`
|
||||
|
||||
```HTML
|
||||
<img src="image05.jpg" alt="">
|
||||
<img src="image04.jpg" alt="">
|
||||
<img src="image03.jpg" alt="">
|
||||
<img src="image02.jpg" alt="">
|
||||
<img src="image01.jpg" alt="">
|
||||
```
|
||||
|
||||
To start the numbering from specific number, use this way
|
||||
|
||||
`img[src=emmet$@100.jpg]*5`
|
||||
|
||||
```HTML
|
||||
<img src="emmet100.jpg" alt="">
|
||||
<img src="emmet101.jpg" alt="">
|
||||
<img src="emmet102.jpg" alt="">
|
||||
<img src="emmet103.jpg" alt="">
|
||||
<img src="emmet104.jpg" alt="">
|
||||
```
|
||||
|
||||
## Tips
|
||||
* Use `:` to expand known abbreviations
|
||||
|
||||
`input:date`
|
||||
```HTML
|
||||
<input type="date" name="" id="">
|
||||
```
|
||||
|
||||
`form:post`
|
||||
```HTML
|
||||
<form action="" method="post"></form>
|
||||
```
|
||||
|
||||
`link:css`
|
||||
```html
|
||||
<link rel="stylesheet" href="style.css">
|
||||
```
|
||||
|
||||
* Building Navbar
|
||||
|
||||
`.navbar>ul>li*3>a[href=#]{Item $@-}`
|
||||
|
||||
```HTML
|
||||
<div class="navbar">
|
||||
<ul>
|
||||
<li><a href="#">Item 3</a></li>
|
||||
<li><a href="#">Item 2</a></li>
|
||||
<li><a href="#">Item 1</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
```
|
||||
|
||||
|
||||
## CSS
|
||||
|
||||
Emmet works surprisingly well with css as well.
|
||||
|
||||
* `f:l`
|
||||
|
||||
```css
|
||||
float: left;
|
||||
```
|
||||
|
||||
You can also use any options n/r/l
|
||||
|
||||
* `pos:a`
|
||||
|
||||
```css
|
||||
position: absolute;
|
||||
```
|
||||
|
||||
Also use any options, pos:a/r/f
|
||||
|
||||
* `d:n/b/f/i/ib`
|
||||
|
||||
`d:ib`
|
||||
|
||||
```css
|
||||
display: inline-block;
|
||||
```
|
||||
|
||||
* You can use `m` for margin and `p` for padding followed by direction
|
||||
|
||||
`mr` -> `margin-right`
|
||||
|
||||
`pr` -> `padding-right`
|
||||
|
||||
* `@f` will result in
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family:;
|
||||
src:url();
|
||||
}
|
||||
```
|
||||
|
||||
You can also use these shorthands
|
||||
|
||||
| Shorthand | Description |
|
||||
| ----------- | ----------- |
|
||||
| z | z-index |
|
||||
| w | width |
|
||||
| h | height |
|
||||
| fz | font-size |
|
||||
| ff | font-family |
|
||||
| fw | font-weight |
|
||||
| @lh | line-height |
|
||||
| maw | max-width |
|
||||
| mah | max-height |
|
||||
| miw | min-width |
|
||||
| mih | min-width |
|
||||
| ! | !important |
|
||||
| @f | font-face |
|
||||
| @op | opacity |
|
||||
| @lh | line-height |
|
||||
| @op | opacity |
|
||||
178
tools/gcp.md
Normal file
178
tools/gcp.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# GCLOUD SDK AND TOOLBELT CHEATSHEET
|
||||
|
||||
## GCP BASICS
|
||||
|
||||
- `Check Version and Settings`: gcloud version, gcloud info, gcloud components list
|
||||
|
||||
- `Init Profile`: gcloud init This will ask you to open an OpenID URL
|
||||
|
||||
- `List all zones`: gcloud compute zones list
|
||||
|
||||
- `Upgrade local SDK`: gcloud components update, gcloud components update --version 219.0.1
|
||||
|
||||
|
||||
## BUCKET BASICS
|
||||
|
||||
- `List all buckets and files`: gsutil ls, gsutil ls -lh gs://<bucket-name>
|
||||
|
||||
- `Download file`: gsutil cp gs://<bucket-name>/<dir-path>/package-1.1.tgz .
|
||||
|
||||
- `Upload file`: gsutil cp <filename> gs://<bucket-name>/<directory>/
|
||||
|
||||
- `Cat file`: gsutil cat gs://<bucket-name>/<filepath>/
|
||||
|
||||
- `Delete file`: gsutil rm gs://<bucket-name>/<filepath>
|
||||
|
||||
- `Move file`: gsutil mv <src-filepath> gs://<bucket-name>/<directory>/<dest-filepath>
|
||||
|
||||
- `Copy folder`: gsutil cp -r ./conf gs://<bucket-name>/
|
||||
|
||||
- `Show disk usage`: gsutil du -h gs://<bucket-name>/<directory>/
|
||||
|
||||
- `Create bucket`: gsutil mb gs://<bucket-name>
|
||||
|
||||
- `Caculate file sha1sum`: gsha1sum syslog-migration-10.0.2.tgz, shasum syslog-migration-10.0.2.tgz
|
||||
|
||||
- `Gsutil help`: gsutil help, gsutil help cp, gsutil help options
|
||||
|
||||
|
||||
## GCP PROJECT
|
||||
|
||||
- `List projects `: gcloud config list, gcloud config list project
|
||||
|
||||
- `Show project info `: gcloud compute project-info describe
|
||||
|
||||
- `Switch project `: gcloud config set project <project-id>
|
||||
|
||||
|
||||
## GKE
|
||||
|
||||
- `Display a list of credentialed accounts `: gcloud auth list
|
||||
|
||||
- `Set the active account `: gcloud config set account <ACCOUNT>
|
||||
|
||||
- `Set kubectl context `: gcloud container clusters get-credentials <cluster-name>
|
||||
|
||||
- `Change region `: gcloud config set compute/region us-west
|
||||
|
||||
- `Change zone `: gcloud config set compute/zone us-west1-b
|
||||
|
||||
- `List all container clusters `: gcloud container clusters list
|
||||
|
||||
|
||||
## IAM
|
||||
|
||||
- `Authenticate client `: gcloud auth activate-service-account --key-file <key-file>
|
||||
|
||||
- `Display a list of credentialed accounts `: gcloud auth list
|
||||
|
||||
- `Set the active account `: gcloud config set account <ACCOUNT>
|
||||
|
||||
- `Auth to GCP Container Registry `: gcloud auth configure-docker
|
||||
|
||||
- `Print token for active account `: gcloud auth print-access-token, gcloud auth print-refresh-token
|
||||
|
||||
- `Revoke previous generated credential `: gcloud auth <application-default> revoke
|
||||
|
||||
|
||||
## BUCKET SECURITY
|
||||
|
||||
- `Make all files readable `: gsutil -m acl set -R -a public-read gs://<bucket-name>/
|
||||
|
||||
- `Config auth `: gsutil config -a
|
||||
|
||||
- `Grant bucket access `: gsutil iam ch user:denny@gmail.com:objectCreator,objectViewer gs://<bucket-name>
|
||||
|
||||
- `Remove bucket access `: gsutil iam ch -d user:denny@gmail.com:objectCreator,objectViewer gs://<bucket-name>
|
||||
|
||||
|
||||
## VM
|
||||
|
||||
- `List all instances `: gcloud compute instances list, gcloud compute instance-templates list
|
||||
|
||||
- `Show instance info `: gcloud compute instances describe "<instance-name>" --project "<project-name>" --zone "us-west2-a"
|
||||
|
||||
- `Stop an instance `: gcloud compute instances stop instance-2
|
||||
|
||||
- `Start an instance `: gcloud compute instances start instance-2
|
||||
|
||||
- `Create an instance `: gcloud compute instances create vm1 --image image-1 --tags test --zone "<zone>" --machine-type f1-micro
|
||||
|
||||
- `SSH to instance `: gcloud compute ssh --project "<project-name>" --zone "<zone-name>" "<instance-name>"
|
||||
|
||||
- `Download files `: gcloud compute copy-files example-instance:~/REMOTE-DIR ~/LOCAL-DIR --zone us-central1-a
|
||||
|
||||
- `Upload files `: gcloud compute copy-files ~/LOCAL-FILE-1 example-instance:~/REMOTE-DIR --zone us-central1-a
|
||||
|
||||
|
||||
## DISKS & VOLUMES
|
||||
|
||||
- `List all disks `: gcloud compute disks list
|
||||
|
||||
- `List all disk types `: gcloud compute disk-types list
|
||||
|
||||
- `List all snapshots `: gcloud compute snapshots list
|
||||
|
||||
- `Create snapshot `: gcloud compute disks snapshot <diskname> --snapshotname <name1> --zone $zone
|
||||
|
||||
|
||||
## NETWORK
|
||||
|
||||
- `List all networks `: gcloud compute networks list
|
||||
|
||||
- `Detail of one network `: gcloud compute networks describe <network-name> --format json
|
||||
|
||||
- `Create network `: gcloud compute networks create <network-name>
|
||||
|
||||
- `Create subnet `: gcloud compute networks subnets create subnet1 --network net1 --range 10.5.4.0/24
|
||||
|
||||
- `Get a static ip `: gcloud compute addresses create --region us-west2-a vpn-1-static-ip
|
||||
|
||||
- `List all ip addresses `: gcloud compute addresses list
|
||||
|
||||
- `Describe ip address `: gcloud compute addresses describe <ip-name> --region us-central1
|
||||
|
||||
- `List all routes `: gcloud compute routes list
|
||||
|
||||
|
||||
## DNS
|
||||
|
||||
- `List of all record-sets in my zone `: gcloud dns record-sets list --zone my_zone
|
||||
|
||||
- `List first 10 DNS records `: gcloud dns record-sets list --zone my_zone --limit=10
|
||||
|
||||
|
||||
## FIREWALL
|
||||
|
||||
- `List all firewall rules `: gcloud compute firewall-rules list
|
||||
|
||||
- `List all forwarding rules `: gcloud compute forwarding-rules list
|
||||
|
||||
- `Describe one firewall rule `: gcloud compute firewall-rules describe <rule-name>
|
||||
|
||||
- `Create one firewall rule `: gcloud compute firewall-rules create my-rule --network default --allow tcp:9200 tcp:3306
|
||||
|
||||
- `Update one firewall rule `: gcloud compute firewall-rules update default --network default --allow tcp:9200 tcp:9300
|
||||
|
||||
|
||||
## IMAGES & CONTAINERS
|
||||
|
||||
- `List all images `: gcloud compute images list
|
||||
|
||||
- `List all container clusters `: gcloud container clusters list
|
||||
|
||||
- `Set kubectl context `: gcloud container clusters get-credentials <cluster-name>
|
||||
|
||||
|
||||
## RDS
|
||||
|
||||
- `List all sql instances `: gcloud sql instances list
|
||||
|
||||
|
||||
## SERVICES
|
||||
|
||||
- `List my backend services `: gcloud compute backend-services list
|
||||
|
||||
- `List all my health check endpoints `: gcloud compute http-health-checks list
|
||||
|
||||
- `List all URL maps `: gcloud compute url-maps list
|
||||
99
tools/git.sh
Normal file
99
tools/git.sh
Normal file
@@ -0,0 +1,99 @@
|
||||
git init # initiates git in the current directory
|
||||
git remote add origin https://github.com/repo_name.git # add remote reposiory
|
||||
git clone <address> # creates a git repo from given address (get the address from your git-server)
|
||||
git clone <address> -b <branch_name> <path/to/directory> # clones a git repo from the address into the given directory and checkout's the given branch
|
||||
git clone <address> -b <branch_name> --single-branch # Clones a single branch
|
||||
|
||||
git add file.txt # adds(stages) file.txt to the git
|
||||
git add * # adds(stages) all new modifications, deletions, creations to the git
|
||||
git reset file.txt # Removes file.txt from the stage
|
||||
git reset --hard # Throws away all your uncommitted changes, hard reset files to HEAD
|
||||
git rm file.txt # removes file.txt both from git and file system
|
||||
git rm --cached file.txt # only removes file.txt both from git index
|
||||
git status # shows the modifications and stuff that are not staged yet
|
||||
|
||||
git branch # shows all the branches (current branch is shown with a star)
|
||||
git branch my-branch # creates my-branch
|
||||
git branch -d my-branch # deletes my-branch
|
||||
git checkout my-branch # switches to my-branch
|
||||
git merge my-branch # merges my-branch to current branch
|
||||
git push origin --delete my-branch # delete remote branch
|
||||
git branch -m <new-branch-name> # rename the branch
|
||||
git checkout --orphan <branch_name> # checkout a branch with no commit history
|
||||
git branch -vv # list all branches and their upstreams, as well as last commit on branch
|
||||
git branch -a # List all local and remote branches
|
||||
|
||||
git cherry-pick <commit_id> # merge the specified commit
|
||||
git cherry-pick <commit_id_A>^..<commit_id_B> # pick the entire range of commits where A is older than B ( the ^ is for including A as well )
|
||||
|
||||
git remote # shows the remotes
|
||||
git remote -v # shows the remote for pull and push
|
||||
git remote add my-remote <address> # creates a remote (get the address from your git-server)
|
||||
git remote rm my-remote # Remove a remote
|
||||
|
||||
git log # shows the log of commits
|
||||
git log --oneline # shows the log of commits, each commit in a single line
|
||||
git log -p <file_name> # change over time for a specific file
|
||||
git log <Branch1> ^<Branch2> # lists commit(s) in branch1 that are not in branch2
|
||||
git log -n <x> # lists the last x commits
|
||||
git log -n <x> --oneline # lists the last x commits, each commit in single line
|
||||
git grep --heading --line-number '<string/regex>' # Find lines matching the pattern in tracked files
|
||||
git log --grep='<string/regex>' # Search Commit log
|
||||
|
||||
git commit -m "msg" # commit changes with a msg
|
||||
git commit --amend # combine staged changes with the previous commit, or edit the previous commit message without changing its snapshot
|
||||
git commit --amend --no-edit # amends a commit without changing its commit message
|
||||
git commit --amend --author='Author Name <email@address.com>' # Amend the author of a commit
|
||||
git push my-remote my-branch # pushes the commits to the my-remote in my-branch (does not push the tags)
|
||||
git revert <commit-id> # Undo a commit by creating a new commit
|
||||
|
||||
git show # shows one or more objects (blobs, trees, tags and commits).
|
||||
git diff # show changes between commits, commit and working tree
|
||||
git diff --color # show colored diff
|
||||
git diff --staged # Shows changes staged for commit
|
||||
|
||||
git tag # shows all the tags
|
||||
git tag -a v1.0 -m "msg" # creates an annotated tag
|
||||
git show v1.0 # shows the description of version-1.0 tag
|
||||
git tag --delete v1.0 # deletes the tag in local directory
|
||||
git push --delete my-remote v1.0 # deletes the tag in my-remote (be carefore to not delete a branch)
|
||||
git push my-remote my-branch v1.0 # push v1.0 tag to my-remote in my-branch
|
||||
git fetch --tags # pulls the tags from remote
|
||||
|
||||
git pull my-remote my-branch # pulls and tries to merge my-branch from my-remote to the current branch
|
||||
|
||||
git stash # stashes the staged and unstaged changes (git status will be clean after it)
|
||||
git stash -u # stash everything including new untracked files (but not .gitignore)
|
||||
git stash save "msg" # stash with a msg
|
||||
git stash list # list all stashes
|
||||
git stash pop # delete the recent stash and applies it
|
||||
git stash pop stash@{2} # delete the {2} stash and applies it
|
||||
git stash show # shows the description of stash
|
||||
git stash apply # keep the stash and applies it to the git
|
||||
git stash branch my-branch stash@{1} # creates a branch from your stash
|
||||
git stash drop stash@{1} # deletes the {1} stash
|
||||
git stash clear # clears all the stash
|
||||
|
||||
git rebase -i <commit_id> # Rebase commits from a commit ID
|
||||
git rebase --abort # Abort a running rebase
|
||||
git rebase --continue # Continue rebasing after fixing all conflicts
|
||||
|
||||
git clean -f # clean untracked files permanently
|
||||
git clean -f -d/git clean -fd # To remove directories permanently
|
||||
git clean -f -X/git clean -fX # To remove ignored files permanently
|
||||
git clean -f -x/git clean -fx # To remove ignored and non-ignored files permanently
|
||||
|
||||
git config --global --list # lists the git configuration for all repos
|
||||
git config --global --edit # opens an editor to edit the git config file
|
||||
git config --global alias.<handle> <command> # add git aliases to speed up workflow , eg. if handle is st and command is status then running git st would execute git status
|
||||
|
||||
|
||||
.gitignore
|
||||
# is a file including names of stuff that you don"t want to be staged or tracked.
|
||||
# You usually keep your local files like database, media, and etc here.
|
||||
# You can find good resources online about ignoring specific files in your project files.
|
||||
# .gitignore is also get ignored
|
||||
.git
|
||||
# is a hidden directory in repo directory including git files. It is created after "git init".
|
||||
|
||||
|
||||
118
tools/heroku.sh
Normal file
118
tools/heroku.sh
Normal file
@@ -0,0 +1,118 @@
|
||||
# ##############################################################################
|
||||
##### HEROKU TOOLBELT COMPLETE GUIDE ###########################################
|
||||
################################################################################
|
||||
|
||||
|
||||
|
||||
# Installing Heroku toolbelt using command line
|
||||
|
||||
# For MacOS...
|
||||
brew tap heroku/brew && brew install heroku
|
||||
|
||||
# For Ubuntu...
|
||||
sudo snap install --classic heroku
|
||||
|
||||
# Other installation methods are
|
||||
|
||||
curl https://cli-assets.heroku.com/install.sh | sh # only for unix based systems, windows incompatible as it needs sudo
|
||||
|
||||
curl https://cli-assets.heroku.com/install-ubuntu.sh | sh # Ubuntu/Debian apt-get
|
||||
|
||||
yay -S heroku-cli # Arch linux, Note: This package is community maintained not by heroku
|
||||
|
||||
npm install -g heroku # This installation method is required for users on ARM and BSD...
|
||||
|
||||
|
||||
############
|
||||
|
||||
# Verifying your installation
|
||||
|
||||
heroku --version
|
||||
|
||||
|
||||
# Let's get started with heroku
|
||||
|
||||
heroku login # To login into the heroku toolbelt with your heroku account, this will open browser for you.
|
||||
|
||||
heroku login -i # If you prefer to stay in the command line environment, then you can execute this command
|
||||
|
||||
|
||||
# Now navigate to your desired directory and create a blank heroku application
|
||||
|
||||
cd ~/myapp
|
||||
heorku create
|
||||
|
||||
|
||||
# If you are facing login issues, try to execute the following command
|
||||
|
||||
mv ~/.netrc ~/.netrc.backup
|
||||
heroku login
|
||||
|
||||
|
||||
# Uninstalling the heroku CLI
|
||||
|
||||
# For macOS
|
||||
rm -rf /usr/local/heroku /usr/local/lib/heroku /usr/local/bin/heroku ~/.local/share/heroku ~/Library/Caches/heroku
|
||||
|
||||
# or you can try the below command also on macOS
|
||||
brew uninstall heroku
|
||||
rm -rf ~/.local/share/heroku ~/Library/Caches/heroku
|
||||
|
||||
# For Linux (Standalone installs)
|
||||
rm /usr/local/bin/heroku
|
||||
rm -rf /usr/local/lib/heroku /usr/local/heroku
|
||||
rm -rf ~/.local/share/heroku ~/.cache/heroku
|
||||
|
||||
# For Linux (Debian and Ubuntu installs)
|
||||
sudo apt-get remove heroku heroku-toolbelt
|
||||
sudo rm /etc/apt/sources.list.d/heroku.list
|
||||
|
||||
|
||||
|
||||
|
||||
#####################################################################################################
|
||||
### Managing and deploying applications on Heroku (Using Git) ###################################
|
||||
#####################################################################################################
|
||||
|
||||
|
||||
cd myapp # Changing into the project directory
|
||||
git init # Initializing the project into a git repository
|
||||
git add -f example.json # Adding a perticular content of the project into the repository this will include the content from .gitignore
|
||||
git add . # Adding all the contents of the project into the repository excluding .gitignore content
|
||||
git commit -m "My first commit" # Commiting the content to the repository
|
||||
|
||||
heroku create appname # Creating a new application on Heroku here ( appname ) represent the name u give to your app
|
||||
git remote -v # verifying that the remote is set to the heroku
|
||||
|
||||
heroku git:remote -a thawing-inlet-61413 # For an existing heroku app, you can add remote to the application
|
||||
git remote rename heroku heroku-staging # renaming remotes
|
||||
|
||||
git push heroku master # Deploying code to the heroku application
|
||||
git push heroku master --force # Force Pushing to heroku ( required if the remote contain works that u do not have locally )
|
||||
git push heroku testbranch:master # Deploying code from a non-master branch to the heroku application
|
||||
|
||||
heroku create --ssh-git # ssh git transport for the application instead of https
|
||||
git config --global url.ssh://git@heroku.com/.insteadOf https://git.heroku.com/ # For using ssh always
|
||||
git config --global --remove-section url.ssh://git@heroku.com/ # To remove this rewrite setting run the command
|
||||
|
||||
|
||||
|
||||
|
||||
#####################################################################################################
|
||||
### Managing and deploying applications on Heroku (Using Docker) ###################################
|
||||
#####################################################################################################
|
||||
|
||||
# Setting stack of your app to a Container
|
||||
heroku stack:set container
|
||||
|
||||
heroku container:login # Login to the container resistry
|
||||
git clone https://github.com/heroku/alpinehelloworld.git # Get sample code by cloning into the following repository
|
||||
heroku create appname # Creating a heroku application here ( appname ) represent the name u give to your app
|
||||
|
||||
heroku container:push web # Build the image and push to Container Registry
|
||||
heroku container:push --recursive # Pushing from the root directory of the project in recursive manner
|
||||
heroku container:push web worker --recursive # Building the image and pushing to container resistry in recursive manner
|
||||
heroku container:release web # Releasing the image to your application
|
||||
|
||||
heroku open # Open the application in the browser
|
||||
|
||||
179
tools/kubernetes.md
Normal file
179
tools/kubernetes.md
Normal file
@@ -0,0 +1,179 @@
|
||||
# Kubernetes
|
||||
|
||||
* PDF: https://sematext.com/kubernetes-cheat-sheet/
|
||||
* WEBSITE: https://kubernetes.io/
|
||||
* DOCUMENTATION: https://kubernetes.io/docs/home
|
||||
|
||||
## Client Configuration
|
||||
|
||||
* Setup autocomplete in bash; bash-completion package should be installed first
|
||||
```
|
||||
source <(kubectl completion bash)
|
||||
```
|
||||
|
||||
* View Kubernetes config
|
||||
```
|
||||
kubectl config view
|
||||
```
|
||||
|
||||
* View specific config items by json path
|
||||
```
|
||||
kubectl config view -o jsonpath='{.users[?(@.name == "k8s")].user.password}'
|
||||
```
|
||||
|
||||
* Set credentials for `foo.kuberntes.com`
|
||||
```
|
||||
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
|
||||
```
|
||||
|
||||
* Set active namespace
|
||||
```
|
||||
kubectl config set-context --current --namespace=namespace_name
|
||||
```
|
||||
|
||||
## Viewing, Finding resources
|
||||
|
||||
* List all services in the namespace
|
||||
```
|
||||
kubectl get services
|
||||
```
|
||||
|
||||
* List all pods in all namespaces in wide format
|
||||
```
|
||||
kubectl get pods -o wide --all-namespaces
|
||||
```
|
||||
|
||||
* List all pods in json (or yaml) format
|
||||
```
|
||||
kubectl get pods -o json
|
||||
```
|
||||
|
||||
* Describe resource details (node, pod, svc)
|
||||
```
|
||||
kubectl describe nodes my-node
|
||||
```
|
||||
|
||||
* List services sorted by name
|
||||
```
|
||||
kubectl get services --sort-by=.metadata.name
|
||||
```
|
||||
|
||||
* List pods sorted by restart count
|
||||
```
|
||||
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
|
||||
```
|
||||
|
||||
* Rolling update pods for frontend-v1
|
||||
```
|
||||
kubectl rolling-update frontend-v1 -f frontend-v2.json
|
||||
```
|
||||
|
||||
* Scale a replicaset named 'foo' to 3
|
||||
```
|
||||
kubectl scale --replicas=3 rs/foo
|
||||
```
|
||||
|
||||
* Scale a resource specified in "foo.yaml" to 3
|
||||
```
|
||||
kubectl scale --replicas=3 -f foo.yaml
|
||||
```
|
||||
|
||||
* Execute a command in every pod / replica
|
||||
```
|
||||
for i in 0 1; do kubectl exec foo-$i -- sh -c 'echo $(hostname) > /usr/share/nginx/html/index.html'; done
|
||||
```
|
||||
|
||||
## Manage Resources
|
||||
|
||||
* Get documentation for pod or service
|
||||
```
|
||||
kubectl explain pods,svc
|
||||
```
|
||||
|
||||
* Create resource(s) like pods, services or daemonsets
|
||||
```
|
||||
kubectl create -f ./my-manifest.yaml
|
||||
```
|
||||
|
||||
* Apply a configuration to a resource
|
||||
```
|
||||
kubectl apply -f ./my-manifest.yaml
|
||||
```
|
||||
|
||||
* Start a single instance of Nginx
|
||||
```
|
||||
kubectl run nginx --image=nginx
|
||||
```
|
||||
|
||||
* Create a secret with several keys
|
||||
```
|
||||
cat <<EOF | kubectl create -f -
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: mysecret
|
||||
type: Opaque
|
||||
data:
|
||||
password: $(echo "s33msi4" | base64)
|
||||
username: $(echo "jane"| base64)
|
||||
EOF
|
||||
```
|
||||
|
||||
* Delete a resource
|
||||
```
|
||||
kubectl delete -f ./my-manifest.yaml
|
||||
```
|
||||
|
||||
## Monitoring & Logging
|
||||
|
||||
* Deploy Heapster from Github repository
|
||||
```
|
||||
kubectl create -f deploy/kube-config/standalone/
|
||||
```
|
||||
|
||||
* Show metrics for nodes
|
||||
```
|
||||
kubectl top node
|
||||
```
|
||||
|
||||
* Show metrics for pods
|
||||
```
|
||||
kubectl top pod
|
||||
```
|
||||
|
||||
* Show metrics for a given pod and its containers
|
||||
```
|
||||
kubectl top pod pod_name --containers
|
||||
```
|
||||
|
||||
* Dump pod logs (stdout)
|
||||
```
|
||||
kubectl logs pod_name
|
||||
```
|
||||
|
||||
* Stream pod container logs (stdout, multi-container case)
|
||||
```
|
||||
kubectl logs -f pod_name -c my-container
|
||||
```
|
||||
|
||||
## Interacting with running pods
|
||||
|
||||
* Run command in pod
|
||||
```
|
||||
kubectl exec pod_name -- command_name
|
||||
```
|
||||
|
||||
* Run command in pod with multiple containers
|
||||
```
|
||||
kubectl exec pod_name -c container_name -- command_name
|
||||
```
|
||||
|
||||
* Get terminal of pod
|
||||
```
|
||||
kubectl exec -it pod_name /bin/sh
|
||||
```
|
||||
|
||||
* Get terminal of a container running in pod with multiple containers
|
||||
```
|
||||
kubectl exec -it pod_name -c container_name /bin/sh
|
||||
```
|
||||
@@ -1,117 +0,0 @@
|
||||
##############################################################################
|
||||
# KUBERNETES
|
||||
# PDF: https://sematext.com/kubernetes-cheat-sheet/
|
||||
# WEBSITE: https://kubernetes.io/
|
||||
# DOCUMENTATION: https://kubernetes.io/docs/home
|
||||
##############################################################################
|
||||
|
||||
|
||||
##############################################################################
|
||||
# CLIENT CONFIGURATION
|
||||
##############################################################################
|
||||
|
||||
|
||||
# Setup autocomplete in bash; bash-completion package should be installed first
|
||||
source <(kubectl completion bash)
|
||||
|
||||
# View Kubernetes config
|
||||
kubectl config view
|
||||
|
||||
# View specific config items by json path
|
||||
kubectl config view -o jsonpath='{.users[?(@.name == "k8s")].user.password}'
|
||||
|
||||
# Set credentials for foo.kuberntes.com
|
||||
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
|
||||
|
||||
|
||||
##############################################################################
|
||||
# VIEWING, FINDING RESOURCES
|
||||
##############################################################################
|
||||
|
||||
|
||||
# List all services in the namespace
|
||||
kubectl get services
|
||||
|
||||
# List all pods in all namespaces in wide format
|
||||
kubectl get pods -o wide --all-namespaces
|
||||
|
||||
# List all pods in json (or yaml) format
|
||||
kubectl get pods -o json
|
||||
|
||||
# Describe resource details (node, pod, svc)
|
||||
kubectl describe nodes my-node
|
||||
|
||||
# List services sorted by name
|
||||
kubectl get services --sort-by=.metadata.name
|
||||
|
||||
# List pods sorted by restart count
|
||||
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
|
||||
|
||||
# Rolling update pods for frontend-v1
|
||||
kubectl rolling-update frontend-v1 -f frontend-v2.json
|
||||
|
||||
# Scale a replicaset named 'foo' to 3
|
||||
kubectl scale --replicas=3 rs/foo
|
||||
|
||||
# Scale a resource specified in "foo.yaml" to 3
|
||||
kubectl scale --replicas=3 -f foo.yaml
|
||||
|
||||
# Execute a command in every pod / replica
|
||||
for i in 0 1; do kubectl exec foo-$i -- sh -c 'echo $(hostname) > /usr/share/nginx/html/index.html'; done
|
||||
|
||||
|
||||
##############################################################################
|
||||
# MANAGE RESOURCES
|
||||
##############################################################################
|
||||
|
||||
|
||||
# Get documentation for pod or service
|
||||
kubectl explain pods,svc
|
||||
|
||||
# Create resource(s) like pods, services or daemonsets
|
||||
kubectl create -f ./my-manifest.yaml
|
||||
|
||||
# Apply a configuration to a resource
|
||||
kubectl apply -f ./my-manifest.yaml
|
||||
|
||||
# Start a single instance of Nginx
|
||||
kubectl run nginx --image=nginx
|
||||
|
||||
# Create a secret with several keys
|
||||
cat <<EOF | kubectl create -f -
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: mysecret
|
||||
type: Opaque
|
||||
data:
|
||||
password: $(echo "s33msi4" | base64)
|
||||
username: $(echo "jane"| base64)
|
||||
EOF
|
||||
|
||||
# Delete a resource
|
||||
kubectl delete -f ./my-manifest.yaml
|
||||
|
||||
|
||||
##############################################################################
|
||||
# MONITORING & LOGGING
|
||||
##############################################################################
|
||||
|
||||
|
||||
# Deploy Heapster from Github repository
|
||||
kubectl create -f deploy/kube-config/standalone/
|
||||
|
||||
# Show metrics for nodes
|
||||
kubectl top node
|
||||
|
||||
# Show metrics for pods
|
||||
kubectl top pod
|
||||
|
||||
# Show metrics for a given pod and its containers
|
||||
kubectl top pod pod_name --containers
|
||||
|
||||
# Dump pod logs (stdout)
|
||||
kubectl logs pod_name
|
||||
|
||||
# Stream pod container logs (stdout, multi-container case)
|
||||
kubectl logs -f pod_name -c my-container
|
||||
215
tools/nginx.sh
Normal file
215
tools/nginx.sh
Normal file
@@ -0,0 +1,215 @@
|
||||
##############################################################################
|
||||
# NGINX
|
||||
# DOCUMENTATION: https://nginx.org/en/docs/
|
||||
##############################################################################
|
||||
|
||||
sudo nginx -t # Check syntax
|
||||
sudo systemctl status nginx # nginx current status
|
||||
sudo systemctl reload nginx # Reload nginx
|
||||
sudo systemctl restart nginx # Restart nginx
|
||||
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ # Link website
|
||||
|
||||
# *****************************************************************************
|
||||
# General Settings
|
||||
# *****************************************************************************
|
||||
|
||||
# Ports
|
||||
|
||||
server {
|
||||
# Use HTTP protocol
|
||||
listen 80;
|
||||
|
||||
# Use HTTPS protocol
|
||||
listen 443 ssl;
|
||||
|
||||
# Listen on port 80 using IPv6
|
||||
listen [::]:80;
|
||||
|
||||
# Listen on port 80 using **only** IPv6
|
||||
listen [::]:80 ipv6only=on;
|
||||
}
|
||||
|
||||
# Domain name (server_name)
|
||||
|
||||
server {
|
||||
# Listen to example.com
|
||||
server_name example.com;
|
||||
|
||||
# Listen to multiple domains
|
||||
server_name example.com www.example.com;
|
||||
|
||||
# Listen to all sub-domains
|
||||
server_name *.example.com;
|
||||
|
||||
# Listen to all top-level domains
|
||||
server_name example.*;
|
||||
|
||||
# Listen to unspecified hostnames (listens to IP address itself)
|
||||
server_name "";
|
||||
}
|
||||
|
||||
# *****************************************************************************
|
||||
# Serving Files
|
||||
# *****************************************************************************
|
||||
|
||||
# Static assets (traditional web server)
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
|
||||
root /path/to/website;
|
||||
# root /www/data/ for example
|
||||
|
||||
# If there's no 'root' inside, it will look for /www/data/index.html
|
||||
location / {
|
||||
}
|
||||
|
||||
# If there's no 'root' inside, it will look for /www/data/images/index.html
|
||||
location /images/ {
|
||||
}
|
||||
|
||||
# Since there's 'root' inside, it will look for /www/media/videos/index.html
|
||||
location /videos/ {
|
||||
root /www/media;
|
||||
}
|
||||
}
|
||||
|
||||
# *****************************************************************************
|
||||
# Redirects
|
||||
# *****************************************************************************
|
||||
|
||||
# 301 Permanent
|
||||
|
||||
server {
|
||||
# Redirect www.example.com to example.com
|
||||
listen 80;
|
||||
server_name www.example.com;
|
||||
return 301 http://example.com$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
# Redirect http to https
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
return 301 https://example.com$request_uri;
|
||||
}
|
||||
|
||||
# 302 Temporary
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name yourdomain.com;
|
||||
return 302 http://otherdomain.com;
|
||||
}
|
||||
|
||||
# *****************************************************************************
|
||||
# Reverse proxy
|
||||
# *****************************************************************************
|
||||
|
||||
# Useful for Node.js, Streamlit, Jupyter, etc
|
||||
|
||||
# Basic
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
|
||||
location / {
|
||||
proxy_pass http://0.0.0.0:3000;
|
||||
# where 0.0.0.0:3000 is your Node.js Server bound on 0.0.0.0 listing on port 3000
|
||||
}
|
||||
}
|
||||
|
||||
# Basic + (upstream)
|
||||
|
||||
upstream node_js {
|
||||
server 0.0.0.0:3000;
|
||||
# where 0.0.0.0:3000 is your Node.js Server bound on 0.0.0.0 listing on port 3000
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
|
||||
location / {
|
||||
proxy_pass http://node_js;
|
||||
}
|
||||
}
|
||||
|
||||
# Upgraded Connection (useful for applications with support for WebSockets)
|
||||
|
||||
upstream node_js {
|
||||
server 0.0.0.0:3000;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
|
||||
location / {
|
||||
proxy_pass http://node_js;
|
||||
proxy_redirect off;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
# *****************************************************************************
|
||||
# HTTPS Protocol
|
||||
# *****************************************************************************
|
||||
|
||||
# The majority of SSL options depend on what your application does or needs
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name example.com;
|
||||
|
||||
ssl on;
|
||||
|
||||
ssl_certificate /path/to/cert.pem;
|
||||
ssl_certificate_key /path/to/privkey.pem;
|
||||
|
||||
ssl_stapling on;
|
||||
ssl_stapling_verify on;
|
||||
ssl_trusted_certificate /path/to/fullchain.pem;
|
||||
|
||||
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
|
||||
ssl_session_timeout 1d;
|
||||
ssl_session_cache shared:SSL:50m;
|
||||
add_header Strict-Transport-Security max-age=15768000;
|
||||
}
|
||||
|
||||
# Permanent redirect to HTTPS secured domain
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name yourdomain.com;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
# You can easily secure you website/app using Let's Encrypt.
|
||||
# Go https://certbot.eff.org/lets-encrypt/ubuntuxenial-nginx.html for more information
|
||||
|
||||
# *****************************************************************************
|
||||
# Load Balancing
|
||||
# *****************************************************************************
|
||||
|
||||
# Useful for large applications running in multiple instances. Below example is for reverse proxy
|
||||
upstream node_js {
|
||||
server 0.0.0.0:3000;
|
||||
server 0.0.0.0:4000;
|
||||
server 127.155.142.421;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
|
||||
location / {
|
||||
proxy_pass http://node_js;
|
||||
}
|
||||
}
|
||||
26
tools/pm2.sh
Normal file
26
tools/pm2.sh
Normal file
@@ -0,0 +1,26 @@
|
||||
##############################################################################
|
||||
# PM2
|
||||
##############################################################################
|
||||
|
||||
# Start commands
|
||||
pm2 start <file> # Start an application
|
||||
pm2 start <app_id> # Start a stopped application
|
||||
pm2 start <app_id> ecosystem.config.js # Start an app with the configuration in ecosystem file
|
||||
pm2 start <file> -i <number_of_instances> # Start an app in cluster mode with n duplicated instances
|
||||
|
||||
# Management commands
|
||||
pm2 ls # List all processes
|
||||
pm2 save # Save process list to respawn at reboot
|
||||
pm2 restart <app_id> # Restart an app by ID
|
||||
pm2 reload <app_id> # Reload an app by ID
|
||||
pm2 stop <app_id> # Stop an app by ID
|
||||
pm2 stop all # Stop all running instances
|
||||
pm2 delete <app_id> # Delete an app by ID
|
||||
pm2 delete all # Delete all instances
|
||||
pm2 ecosystem # Generate a sample ecosystem.config.js file
|
||||
|
||||
# Monitoring
|
||||
pm2 show <app_id> # Show a specific app's description
|
||||
pm2 logs <app_id> --lines=<number_of_lines> # Show the last n lines of logs of an app
|
||||
pm2 env <app_id> # Show all environment variables of an app
|
||||
pm2 monit # Monitor all applications' logs, metrics,etc
|
||||
477
tools/puppeteer.js
Normal file
477
tools/puppeteer.js
Normal file
@@ -0,0 +1,477 @@
|
||||
/* *******************************************************************************************
|
||||
* PUPPETEER
|
||||
* https://pptr.dev/
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win)
|
||||
// that is guaranteed to work with the API.
|
||||
npm install puppeteer
|
||||
|
||||
// A lightweight version of Puppeteer for launching an existing browser installation or for connecting to a remote one.
|
||||
// Be sure that the version of puppeteer-core you install is compatible with the browser you intend to connect to.
|
||||
// More about the difference between puppeteer vs puppeteer-core
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-puppeteer-vs-puppeteer-core
|
||||
npm install puppeteer-core
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* ENVIRONMENT VARIABLES
|
||||
* ******************************************************************************************* */
|
||||
|
||||
HTTP_PROXY // Defines HTTP proxy settings that are used to download and run Chromium.
|
||||
HTTPS_PROXY // Defines HTTP proxy settings that are used to download and run Chromium.
|
||||
NO_PROXY // Defines HTTP proxy settings that are used to download and run Chromium.
|
||||
|
||||
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD // Do not download bundled Chromium during installation step.
|
||||
PUPPETEER_DOWNLOAD_HOST // Overwrite URL prefix that is used to download Chromium. Note: this includes protocol and might even include path prefix. Defaults to https://storage.googleapis.com.
|
||||
PUPPETEER_CHROMIUM_REVISION // Specify a certain version of Chromium you'd like Puppeteer to use. See puppeteer.launch([options]) on how executable path is inferred. BEWARE: Puppeteer is only guaranteed to work with the bundled Chromium, use at your own risk.
|
||||
PUPPETEER_EXECUTABLE_PATH // Specify an executable path to be used in puppeteer.launch. See puppeteer.launch([options]) on how the executable path is inferred. BEWARE: Puppeteer is only guaranteed to work with the bundled Chromium, use at your own risk.
|
||||
PUPPETEER_PRODUCT // Specify which browser you'd like Puppeteer to use. Must be one of chrome or firefox. Setting product programmatically in puppeteer.launch([options]) supercedes this environment variable. The product is exposed in puppeteer.product
|
||||
|
||||
/* *******************************************************************************************
|
||||
* API
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// PUPPETEER
|
||||
// -----
|
||||
// Puppeteer module provides a method to launch a Chromium instance.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-puppeteer
|
||||
|
||||
const puppeteer = require('puppeteer');
|
||||
|
||||
puppeteer.devices; // Returns a list of devices to be used with page.emulate(options)
|
||||
puppeteer.errors; // Returns the specific error classes
|
||||
puppeteer.product; // Returns the name of the browser that is under automation ("chrome" or "firefox")
|
||||
|
||||
puppeteer.connect(options); // Attaches Puppeteer to an existing Chromium instance.
|
||||
puppeteer.createBrowserFetcher([options]); // Create a brower fetcher instance
|
||||
puppeteer.defaultArgs([options]); // The default flags that Chromium will be launched with.
|
||||
puppeteer.executablePath(); // Returns a path where Puppeteer expects to find bundled Chromium.
|
||||
puppeteer.launch([options]); // Launch a browser instance
|
||||
|
||||
// BROWSER FETCHER
|
||||
// -----
|
||||
// BrowserFetcher can download and manage different versions of Chromium.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-browserfetcher
|
||||
|
||||
const browserFetcher = puppeteer.createBrowserFetcher();
|
||||
|
||||
browserFetcher.canDownload(revision) // Initiates a HEAD request to check if the revision is available.
|
||||
browserFetcher.download(revision[, progressCallback]) // Initiates a GET request to download the revision from the host.
|
||||
browserFetcher.localRevisions() // Returns a list of all revisions available locally on disk.
|
||||
browserFetcher.platform() // Returns one of mac, linux, win32 or win64.
|
||||
browserFetcher.remove(revision) // Resolves when the revision has been removed.
|
||||
browserFetcher.revisionInfo(revision) // Returns all the information on the revision.
|
||||
|
||||
// BROWSER
|
||||
// -----
|
||||
// A Browser is created when Puppeteer connects to a Chromium instance, either through puppeteer.launch or puppeteer.connect.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-browser
|
||||
|
||||
const browser = await puppeteer.launch();
|
||||
|
||||
browser.on('disconnected') // Emitted when Puppeteer gets disconnected from the Chromium instance.
|
||||
browser.on('targetchanged') // Emitted when the url of a target changes.
|
||||
browser.on('targetcreated') // Emitted when a target is created, for example when a new page is opened by window.open or browser.newPage.
|
||||
browser.on('targetdestroyed') // Emitted when a target is destroyed, for example when a page is closed.
|
||||
|
||||
browser.browserContexts() // Returns an array of all open browser contexts.
|
||||
browser.close() // Closes Chromium and all of its pages (if any were opened).
|
||||
browser.createIncognitoBrowserContext() // Creates a new incognito browser context.
|
||||
browser.defaultBrowserContext() // Returns the default browser context.
|
||||
browser.disconnect() // Disconnects Puppeteer from the browser, but leaves the Chromium process running.
|
||||
browser.isConnected() // Indicates that the browser is connected.
|
||||
browser.newPage() // Promise which resolves to a new Page object.
|
||||
browser.pages() // An array of all pages inside the Browser.
|
||||
browser.process() // Returns Spawned browser process.
|
||||
browser.target() // A target associated with the browser.
|
||||
browser.targets() // An array of all active targets inside the Browser.
|
||||
browser.userAgent() // Promise which resolves to the browser's original user agent.
|
||||
browser.version() // Returns the browser version (e.g. Chrome/61.0.3153.0)
|
||||
browser.waitForTarget(predicate[, options]) // Promise which resolves to the first target found that matches the predicate function.
|
||||
browser.wsEndpoint() // Returns the browser websocket url.
|
||||
|
||||
// BROWSER CONTEXT
|
||||
// -----
|
||||
// BrowserContexts provide a way to operate multiple independent browser sessions
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-browsercontext
|
||||
|
||||
const context = await browser.createIncognitoBrowserContext();
|
||||
|
||||
browserContext.on('targetchanged') // Emitted when the url of a target inside the browser context changes.
|
||||
browserContext.on('targetcreated') // Emitted when a new target is created inside the browser context.
|
||||
browserContext.on('targetdestroyed') // Emitted when a target inside the browser context is destroyed, for example when a page is closed.
|
||||
|
||||
browserContext.browser() // The browser this browser context belongs to.
|
||||
browserContext.clearPermissionOverrides() // Clears all permission overrides for the browser context.
|
||||
browserContext.close() // Closes the browser context. All the targets that belong to the browser context will be closed.
|
||||
browserContext.isIncognito() // Returns whether BrowserContext is incognito.
|
||||
browserContext.newPage() // Creates a new page in the browser context.
|
||||
browserContext.overridePermissions(origin, permissions) // Overrides permissions to grant.
|
||||
browserContext.pages() // An array of all pages inside the browser context.
|
||||
browserContext.targets() // An array of all active targets inside the browser context.
|
||||
browserContext.waitForTarget(predicate[, options]) // Promise which resolves to the first target found that matches the predicate function.
|
||||
|
||||
// PAGE
|
||||
// -----
|
||||
// Page provides methods to interact with a single tab or extension background page in Chromium.
|
||||
// One Browser instance might have multiple Page instances.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-page
|
||||
|
||||
const page = await browser.newPage();
|
||||
|
||||
page.on('close') // Emitted when the page closes.
|
||||
page.on('console') // Emitted when JavaScript within the page calls one of console API methods.
|
||||
page.on('dialog') // Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload.
|
||||
page.on('domcontentloaded') // Emitted when the JavaScript DOMContentLoaded event is dispatched.
|
||||
page.on('error') // Emitted when the page crashes.
|
||||
page.on('frameattached') // Emitted when a frame is attached.
|
||||
page.on('framedetached') // Emitted when a frame is detached.
|
||||
page.on('framenavigated') // Emitted when a frame is navigated to a new url.
|
||||
page.on('load') // Emitted when the JavaScript load event is dispatched.
|
||||
page.on('metrics') // Emitted when the JavaScript code makes a call to console.timeStamp.
|
||||
page.on('pageerror') // Emitted when an uncaught exception happens within the page.
|
||||
page.on('popup') // Emitted when the page opens a new tab or window.
|
||||
page.on('request') // Emitted when a page issues a request.
|
||||
page.on('requestfailed') // Emitted when a request fails, for example by timing out.
|
||||
page.on('requestfinished') // Emitted when a request finishes successfully.
|
||||
page.on('response') // Emitted when a response is received.
|
||||
page.on('workercreated') // Emitted when a dedicated WebWorker is spawned by the page.
|
||||
page.on('workerdestroyed') // Emitted when a dedicated WebWorker is terminated.
|
||||
|
||||
page.accessibility // returns Accessibility
|
||||
page.coverage // returns Coverage
|
||||
page.keyboard // returns Keyboard
|
||||
page.mouse // returns Mouse
|
||||
page.touchscreen // returns Touchscreen
|
||||
page.tracing // returns Tracing
|
||||
|
||||
page.$(selector) // The method runs document.querySelector within the page. If no element matches the selector, the return value resolves to null.
|
||||
page.$$(selector) // The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolves to [].
|
||||
page.$eval(selector, pageFunction[, ...args]) // This method runs document.querySelector within the page and passes it as the first argument to pageFunction. If there's no element matching selector, the method throws an error.
|
||||
page.$$eval(selector, pageFunction[, ...args]) // This method runs Array.from(document.querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction.
|
||||
page.$x(expression) // The method evaluates the XPath expression.
|
||||
page.addScriptTag(options) // Adds a <script> tag into the page with the desired url or content.
|
||||
page.addStyleTag(options) // Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content.
|
||||
page.authenticate(credentials) // Provide credentials for HTTP authentication.
|
||||
page.bringToFront() // Brings page to front (activates tab).
|
||||
page.browser() // Get the browser the page belongs to.
|
||||
page.browserContext() // Get the browser context that the page belongs to.
|
||||
page.click(selector[, options]) // This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.
|
||||
page.close([options]) // Close the page
|
||||
page.content() // Gets the full HTML contents of the page, including the doctype.
|
||||
page.cookies([...urls]) // If no URLs are specified, this method returns cookies for the current page URL. If URLs are specified, only cookies for those URLs are returned.
|
||||
page.deleteCookie(...cookies) // Delete a cookie
|
||||
page.emulate(options) // Emulates given device metrics and user agent.
|
||||
page.emulateMediaFeatures(features) // Emulates CSS media features on the page.
|
||||
page.emulateMediaType(type) // Changes the CSS media type of the page.
|
||||
page.emulateTimezone(timezoneId) // Changes the timezone of the page.
|
||||
page.evaluate(pageFunction[, ...args]) // Evaluate the page.
|
||||
page.evaluateHandle(pageFunction[, ...args]) // Evaluate the page and return returns in-page object (JSHandle).
|
||||
page.evaluateOnNewDocument(pageFunction[, ...args]) // Adds a function which would be invoked whenever the page is navigated or whenever the child frame is attached or navigated.
|
||||
page.exposeFunction(name, puppeteerFunction) // Adds a function called name on the page's window object.
|
||||
page.focus(selector) // Fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.
|
||||
page.frames() // Returns an array of all frames attached to the page.
|
||||
page.goBack([options]) // Navigate to the previous page in history.
|
||||
page.goForward([options]) // Navigate to the next page in history.
|
||||
page.goto(url[, options]) // Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
|
||||
page.hover(selector) // Fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to hover over the center of the element.
|
||||
page.isClosed() // Indicates that the page has been closed.
|
||||
page.mainFrame() // Returns the page's main frame.
|
||||
page.metrics() // Returns an object containing the page metrics.
|
||||
page.pdf([options]) // Generates a pdf of the page with print css media.
|
||||
page.queryObjects(prototypeHandle) // Iterates the JavaScript heap and finds all the objects with the given prototype.
|
||||
page.reload([options]) // Reloads the page.
|
||||
page.screenshot([options]) // Takes a screenshot.
|
||||
page.select(selector, ...values) // Triggers a change and input event once all the provided options have been selected. If there's no <select> element matching selector, the method throws an error.
|
||||
page.setBypassCSP(enabled) // Toggles bypassing page's Content-Security-Policy.
|
||||
page.setCacheEnabled([enabled]) // Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.
|
||||
page.setContent(html[, options]) // Asssigns HTML markup to the page.
|
||||
page.setCookie(...cookies) // Sets a cookie.
|
||||
page.setDefaultNavigationTimeout(timeout) // Changes the default maximum navigation timeout (see docs for the concerned methods).
|
||||
page.setDefaultTimeout(timeout) // Changes the default maximum navigation timeout (for all methods).
|
||||
page.setExtraHTTPHeaders(headers) // Sets extra HTTP headers to be sent with every request the page initiates.
|
||||
page.setGeolocation(options) // Sets the page's geolocation.
|
||||
page.setJavaScriptEnabled(enabled) // Whether or not to enable JavaScript on the page.
|
||||
page.setOfflineMode(enabled) // When true, enables offline mode for the page.
|
||||
page.setRequestInterception(value) // Whether to enable request interception.
|
||||
page.setUserAgent(userAgent) // Sets the specific user agent to use in this page.
|
||||
page.setViewport(viewport) // Sets the viewport.
|
||||
page.tap(selector) // This method fetches an element with selector, scrolls it into view if needed, and then uses page.touchscreen to tap in the center of the element. If there's no element matching selector, the method throws an error.
|
||||
page.target() // Returns a target this page was created from.
|
||||
page.title() // Returns the page title.
|
||||
page.type(selector, text[, options]) // Sends a keydown, keypress/input, and keyup event for each character in the text.
|
||||
page.url() // This is a shortcut for page.mainFrame().url()
|
||||
page.viewport() // Returns the viewport information.
|
||||
page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]]) // Wait for the element to appear.
|
||||
page.waitForFileChooser([options]) // Wait for the file chooser.
|
||||
page.waitForFunction(pageFunction[, options[, ...args]]) // Wait for the function.
|
||||
page.waitForNavigation([options]) // Wait for navigation.
|
||||
page.waitForRequest(urlOrPredicate[, options]) // Wait for the request.
|
||||
page.waitForResponse(urlOrPredicate[, options]) // Wait for the response.
|
||||
page.waitForSelector(selector[, options]) // Wait for the selector.
|
||||
page.waitForXPath(xpath[, options]) // Wait for the XPath selector.
|
||||
page.workers() // Returns all of the dedicated WebWorkers associated with the page.
|
||||
|
||||
// WORKER
|
||||
// -----
|
||||
// The Worker class represents a WebWorker.
|
||||
// The events workercreated and workerdestroyed are emitted on the page object to signal the worker lifecycle.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-worker
|
||||
|
||||
worker.evaluate(pageFunction[, ...args]) // Evaluate a function in the worker context.
|
||||
worker.evaluateHandle(pageFunction[, ...args]) // Evaluate a function in the worker context and returns in-page object (JSHandle).
|
||||
worker.executionContext() // Returns ExecutionContext.
|
||||
worker.url() // Returns worker url.
|
||||
|
||||
// ACCESSIBILITY
|
||||
// -----
|
||||
// The Accessibility class provides methods for inspecting Chromium's accessibility tree.
|
||||
// The accessibility tree is used by assistive technology such as screen readers or switches.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-accessibility
|
||||
|
||||
accessibility.snapshot([options]) // Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.
|
||||
|
||||
// KEYBOARD
|
||||
// -----
|
||||
// Keyboard provides an api for managing a virtual keyboard.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-keyboard
|
||||
|
||||
keyboard.down(key[, options]) // Dispatches a keydown event.
|
||||
keyboard.press(key[, options]) // Shortcut for keyboard.down and keyboard.up.
|
||||
keyboard.sendCharacter(char) // Dispatches a keypress and input event. This does not send a keydown or keyup event.
|
||||
keyboard.type(text[, options]) // Sends a keydown, keypress/input, and keyup event for each character in the text.
|
||||
keyboard.up(key) // Dispatches a keyup event.
|
||||
|
||||
// MOUSE
|
||||
// -----
|
||||
// The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-mouse
|
||||
|
||||
mouse.click(x, y[, options]) // Shortcut for mouse.move, mouse.down and mouse.up.
|
||||
mouse.down([options]) // Dispatches a mousedown event.
|
||||
mouse.move(x, y[, options]) // Dispatches a mousemove event.
|
||||
mouse.up([options]) // Dispatches a mouseup event.
|
||||
|
||||
// TOUCHSCREEN
|
||||
// -----
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-touchscreen
|
||||
|
||||
touchscreen.tap(x, y) // Dispatches a touchstart and touchend event.
|
||||
|
||||
// TRACING
|
||||
// -----
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-tracing
|
||||
|
||||
tracing.start([options]) // Start trace.
|
||||
tracing.stop() // Stop trace.
|
||||
|
||||
// FILE CHOOSER
|
||||
// -----
|
||||
// FileChooser objects are returned via the 'page.waitForFileChooser' method.
|
||||
// File choosers let you react to the page requesting for a file.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-filechooser
|
||||
|
||||
fileChooser.accept(filePaths) // Accept the file chooser request with given paths.
|
||||
fileChooser.cancel() // Closes the file chooser without selecting any files.
|
||||
fileChooser.isMultiple() // Returns whether file chooser allow for multiple file selection.
|
||||
|
||||
// DIALOG
|
||||
// -----
|
||||
// Dialog objects are dispatched by page via the 'dialog' event.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-dialog
|
||||
|
||||
dialog.accept([promptText]) // Resolves when the dialog has been accepted.
|
||||
dialog.defaultValue() // If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
|
||||
dialog.dismiss() // Resolves when the dialog has been dismissed.
|
||||
dialog.message() // Returns a message displayed in the dialog.
|
||||
dialog.type() // Returns dialog's type, can be one of: alert, beforeunload, confirm or prompt.
|
||||
|
||||
// CONSOLE MESSAGE
|
||||
// -----
|
||||
// ConsoleMessage objects are dispatched by page via the 'console' event.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-consolemessage
|
||||
|
||||
consoleMessage.args() // Returns JSHandle.
|
||||
consoleMessage.location() // Returns location.
|
||||
consoleMessage.text() // Returns message text.
|
||||
consoleMessage.type() // Returns message type.
|
||||
|
||||
// FRAME
|
||||
// -----
|
||||
// At every point of time, page exposes its current frame tree via the page.mainFrame() and frame.childFrames() methods.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-frame
|
||||
|
||||
frame.$(selector) // The method queries frame for the selector. If there's no such element within the frame, the method will resolve to null.
|
||||
frame.$$(selector) // The method runs document.querySelectorAll within the frame. If no elements match the selector, the return value resolves to [].
|
||||
frame.$$eval(selector, pageFunction[, ...args]) // This method runs Array.from(document.querySelectorAll(selector)) within the frame and passes it as the first argument to pageFunction.
|
||||
frame.$eval(selector, pageFunction[, ...args]) // This method runs document.querySelector within the frame and passes it as the first argument to pageFunction. If there's no element matching selector, the method throws an error.
|
||||
frame.$x(expression) // The method evaluates the XPath expression.
|
||||
frame.addScriptTag(options) // Adds a <script> tag into the page with the desired url or content.
|
||||
frame.addStyleTag(options) // Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content.
|
||||
frame.childFrames() // Returns all child frames.
|
||||
frame.click(selector[, options]) // This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.
|
||||
frame.content() // Gets the full HTML contents of the frame, including the doctype.
|
||||
frame.evaluate(pageFunction[, ...args]) // Evaluates function in the context of the frame.
|
||||
frame.evaluateHandle(pageFunction[, ...args]) // Evaluates function in the context of the frame and returns JSHandle.
|
||||
frame.executionContext() // Returns promise that resolves to the frame's default execution context.
|
||||
frame.focus(selector) // This method fetches an element with selector and focuses it. If there's no element matching selector, the method throws an error.
|
||||
frame.goto(url[, options]) // Goes to url.
|
||||
frame.hover(selector) // This method fetches an element with selector, scrolls it into view if needed, and then uses page.mouse to hover over the center of the element. If there's no element matching selector, the method throws an error.
|
||||
frame.isDetached() // Returns true if the frame has been detached, or false otherwise.
|
||||
frame.name() // Returns frame's name attribute as specified in the tag.
|
||||
frame.parentFrame() // Returns parent frame if any.
|
||||
frame.select(selector, ...values) // Triggers a change and input event once all the provided options have been selected. If there's no <select> element matching selector, the method throws an error.
|
||||
frame.setContent(html[, options]) // Set content in iframe.
|
||||
frame.tap(selector) // This method fetches an element with selector, scrolls it into view if needed, and then uses page.touchscreen to tap in the center of the element. If there's no element matching selector, the method throws an error.
|
||||
frame.title() // Returns the page's title.
|
||||
frame.type(selector, text[, options]) // Sends a keydown, keypress/input, and keyup event for each character in the text.
|
||||
frame.url() // Returns frame's url.
|
||||
frame.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]]) // Wait for something.
|
||||
frame.waitForFunction(pageFunction[, options[, ...args]]) // Wait for function.
|
||||
frame.waitForNavigation([options]) // Wait for navigation.
|
||||
frame.waitForSelector(selector[, options]) // Wait for selector.
|
||||
frame.waitForXPath(xpath[, options]) // Wait for XPath selector.
|
||||
|
||||
// EXECUTION CONTEXT
|
||||
// -----
|
||||
// The class represents a context for JavaScript execution.
|
||||
// Besides pages, execution contexts can be found in workers.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-executioncontext
|
||||
|
||||
executionContext.evaluate(pageFunction[, ...args]) // Evaluate function in execution context.
|
||||
executionContext.evaluateHandle(pageFunction[, ...args]) // Evaluate function in execution context and returns JSHandle.
|
||||
executionContext.frame() // Returns frame associated with this execution context.
|
||||
executionContext.queryObjects(prototypeHandle) // The method iterates the JavaScript heap and finds all the objects with the given prototype.
|
||||
|
||||
// JSHANDLE
|
||||
// -----
|
||||
// JSHandle represents an in-page JavaScript object.
|
||||
// JSHandles can be created with the page.evaluateHandle method.
|
||||
// const windowHandle = await page.evaluateHandle(() => window);
|
||||
|
||||
jsHandle.asElement() // Returns either null or the object handle itself, if the object handle is an instance of ElementHandle.
|
||||
jsHandle.dispose() // Resolves when the object handle is successfully disposed.
|
||||
jsHandle.evaluate(pageFunction[, ...args]) // Evaluate function in the execution context the handle belongs to.
|
||||
jsHandle.evaluateHandle(pageFunction[, ...args]) // Evaluate function in the execution context the handle belongs to and returns JS handle.
|
||||
jsHandle.executionContext() // Returns execution context the handle belongs to.
|
||||
jsHandle.getProperties() // Returns a map with property names as keys and JSHandle instances for the property values.
|
||||
jsHandle.getProperty(propertyName) // Fetches a single property from the referenced object.
|
||||
jsHandle.jsonValue() // Returns a JSON representation of the object. If the object has a toJSON function, it will not be called.
|
||||
|
||||
// ELEMENTHANDLE
|
||||
// -----
|
||||
// ElementHandle represents an in-page DOM element.
|
||||
// ElementHandles can be created with the page.$ method.
|
||||
// const hrefElement = await page.$('a');
|
||||
|
||||
elementHandle.$(selector) // The method runs element.querySelector within the page. If no element matches the selector, the return value resolves to null.
|
||||
elementHandle.$$(selector) // The method runs element.querySelectorAll within the page. If no elements match the selector, the return value resolves to [].
|
||||
elementHandle.$$eval(selector, pageFunction[, ...args]) // This method runs document.querySelectorAll within the element and passes it as the first argument to pageFunction. If there's no element matching selector, the method throws an error.
|
||||
elementHandle.$eval(selector, pageFunction[, ...args]) // This method runs document.querySelector within the element and passes it as the first argument to pageFunction. If there's no element matching selector, the method throws an error.
|
||||
elementHandle.$x(expression) // The method evaluates the XPath expression relative to the elementHandle. If there are no such elements, the method will resolve to an empty array.
|
||||
elementHandle.asElement() // Returns ElementHandle.
|
||||
elementHandle.boundingBox() // Returns the bounding box of the element (relative to the main frame), or null if the element is not visible.
|
||||
elementHandle.boxModel() // Returns boxes of the element, or null if the element is not visible.
|
||||
elementHandle.click([options]) // This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element. If the element is detached from DOM, the method throws an error.
|
||||
elementHandle.contentFrame() // Resolves to the content frame for element handles referencing iframe nodes, or null otherwise
|
||||
elementHandle.dispose() // Stops referencing the element handle.
|
||||
elementHandle.evaluate(pageFunction[, ...args]) // Evaluates function in the execution content the element handle belongs to.
|
||||
elementHandle.evaluateHandle(pageFunction[, ...args]) // Evaluates function in the execution content the element handle belongs to and returns JS handle.
|
||||
elementHandle.executionContext() // Returns execution context.
|
||||
elementHandle.focus() // Calls focus on the element.
|
||||
elementHandle.getProperties() // The method returns a map with property names as keys and JSHandle instances for the property values.
|
||||
elementHandle.getProperty(propertyName) // Fetches a single property from the objectHandle.s
|
||||
elementHandle.hover() // This method scrolls element into view if needed, and then uses page.mouse to hover over the center of the element. If the element is detached from DOM, the method throws an error.
|
||||
elementHandle.isIntersectingViewport() // Resolves to true if the element is visible in the current viewport.
|
||||
elementHandle.jsonValue() // Returns a JSON representation of the object.
|
||||
elementHandle.press(key[, options]) // Focuses the element, and then uses keyboard.down and keyboard.up.
|
||||
elementHandle.screenshot([options]) // This method scrolls element into view if needed, and then uses page.screenshot to take a screenshot of the element.
|
||||
elementHandle.select(...values) // Triggers a change and input event once all the provided options have been selected. If there's no <select> element matching selector, the method throws an error.
|
||||
elementHandle.tap() // This method scrolls element into view if needed, and then uses touchscreen.tap to tap in the center of the element. If the element is detached from DOM, the method throws an error.
|
||||
elementHandle.toString() // Returns string.
|
||||
elementHandle.type(text[, options]) // Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.
|
||||
elementHandle.uploadFile(...filePaths) // Uploads file.
|
||||
|
||||
// REQUEST
|
||||
// -----
|
||||
// Represents a request which are sent by a page.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-request
|
||||
|
||||
request.abort([errorCode]) // Aborts request.
|
||||
request.continue([overrides]) // Continues request with optional request overrides.
|
||||
request.failure() // The method returns null unless this request was failed, as reported by requestfailed event.
|
||||
request.frame() // Returns the Frame that initiated this request, or null if navigating to error pages.
|
||||
request.headers() // Returns an object with HTTP headers associated with the request. All header names are lower-case.
|
||||
request.isNavigationRequest() // Whether this request is driving frame's navigation.
|
||||
request.method() // Returns Request's method (GET, POST, etc.)
|
||||
request.postData() // Returns Request's post body, if any.
|
||||
request.redirectChain() // Returns the redirect chain.
|
||||
request.resourceType() // Returns the request's resource type as it was perceived by the rendering engine.
|
||||
request.respond(response) // Fulfills request with given response.
|
||||
request.response() // Returns a matching Response object, or null if the response has not been received yet.
|
||||
request.url() // Returns URL of the request.
|
||||
|
||||
// RESPONSE
|
||||
// -----
|
||||
// Response class represents responses which are received by page.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-response
|
||||
|
||||
response.buffer() // Resolves to a buffer with response body.
|
||||
response.frame() // Returns the frame that initiated this response, or null if navigating to error pages.
|
||||
response.fromCache() // True if the response was served from either the browser's disk cache or memory cache.
|
||||
response.fromServiceWorker() // True if the response was served by a service worker.
|
||||
response.headers() // Returns an object with HTTP headers associated with the response. All header names are lower-case.
|
||||
response.json() // Resolves to a JSON representation of response body.
|
||||
response.ok() // Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
|
||||
response.remoteAddress() // Returns remote address.
|
||||
response.request() // Retuns the matching Request object.
|
||||
response.securityDetails() // Returns the security details if the response was received over the secure connection, or null otherwise.
|
||||
response.status() // Contains the status code of the response (e.g., 200 for a success).
|
||||
response.statusText() // Contains the status text of the response (e.g. usually an "OK" for a success).
|
||||
response.text() // Resolves to a text representation of response body.
|
||||
response.url() // Contains the URL of the response.
|
||||
|
||||
// SECURITY DETAILS
|
||||
// -----
|
||||
// SecurityDetails class represents the security details when response was received over the secure connection.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-securitydetails
|
||||
|
||||
securityDetails.issuer() // Returns a string with the name of issuer of the certificate.
|
||||
securityDetails.protocol() // Returns a string with the security protocol, eg. "TLS 1.2".
|
||||
securityDetails.subjectName() // Returns the name of the subject to which the certificate was issued to.
|
||||
securityDetails.validFrom() // Returns UnixTime stating the start of validity of the certificate.
|
||||
securityDetails.validTo() // Returns UnixTime stating the end of validity of the certificate.
|
||||
|
||||
// TARGET
|
||||
// -----
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-target
|
||||
|
||||
target.browser() // Get the browser the target belongs to.
|
||||
target.browserContext() // Returns the browser context.
|
||||
target.createCDPSession() // Creates a Chrome Devtools Protocol session attached to the target.
|
||||
target.opener() // Get the target that opened this target. Top-level targets return null.
|
||||
target.page() // Returns the page.
|
||||
target.type() // Identifies what kind of target this is.
|
||||
target.url() // Returns url.
|
||||
target.worker() // Returns worker.
|
||||
|
||||
// CDPSESSION
|
||||
// -----
|
||||
// The CDPSession instances are used to talk raw Chrome Devtools Protocol
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-cdpsession
|
||||
|
||||
cdpSession.detach() // Detaches the cdpSession from the target. Once detached, the cdpSession object won't emit any events and can't be used to send messages.
|
||||
cdpSession.send(method[, params]) // Send message.
|
||||
|
||||
// COVERAGE
|
||||
// -----
|
||||
// Coverage gathers information about parts of JavaScript and CSS that were used by the page.
|
||||
// https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-class-coverage
|
||||
|
||||
coverage.startCSSCoverage([options]) // Start CSS coverage.
|
||||
coverage.startJSCoverage([options]) // Start JS coverage.
|
||||
coverage.stopCSSCoverage() // Stop CSS coverage.
|
||||
coverage.stopJSCoverage() // Stop JS coverage.
|
||||
145
tools/sublime_text.md
Normal file
145
tools/sublime_text.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# SUBLIME TEXT 3 CHEATSHEET
|
||||
|
||||
## Access every command with the command palette
|
||||
|
||||
- `shift + cmd + P `: Command palette
|
||||
|
||||
|
||||
## Goto anything
|
||||
|
||||
- `cmd + P `: Goto file
|
||||
|
||||
- `ctrl + G `: Goto line
|
||||
|
||||
- `cmd + P `: Fuzzy search
|
||||
|
||||
- `cmd + R `: Goto symbol
|
||||
|
||||
|
||||
## Quick selections
|
||||
|
||||
- `cmd + D `: Select word
|
||||
|
||||
- `cmd + K, cmd + D `: Skip and add next
|
||||
|
||||
- `cmd + U `: Undo quick select
|
||||
|
||||
- `cmd + L `: Select line
|
||||
|
||||
- `ctrl + cmd + G `: Select all in file
|
||||
|
||||
- `shift + cmd + space `: Expand selection to scope
|
||||
|
||||
- `shift + cmd + L `: Split into lines
|
||||
|
||||
|
||||
## Edit code
|
||||
|
||||
- `cmd + J `: Join 2 lines
|
||||
|
||||
- `cmd + shift + D `: Duplicate line
|
||||
|
||||
- `cmd + shift + R `: Reindent
|
||||
|
||||
- `cmd + shift + K `: Delete line
|
||||
|
||||
- `ctrl + cmd + up/down `: Move line/selection up/down
|
||||
|
||||
- `alt + cmd + V `: Paste from history
|
||||
|
||||
- `shift + cmd + / `: Comment/uncomment line
|
||||
|
||||
- `alt + backspace `: Delete word by word
|
||||
|
||||
- `alt + fn + backspace `: Forward delete word by word
|
||||
|
||||
- `cmd + shift + enter `: Insert line before
|
||||
|
||||
- `cmd + enter `: Insert line after
|
||||
|
||||
- `ctrl + k, ctrl + l ` : To Lowercase
|
||||
|
||||
- `ctrl + k, ctrl + u ` : To Uppercase
|
||||
|
||||
|
||||
## Searching
|
||||
|
||||
- `cmd + F `: Search in file
|
||||
|
||||
- `shift + cmd + F `: Search in all files
|
||||
|
||||
- `<open files> `: where filter
|
||||
|
||||
|
||||
## Miscelaneous
|
||||
|
||||
- `alt + cmd + right/left `: Switch open tab
|
||||
|
||||
- `ctrl + ]`: Indent selection
|
||||
|
||||
- `ctrl + [ `: Unindent selection
|
||||
|
||||
- `alt + - `: Go to previous cursor position
|
||||
|
||||
- `alt + shift + - `: Go to next previous cursor position
|
||||
|
||||
- `ctrl + b `: Build and execute file
|
||||
|
||||
|
||||
## Must have packages
|
||||
|
||||
`A file icon, BracketHighlighter, Color Highlighter, Comment-Snippets, DevDocs, EditorConfig, Emmet, File Rename, Git, Git blame, GitGutter, HTML-CSS-JS Prettify, JavaScript Completions, JavaScript Patterns, JavaScript Snippets, LESS, Nodejs, Package Control, Pretty JSON, SideBarEnhancements, SublimeLinter, SublimeLinter-contrib-eslint, Terminal, Termius, auto save`
|
||||
|
||||
|
||||
## Preferences
|
||||
|
||||
```javascript
|
||||
{
|
||||
"color_scheme": "Packages/User/Color Highlighter/themes/Boxy Ocean.tmTheme",
|
||||
"detect_indentation": false,
|
||||
"folder_exclude_patterns":
|
||||
[
|
||||
"node_modules",
|
||||
".svn",
|
||||
".git",
|
||||
".meteor/local"
|
||||
],
|
||||
"ignored_packages":
|
||||
[
|
||||
"Vintage"
|
||||
],
|
||||
"show_definitions": true,
|
||||
"theme": "Adaptive.sublime-theme"
|
||||
}
|
||||
```
|
||||
|
||||
## Keymap
|
||||
|
||||
```javascript
|
||||
[
|
||||
{ "keys": ["super+v"], "command": "paste_and_indent" },
|
||||
{ "keys": ["super+shift+v"], "command": "paste" },
|
||||
{ "keys": ["super+shift+r"], "command": "reindent" },
|
||||
{ "keys": ["super+h"], "command": "dev_docs_search_selection" }
|
||||
]
|
||||
|
||||
```
|
||||
|
||||
## Syncing settings with iCloud
|
||||
|
||||
- `cd ~/Library/Application\ Support/Sublime\ Text\ 3/Packages`
|
||||
|
||||
- `mkdir -p ~/Library/Mobile\ Documents/com\~apple\~CloudDocs/WebDev/ST3/Plugins`
|
||||
|
||||
- `mv User ~/Library/Mobile\ Documents/com\~apple\~CloudDocs/WebDev/ST3/Plugins`
|
||||
|
||||
- `ln -s ~/Library/Mobile\ Documents/com\~apple\~CloudDocs/WebDev/ST3/Plugins/User`
|
||||
|
||||
|
||||
## Restore settings from iCloud
|
||||
|
||||
- `cd ~/Library/Application\ Support/Sublime\ Text\ 3/Packages`
|
||||
|
||||
- `rm -rf User`
|
||||
|
||||
- `ln -s ~/Library/Mobile\ Documents/com\~apple\~CloudDocs/WebDev/ST3/Plugins/User`
|
||||
19
tools/ubuntu.sh
Normal file
19
tools/ubuntu.sh
Normal file
@@ -0,0 +1,19 @@
|
||||
##############################################################################
|
||||
# UBUNTU
|
||||
##############################################################################
|
||||
|
||||
scp /path/to/file user@server:/path/to/destination # Copy file from local to server
|
||||
|
||||
df -h # Check the amount of free space
|
||||
|
||||
sudo ufw status # Check status
|
||||
sudo ufw allow from remote_IP_address to any port 3306 # Allow external ip to access port
|
||||
|
||||
scp user@remote_host:remote_file local_file # download: remote -> local
|
||||
scp local_file user@remote_host:remote_file # upload: local -> remote
|
||||
|
||||
sudo -s # Log as root
|
||||
|
||||
cat /proc/<process_id>/maps # Show the current virtual memory usage of a Linux process
|
||||
|
||||
ip r # Display ip of the server
|
||||
@@ -87,6 +87,7 @@ J join line below to the current one
|
||||
cc change (replace) an entire line
|
||||
cw change (replace) to the end of word
|
||||
C change (replace) to the end of line
|
||||
ct' change (replace) until the ' character (can change ' for any character)
|
||||
s delete character at cursor and substitute text
|
||||
S delete line at cursor and substitute text (same as cc)
|
||||
xp transpose two letters (delete and paste, technically)
|
||||
@@ -118,6 +119,7 @@ x delete current character
|
||||
X delete previous character
|
||||
dw delete the current word
|
||||
dd delete (cut) a line
|
||||
dt' delete until the next ' character on the line (replace ' by any character)
|
||||
D delete from cursor to end of line
|
||||
:[range]d delete [range] lines
|
||||
|
||||
@@ -232,6 +234,8 @@ n repeat search in same direction
|
||||
N repeat search in opposite direction
|
||||
* search forward, word under cursor
|
||||
# search backward, word under cursor
|
||||
set ic ignore case: turn on
|
||||
set noic ignore case: turn off
|
||||
:%s/old/new/g replace all old with new throughout file
|
||||
:%s/old/new/gc replace all old with new throughout file with confirmation
|
||||
:argdo %s/old/new/gc | wq open multiple files and run this command to replace old
|
||||
@@ -251,6 +255,8 @@ N repeat search in opposite direction
|
||||
:bd delete a buffer (close a file)
|
||||
:b1 show buffer 1
|
||||
:b vimrc show buffer whose filename begins with "vimrc"
|
||||
:bufdo <command> run 'command(s)' in all buffers
|
||||
:[range]bufdo <command> run 'command(s)' for buffers in 'range'
|
||||
|
||||
|
||||
##############################################################################
|
||||
@@ -275,6 +281,7 @@ CTRL-w < increase window width
|
||||
CTRL-w > decrease window width
|
||||
CTRL-w = equal window
|
||||
CTRL-w o close other windows
|
||||
zz Centers the window to the current line
|
||||
|
||||
|
||||
##############################################################################
|
||||
|
||||
@@ -4,85 +4,97 @@
|
||||
|
||||
### HTML & CSS
|
||||
|
||||
- `CSScomb`: Codeing style formatter for CSS, Less, SCSS and Saas.
|
||||
- [`CSScomb`](https://marketplace.visualstudio.com/items?itemName=mrmlnc.vscode-csscomb): Coding style formatter for CSS, Less, SCSS and Saas.
|
||||
|
||||
- `Puglint`: Linter and style checker for pug.
|
||||
- [`Puglint`](https://marketplace.visualstudio.com/items?itemName=mrmlnc.vscode-puglint): Linter and style checker for pug.
|
||||
|
||||
- `Sass`: Indented Sass syntax highlighting, autocomplete & snippets.
|
||||
- [`Sass`](https://marketplace.visualstudio.com/items?itemName=Syler.sass-indented): Indented Sass syntax highlighting, autocomplete & snippets.
|
||||
|
||||
- `SCSS IntelliSense`: Advanced autocompletion and refactoring support for SCSS.
|
||||
- [`SCSS IntelliSense`](https://marketplace.visualstudio.com/items?itemName=mrmlnc.vscode-scss): Advanced autocompletion and refactoring support for SCSS.
|
||||
|
||||
- [`XML Format`](https://marketplace.visualstudio.com/items?itemName=mikeburgh.xml-format): Format XML documents.
|
||||
|
||||
### JavaScript, Node & NPM
|
||||
|
||||
- `Import Cost`: This extension will display inline in the editor the size of the imported package.
|
||||
- [`Import Cost`](https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost): This extension will display inline in the editor the size of the imported package.
|
||||
|
||||
- `ESLint`: Integrates ESLint into VS Code
|
||||
- [`ESLint`](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint): Integrates ESLint into VS Code
|
||||
|
||||
- `NPM`: NPM support for VS Code.
|
||||
- [`NPM`](https://marketplace.visualstudio.com/items?itemName=eg2.vscode-npm-script): NPM support for VS Code.
|
||||
|
||||
- `NPM Intellisense`: Visual Studio Code plugin that autocompletes NPM modules in import statements.
|
||||
- [`NPM Intellisense`](https://marketplace.visualstudio.com/items?itemName=christian-kohler.npm-intellisense): Visual Studio Code plugin that autocompletes NPM modules in import statements.
|
||||
|
||||
- `Version Lens`: Shows the latest version for each package using code lens.
|
||||
- [`Version Lens`](https://marketplace.visualstudio.com/items?itemName=pflannery.vscode-versionlens): Shows the latest version for each package using code lens.
|
||||
|
||||
- `Vetur`: Vue tooling for VS Code.
|
||||
- [`Vetur`](https://marketplace.visualstudio.com/items?itemName=octref.vetur): Vue tooling for VS Code.
|
||||
|
||||
### PHP
|
||||
|
||||
- `Better PHPUnit`: A better PHPUnit test runner.
|
||||
- [`Better PHPUnit`](https://marketplace.visualstudio.com/items?itemName=calebporzio.better-phpunit): A better PHPUnit test runner.
|
||||
|
||||
- `Laravel Artisan`: Laravel Artisan commands within Visual Studio Code.
|
||||
- [`Laravel Artisan`](https://marketplace.visualstudio.com/items?itemName=ryannaddy.laravel-artisan): Laravel Artisan commands within Visual Studio Code.
|
||||
|
||||
- `PHP CS Fixer`: PHP CS Fixer extension for VS Code, php formatter, php code beautify tool.
|
||||
- [`PHP CS Fixer`](https://marketplace.visualstudio.com/items?itemName=junstyle.php-cs-fixer): PHP CS Fixer extension for VS Code, php formatter, php code beautify tool.
|
||||
|
||||
- `PHP Doc Comment VSCode Plugin`: Add phpdoc @param and @return tag for selected function signatures.
|
||||
- [`PHP Doc Comment VSCode Plugin`](https://marketplace.visualstudio.com/items?itemName=rexshi.phpdoc-comment-vscode-plugin): Add phpdoc @param and @return tag for selected function signatures.
|
||||
|
||||
- `PHP IntelliSense`: Advanced Autocompletion and Refactoring support for PHP.
|
||||
- [`PHP IntelliSense`](https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-intellisense): Advanced Autocompletion and Refactoring support for PHP.
|
||||
|
||||
### Perl
|
||||
|
||||
- [`Perl`](https://marketplace.visualstudio.com/items?itemName=cfgweb.vscode-perl): Code intelligence for the Perl language.
|
||||
|
||||
- [`Perl Toolbox`](https://marketplace.visualstudio.com/items?itemName=d9705996.perl-toolbox): Perl Toolbox for linting and syntax checking for Perl.
|
||||
|
||||
- [`Perl Moose`](https://marketplace.visualstudio.com/items?itemName=torrentalle.perl-moose): Perl Moose syntax highlight support for Visual Studio Code.
|
||||
|
||||
### Git
|
||||
|
||||
- `Git History`: View git log, file history, compare branches or commits.
|
||||
- [`Git History`](https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory): View git log, file history, compare branches or commits.
|
||||
|
||||
- `Gitignore`: A extension for Visual Studio Code that assists you in working with .gitignore files.
|
||||
- [`Gitignore`](https://marketplace.visualstudio.com/items?itemName=codezombiech.gitignore): An extension for Visual Studio Code that assists you in working with .gitignore files.
|
||||
|
||||
### Themes
|
||||
|
||||
- `Material Icon Theme`: Material Design Icons for Visual Studio Code.
|
||||
- [`Material Icon Theme`](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme): Material Design Icons for Visual Studio Code.
|
||||
|
||||
- `Palenight Theme`: An elegant and juicy material-like theme for Visual Studio Code.
|
||||
- [`Palenight Theme`](https://marketplace.visualstudio.com/items?itemName=whizkydee.material-palenight-theme): An elegant and juicy material-like theme for Visual Studio Code.
|
||||
|
||||
### Handy
|
||||
|
||||
- `Debugger for Chrome`: Debug your JavaScript code in the Chrome browser.
|
||||
- [`Better comments`](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments): Improve your code commenting by annotating with alert, informational, TODOs, and more!
|
||||
|
||||
- `EditorConfig for VS Code`: EditorConfig Support for Visual Studio Code.
|
||||
- [`Debugger for Chrome`](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome): Debug your JavaScript code in the Chrome browser.
|
||||
|
||||
- `File Utils`: A convenient way of creating, duplicating, moving, renaming and deleting files and directories.
|
||||
- [`EditorConfig for VS Code`](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig): EditorConfig Support for Visual Studio Code.
|
||||
|
||||
- `Final-Newline`: Inserts a final newline when saving the document.
|
||||
- [`File Utils`](https://marketplace.visualstudio.com/items?itemName=sleistner.vscode-fileutils): A convenient way of creating, duplicating, moving, renaming and deleting files and directories.
|
||||
|
||||
- `Formatting Toggle`: A VS Code extension that allows you to toggle the formatter (Prettier, Beautify, …) ON and OFF with a simple click.
|
||||
- [`Final-Newline`](https://marketplace.visualstudio.com/items?itemName=samverschueren.final-newline): Inserts a final newline when saving the document.
|
||||
|
||||
- `Open in Github/Bitbucket...`: Jump to a source code line in Github / Bitbucket, Gitlab, VisualStudio.com
|
||||
- [`Formatting Toggle`](https://marketplace.visualstudio.com/items?itemName=tombonnike.vscode-status-bar-format-toggle): A VS Code extension that allows you to toggle the formatter (Prettier, Beautify, …) ON and OFF with a simple click.
|
||||
|
||||
- `OpenChrome`: Open file with Chrome.
|
||||
- [`Open in Github/Bitbucket...`](https://marketplace.visualstudio.com/items?itemName=ziyasal.vscode-open-in-github): Jump to a source code line in Github / Bitbucket, Gitlab, VisualStudio.com
|
||||
|
||||
- `Output Colorizer`: Syntax Highlighting for log files.
|
||||
- [`OpenChrome`](https://marketplace.visualstudio.com/items?itemName=huazaierli.openchrome&ssr=false#overview): Open file with Chrome.
|
||||
|
||||
- `Prettier - Code formatter`: VS Code plugin for prettier/prettier.
|
||||
- [`Output Colorizer`](https://marketplace.visualstudio.com/items?itemName=IBM.output-colorizer): Syntax Highlighting for log files.
|
||||
|
||||
- `Project Manager`: Easily switch between projects.
|
||||
- [`Prettier - Code formatter`](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode): VS Code plugin for prettier/prettier.
|
||||
|
||||
- `REST Client`: REST Client for Visual Studio Code.
|
||||
- [`Project Manager`](https://marketplace.visualstudio.com/items?itemName=alefragnani.project-manager): Easily switch between projects.
|
||||
|
||||
- `SVG Viewer`: SVG Viewer for Visual Studio Code.
|
||||
- [`REST Client`](https://marketplace.visualstudio.com/items?itemName=humao.rest-client): REST Client for Visual Studio Code.
|
||||
|
||||
- `Terminal`: Terminal for Visual Studio Code.
|
||||
- [`SVG Viewer`](https://marketplace.visualstudio.com/items?itemName=cssho.vscode-svgviewer): SVG Viewer for Visual Studio Code.
|
||||
|
||||
- `Vue Peek`: Allows peek and goto definition for Vue single-file components.
|
||||
- [`Terminal`](https://marketplace.visualstudio.com/items?itemName=formulahendry.terminal): Terminal for Visual Studio Code.
|
||||
|
||||
- `VS Live Share`: Real-time collaborative development from the comfort of your favorite tools.
|
||||
- [`Vue Peek`](https://marketplace.visualstudio.com/items?itemName=dariofuzinato.vue-peek): Allows peek and goto definition for Vue single-file components.
|
||||
|
||||
- `Wrap Console Log`: Wrap to console.log by word or selection.
|
||||
- [`VS Live Share`](https://marketplace.visualstudio.com/items?itemName=MS-vsliveshare.vsliveshare): Real-time collaborative development from the comfort of your favorite tools.
|
||||
|
||||
- [`Wrap Console Log`](https://marketplace.visualstudio.com/items?itemName=midnightsyntax.vscode-wrap-console-log): Wrap to console.log by word or selection.
|
||||
|
||||
## My Settings
|
||||
|
||||
|
||||
Reference in New Issue
Block a user