mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-04-18 11:26:27 +00:00
merge main into NET-6
This commit is contained in:
commit
b33336d7c1
21 changed files with 299 additions and 178 deletions
|
@ -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
|
||||
|
|
|
@ -257,6 +257,80 @@ Project
|
|||
}
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
### Blazor WASM
|
||||
|
||||
```cs
|
||||
// setup state singleton
|
||||
builder.Services.AddSingleton<StateContainer>();
|
||||
```
|
||||
|
||||
```cs
|
||||
// StateContainer singleton
|
||||
using System;
|
||||
|
||||
public class StateContainer
|
||||
{
|
||||
private int _counter;
|
||||
|
||||
public string Property
|
||||
{
|
||||
get => _counter;
|
||||
set
|
||||
{
|
||||
_counter = value;
|
||||
NotifyStateChanged(); // will trigger StateHasChanged(), causing a render
|
||||
}
|
||||
}
|
||||
|
||||
public event Action OnChange;
|
||||
|
||||
private void NotifyStateChanged() => OnChange?.Invoke();
|
||||
}
|
||||
```
|
||||
|
||||
```cs
|
||||
// component that changes the state
|
||||
@inject StateContainer State
|
||||
|
||||
// Delegate event handlers automatically trigger a UI render
|
||||
<button @onClick="@HandleClick">
|
||||
Change State
|
||||
</button>
|
||||
|
||||
@code {
|
||||
private void HandleClick()
|
||||
{
|
||||
State.Property += 1; // update state
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```cs
|
||||
// component that should be update on state change
|
||||
@implements IDisposable
|
||||
@inject StateContainer State
|
||||
|
||||
<p>Property: <b>@State.Property</b></p>
|
||||
|
||||
@code {
|
||||
|
||||
// StateHasChanged notifies the component that its state has changed.
|
||||
// When applicable, calling StateHasChanged causes the component to be rerendered.
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
State.OnChange += StateHasChanged;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
State.OnChange -= StateHasChanged;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Javascript/.NET Interop
|
||||
|
||||
[Call Javascript from .NET](https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet)
|
||||
|
|
127
DotNet/C#/C#.md
127
DotNet/C#/C#.md
|
@ -33,7 +33,7 @@ to native code later.
|
|||
```cs
|
||||
// comment
|
||||
/* multi line comment */
|
||||
// / single line xml comment (docstring)
|
||||
/// single line xml comment (docstring)
|
||||
/** multi line xml string (docsting) */
|
||||
```
|
||||
|
||||
|
@ -1219,16 +1219,6 @@ type OutMethod(type param1, out type param2){}
|
|||
OutMethod(arg1, out var arg2); // create out variable on the fly
|
||||
```
|
||||
|
||||
<!-- TODO: ### References to variables
|
||||
|
||||
**Constraints**:
|
||||
|
||||
```cs
|
||||
string _string = null; // init string object
|
||||
ref string referenceToString = ref _string; // referenceToString points to _string, it's a reference
|
||||
referenceToString = "value"; // data goes through referenceToString and into _string
|
||||
``` -->
|
||||
|
||||
### Returning Multiple Values with Tuples
|
||||
|
||||
**Must** be C# 7+.
|
||||
|
@ -2101,13 +2091,13 @@ Any method from any accessible class or struct that matches the delegate type ca
|
|||
This makes it possible to programmatically change method calls, and also plug new code into existing classes.
|
||||
|
||||
```cs
|
||||
// dedlegate definition
|
||||
public delegate Type DelegateName(Type param, ...); // can take any method with specidied type params and return type
|
||||
public delegate bool Predicate<in T>(T obj);
|
||||
// delegate definition
|
||||
public delegate Type Delegate(Type param, ...); // can take any method with specidied type params and return type
|
||||
public delegate Type Delegate<T>(T param); // generic delegate
|
||||
|
||||
// delegate creation
|
||||
var delegate = new Delegate<Type>(method); // explicit creation, useful when compiler cannot infer delegate type
|
||||
Delegate<Type> delegate = method; // implicit creation
|
||||
var delegate = new Delegate<Type>(Method); // explicit creation, useful when compiler cannot infer delegate type
|
||||
Delegate<Type> delegate = Method; // implicit creation
|
||||
```
|
||||
|
||||
### [Multicast Delegates](https://docs.microsoft.com/en-us/dotnet/api/system.multicastdelegate)
|
||||
|
@ -2115,9 +2105,9 @@ Delegate<Type> delegate = method; // implicit creation
|
|||
**Multicast Delegares** are delegates that can have more than one element in their invocation list.
|
||||
|
||||
```cs
|
||||
Delegate<Type> multicastDelegate = method1 + method2 + ...; // multicast delegate creation
|
||||
multicastDelegate += method; // add method to delegate
|
||||
multicastDelegate -= method; // remove method from delegate
|
||||
Delegate<Type> multicastDelegate = Method1 + Method2 + ...; // multicast delegate creation
|
||||
multicastDelegate += Method; // add method to delegate
|
||||
multicastDelegate -= Method; // remove method from delegate
|
||||
```
|
||||
|
||||
**NOTE**: Delegate removal behaves in a potentially surprising way if the delegate removed refers to multiple methods.
|
||||
|
@ -2129,7 +2119,7 @@ Invoking a delegate with a single target method works as though the code had cal
|
|||
Invoking a multicast delegate is just like calling each of its target methods in turn.
|
||||
|
||||
```cs
|
||||
Delegate<Type> delegate = method;
|
||||
Delegate<Type> delegate = Method;
|
||||
|
||||
delegate(args); // use delegat as standard method
|
||||
delegate.DynamicInvoke(argsArray); // Dynamically invokes the method represented by the current delegate.
|
||||
|
@ -2181,12 +2171,6 @@ var f = int (x) => x; // explicitly specifying the return type of an implicit i
|
|||
var f = static void (_) => Console.Write("Help");
|
||||
```
|
||||
|
||||
### Captured Variables
|
||||
|
||||
<!-- TODO: page 396 of Ian Griffiths - Programming C%23 8.0_Build Cloud, Web, and Desktop Applications -->
|
||||
|
||||
<!-- todo: static anonymous functions -->
|
||||
|
||||
---
|
||||
|
||||
## [Events](https://www.tutorialsteacher.com/csharp/csharp-event)
|
||||
|
@ -2197,10 +2181,11 @@ The class who raises events is called _Publisher_, and the class who receives th
|
|||
Typically, a publisher raises an event when some action occurred. The subscribers, who are interested in getting a notification when an action occurred, should register with an event and handle it.
|
||||
|
||||
```cs
|
||||
public delegate void EventDelegate(object sender, CustomEventArgs args); // called on event trigger
|
||||
|
||||
public class Publisher
|
||||
{
|
||||
|
||||
public event Delegate<Type> Event;
|
||||
public event EventDelegate Event;
|
||||
|
||||
// A derived class should always call the On<EventName> method of the base class to ensure that registered delegates receive the event.
|
||||
public virtual void OnEvent(Type param)
|
||||
|
@ -2215,19 +2200,15 @@ public class Publisher
|
|||
```cs
|
||||
public class Subscriber
|
||||
{
|
||||
|
||||
Publisher publisher = new Publisher();
|
||||
|
||||
public Subscriber()
|
||||
{
|
||||
publisher.Event += eh_Event; // register handler (+= syntax)
|
||||
publisher.OnEvent += Handler; // register handler (+= syntax)
|
||||
}
|
||||
|
||||
// event handler, handles the event because it matches the signature of the Event delegate.
|
||||
public Delegate<Type> eh_Event()
|
||||
{
|
||||
// act
|
||||
}
|
||||
// event handler, matches the signature of the Event delegate.
|
||||
public Type Handler() { /* act */ }
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -2254,22 +2235,17 @@ public class Subsciber
|
|||
|
||||
public Subscriber()
|
||||
{
|
||||
publisher.Event += eh_Event; // register handler (+= syntax)
|
||||
publisher.OnEvent += Handler; // register handler (+= syntax)
|
||||
}
|
||||
|
||||
public void eh_Event(object sender, EventArgs e)
|
||||
{
|
||||
// act
|
||||
}
|
||||
public Type Handler(object sender, EventArgs e) { /* act */ }
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Event Args
|
||||
|
||||
```cs
|
||||
public class CustomEventArgs : EventArgs {
|
||||
// custom attributes
|
||||
}
|
||||
public class CustomEventArgs : EventArgs { }
|
||||
|
||||
public class Publisher
|
||||
{
|
||||
|
@ -2287,13 +2263,10 @@ public class Subsciber
|
|||
|
||||
public Subscriber()
|
||||
{
|
||||
publisher.Event += eh_Event; // register handler (+= syntax)
|
||||
publisher.OnEvent += Handler; // register handler (+= syntax)
|
||||
}
|
||||
|
||||
public void eh_Event(object sender, CustomEventArgs e)
|
||||
{
|
||||
// act
|
||||
}
|
||||
public Type Handler(object sender, CustomEventArgs e) { /* act */ }
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -2900,6 +2873,53 @@ n << m
|
|||
n * 2^m
|
||||
```
|
||||
|
||||
## Unsafe Code & Pointers
|
||||
|
||||
The `unsafe` keyword denotes an *unsafe context*, which is required for any operation involving pointers.
|
||||
|
||||
In an unsafe context, several constructs are available for operating on pointers:
|
||||
|
||||
- The `*` operator may be used to perform pointer indirection ([Pointer indirection][ptr_indirection]).
|
||||
- The `->` operator may be used to access a member of a struct through a pointer ([Pointer member access][ptr_member_acces]).
|
||||
- The `[]` operator may be used to index a pointer ([Pointer element access][ptr_elem_access]).
|
||||
- The `&` operator may be used to obtain the address of a variable ([The address-of operator][ptr_addr_of]).
|
||||
- The `++` and `--` operators may be used to increment and decrement pointers ([Pointer increment and decrement][ptr_incr_decr]).
|
||||
- The `+` and `-` operators may be used to perform pointer arithmetic ([Pointer arithmetic][ptr_math]).
|
||||
- The `==`, `!=`, `<`, `>`, `<=`, and `>=` operators may be used to compare pointers ([Pointer comparison][ptr_comparison]).
|
||||
- The `stackalloc` operator may be used to allocate memory from the call stack ([Stack allocation][stack_alloc]).
|
||||
|
||||
The `fixed` statement prevents the garbage collector from relocating a movable variable. It's only permitted in an unsafe context.
|
||||
It's also possible to use the fixed keyword to create fixed size buffers.
|
||||
|
||||
The `fixed` statement sets a pointer to a managed variable and "pins" that variable during the execution of the statement.
|
||||
Pointers to movable managed variables are useful only in a fixed context. Without a fixed context, garbage collection could relocate the variables unpredictably.
|
||||
The C# compiler only allows to assign a pointer to a managed variable in a fixed statement.
|
||||
|
||||
```cs
|
||||
unsafe Type UnsafeMethod() { /* unasfe context */ }
|
||||
// or
|
||||
unsafe
|
||||
{
|
||||
// Using fixed allows the address of pt members to be taken,
|
||||
// and "pins" pt so that it is not relocated.
|
||||
Point pt = new Point();
|
||||
fixed (int* p = &pt.x)
|
||||
{
|
||||
*p = 1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[ptr_indirection]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-indirection)
|
||||
[ptr_member_acces]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-member-access)
|
||||
[ptr_elem_access]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-element-access)
|
||||
[ptr_addr_of]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#the-address-of-operator)
|
||||
[ptr_incr_decr]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-increment-and-decrement)
|
||||
[ptr_math]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-arithmetic)
|
||||
[ptr_comparison]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#pointer-comparison)
|
||||
[stack_alloc]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#stack-allocation)
|
||||
[fixed_buffers]: (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code#fixed-size-buffers)
|
||||
|
||||
### Native Memory
|
||||
|
||||
```cs
|
||||
|
@ -2912,3 +2932,14 @@ unsafe
|
|||
NativeMemory.Free(buffer);
|
||||
}
|
||||
```
|
||||
|
||||
### DllImport & Extern
|
||||
|
||||
The `extern` modifier is used to declare a method that is implemented externally.
|
||||
A common use of the extern modifier is with the `DllImport` attribute when using Interop services to call into *unmanaged* code.
|
||||
In this case, the method must also be declared as `static`.
|
||||
|
||||
```cs
|
||||
[DllImport("avifil32.dll")]
|
||||
private static extern void AVIFileInit();
|
||||
```
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# Reactive Extensions (Rx)
|
||||
|
||||
The **Reactive Extensions** for .NET, or **Rx**, are designed for working with asynchro‐nous and event-based sources of information.
|
||||
The **Reactive Extensions** for .NET, or **Rx**, are designed for working with asynchronous and event-based sources of information.
|
||||
Rx provides services that help orchestrate and synchronize the way code reacts to data from these kinds of sources.
|
||||
|
||||
Rx’s fundamental abstraction, `IObservable<T>`, represents a sequence of items, and its operators are defined as extension methods for this interface.
|
||||
|
@ -14,8 +14,8 @@ Because Rx implements standard LINQ operators, it's possible to write queries ag
|
|||
|
||||
## Foundamental Interfaces
|
||||
|
||||
The two most important types in Rx are the `IObservable<T>` and `IObserver<T>` interfaces. They are important enough to be in the System namespace.
|
||||
The other parts of Rx are in the `System.Reactive` NuGet package.
|
||||
The two most important types in Rx are the `IObservable<T>` and `IObserver<T>` interfaces.
|
||||
They are important enough to be in the System namespace. The other parts of Rx are in the `System.Reactive` NuGet package.
|
||||
|
||||
```cs
|
||||
public interface IObservable<out T>
|
||||
|
@ -31,7 +31,8 @@ public interface IObserver<in T>
|
|||
}
|
||||
```
|
||||
|
||||
The fundamental abstraction in Rx, `IObservable<T>`, is implemented by *event sources*. Instead of using the `event` keyword, it models events as a *sequence of items*. An `IObservable<T>` provides items to subscribers as and when it’s ready to.
|
||||
The fundamental abstraction in Rx, `IObservable<T>`, is implemented by *event sources*. Instead of using the `event` keyword, it models events as a *sequence of items*.
|
||||
An `IObservable<T>` provides items to subscribers as and when it’s ready to do so.
|
||||
|
||||
It's possible to subscribe to a source by passing an implementation of `IObserver<T>` to the `Subscribe` method.
|
||||
The source will invoke `OnNext` when it wants to report events, and it can call `OnCompleted` to indicate that there will be no further activity.
|
||||
|
|
14
Java/Java.md
14
Java/Java.md
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -4,8 +4,10 @@
|
|||
npx degit sveltejs/template <project name>
|
||||
|
||||
# set project to use typescript
|
||||
npm install --save-dev @tsconfig/svelte typescript svelte-preprocess svelte-check
|
||||
node scripts/setupTypeScript.js
|
||||
|
||||
# or using vite
|
||||
npm init vite@latest
|
||||
```
|
||||
|
||||
## App Entrypoint
|
||||
|
|
|
@ -11,7 +11,7 @@ https.request(
|
|||
method: "GET", // POST, ...
|
||||
path: "/page/?param=value"
|
||||
},
|
||||
(response) => { // respnse is IncomingMessage
|
||||
(response) => { // response is IncomingMessage
|
||||
// do stuff
|
||||
}
|
||||
).end();
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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/)
|
||||
|
||||
|
|
51
PHP/PHP.md
51
PHP/PHP.md
|
@ -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.
|
||||
|
@ -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`.
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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/
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
15
PHP/Web.md
15
PHP/Web.md
|
@ -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`
|
||||
|
@ -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)
|
||||
|
|
|
@ -80,7 +80,9 @@ crate::module::function(); // abs path (same crate)
|
|||
|
||||
### Public vs Private
|
||||
|
||||
Modules aren’t useful only for organizing the code. They also define Rust’s privacy boundary: the line that encapsulates the implementation details external code isn’t allowed to know about, call, or rely on. So, to make an item like a function or struct private, put it in a module.
|
||||
Modules aren’t useful only for organizing the code. They also define Rust’s privacy boundary:
|
||||
the line that encapsulates the implementation details external code isn’t allowed to know about, call, or rely on.
|
||||
So, to make an item like a function or struct private, put it in a module.
|
||||
|
||||
The way privacy works in Rust is that all items (functions, methods, structs, enums, modules, and constants) are *private by default*.
|
||||
Items in a parent module can’t use the private items inside child modules, but items in child modules can use the items in their ancestor modules.
|
||||
|
@ -100,7 +102,8 @@ mod file_level_module; // define a module for the whole file (same name as file
|
|||
```
|
||||
|
||||
It's possible to use `pub` to designate *structs* and *enums* as public, but there are a few extra details.
|
||||
If `pub` is used before a struct definition, this makes the struct public, but the struct’s fields will still be private. It's possible make each field public or not on a case-by-case basis.
|
||||
If `pub` is used before a struct definition, this makes the struct public, but the struct’s fields will still be private.
|
||||
It's possible make each field public or not on a case-by-case basis.
|
||||
|
||||
In contrast, if an enum is made public, all of its variants are then public.
|
||||
|
||||
|
@ -108,14 +111,14 @@ In contrast, if an enum is made public, all of its variants are then public.
|
|||
|
||||
```rs
|
||||
use <crate_name>::module; // import module (abs path, other crate)
|
||||
use crate::module; // s (abs path, same crate)
|
||||
use self::module; // // import module (rel path, same crate)
|
||||
use crate::module; // import module (abs path, same crate)
|
||||
use self::module; // import module (rel path, same crate)
|
||||
|
||||
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
|
||||
```
|
||||
|
@ -124,9 +127,17 @@ module::function(); // use func w/ shorter path
|
|||
|
||||
```txt
|
||||
src
|
||||
|_main.rs --> app entrypoint
|
||||
|_lib.rs --> export module-folders
|
||||
|_main.rs --> default executable file
|
||||
|_lib.rs --> default library file
|
||||
|__module
|
||||
| |_mod.rs --> export module-files
|
||||
| |_file.rs
|
||||
| |_mod.rs --> export submodules
|
||||
| |_submodule.rs --> submodule
|
||||
```
|
||||
|
||||
```rs
|
||||
// main.rs
|
||||
mod module; // delcare module direcotry as a module
|
||||
|
||||
// mod.rs
|
||||
pub mod sub_module; // declare sub_module file as a module
|
||||
```
|
||||
|
|
13
Rust/Rust.md
13
Rust/Rust.md
|
@ -51,7 +51,8 @@ io::stdin() // read line from stdin
|
|||
.expect("Error Message"); // in case of errors return an error message (io::Result) -- NEEDED
|
||||
```
|
||||
|
||||
The `::` syntax in the `::new` line indicates that `new` is an **associated function** of the `String` type. An associated function is implemented on a type rather than on a particular instance of the type. Some languages call this a `static method`.
|
||||
The `::` syntax in the `::new` line indicates that `new` is an **associated function** of the `String` type.
|
||||
An associated function is implemented on a type rather than on a particular instance of the type. Some languages call this a `static method`.
|
||||
|
||||
The `&` indicates that this argument is a reference, which gives a way to let multiple parts of the code access one piece of data without needing to copy that data into memory multiple times.
|
||||
|
||||
|
@ -74,7 +75,8 @@ const CONSTANT_NAME: type = value; // constant must have the type annotation
|
|||
It's possible declare a new variable with the *same name* as a previous variable, and the new variable *shadows* the previous variable.
|
||||
By using let, it's possible to perform a few transformations on a value but have the variable be immutable after those transformations have been completed.
|
||||
|
||||
The other difference between *mut* and *shadowing* is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name.
|
||||
The other difference between *mut* and *shadowing* is that because we’re effectively creating a new variable when we use the let keyword again,
|
||||
we can change the type of the value but reuse the same name.
|
||||
|
||||
```rs
|
||||
let x: u32 = 10;
|
||||
|
@ -533,7 +535,8 @@ enum Option<T> {
|
|||
|
||||
### Match Expression + Comparing
|
||||
|
||||
A **match expression** is made up of *arms*. An arm consists of a *pattern* and the code that should be run if the value given to the beginning of the match expression fits that arm’s pattern.
|
||||
A **match expression** is made up of *arms*.
|
||||
An arm consists of a *pattern* and the code that should be run if the value given to the beginning of the match expression fits that arm’s pattern.
|
||||
Rust takes the value given to match and looks through each arm’s pattern in turn.
|
||||
|
||||
**NOTE**: `match` arms must be exaustive for compilation.
|
||||
|
@ -595,7 +598,3 @@ let v = vec![
|
|||
Enum::Text("TEST")
|
||||
];
|
||||
```
|
||||
|
||||
### String
|
||||
|
||||
### Hash Map
|
||||
|
|
|
@ -14,7 +14,7 @@ SwiftUI memorizes internally the value of the `@State` property and updates the
|
|||
|
||||
- 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.
|
||||
|
|
Loading…
Add table
Reference in a new issue