Make various corrections to notes

This commit is contained in:
Marcello 2021-07-12 16:18:53 +02:00
parent 411d740dd4
commit 23c1d6578f
16 changed files with 82 additions and 79 deletions

View file

@ -328,7 +328,7 @@ db.getCollectionNames().forEach(function(collection) {
print("Indexes for " + collection + ":");
printjson(indexes);
});
db.<collection>.getIndexes() # view collenction's index
db.<collection>.getIndexes() # view collection's index
db.<collection>.dropIndexes() # drop all indexes
db.<collection>.dropIndex( { "index-name": 1 } ) # drop a specific index

View file

@ -85,7 +85,7 @@ The body contains the actual content of the page. Everything that is contained i
## JavaScript
XHTML and older: `<script src="js/scripts.js" type="text/javascript"></script>`
HTML5: `<script src="js/scripts.js"></script>` (HTML5 spect states that `type` attribute is redundant and shoul be omitted)
HTML5: `<script src="js/scripts.js"></script>` (HTML5 spect states that `type` attribute is redundant and shoul be omitted)
The `<script>` tag is used to define a client-side script (JavaScript).
The `<script>` element either contains scripting statements, or it points to an external script file through the src attribute.

View file

@ -55,7 +55,7 @@ System.out.print(output_1 + _ + output_n);
[String.format() Examples](https://dzone.com/articles/java-string-format-examples)
```java
System.out.printf("stringa %..", variable);
System.out.printf("string %..", variable);
System.out.println(String.format(format, args));
```
@ -79,11 +79,11 @@ Scanner scanner = new Scanner(System.in); //Scanner obj init
scanner.useDelimiter("delimitatore"); //delimiter setting
scanner.close() //closing of Scanner, releases memory
int variabile_int_1 = scanner.nextInt(); //takes integer number
int variable_int_1 = scanner.nextInt(); //takes integer number
String string_1 = scanner.nextLine(); //takes line of text (\n ends line)
String string_1 = scanner.next(); //takes text (spacec ends word)
double variabile_double_1 = scanner.nextDouble(); //takes double decimal number
boolean variabile_bool = scanner.netxBoolean(); //takes boolean value
double variable_double_1 = scanner.nextDouble(); //takes double decimal number
boolean variable_bool = scanner.netxBoolean(); //takes boolean value
//(TRUE, FALSE, true, false, True, False)
```
@ -137,8 +137,8 @@ Type variable = new WrapperClass(primitiveValue); //automatic unboxing
WrapperClass.MIN_VALUE //constant holding min possible value of wrapper class
WrapperClass.MAX_VALUE //constant holding man possible value of wrapper class
ClasseWrapper.parseClasseWrapper(stringa); //converte il valore di una stringa in uno della classe wrapper (metodo statico), eccezione NumberFOrmatException se l'operazione fallisce
ClasseWrapper.toString(valore_tipo_primitivo); //converte il valore della classe wrapper in una string (metodo statico)
WrapperClass.parseClasseWrapper(string); // converts the tring to the wrapper class, NumberFOrmatException on error
WrapperClass.toString(primitive); // converts the wrapper class value to a string
```
### String & Char
@ -167,7 +167,7 @@ Escape Character | Character
### String Concatenation
The value of the variable is appende to the string literal.
`"text" + variabile`
`"text" + variable`
String are immutable. Concatenation creates a new string.
### String Conversion to Number

View file

@ -7,7 +7,7 @@ The document object is *globally available* in the browser. It allows to access
### Selecting Nodes from the DOM
`getElementById()` and `querySelector()` return a single element.
`getElementById()` and `querySelector()` return a single element.
`getElementsByClassName()`, `getElementsByTagName()`, and `querySelectorAll()` return a collection of elements.
```js
@ -16,14 +16,14 @@ Javascript
var node = document.getElementById('id');
// By Tag Name
var node = document.getElementsByTagName('tag');
var nodes = document.getElementsByTagName('tag');
// By Class Name
var node = document.getElementsByClassName('class');
var nodes = document.getElementsByClassName('class');
// By CSS Query
var node = document.querySelector('css-selector');
var node = document.querySelectorAll('css-selector');
var nodes = document.querySelectorAll('css-selector');
```
## Manupulating the DOM
@ -119,7 +119,7 @@ document.createTextNode('text');
domNode.appendChild(childToAppend); // insert childTaAppend after domNode
// insert node before domNode
domNode.insertBEfore(childToInsert, domnode);
domNode.insertBefore(childToInsert, domnode);
domNode.parentNode.insertBefore(childToInsert, nodeAfterChild);
// remove a node

View file

@ -63,6 +63,9 @@ window.setInterval(callbackFunction, delayMilliseconds);
//To stop an animation store the timer into a variable and clear it
window.clearTimeout(timer);
window.clearInterval(timer);
// execute a callback at each frame
window.requestAnimationFrame(callbackFunction);
```
### Element Position & dimensions

View file

@ -28,16 +28,15 @@
*/
```
### Naming Conventions
| Elements | Case |
| -------- | --------- |
| variable | camelCase |
### Modern Mode
If located at the top of the script the whole script works the “modern” way (enables post-ES5 functionalities).
`"use strict"`
```js
"use strict"
// script contents
```
### Pop-Up message
@ -328,8 +327,7 @@ if (condition) {
### Ternary Operator
`condition ? instruction1 : istruction2;`
Ff TRUE execute instruction1, execute instruction2 otherwise.
`condition ? <expr1> : <expr2>;`
### Switch Statement
@ -480,6 +478,7 @@ for(let key in dict) {
// do something with "key" and "value" variables
}
Object.keys(dict).forEach(key => { });
```
## Functions

View file

@ -11,7 +11,7 @@ https.request(
method: "GET", // POST, ...
path: "/page/?param=value"
},
(response) => { // respnse is IncomingMessage
(response) => { // response is IncomingMessage
// do stuff
}
).end();

View file

@ -62,7 +62,7 @@ $stmt->execute();
By default PDO converts all results into strings since it is a generic driver for multiple databases.
Its possible to disable this behaviour setting `PDO::ATTR_STRINGIFY_FETCHES` and `PDO::ATTR_EMULATE_PREPARES` as `false`.
**NOTE**: `FETCH_OBJ` abd `FETCH_CLASS` return classes and don't have this bheaviour.
**NOTE**: `FETCH_OBJ` abd `FETCH_CLASS` return classes and don't have this behaviour.
```php
pdo->setAttribute()
@ -82,7 +82,7 @@ $stmt = $pdo->prepare($sql);
$stmt->execute([':marker' => value]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->debugDumpParams(); # print the SQK query that has been sent to the database
$stmt->debugDumpParams(); # print the SQL query that has been sent to the database
```
## [SQLite3](https://www.php.net/manual/en/book.sqlite3.php)

View file

@ -15,7 +15,6 @@ class Foo
## Dependency Injection Container
The **Dependecy Injection Container** (DIC) allow to archive all the dependencies in a single `Container` class. Some offer automatic resolution of the dependecies.
Containers aid the developer in the handling of the dependecies: get/has/set.
## [PHP-DI](https://php-di.org/)

View file

@ -15,7 +15,7 @@ declare(strict_types=1); # activates variable type checking on function argumen
include "path\\file.php"; # import an external php file, E_WARNING if fails
include_once "path\\file.php"; # imports only if not already loaded
require "path\\file.php"; # # import an external php file, E_COMPILE_ERROR if fails
require "path\\file.php"; # import an external php file, E_COMPILE_ERROR if fails
require_once "path\\file.php"; # imports only if not already loaded
```
@ -34,7 +34,7 @@ return [
```
```php
$config = include "config.php"; // retireve config wnd store into variable
$config = include "config.php"; // retireve config and store into variable
```
## Namespace
@ -136,12 +136,12 @@ $c = 7E-10; // 0.0000000007
### Mathematical Operators
| Operator | Operation |
|----------|----------------|
| -------- | -------------- |
| `-` | Subtraction |
| `*` | Multiplication |
| `/` | Division |
| `%` | Modulo |
| `**` | Exponentiatio |
| `**` | Exponentiation |
| `var++` | Post Increment |
| `++var` | Pre Increment |
| `var--` | Post Decrement |
@ -164,7 +164,7 @@ A string is a sequrnce of ASCII characters. In PHP a string is an array of chara
### String Concatenation
```php
$string1 . $string2; method 1
$string1 . $string2; # method 1
$string1 .= $string2; # method 2
```
@ -190,7 +190,7 @@ define ('CONSTANT_NAME', 'value')
### Magic Constants `__NAME__`
- `__FILE__`: sctipt path + scrit filename
- `__FILE__`: script path + script filename
- `__DIR__`: file directory
- `__LINE__`: current line number
- `__FUNCTION__`: the function name, or {closure} for anonymous functions.
@ -261,7 +261,7 @@ list($array1 [, $array2, ...]) = $data; # Python-like tuple unpacking
### Associative Arrays
Associative arrays have a value as an index. Alternative names are *hash tables* or *dictionaries*.
Associative arrays have a value as an index. Alternative names are _hash tables_ or _dictionaries_.
```php
$italianDay = [
@ -282,7 +282,7 @@ $italianDay["Mon"]; # evaluates to Lunedì
### Conditional Opeartors
| Operator | Operation |
|-------------|--------------------------|
| ----------- | ------------------------ |
| $a `==` $b | value equality |
| $a `===` $b | value & type equality |
| $a `!=` $b | value inequality |
@ -299,13 +299,13 @@ With `==` a string evaluates to `0`.
### Logical Operators
| Operator | Example | Result |
|----------|-------------|------------------------------------------------------|
| -------- | ----------- | ---------------------------------------------------- | --- | ------------------------------------ |
| `and` | `$a and $b` | TRUE if both `$a` and `$b` are TRUE. |
| `or` | `$a or $b` | TRUE if either `$a` or `$b` is TRUE. |
| `xor` | `$a xor $b` | TRUE if either `$a` or `$b` is TRUE, but *not both*. |
| `not` | `!$a` | TRUE if `$a` is *not* TRUE. |
| `xor` | `$a xor $b` | TRUE if either `$a` or `$b` is TRUE, but _not both_. |
| `not` | `!$a` | TRUE if `$a` is _not_ TRUE. |
| `and` | `$a && $b` | TRUE if both `$a` and `$b` are TRUE. |
| `or` | `$a || $b` | TRUE if either `$a` or `$b` is TRUE. |
| `or` | `$a | | $b` | TRUE if either `$a` or `$b` is TRUE. |
### Ternary Operator
@ -334,7 +334,7 @@ if $a > $b
if $a == $b
return 0;
if $a < $b
return 0;
return -1;
```
### `If` - `Elseif` - `Else`
@ -535,7 +535,7 @@ $foo = function (type $parameter) use ($average) {
### Union Types (PHP 8)
**Union types** are a collection of two or more types which indicate that *either* one of those *can be used*.
**Union types** are a collection of two or more types which indicate that _either_ one of those _can be used_.
```php
public function foo(Foo|Bar $input): int|float;
@ -560,8 +560,8 @@ foo(
### Scope & Visibility
`public` methods and attrivutes are visible to anyone (*default*).
`private` methods and attrivutes are visible only inside the class in which are declared.
`public` methods and attributes are visible to anyone (_default_).
`private` methods and attributes are visible only inside the class in which are declared.
`protected` methods and attributes are visible only to child classes.
`final` classes cannot be extended.
@ -595,15 +595,15 @@ class ClassName
}
}
$object = new ClassName; # case insensitive (CLASSNAME, CLassName, classname)
$object->attrivute = value;
$object = new ClassName; # case insensitive (CLASSNAME, ClassName, classname)
$object->attribute = value;
$object->func();
$object::CONSTANT;
$var = $object; # copy by reference
$var = clone $object # copy by value
$object instanceof ClassName // check typo of the object
$object instanceof ClassName // check type of the object
```
### Static classes, attributes & methods
@ -698,10 +698,10 @@ class ClassName implements InterfaceName {
### Traits
`Traits` allows the riutilization of code inside different classes without links of inheritance.
It can be used to mitigate the problem of *multiple inheritance*, which is absent in PHP.
`Traits` allows the reutilization of code inside different classes without links of inheritance.
It can be used to mitigate the problem of _multiple inheritance_, which is absent in PHP.
In case of functions name conflic it's possible to use `insteadof` to specify which function to use. It's also possible to use an *alias* to resolve the conflicts.
In case of functions name conflic it's possible to use `insteadof` to specify which function to use. It's also possible to use an _alias_ to resolve the conflicts.
```php
trait TraitName {
@ -784,7 +784,7 @@ hash($algorithm, $data);
Algorithms currently supported:
- **PASSWORD_DEFAULT** - Use the *bcrypt* algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.
- **PASSWORD_DEFAULT** - Use the _bcrypt_ algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.
- **PASSWORD_BCRYPT** - Use the **CRYPT_BLOWFISH** algorithm to create the hash. This will produce a standard `crypt()` compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.
- **PASSWORD_ARGON2I** - Use the **Argon2i** hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.
- **PASSWORD_ARGON2ID** - Use the **Argon2id** hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.
@ -792,11 +792,11 @@ Algorithms currently supported:
**Supported options for PASSWORD_BCRYPT**:
- **salt** (string) - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.
If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.
**Warning**: The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.
If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.
**Warning**: The salt option has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.
- **cost** (integer) - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.
If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.
If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.
**Supported options for PASSWORD_ARGON2I and PASSWORD_ARGON2ID**:
@ -868,19 +868,18 @@ error_log(sprintf("[%s] Error: _", date("Y-m-d h:i:s")), 3, "path\\log.log")
## Exception Handling
PHP offers the possibility to handle errors with the *exception model*.
PHP offers the possibility to handle errors with the _exception model_.
```php
try {
// dangerous code
} catch(ExcpetionType1 | ExceptionType2 $e) {
printf("Errore: %s", $e->getMessage());
} catch(Excpetion $e) {
// handle or report exception
}
throw new ExceptionType("message"); // trow an exception
throw new ExceptionType("message"); // throw an exception
```
All exceptions in PHP implement the interface `Throwable`.

View file

@ -1,6 +1,8 @@
# [SimpleMVC](https://github.com/ezimuel/simplemvc) Mini-Framework
Mini framework MVC per scopi didattici basato su Dependency Injection ([PHP-DI][php-di]), Routing ([FastRoute][fastroute]), PSR-7 ([nyholm/psr7][psr7]) e Templates ([Plates][plates])
SimpleMVC is a micro MVC framework for PHP using [FastRoute][fastroute], [PHP-DI][php-di], [Plates][plates] and [PHP-DI][php-di] standard for HTTP messages.
This framework is mainly used as tutorial for introducing the Model-View-Controller architecture in modern PHP applications.
[php-di]: https://php-di.org/
[fastroute]: https://github.com/nikic/FastRoute

View file

@ -95,7 +95,7 @@ echo $template->render('template_name', [ "marker" => value, ... ]);
It's necessary to verify that the output is in the necessary format.
Plates offerts `$this->escape()` or `$this->e()` to validate the output.
In general the output validation allows toprevent [Cross-Site Scripting][owasp-xss] (XSS).
In general the output validation allows to prevent [Cross-Site Scripting][owasp-xss] (XSS).
[owasp-xss]: https://owasp.org/www-community/attacks/xss/

View file

@ -42,7 +42,8 @@ PHPUnit can be configured in a XML file called `phpunit.xml`:
### Test Structure
**PHPUnit** tests are grouped in classes suffixed with `Test`. Each class *extends* `PHPUnit\Framework\TestCase`. A test is a method of a *test class* prefized with `test`.
**PHPUnit** tests are grouped in classes suffixed with `Test`. Each class *extends* `PHPUnit\Framework\TestCase`.
A test is a method of a *test class* prefized with `test`.
PHPUnit is executed from the command line with `vendor/bin/phpunit --colors`.
```php
@ -120,16 +121,15 @@ public function testExceptionNotTrown()
// same as
/**
* @dataProvider provideExamNames
* @doesNotPerformAssertions
*/
public function testAggiungiEsameNoExceptions(string $esame)
public function testNoExceptions(string $esame)
{
$this->studente->aggiungiEsame($esame);
// code that should succeed (exceptions will make the test fail)
}
```
### Test Setup & Teardown
### Test Setup & Teardown (Example)
```php
class ClassTest extends TestCase

View file

@ -25,9 +25,9 @@ Handling of HTTP requests happend using the following global variables:
```html
<!-- method MUST BE post -->
<!-- must have enctype="multipart/form-data" attribute -->
<form name="invio_file" action="file.php" method="POST" enctype="multipart/form-data">
<form name="<name>" action="file.php" method="POST" enctype="multipart/form-data">
<input type="file" name="photo" />
<input type="submit" name="Invio" />
<input type="submit" name="Send" />
</form>
```
@ -36,13 +36,13 @@ Files in `$_FILES` are memorized in a system temp folder. They can be moved with
```php
if (! isset($_FILES['photo']['error'])) {
http_response_code(400); # send a response code
echo'<h1>Non è stato inviato nessun file</h1>';
echo'<h1>No file has been sent</h1>';
exit();
}
if ($_FILES['photo']['error'] != UPLOAD_ERR_OK) {
http_response_code(400);
echo'<h1>Il file inviato non è valido</h1>';
echo'<h1>The sent file is invalid</h1>';
exit();
}
@ -50,11 +50,11 @@ $path = '/path/to/' . $_FILES['photo']['name'];
if (! move_uploaded_file($_FILES['photo']['tmp_name'], $path)) {
http_response_code(400);
echo'<h1>Errore durante la scrittura del file</h1>';
echo'<h1>Error while writing the file</h1>';
exit();
}
echo'<h1>File inviato con successo</h1>';
echo'<h1>File succesfully sent</h1>';
```
### `$_SERVER`
@ -80,7 +80,7 @@ $_SERVER["HTTP_USER_AGENT"];
All sites **must** have a page for the consensus about using cookies.
**Cookies** are HTTP headers used to memorize key-value info *on the client*. They are sent from the server to the client to keep track of info on the user that is visting the website.
**Cookies** are HTTP headers used to memorize key-value info *on the client*. They are sent from the server to the client to keep track of info on the user that is visting the website.
When a client recieves a HTTP response that contains `Set-Cookie` headers it has to memorize that info and reuse them in future requests.
```http
@ -127,7 +127,8 @@ if(isset($_COOKIE["cookie_name"])) {}
PHP generates a cookie named `PHPSESSID` containing a *session identifier* and an *hash* generated from `IP + timestamp + pseudo-random number`.
To use the session it's necesary to recall the function `session_start()` at the beginning of a PHP script that deals with sesssions; after starting the session information in be savend in the `$_SESSION` array.
To use the session it's necesary to recall the function `session_start()` at the beginning of a PHP script that deals with sessions.
After starting the session information in be savend in the `$_SESSION` array.
```php
$_SESSION["key"] = value; // save data in session file (serialized data)

View file

@ -115,7 +115,7 @@ use <crate_name>::module as alias; // import module w/ aliass
pub use <crate_name>::module; // re-exporting (import and make available to others)
use <crate_name>::module::{self, Item}; // import multiple paths
use use <crate_name>::module::*; // import all public items (Glob operator)
pub use <crate_name>::module::*; // import all public items (Glob operator)
module::function(); // use func w/ shorter path
```

View file

@ -4,17 +4,17 @@ A page of the app.
## Views, Functions & Variables
`@State` allows the view to respond to every change of the anotated variable. This variables get initialized by the view in which they belong and are not "recieved" from external objects.
`@State` allows the view to respond to every change of the anotated variable. This variables get initialized by the view in which they belong and are not "recieved" from external objects.
SwiftUI memorizes internally the value of the `@State` property and updates the view every time it changes.
`@Binding` is used for properties that are passed to the view from another. The recieveing view can read the binfing value, react to changes and modify it's value.
`@Binding` is used for properties that are passed to the view from another. The recieveing view can read the binfing value, react to changes and modify it's value.
`@Binding` variables are passed with the prefix `$`,
### Simple View
- Simplest view.
- Permits the visualization of simple UIs.
- Constituited bay a body of type `View`
- Constituited by a body of type `View`
```swift
struct SimpleViewName: View {
@ -58,8 +58,8 @@ Most common view to present array contents, it automatically hendles the scrolli
I can be inegrate d in a `NavigaionView` to handle a `DeailView` of a selectted item in the list.
The basic object that creates the table view is the `List()`. It's job is to create a "cell" for every element in the array.
The array can be filttered with a *search bar*.
The array elements can be grouped with the `Section()` object that groups cells under a common name un the table.
The array can be filtered with a *search bar*.
The array elements can be grouped with the `Section()` object that groups cells under a common name in the table.
```swift
// view name can be any
@ -83,7 +83,7 @@ struct TableCell: View {
}
```
Every cell can have a link to visualize he details of the selected object. This is done by using `NavigationView` and `NavigationLink`.
Every cell can have a link to visualize the details of the selected object. This is done by using `NavigationView` and `NavigationLink`.
The `NavigationView` contains the list and the property `.navigationBarTitle()` sets the view title.
It's possible to add other controls in the top part of the view (buttons, ...) using the property `.navigationBarItems()`.
@ -129,7 +129,7 @@ struct TabBarView: View {
}
```
The `TabBar` conostruction is made applying the `.tabItem{}` parameter to the object or page that the tab will link to.
The `TabBar` construction is made applying the `.tabItem{}` parameter to the object or page that the tab will link to.
It's possible to specify up to 5 `.tabItem{}` elements that will be displayed singularly in the `TabBar`.
Fron the 6th elemnet onwards, the first 4 elemens will appear normally, meanwhile the 5th will become a "more" element that will open a `TableView` with the list of the other `.tabItem{}` elements. This page permis to define which elements will be visible.