-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
324 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
content/c/concepts/user-input/user-input.md | ||
content/general/concepts/jit-compilation/jit-compilation.md |
196 changes: 196 additions & 0 deletions
196
content/javascript/concepts/optional-chaining/optional-chaining.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,196 @@ | ||
--- | ||
Title: 'Optional Chaining' | ||
Description: 'The optional chaining operator allows safe access to nested object properties or methods without having to explicitly check if intermediate properties exist.' | ||
Subjects: | ||
- 'Web Development' | ||
- 'Computer Science' | ||
Tags: | ||
- 'Data' | ||
- 'Operators' | ||
CatalogContent: | ||
- 'introduction-to-javascript' | ||
- 'paths/front-end-engineer-career-path' | ||
--- | ||
|
||
The **optional chaining** (**`?.`**) operator simplifies comparing multiple data properties in a chain of connected objects. This is especially valuable if any of the properties are `null`, as the operator will return `undefined` instead of throwing an error. | ||
|
||
Optional chaning can be used to validate nested object properties, call optional functions or methods on optional objects, accessing array elements, and more. | ||
|
||
The primary benefits of using optional chaining instead of regular syntax include simplifying the code to achieve the same result, making it easier to read, protecting against runtime errors, and enhancing maintainability. | ||
|
||
## Syntax | ||
|
||
The basic syntax for using optional chaining is as follows: | ||
|
||
```pseudo | ||
// To access an object property | ||
object?.property; | ||
//To access an element in an array | ||
array?.[index]; | ||
//To invoke a function (if it exists) | ||
object?.method?.(); | ||
``` | ||
|
||
## Examples | ||
|
||
### Accessing Object Properties | ||
|
||
To search for the `state` object of `person`: | ||
|
||
```js | ||
const person = { | ||
name: 'Alice', | ||
gender: 'Female', | ||
age: 12, | ||
address: { | ||
street: '1111 Palm Ave', | ||
city: 'Broken Arrow', | ||
state1: 'Oklahoma', | ||
}, | ||
favoriteFoods: ['pizza', 'ice cream', 'cake'], | ||
commonPhrase: function () { | ||
return `${this.name} always says "I love ${this.address.state1}."`; | ||
}, | ||
}; | ||
|
||
// Regular syntax for checking if the state1 property exists | ||
const state1Regular = person && person.address && person.address.state1; | ||
console.log(`State (regular syntax) is: ${state1Regular}`); | ||
|
||
// This can be rewritten as: | ||
const state1Chaining = person?.address?.state1; | ||
console.log(`State (optional chaining) is: ${state1Chaining}`); | ||
``` | ||
The output of the above code will be as follows: | ||
```shell | ||
State (regular syntax) is: Oklahoma | ||
State (optional chaining) is: Oklahoma | ||
``` | ||
|
||
### Accessing Array Elements | ||
|
||
To search for the `cake` in the `favoriteFoods` array of `person`: | ||
|
||
```js | ||
const person = { | ||
name: 'Alice', | ||
gender: 'Female', | ||
age: 12, | ||
address: { | ||
street: '1111 Palm Ave', | ||
city: 'Broken Arrow', | ||
state1: 'Oklahoma', | ||
}, | ||
favoriteFoods: ['pizza', 'ice cream', 'cake'], | ||
commonPhrase: function () { | ||
return `${this.name} always says "I love ${this.address.state1}."`; | ||
}, | ||
}; | ||
|
||
// Regular Syntax for searching favorite food | ||
const foodRegular = | ||
person && | ||
person.favoriteFoods && | ||
person.favoriteFoods.find((item) => item === 'cake'); | ||
console.log(`Favorite Food (regular syntax) is: ${foodRegular}`); | ||
|
||
// This can be rewritten as: | ||
const foodChaining = person?.favoriteFoods.find((item) => item === 'cake'); | ||
console.log(`Favorite Food (optional chaining) is: ${foodChaining}`); | ||
``` | ||
The output of the above code will be as follows: | ||
```shell | ||
Favorite Food (regular syntax) is: cake | ||
Favorite Food (optional chaining) is: cake | ||
``` | ||
|
||
### Accessing Object Functions | ||
|
||
To determine if the `commonPhrase` function exists in `person` before invoking it: | ||
|
||
```js | ||
//Regular Syntax | ||
if (person && typeof person.commonPhrase === 'function') { | ||
const phrase = person.commonPhrase(); | ||
console.log(`${phrase}`); | ||
} | ||
|
||
//This can be rewritten as: | ||
const phrase = person?.commonPhrase?.(); | ||
console.log(`${phrase}`); | ||
``` | ||
The output of the above code will be as follows: | ||
```shell | ||
Alice always says "I love Oklahoma." | ||
Alice always says "I love Oklahoma." | ||
``` | ||
## Codebyte Example | ||
Run the following example and compare the regular syntax of conditional statements and optional chaining on a more complex data set: | ||
```codebyte/javascript | ||
const people = [ | ||
{ | ||
name: "Blake", | ||
gender: "Male", | ||
age: null, | ||
address: { | ||
street: "456 Maple Dr", | ||
city: "Austin", | ||
state: "Texas" | ||
} | ||
}, | ||
{ | ||
name: "Eve", | ||
gender: "Female", | ||
age: 15, | ||
address: { | ||
street: "789 Birch Ln", | ||
city: "", | ||
state: "Colorado" | ||
} | ||
}, | ||
null, | ||
{ | ||
name: "David", | ||
gender: "Male", | ||
age: 72, | ||
address: { | ||
street: "123 Acorn St", | ||
city: "Tampa", | ||
state: "Florida" | ||
} | ||
}, | ||
{ | ||
name: "Jospeh", | ||
gender: "Male", | ||
age: 9, | ||
address: { | ||
street: "987 Pine Ave", | ||
city: "Taos", | ||
state: "New Mexico" | ||
} | ||
} | ||
]; | ||
|
||
console.log("Using Regular Syntax for City:"); | ||
people.forEach((person, index) => { | ||
const city = person && person.address && person.address.city; | ||
console.log(`Person ${index + 1}: City: ${city ?? "Not Available"}`); | ||
}); | ||
console.log("\nUsing Optional Chaining for Age:"); | ||
people.forEach((person, index) => { | ||
const age = person?.age; | ||
console.log(`Person ${index + 1}: Age: ${age ?? "Not Available"}`); | ||
}); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
--- | ||
Title: 'Logit' | ||
Description: 'Returns the log-odds of a binary outcome using logistic regression.' | ||
Subjects: | ||
- 'Python' | ||
- 'Statistics' | ||
Tags: | ||
- 'Logit' | ||
- 'Logistic Regression' | ||
- 'Statsmodels' | ||
CatalogContent: | ||
- 'learn-statistics' | ||
- 'paths/data-science-inf' | ||
--- | ||
|
||
**Logit** is a term used in statistics, specifically in the context of logistic regression. It represents the log-odds of a binary outcome, mapping probabilities from the 0 to 1 range to the entire real number line. The **`.Logit()`** function is a key part of many statistical models, particularly in binary classification tasks. | ||
|
||
## Syntax | ||
|
||
```pseudo | ||
statsmodels.api.Logit(endog, exog) | ||
``` | ||
|
||
- `endog`: The dependent (binary) variable, which must be a binary outcome (0 or 1). | ||
- `exog`: The independent variables (features or predictors). | ||
|
||
## Example | ||
|
||
This example demonstrates how to use the `.Logit()` function in the `statsmodels` library to perform logistic regression: | ||
|
||
```py | ||
import statsmodels.api as sm | ||
|
||
# Example data | ||
X = sm.add_constant([[1], [2], [3], [4], [5]]) # Adding a constant for the intercept | ||
y = [0, 0, 1, 1, 1] | ||
|
||
# Fitting the logistic regression model | ||
model = sm.Logit(y, X) | ||
result = model.fit() | ||
|
||
# Output the results | ||
print(result.summary()) | ||
``` | ||
|
||
> **Note:** The dependent variable (`y`) must contain only binary values (0 or 1) for the logistic regression to be valid. | ||
This example produces a summary of the logistic regression model's results, showing coefficients, standard errors, p-values, and other statistics relevant to evaluating the model fit: | ||
|
||
```shell | ||
Logit Regression Results | ||
============================================================================== | ||
Dep. Variable: y No. Observations: 5 | ||
Model: Logit Df Residuals: 3 | ||
Method: MLE Df Model: 1 | ||
Date: Tue, 24 Dec 2024 Pseudo R-squ.: 1.000 | ||
Time: 12:28:45 Log-Likelihood: -5.0138e-10 | ||
converged: False LL-Null: -3.3651 | ||
Covariance Type: nonrobust LLR p-value: 0.009480 | ||
============================================================================== | ||
coef std err z P>|z| [0.025 0.975] | ||
------------------------------------------------------------------------------ | ||
const -110.4353 2.23e+05 -0.000 1.000 -4.38e+05 4.38e+05 | ||
x1 44.2438 9.07e+04 0.000 1.000 -1.78e+05 1.78e+05 | ||
============================================================================== | ||
|
||
Complete Separation: The results show that there iscomplete separation or perfect prediction. | ||
In this case the Maximum Likelihood Estimator does not exist and the parameters | ||
are not identified. | ||
``` |
55 changes: 55 additions & 0 deletions
55
content/pytorch/concepts/tensor-operations/terms/nonzero/nonzero.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
--- | ||
Title: '.nonzero()' | ||
Description: 'Returns a tensor containing the indices of non-zero elements in the input tensor.' | ||
Subjects: | ||
- 'AI' | ||
- 'Data Science' | ||
Tags: | ||
- 'AI' | ||
- 'Data Types' | ||
- 'Deep Learning' | ||
- 'Functions' | ||
CatalogContent: | ||
- 'intro-to-py-torch-and-neural-networks' | ||
- 'paths/data-science' | ||
--- | ||
|
||
In PyTorch, the **`.nonzero()`** function returns a tensor of indices of all non-zero elements in the input [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors). This function is useful for identifying the locations of non-zero values in sparse tensors or when performing operations based on the positions of non-zero elements. | ||
|
||
## Syntax | ||
|
||
```pseudo | ||
torch.nonzero(input, *, out=None, as_tuple=False) | ||
``` | ||
|
||
- `input`: The input tensor for which the indices of non-zero elements are to be found. | ||
- `out` (Optional): A tensor to store the result. It must have the appropriate shape to accommodate the output. If not provided, a new tensor will be allocated to store the result. | ||
- `as_tuple` (Optional): If set to `True`, the result will be a tuple of 1-D tensors, each containing the indices for a specific dimension of the input tensor. If set to `False` (default), the result will be a 2-D tensor where each row represents the index of a non-zero element in the input tensor. | ||
|
||
## Example | ||
|
||
The following example demonstrates the usage of the `.nonzero()` function: | ||
|
||
```py | ||
import torch | ||
|
||
# Create a tensor | ||
ten = torch.tensor([[1, 0, 3], [0, 5, 6]]) | ||
|
||
# Get the indices of non-zero elements | ||
indices = torch.nonzero(ten) | ||
|
||
# Print the result | ||
print(indices) | ||
``` | ||
|
||
The above code produces the following output: | ||
|
||
```shell | ||
tensor([[0, 0], | ||
[0, 2], | ||
[1, 1], | ||
[1, 2]]) | ||
``` | ||
|
||
In this example, the tensor's non-zero elements are located at indices _(0,0)_, _(0,2)_, _(1,1)_, and _(1,2)_. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters