Search is not available for this dataset
project
stringlengths
1
235
source
stringclasses
16 values
language
stringclasses
48 values
content
stringlengths
909
64.8M
@material-ui/envinfo
npm
JavaScript
@material-ui/envinfo === Prints information about the current environment relevant to Material-UI packages to the console. Please use this package if you report [issues to Material-UI](https://github.com/mui-org/material-ui/issues). Usage --- ``` $ npx @material-ui/envinfo System: OS: Linux 5.4 Ubuntu 20.04.1 LTS (Focal Fossa) Binaries: Node: 12.20.0 - ~/.nvm/versions/node/v12.20.0/bin/node Yarn: 1.22.4 - /usr/bin/yarn npm: 6.14.8 - ~/.nvm/versions/node/v12.20.0/bin/npm Browsers: Chrome: 87.0.4280.66 Firefox: 83.0 npmPackages: @emotion/react: ^11.0.0 => 11.1.1 @emotion/styled: ^11.0.0 => 11.0.0 @material-ui/codemod: 5.0.0-alpha.17 @material-ui/core: 5.0.0-alpha.18 @material-ui/docs: 5.0.0-alpha.1 @material-ui/envinfo: 1.0.0 @material-ui/icons: 5.0.0-alpha.15 @material-ui/lab: 5.0.0-alpha.18 @material-ui/styled-engine: 5.0.0-alpha.18 @material-ui/styled-engine-sc: 5.0.0-alpha.18 @material-ui/styles: 5.0.0-alpha.18 @material-ui/system: 5.0.0-alpha.18 @material-ui/types: 5.1.0 @material-ui/unstyled: 5.0.0-alpha.18 @material-ui/utils: 5.0.0-alpha.18 @types/react: ^17.0.0 => 17.0.0 react: ^16.14.0 => 16.14.0 react-dom: ^16.14.0 => 16.14.0 styled-components: 5.2.1 typescript: ^4.0.2 => 4.0.5 ``` Readme --- ### Keywords none
micompr
cran
R
Package ‘micompr’ August 20, 2023 Title Multivariate Independent Comparison of Observations Version 1.1.4 Maintainer <NAME> <<EMAIL>> Description A procedure for comparing multivariate samples associated with different groups. It uses principal component analysis to convert multivariate observations into a set of linearly uncorrelated statistical measures, which are then compared using a number of statistical methods. The procedure is independent of the distributional properties of samples and automatically selects features that best explain their differences, avoiding manual selection of specific points or summary statistics. It is appropriate for comparing samples of time series, images, spectrometric measures or similar multivariate observations. This package is described in Fachada et al. (2016) <doi:10.32614/RJ-2016-055>. Depends R (>= 4.1.0) Imports utils, graphics, methods, stats Suggests biotools, MVN (>= 5.0), testthat (>= 0.8), knitr, roxygen2, devtools License MIT + file LICENSE URL https://github.com/nunofachada/micompr BugReports https://github.com/nunofachada/micompr/issues LazyData true Encoding UTF-8 VignetteBuilder knitr RoxygenNote 7.2.3 NeedsCompilation no Author <NAME> [aut, cre] (<https://orcid.org/0000-0002-8487-5837>) Repository CRAN Date/Publication 2023-08-19 23:42:32 UTC R topics documented: assumption... 3 assumptions.cmpoutpu... 3 assumptions.micom... 4 assumptions_manov... 5 assumptions_paru... 6 centerscal... 6 cmpoutpu... 8 concat_output... 9 grpoutput... 10 micom... 12 plot.assumptions_cmpoutpu... 14 plot.assumptions_manov... 15 plot.assumptions_micom... 16 plot.assumptions_paru... 17 plot.cmpoutpu... 18 plot.grpoutput... 19 plot.micom... 20 pphpc_dif... 21 pphpc_noshuf... 21 pphpc_o... 22 print.assumptions_cmpoutpu... 22 print.assumptions_manov... 23 print.assumptions_micom... 24 print.assumptions_paru... 24 print.cmpoutpu... 25 print.grpoutput... 26 print.micom... 27 pval... 27 pvalf.defaul... 28 summary.assumptions_cmpoutpu... 29 summary.assumptions_micom... 30 summary.cmpoutpu... 31 summary.grpoutput... 32 summary.micom... 33 tikzsca... 34 toLatex.cmpoutpu... 35 toLatex.micom... 36 assumptions Parametric tests assumptions Description Generic function to get the assumptions for parametric tests applied to the comparison of output observations. Usage assumptions(obj) Arguments obj Object from which to get the assumptions. Value Assumptions for parametric tests applied to the comparison of outputs. See Also assumptions.cmpoutput, assumptions.micomp assumptions.cmpoutput Get assumptions for parametric tests performed on output compar- isons Description Get assumptions for parametric tests performed on output comparisons (i.e. from objects of class cmpoutput). Usage ## S3 method for class 'cmpoutput' assumptions(obj) Arguments obj Object of class cmpoutput. Value Object of class assumptions_cmpoutput containing the assumptions for parametric tests per- formed on an output comparison. Basically a list containing the assumptions for the MANOVA (list of objects of class assumptions_manova, one per explained variance) and univariate paramet- ric tests for each principal component (object of class assumptions_paruv). Examples # Create a cmpoutput object from the provided datasets cmp <- cmpoutput("All", 0.9, pphpc_ok$data[["All"]], pphpc_ok$obs_lvls) # Get the assumptions for the parametric tests performed in cmp acmp <- assumptions(cmp) assumptions.micomp Get assumptions for parametric tests performed on each comparisons Description Get assumptions for parametric tests performed on multiple comparisons (i.e. from objects of class micomp). Usage ## S3 method for class 'micomp' assumptions(obj) Arguments obj Object of class micomp. Value Object of class assumptions_micomp containing the assumptions for parametric tests performed for the multiple comparisons held by the mcmp object. This object is a multi-dimensional list of assumptions_cmpoutput objects. Rows are associated with individual outputs, while columns are associated with separate comparisons. Examples # Create a micomp object, use provided dataset mic <- micomp(6, 0.8, list(list(name = "NLOKvsJEXOK", grpout = pphpc_ok), list(name = "NLOKvsJEXNOSHUFF", grpout = pphpc_noshuff), list(name = "NLOKvsJEXDIFF", grpout = pphpc_diff))) # Create an object containing the statistic tests evaluating the assumptions # of the comparisons performed in the mic object a <- assumptions(mic) assumptions_manova Determine the assumptions for the MANOVA test Description Determine two assumptions for the MANOVA test: a) multivariate normality of each group; b) homogeneity of covariance matrices. Usage assumptions_manova(data, factors) Arguments data Data used for the MANOVA test (rows correspond to observations, columns to dependent variables). factors Groups to which rows of data belong to (independent variables). Value An object of class assumptions_manova which is a list containing two elements: mvntest List of results from the Royston multivariate normality test (mvn), one result per group. vartest Result of Box’s M test for homogeneity of covariance matrices (boxM). Note This function requires the MVN and biotools packages. Examples # Determine the assumptions of applying MANOVA to the iris data # (i.e. multivariate normality of each group and homogeneity of covariance # matrices) a <- assumptions_manova(iris[, 1:4], iris[, 5]) assumptions_paruv Determine the assumptions for the parametric comparison test Description Determine two assumptions for the parametric comparison tests (i.e. either t.test or aov) for each principal component, namely: a) univariate normality of each group; b) homogeneity of variances. Usage assumptions_paruv(data, factors) Arguments data Data used in the parametric test (rows correspond to observations, columns to principal components). factors Groups to which rows of data belong to. Value An object of class assumptions_paruv which is a list containing two elements: uvntest List of results from the Shapiro-Wilk normality test (shapiro.test), one result per group per principal component. vartest Result of Bartlett test for homogeneity of variances (bartlett.test). Examples # Determine the assumptions of applying ANOVA to each column (dependent # variable) of the iris data (i.e. normality of each group and homogeneity of # variances) a <- assumptions_paruv(iris[, 1:4], iris[, 5]) centerscale Center and scale vector Description Center and scale input vector using the specified method. Usage centerscale(v, type) Arguments v Vector to center and scale. type Type of scaling: "center", "auto", "range", "iqrange", "vast", "pareto", "level" or "none". Value Center and scaled vector using the specified method. References <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. (2006). Centering, scaling, and transformations: improving the biological information content of metabolomics data. BMC Genomics 7, 142. DOI: 10.1186/1471-2164-7-142 Examples v <- c(-100, 3, 4, 500, 10, 25, -8, -33, 321, 0, 2) centerscale(v, "center") # [1] -165.81818 -62.81818 -61.81818 434.18182 -55.81818 -40.81818 # [7] -73.81818 -98.81818 255.18182 -65.81818 -63.81818 centerscale(v, "auto") # [1] -0.9308937 -0.3526577 -0.3470437 2.4374717 -0.3133601 -0.2291509 # [7] -0.4144110 -0.5547596 1.4325760 -0.3694995 -0.3582716 centerscale(v, "range") # [1] -0.2763636 -0.1046970 -0.1030303 0.7236364 -0.0930303 -0.0680303 # [7] -0.1230303 -0.1646970 0.4253030 -0.1096970 -0.1063636 centerscale(v, "iqrange") # [1] -6.085071 -2.305254 -2.268557 15.933278 -2.048374 -1.497915 -2.708924 # [8] -3.626355 9.364470 -2.415346 -2.341952 centerscale(v, "vast") # [1] -0.34396474 -0.13030682 -0.12823247 0.90064453 -0.11578638 -0.08467115 # [7] -0.15312466 -0.20498338 0.52933609 -0.13652987 -0.13238117 centerscale(v, "pareto") # [1] -12.424134 -4.706731 -4.631804 32.531614 -4.182247 -3.058353 # [7] -5.530919 -7.404075 19.119816 -4.931509 -4.781657 centerscale(v, "level") # [1] -2.5193370 -0.9544199 -0.9392265 6.5966851 -0.8480663 -0.6201657 # [7] -1.1215470 -1.5013812 3.8770718 -1.0000000 -0.9696133 centerscale(v, "none") # [1] -100 3 4 500 10 25 -8 -33 321 0 2 cmpoutput Compares output observations from two or more groups Description Compares output observations from two or more groups. Usage cmpoutput(name, ve_npcs, data, obs_lvls, lim_npcs = TRUE, mnv_test = "Pillai") Arguments name Comparison name (useful when calling this function to perform multiple com- parisons). ve_npcs Percentage (0 < ve_npcs < 1) of variance explained by the q principal compo- nents (i.e. number of dimensions) used in MANOVA, or the number of principal components (ve_npcs > 1, must be integer). Can be a vector, in which case the MANOVA test will be applied multiple times, one per specified variance to ex- plain / number of principal components. data A n x m matrix, where n is the total number of output observations (runs) and m is the number of variables (i.e. output length). obs_lvls Levels or groups associated with each observation. lim_npcs Limit number of principal components used for MANOVA to minimum number of observations per group? mnv_test The name of the test statistic to be used in MANOVA, as described in summary.manova. Value Object of class cmpoutput containing the following data: scores n x n matrix containing projections of output data in the principal components space. Rows correspond to observations, columns to principal components. obs_lvls Levels or groups associated with each observation. varexp Percentage of variance explained by each principal component. npcs Number of principal components specified in ve_npcs OR which explain the variance per- centages given in ve_npcs. ve Percentage (between 0 and 1) of variance explained by the q principal components (i.e. number of dimensions) used in MANOVA. name Comparison name (useful when calling this function to perform multiple comparisons). p.values P-values for the performed statistical tests, namely: manova List of p-values for the MANOVA test for each number of principal component in npcs. parametric Vector of p-values for the parametric test applied to groups along each principal component (t-test for 2 groups, ANOVA for more than 2 groups). nonparametric Vector of p-values for the non-parametric test applied to groups along each principal component (Mann-Whitney U test for 2 groups, Kruskal-Wallis test for more than 2 groups). parametric_adjusted Same as field parametric, but p-values are adjusted using weighted Bonferroni procedure. Percentages of explained variance are used as weights. nonparametric_adjusted Same as field nonparametric, but p-values are adjusted using weighted Bonferroni procedure. Percentages of explained variance are used as weights. tests manova Objects returned by the manova function for each value specified in ve_npcs. parametric List of objects returned by applying t.test (two groups) or aov (more than two groups) to each principal component. nonparametric List of objects returned by applying wilcox.test (two groups) or kruskal.test (more than two groups) to each principal component. Examples # Comparing the first output ("Pop.Sheep") of one the provided datasets. cmp <- cmpoutput("SheepPop", 0.8, pphpc_ok$data[["Pop.Sheep"]], pphpc_ok$obs_lvls) # Compare bogus outputs created from 2 random sources, 5 observations per # source, 20 variables each, yielding a 10 x 20 data matrix. data <- matrix(c(rnorm(100), rnorm(100, mean = 1)), nrow = 10, byrow = TRUE) olvls <- factor(c(rep("A", 5), rep("B", 5))) cmp <- cmpoutput("Bogus", 0.7, data, olvls) concat_outputs Concatenate multiple outputs with multiple observations Description Concatenate multiple outputs with multiple observations. Usage concat_outputs(outputlist, centscal = "none") Arguments outputlist List of outputs. Each output is a n x m matrix, where n is the number of obser- vations and m is the number of variables (i.e. output length). centscal Centering and scaling method: "center", "auto", "range", "iqrange", "vast", "pareto", "level" or "none". This task is delegated to the centerscale function. Value An n x p matrix, representing the n observations of the concatenated output, each observation of length p, which is the sum of individual output lengths. Examples # Collect 20 observations of 3 outputs with different scales and lengths # Output 1, length 100 out1 <- matrix(rnorm(2000, mean = 0, sd = 1), nrow = 20) # Output 2, length 200 out2 <- matrix(rnorm(4000, mean = 100, sd = 200), nrow = 20) # Output 1, length 50 out3 <- matrix(rnorm(1000, mean = -1000, sd = 10), nrow = 20) # Concatenate and range scale outputs, resulting matrix dimensions will be # 20 x 350 outconcat <- concat_outputs(list(out1, out2, out3), "range") grpoutputs Load and group outputs from files Description Load and group outputs from files containing multiple observations of the groups to be compared. Usage grpoutputs( outputs, folders, files, lvls = NULL, concat = F, centscal = "range", ... ) Arguments outputs A vector with the labels of each output, or an integer with the number of outputs (in which case output labels will be assigned automatically). In either case, the number of outputs should account for an additional concatenated output, as specified in the concat parameter. folders Vector of folder names where to read files from. These are recycled if length(folders) < length(files). files Vector of filenames or file sets to load in each folder. File sets can be given as regular expressions, or as wildcards by wrapping them with glob2rx. lvls Vector of factor levels (groups). Must be the same length as files, i.e. each file set will be associated with a different level or group. If not given, default group names will be used. concat If TRUE add an additional output which corresponds to the concatenation of all outputs, properly centered and scaled. centscal Method for centering and scaling outputs if concat is TRUE. It can be one of "center", "auto", "range" (default), "iqrange", "vast", "pareto" or "level". Cen- tering and scaling is performed by the centerscale function. ... Options passed to read.table, which is used to read the files specified in the files parameter. Details Each file corresponds to an observation, and should have a tabular format where columns corre- spond to outputs and rows to variables or dimensions. Observations (files) are grouped by factor levels which correspond to the file groups given in the files parameter. Factor levels differentiate observations from distinct groups. Value Object of class grpoutputs containing the following data: data List of all outputs, each one grouped into a n x m matrix, where n is the total number of output observations and m is the number of variables or dimensions (i.e. output length). groupsize Vector containing number of observations for each level or group. obs_lvls Factor vector of levels or groups associated with each observation. lvls Vector of factor levels in the order they occur (as given in parameter with the same name). concat Boolean indicating if this object was created with an additional concatenated output. Examples # Determine paths for data folders, each containing outputs for 10 runs of # the PPHPC model dir_nl_ok <- system.file("extdata", "nl_ok", package = "micompr") dir_jex_ok <- system.file("extdata", "j_ex_ok", package = "micompr") files <- glob2rx("stats400v1*.tsv") # Create a grouped outputs object using outputs from NetLogo and Java # implementations of the PPHPC model go <- grpoutputs(7, c(dir_nl_ok, dir_jex_ok), c(files, files), lvls = c("NL", "JEX"), concat = TRUE) # Do the same, but specify output names and don't specify levels go <- grpoutputs(c("a", "b", "c", "d", "e", "f"), c(dir_nl_ok, dir_jex_ok), c(files, files)) micomp Multiple independent comparisons of observations Description Performs multiple independent comparisons of output observations. Usage micomp( outputs, ve_npcs, comps, concat = F, centscal = "range", lim_npcs = TRUE, mnv_test = "Pillai", ... ) Arguments outputs A vector with the labels of each output, or an integer with the number of outputs (in which case output labels will be assigned automatically). ve_npcs Percentage (0 < ve_npcs < 1) of variance explained by the q principal compo- nents (i.e. number of dimensions) used in MANOVA, or the number of principal components (ve_npcs > 1, must be integer). Can be a vector, in which case the MANOVA test will be applied multiple times, one per specified variance to ex- plain / number of principal components. comps A list of lists, where each list contains information regarding an individual com- parison. Each list can have one of two configurations: 1. Lists with the first configuration are used to load data from files, and require the following fields: name A string specifying the comparison name. folders Vector of folder names where to read files from. These are recycled if length(folders) < length(files). files Vector of filenames (with wildcards) to load in each folder. lvls Vector of level or group names, must be the same length as files, i.e. each file set will be associated with a different group. If not given, default group names will be set. 2. Lists with the second configuration are used to load data from environment variables, and require the following fields: name A string specifying the comparison name. grpout Either an object of class grpoutputs or a list with the following two fields: data List of all outputs, where tags correspond to output names and values correspond to the output data. Output data is a n x m ma- trix, where n is the total number of output observations and m is the number of variables (i.e. output length). obs_lvls Levels or groups associated with each observation. concat Create an additional, concatenated output? Ignored for sublists passed in the comps which follow the second configuration. centscal Method for centering and scaling outputs if concat is TRUE. It can be one of "center", "auto", "range" (default), "iqrange", "vast", "pareto" or "level". Cen- tering and scaling is performed by the centerscale function. lim_npcs Limit number of principal components used for MANOVA to minimum number of observations per group? mnv_test The name of the test statistic to be used in MANOVA, as described in summary.manova. ... Options passed to read.table, which is used to read the files specified in lists using the first configuration in the comp parameter. Value An object of class micomp, which is a two-dimensional list of cmpoutput objects. Rows are associ- ated with individual outputs, while columns are associated with separate comparisons. Examples # Create a micomp object from existing files and folders dir_nl_ok <- system.file("extdata", "nl_ok", package = "micompr") dir_jex_ok <- system.file("extdata", "j_ex_ok", package = "micompr") dir_jex_noshuff <- system.file("extdata", "j_ex_noshuff", package = "micompr") dir_jex_diff <- system.file("extdata", "j_ex_diff", package = "micompr") files <- glob2rx("stats400v1*.tsv") mic <- micomp(7, 0.8, list(list(name = "NLOKvsJEXOK", folders = c(dir_nl_ok, dir_jex_ok), files = c(files, files), lvls = c("NLOK", "JEXOK")), list(name = "NLOKvsJEXNOSHUFF", folders = c(dir_nl_ok, dir_jex_noshuff), files = c(files, files), lvls = c("NLOK", "JEXNOSHUFF")), list(name = "NLOKvsJEXDIFF", folders = c(dir_nl_ok, dir_jex_diff), files = c(files, files), lvls = c("NLOK", "JEXDIFF"))), concat = TRUE) # Create a micomp object from package datasets (i.e. grpoutputs objects) # directly mic <- micomp(c("o1", "o2", "o3", "o4"), 0.9, list(list(name = "NLOKvsJEXOK", grpout = pphpc_ok), list(name = "NLOKvsJEXNOSHUFF", grpout = pphpc_noshuff), list(name = "NLOKvsJEXDIFF", grpout = pphpc_diff))) # Create a micomp object using manually inserted data mic <- micomp(6, 0.5, list( list(name = "NLOKvsJEXOK", grpout = list(data = pphpc_ok$data, obs_lvls = pphpc_ok$obs_lvls)), list(name = "NLOKvsJEXNOSHUFF", grpout = list(data = pphpc_noshuff$data, obs_lvls = pphpc_noshuff$obs_lvls)), list(name = "NLOKvsJEXDIFF", grpout = list(data = pphpc_diff$data, obs_lvls = pphpc_diff$obs_lvls)))) plot.assumptions_cmpoutput Plot p-values for testing the assumptions of the parametric tests used in output comparison Description Plot method for objects of class assumptions_cmpoutput containing p-values produced by testing the assumptions of the parametric tests used for comparing an output. Usage ## S3 method for class 'assumptions_cmpoutput' plot(x, ...) Arguments x Objects of class assumptions_cmpoutput. ... Extra options passed to plot.default. Details Several bar plots are presented, showing the p-values yielded by the Shapiro-Wilk (shapiro.test) and Royston tests (mvn) for univariate and multivariate normality, respectively, and for the Bartlett (bartlett.test) and Box’s M (boxM) for testing homogeneity of variances and of covariance ma- trices, respectively. The following bar plots are shown: • One bar plot for the p-values of the Bartlett test, one bar (p-value) per individual principal component. • s bar plots for p-values of the Shapiro-Wilk test, where s is the number of groups being com- pared. Individual bars in each plot are associated with a principal component. • t bar plot for the p-values of the Royston test with s bars each, where t is the number of unique MANOVA tests performed (one per requested explained variances) and s is the number of groups being compared. These plots will not show if there is only one principal component being considered. • One plot for the p-values of the Box’s M test, one bar (p-value) per unique MANOVA tests performed (one per requested explained variances). Value None. Examples # Create a cmpoutput object from the provided datasets cmp <- cmpoutput("All", 0.9, pphpc_ok$data[["All"]], pphpc_ok$obs_lvls) # Display a bar plot with the p-values of the assumptions for the parametric # tests performed in cmp plot(assumptions(cmp)) plot.assumptions_manova Plot p-values for testing the multivariate normality assumptions of the MANOVA test Description Plot method for objects of class assumptions_manova which presents a bar plot containing the p-values produced by the Royston multivariate normality test (mvn) for each group being compared. Usage ## S3 method for class 'assumptions_manova' plot(x, ...) Arguments x Objects of class assumptions_manova. ... Extra options passed to barplot. The col parameter defines colors for p-values below 1, 0.05 and 0.01, respectively. Value None. Examples # Plot the Royston test p-value for multivariate normality of each group # (species) of the iris data plot(assumptions_manova(iris[, 1:4], iris[, 5])) # Plot the same data with logarithmic scale for p-values plot(assumptions_manova(iris[, 1:4], iris[, 5]), log = "y") plot.assumptions_micomp Plot p-values for testing the assumptions of the parametric tests used in multiple output comparison Description Plot method for objects of class assumptions_cmpoutput containing p-values produced by testing the assumptions of the parametric tests used for multiple output comparisons. Usage ## S3 method for class 'assumptions_micomp' plot(x, ...) Arguments x Object of class assumptions_micomp. ... Extra options passed to barplot. Details Several bar plots are presented, one for each comparison and output combination, showing the several statistical tests employed to verify the assumptions of the parametric tests. Value None. Examples # Create a micomp object, use provided dataset mic <- micomp(6, 0.65, list(list(name = "NLOKvsJEXOK", grpout = pphpc_ok), list(name = "NLOKvsJEXNOSHUFF", grpout = pphpc_noshuff), list(name = "NLOKvsJEXDIFF", grpout = pphpc_diff))) # Plot the p-values of the statistic tests evaluating the assumptions of the # comparisons performed in the mic object plot(assumptions(mic)) plot.assumptions_paruv Plot p-values for testing the assumptions of the parametric tests used in output comparison Description Plot method for objects of class assumptions_paruv containing p-values produced by testing the assumptions of the parametric tests used for comparing outputs. Usage ## S3 method for class 'assumptions_paruv' plot(x, ...) Arguments x Objects of class assumptions_paruv. ... Extra options passed to barplot. The col parameter defines colors for p-values below 1, 0.05 and 0.01, respectively. Details One bar plot is presented for the Bartlett test (bartlett.test), showing the respective p-values along principal component. s bar plots are presented for the Shapiro-Wilk (shapiro.test), where s is the number of groups being compared; individual bars in each plot represent the p-values associated with each principal component. Value None. Examples # Plot the Shapiro-Wilk and Bartlett test p-values for each dependent # variable of the iris data plot(assumptions_paruv(iris[, 1:4], iris[, 5])) # Plot the same data with logarithmic scale for p-values plot(assumptions_paruv(iris[, 1:4], iris[, 5]), log = "y") plot.cmpoutput Plot comparison of an output Description Plot objects of class cmpoutput. Usage ## S3 method for class 'cmpoutput' plot(x, ...) Arguments x Object of class cmpoutput. ... Extra options passed to plot.default. The col option determines the colors to use on observations of different groups (scatter plot only). Details This method produces four sub-plots, namely: • Scatter plot containing the projection of output observations on the first two dimensions of the principal components space. • Bar plot of the percentage of variance explain per principal component. • Bar plot of p-values for the parametric test for each principal component. • Bar plot of p-values for the non-parametric test for each principal component. Value None. Examples # Comparing the concatenated output of the pphpc_ok dataset, which # contains simulation output data from two similar implementations of the # PPHPC model. plot(cmpoutput("All", 0.95, pphpc_ok$data[["All"]], pphpc_ok$obs_lvls)) plot.grpoutputs Plot grouped outputs Description Plot objects of class grpoutputs. Usage ## S3 method for class 'grpoutputs' plot(x, ...) Arguments x Object of class grpoutputs. ... Extra options passed to plot.default. Details Each output is plotted individually, and observations are plotted on top of each other. Observations from different groups are plotted with different colors (which can be controlled through the col parameter given in ...). This function can be very slow for a large number of observations. Value None. Examples # Determine paths for the data folder containing outputs of different # lengths dir_na <- system.file("extdata", "testdata", "NA", package = "micompr") # Sets of files A and B have 3 files each filesA <- glob2rx("stats400v1*n20A.tsv") filesB <- glob2rx("stats400v1*n20B.tsv") # Instantiate grpoutputs object go <- grpoutputs(7, dir_na, c(filesA, filesB), lvls = c("A", "B"), concat = TRUE) # Plot grpoutputs object plot(go) plot.micomp Plot projection of output observations on the first two dimensions of the principal components space Description For each comparison and output combination, draw a scatter plot containing the projection of output observations on the first two dimensions of the principal components space. Usage ## S3 method for class 'micomp' plot(x, ...) Arguments x An object of class micomp. ... Extra options passed to plot.default. The col option determines the colors to use on observations of different groups. Value None. Examples plot(micomp(c("SheepPop", "WolfPop", "GrassQty"), 0.95, list(list(name = "I", grpout = pphpc_ok), list(name = "II", grpout = pphpc_noshuff), list(name = "III", grpout = pphpc_diff)))) pphpc_diff Data from two implementations of the PPHPC model, one of which setup with a different parameter Description A dataset containing simulation output data from two implementations of the PPHPC model, one of which setup with a different parameter. Usage pphpc_diff Format A grpoutputs object containing simulation output data from 20 runs of the PPHPC model, 10 runs from each implementation. The model has six outputs, but the object contains a seventh output corresponding to the concatenation of the six outputs Source Runs are obtained from the NetLogo and Java (EX with 8 threads) implementations of the PPHPC model available at https://github.com/nunofachada/pphpc. The config400v1.txt configura- tion was used in both cases, with the exception of restart parameter, cr , in the Java implementation, which was set to 9 instead of 10. pphpc_noshuff Data from two implementations of the PPHPC model, one of which has agent list shuffling deactivated Description A dataset containing simulation output data from two implementations of the PPHPC model, one of which has agent list shuffling deactivated. Usage pphpc_noshuff Format A grpoutputs object containing simulation output data from 20 runs of the PPHPC model, 10 runs from each implementation. The model has six outputs, but the object contains a seventh output corresponding to the concatenation of the six outputs Source Runs are obtained from the NetLogo and Java (EX with 8 threads) implementations of the PPHPC model available at https://github.com/nunofachada/pphpc. The config400v1.txt configu- ration was used in both cases. Runs with the Java implementation were performed with the ’-u’ option, i.e. with agent list shuffling turned off. pphpc_ok Data from two similar implementations of the PPHPC model Description A dataset containing simulation output data from two implementations of the PPHPC model. Usage pphpc_ok Format A grpoutputs object containing simulation output data from 20 runs of the PPHPC model, 10 runs from each implementation. The model has six outputs, but the object contains a seventh output corresponding to the concatenation of the six outputs Source Runs are obtained from the NetLogo and Java (EX with 8 threads) implementations of the PPHPC model available at https://github.com/nunofachada/pphpc. The config400v1.txt configu- ration was used in both cases. print.assumptions_cmpoutput Print method for the assumptions of parametric tests used in a com- parison of an output Description Print method for objects of class assumptions_cmpoutput, which contain the assumptions for the parametric tests used in a comparison of an output. Usage ## S3 method for class 'assumptions_cmpoutput' print(x, ...) Arguments x Object of class assumptions_cmpoutput. ... Currently ignored. Value None. Examples # Create a cmpoutput object from the provided datasets cmp <- cmpoutput("All", c(0.7, 0.8, 0.9), pphpc_diff$data[["All"]], pphpc_diff$obs_lvls) print.assumptions_manova Print information about the assumptions of the MANOVA test Description Print information about objects of class assumptions_manova, which represent the assumptions of the MANOVA test performed on a comparison of outputs. Usage ## S3 method for class 'assumptions_manova' print(x, ...) Arguments x Object of class assumptions_manova. ... Currently ignored. Value The argument x, invisibly, as for all print methods. Examples # Print information concerning the assumptions of applying MANOVA to the iris # data (i.e. multivariate normality of each group and homogeneity of # covariance matrices) assumptions_manova(iris[, 1:4], iris[, 5]) print.assumptions_micomp Print information about the assumptions concerning the parametric tests performed on multiple comparisons of outputs Description Print information about objects of class assumptions_micomp, which represent the assumptions concerning the parametric tests performed on multiple comparisons of outputs. Usage ## S3 method for class 'assumptions_micomp' print(x, ...) Arguments x Object of class assumptions_micomp. ... Currently ignored. Value The argument x, invisibly, as for all print methods. Examples # Create a micomp object, use provided dataset mic <- micomp(c("SheepPop", "WolfPop", "GrassQty"), 0.7, list(list(name = "NLOKvsJEXOK", grpout = pphpc_ok), list(name = "NLOKvsJEXNOSHUFF", grpout = pphpc_noshuff), list(name = "NLOKvsJEXDIFF", grpout = pphpc_diff))) # Print the results (p-values) of the statistic tests evaluating the # assumptions of the comparisons performed in the mic object assumptions(mic) print.assumptions_paruv Print information about the assumptions of the parametric test Description Print information about objects of class assumptions_paruv, which represent the assumptions of the parametric test (i.e. either t.test or aov) performed on a comparison of outputs. Usage ## S3 method for class 'assumptions_paruv' print(x, ...) Arguments x Object of class assumptions_paruv. ... Currently ignored. Value The argument x, invisibly, as for all print methods. Examples # Print information about the assumptions of applying ANOVA to each column # (dependent variable) of the iris data (i.e. normality of each group and # homogeneity of variances) assumptions_paruv(iris[, 1:4], iris[, 5]) print.cmpoutput Print information about comparison of an output Description Print information about objects of class cmpoutput. Usage ## S3 method for class 'cmpoutput' print(x, ...) Arguments x Object of class cmpoutput. ... Currently ignored. Value The argument x, invisibly, as for all print methods. Examples # Comparing the fifth output of the pphpc_diff dataset, which contains # simulation output data from two implementations of the PPHPC model executed # with a different parameter. cmpoutput("WolfPop", 0.7, pphpc_diff$data[[5]], pphpc_diff$obs_lvls) print.grpoutputs Print information about grouped outputs Description Print information about objects of class grpoutputs. Usage ## S3 method for class 'grpoutputs' print(x, ...) Arguments x Object of class grpoutputs. ... Currently ignored. Value The argument x, invisibly, as for all print methods. Examples # Determine paths for data folders, each containing outputs for 10 runs of # the PPHPC model dir_nl_ok <- system.file("extdata", "nl_ok", package = "micompr") dir_jex_diff <- system.file("extdata", "j_ex_diff", package = "micompr") files <- glob2rx("stats400v1*.tsv") # Create a grpoutputs object go <- grpoutputs(6, c(dir_nl_ok, dir_jex_diff), c(files, files)) # Print information about object (could just type "go" instead) print(go) print.micomp Print information about multiple comparisons of outputs Description Print information about objects of class micomp. Usage ## S3 method for class 'micomp' print(x, ...) Arguments x Object of class micomp. ... Currently ignored. Value The argument x, invisibly, as for all print. methods. Examples # A micomp object from package datasets (i.e. grpoutputs objects) directly micomp(c("outA", "outB", "outC", "outD"), 0.9, list(list(name = "Comp1", grpout = pphpc_ok), list(name = "Comp2", grpout = pphpc_noshuff), list(name = "Comp3", grpout = pphpc_diff))) pvalf Format p-values Description Generic function to format p-values. Usage pvalf(pval, params) Arguments pval Numeric p-value to format (between 0 and 1). params A list of method-dependent options. Value A string representing the formatted p-value. See Also pvalf.default pvalf.default Default p-value formatting method Description Format a p-value for printing in a LaTeX table. Requires the ulem LaTeX package for underlining the p-values. Usage ## Default S3 method: pvalf(pval, params = list()) Arguments pval Numeric value between 0 and 1. params A list of options. This function accepts the following options: minval If p-value is below this value, return this value preceded by a "<" sign instead instead. lim1val If p-value is below this value, it will be double-underlined. lim2val If p-value is below this value, it will be underlined. na_str String to use for NAs. By default NAs are returned as is. Value A string representing the formatted pval. Examples pvalf(0.1) pvalf(0.000001) pvalf(c(0.06, 0.04, 0.005, 0.00001), list(minval = 0.0001)) summary.assumptions_cmpoutput Summary method for the assumptions of parametric tests used in a comparison of an output Description Summary method for objects of class assumptions_cmpoutput, which contain the assumptions for the parametric tests used in a comparison of an output. Usage ## S3 method for class 'assumptions_cmpoutput' summary(object, ...) Arguments object Object of class assumptions_cmpoutput. ... Currently ignored. Value A list with the following items: manova A matrix of p-values for the MANOVA assumptions. All rows, expect the last one, corre- spond to the Royston test for multivariate normality for each group; the last row corresponds to Box’s M test for homogeneity of covariance matrices. Columns correspond to number of principal components required to explain the percentage of user-specified variance. ttest A matrix of p-values for the t-test assumptions. All rows, expect the last one, correspond to the Shapiro-Wilk normality test for each group; the last row corresponds to Bartlett’s for equality of variances. Columns correspond to the principal components on which the t-test was applied. Examples # Create a cmpoutput object from the provided datasets cmp <- cmpoutput("All", c(0.5, 0.6, 0.7), pphpc_ok$data[["All"]], pphpc_ok$obs_lvls) # Obtain the summary of the assumptions of the cmpoutput object summary(assumptions(cmp)) summary.assumptions_micomp Summary method for the assumptions of parametric tests used in mul- tiple comparisons of outputs Description Summary method for objects of class assumptions_micomp, which contain the assumptions for the parametric tests used in multiple comparisons of outputs. Usage ## S3 method for class 'assumptions_micomp' summary(object, ...) Arguments object Object of class assumptions_micomp. ... Currently ignored. Value A list in which each component is associated with a distinct comparison. Each component contains a matrix, in which columns represent individual outputs and rows correspond to the statistical tests evaluating the assumptions of the parametric tests used in each output. More specifically, each matrix has rows with the following information: Royston (group, ve=%/npcs=) One row per group per variance to explain / number of PCs, with the p-value yielded by the Royston test (mvn) for the respective group and variance/npcs com- bination. Box’s M (ve=%/npcs=) One row per variance to explain with the p-value yielded by Box’s M test (boxM). Shapiro-Wilk (group) One row per group, with the p-value yielded by the Shapiro-Wilk test (shapiro.test) for the respective group. Bartlett One row with the p-value yielded by Bartlett’s test (bartlett.test). Examples # Create a micomp object, use provided dataset mic <- micomp(5, c(0.7, 0.8, 0.9), list(list(name = "NLOKvsJEXOK", grpout = pphpc_ok), list(name = "NLOKvsJEXNOSHUFF", grpout = pphpc_noshuff)), concat = TRUE) # Get the assumptions summary sam <- summary(assumptions(mic)) summary.cmpoutput Summary method for comparison of an output Description Summary method for objects of class cmpoutput. Usage ## S3 method for class 'cmpoutput' summary(object, ...) Arguments object Object of class cmpoutput. ... Currently ignored. Value A list with the following components: output.name Output name. num.pcs Number of principal components which explain var.exp percentage of variance. var.exp Minimum percentage of variance which must be explained by the number of principal components used for the MANOVA test. manova.pvals P-value of the MANOVA test. parametric.test Name of the used parametric test. parametric.pvals Vector of $p$-values returned by applying the parametric test to each principal component. parametric.pvals.adjusted Vector of $p$-values returned by applying the parametric test to each principal component, adjusted with the weighted Bonferroni procedure, percentage of ex- plained variance used as weight. nonparametric.test Name of the used non-parametric test. nonparametric.pvals Vector of $p$-values returned by applying the non-parametric test to each principal component. nonparametric.pvals.adjusted Vector of $p$-values returned by applying the non-parametric test to each principal component, adjusted with the weighted Bonferroni procedure, percentage of explained variance used as weight. Examples # Comparing the concatenated output of the pphpc_noshuff dataset, which # contains simulation output data from two implementations of the PPHPC model # executed with a minor implementation difference. summary( cmpoutput("All", 0.6, pphpc_noshuff$data[["All"]], pphpc_noshuff$obs_lvls) ) summary.grpoutputs Summary method for grouped outputs Description Summary method for objects of class grpoutputs. Usage ## S3 method for class 'grpoutputs' summary(object, ...) Arguments object Object of class grpoutputs. ... Currently ignored. Value A list with the following components: output.dims Dimensions for each output, i.e. number of observations and number of variables (i.e. output length). group.sizes Number of output observations in each group. Examples # Determine paths for data folders, each containing outputs for 10 runs of # the PPHPC model dir_nl_ok <- system.file("extdata", "nl_ok", package = "micompr") dir_jex_noshuff <- system.file("extdata", "j_ex_noshuff", package = "micompr") files <- glob2rx("stats400v1*.tsv") # Create a grpoutputs object go <- grpoutputs(c("o1", "o2"), c(dir_nl_ok, dir_jex_noshuff), c(files, files)) summary.micomp Summary method for multiple comparisons of outputs Description Summary method for objects of class micomp. Usage ## S3 method for class 'micomp' summary(object, ...) Arguments object Object of class micomp. ... Currently ignored. Value A list in which each component is associated with a distinct comparison. Each component contains a matrix, in which columns represent individual outputs and rows have information about the outputs. More specifically, each matrix has the following rows: #PCs (ve=%) Number of principal components required to explain the specified percentage of variance. There is one row of this kind for each percentage of variance specified when creating the micomp object. MANOVA (ve=%) P-value for the MANOVA test applied to the #PCs required to explain the specified percentage of variance. There is one row of this kind for each percentage of variance specified when creating the micomp object. par.test P-value for the parametric test (first principal component). nonpar.test P-value for the non-parametric test (first principal component). par.test.adjust P-value for the parametric test (first principal component), adjusted with the weighted Bonferroni procedure, percentage of explained variance used as weight. nonpar.test.adjust P-value for the non-parametric test (first principal component), adjusted with the weighted Bonferroni procedure, percentage of explained variance used as weight. Examples # A micomp object from package datasets (i.e. grpoutputs objects) directly summary(micomp(5, 0.85, list(list(name = "CompEq", grpout = pphpc_ok), list(name = "CompNoShuf", grpout = pphpc_noshuff), list(name = "CompDiff", grpout = pphpc_diff)))) tikzscat Simple TikZ scatter plot Description Create a simple 2D TikZ scatter plot, useful for plotting PCA data. Usage tikzscat(data, obs_lvls, marks, tscale, axes_color = "gray") Arguments data Data to plot, m x 2 numeric matrix, where m is the number of observations or points to plot. obs_lvls Levels or groups associated with each observation. marks Character vector determining how to draw the points in TikZ, for example: c("mark=square*,mark options={color=red},mark size=0.8pt", "mark=diamond*,mark options={color=black},mark size=1pt", "mark=triangle*,mark options={color=green},mark size=1pt"). tscale The scale property of the TikZ figure. axes_color Axes color (must be a LaTeX/TikZ color). Details This function creates a simple TikZ 2D scatter plot within a tikzpicture environment. The points are plotted on a normalized figure with x and y axes bounded between [-1, 1]. To render adequately, the final LaTeX document should load the plotmarks TikZ library. Value A string containing the TikZ figure code for plotting the specified data. Examples tikzscat(rbind(c(1.5, 2), c(0.5, 1)), factor(c(1,2)), c("mark=square*,mark options={color=red},mark size=0.8pt", "mark=diamond*,mark options={color=black},mark size=1pt"), 6) toLatex.cmpoutput Convert cmpoutput object to LaTeX table Description This method converts cmpoutput objects to character vectors representing LaTeX tables. Usage ## S3 method for class 'cmpoutput' toLatex(object, cmp_name = "Comp. 1", ...) Arguments object A cmpoutput object. cmp_name Comparison name (to appear in table). ... Any options accepted by the toLatex.micomp function. Details This method simply wraps the cmpoutput object into a micomp object, and invokes toLatex.micomp on the wrapped object. Value A character vector where each element holds one line of the corresponding LaTeX table. Examples # Create a cmpoutput object by comparing the first output ("Pop.Sheep") of # one the provided datasets. cmp <- cmpoutput("SheepPop", 0.9, pphpc_ok$data[["Pop.Sheep"]], pphpc_ok$obs_lvls) # Print latex table source to screen toLatex(cmp) toLatex.micomp Convert micomp object to LaTeX table Description This method converts micomp objects to character vectors representing LaTeX tables. Usage ## S3 method for class 'micomp' toLatex( object, ..., orientation = T, data_show = c("npcs-1", "mnvp-1", "parp-1", "nparp-1", "scoreplot"), data_labels = NULL, labels_cmp_show = T, labels_col_show = T, label_row_show = T, tag_comp = "Comp.", tag_data = "Data", tag_outputs = "Outputs", table_placement = "ht", latex_envs = c("center"), booktabs = F, booktabs_cmalign = "l", caption = NULL, caption_cmd = "\\caption", label = NULL, col_width = F, pvalf_f = pvalf.default, pvalf_params = list(), scoreplot_marks = c("mark=square*,mark options={color=red},mark size=0.8pt", "mark=diamond*,mark options={color=black},mark size=1pt", "mark=triangle*,mark options={color=green},mark size=1pt"), scoreplot_scale = 6, scoreplot_before = "\\raisebox{-.5\\height}{\\resizebox {1.2cm} {1.2cm} {", scoreplot_after = "}}" ) Arguments object A micomp object. ... Currently ignored. orientation If TRUE, outputs are placed along columns, while data is placed along rows. If FALSE, outputs are placed along rows, while data is placed along columns. data_show Vector of strings specifying what data to show. Available options are: npcs-i Number of principal components required to explain i-th user-specified percentage of variance. mnvp-i MANOVA p-values for the i-th user-specified percentage of variance to explain. parp-j Parametric test p-values for the j-th principal component. nparp-j Non-parametric test p-values for the j-th principal component. aparp-j Parametric test p-values adjusted with weighted Bonferroni procedure for the j-th principal component. anparp-j Non-parametric test p-values adjusted with weighted Bonferroni pro- cedure for the j-th principal component. varexp-j Explained variance for the j-th principal component. scoreplot Output projection on the first two principal components. sep Place a separator (e.g. midrule) between data. data_labels Vector of strings specifying the labels of the data to show. If NULL, default labels are used for all elements. If individual elements are set to NA, default labels will be used for those elements. labels_cmp_show Show the column containing the comparison labels? labels_col_show Show the column containing the data labels (orientation == T) or the output labels (orientation == F)? label_row_show Show the tag_outputs tag? If TRUE, the row identifier part will have two levels, the tag_outputs label and output names (orientation == T), or the tag_data and data labels (orientation == F). If FALSE only the output names or data labels are shown. tag_comp Tag identifying comparison labels. tag_data Tag identifying data labels. tag_outputs Tag identifying outputs. table_placement LaTeX table placement. latex_envs Wrap table in the specified LaTeX environments. booktabs Use booktabs table beautifier package? booktabs_cmalign How to align cmidule when using the booktabs package. caption Table caption. caption_cmd Command used for table caption. label Table label for cross-referencing. col_width Resize table to page column width? pvalf_f P-value formatter function, which receives a numeric value between 0 and 1 and returns a string containing the formatted value. Default is pvalf.default (requires ulem LaTeX package). pvalf_params Parameters for pvalf_f function. Default is empty list. scoreplot_marks Vector of strings specifying how TikZ should draw points belonging to each group in the score plot. scoreplot_scale TikZ scale for each score plot figure. scoreplot_before LaTeX code to paste before each TikZ score plot figure. scoreplot_after LaTeX code to paste after each TikZ score plot figure. Details This method is inspired by the functionality provided by the xtable and print.xtable functions (from the xtable package), but follows the standard behavior of the toLatex generic. Value A character vector where each element holds one line of the corresponding LaTeX table. Examples # Create a micomp object, use provided dataset, three first outputs, plus # a fourth concatenated output mic <- micomp(4, 0.8, list(list(name = "NLOKvsJEXOK", grpout = pphpc_ok), list(name = "NLOKvsJEXNOSHUFF", grpout = pphpc_noshuff), list(name = "NLOKvsJEXDIFF", grpout = pphpc_diff)), concat = TRUE) # Print latex table source to screen toLatex(mic)
to-file-path
npm
JavaScript
to-file-path === > Create a filepath from an object path (dot notation), list of arguments, > array, number or Arguments object. Please consider following this project's author, [<NAME>](https://github.com/tunnckoCore), and ⭐ the project to show your ❤️ and support. If you have any *how-to* kind of questions, please read the [Contributing Guide](https://github.com/tunnckoCore/opensource/blob/master/CONTRIBUTING.md) and [Code of Conduct](https://github.com/tunnckoCore/opensource/blob/master/CODE_OF_CONDUCT.md) documents. For bugs reports and feature requests, [please create an issue](https://github.com/tunnckoCore/opensource/issues/new) or ping [@tunnckoCore](https://twitter.com/tunnckoCore) at Twitter. Project is [semantically](https://semver.org) versioned & automatically released from [GitHub Actions](https://github.com/features/actions) with [Lerna](https://github.com/lerna/lerna). | Topic | Contact | | --- | --- | | Any legal or licensing questions, like private or commerical use | | | For any critical problems and security reports | | | Consulting, professional support, personal or team training | | | For any questions about Open Source, partnerships and sponsoring | | Table of Contents --- * [Install](#install) * [API](#api) + [toFilePath](#tofilepath) * [See Also](#see-also) * [Contributing](#contributing) + [Guides and Community](#guides-and-community) + [Support the project](#support-the-project) * [Contributors](#contributors) * [License](#license) *(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))* Install --- This project requires [**Node.js**](https://nodejs.org) **>=10.13** *(see [Support & Release Policy](https://github.com/tunnckoCoreLabs/support-release-policy))*. Install it using [**yarn**](https://yarnpkg.com) or [**npm**](https://npmjs.com). *We highly recommend to use Yarn when you think to contribute to this project.* ``` $ yarn add to-file-path ``` API --- *Generated using [jest-runner-docs](https://ghub.now.sh/jest-runner-docs).* ### [toFilePath](https://github.com/tunnckoCore/opensource/blob/HEAD/modules/to-file-path/src/index.js#L23) Create filepath from different type of arguments. #### Signature ``` function(args) ``` #### Params * `...args` **{string|array|Arguments|number|boolean}** - Pass any type and any number of arguments. * `returns` **{string}** - always slash separated filepath #### Examples ``` import toFilePath from 'to-file-path'; console.log(toFilePath('foo.bar.baz')); // => 'foo/bar/baz' console.log(toFilePath('foo.bar', 'qux.baz', 'xxx')); // => 'foo/bar/qux/baz/xxx' console.log(toFilePath('foo', 'qux', 'baz')); // => 'foo/qux/baz' console.log(toFilePath([1, 2, 3], 'foo', 4, 'bar')); // => '1/2/3/foo/4/bar' console.log(toFilePath(null, true)); // => 'null/true' console.log(toFilePath(1, 2, 3)); // => '1/2/3' ``` **[back to top](#readme)** See Also --- Some of these projects are used here or were inspiration for this one, others are just related. So, thanks for your existance! * [arr-includes](https://www.npmjs.com/package/arr-includes): Return positive value if (any of the) passed value(s) exists… [more](https://tunnckocore.com/opensource) | [homepage](https://tunnckocore.com/opensource "Return positive value if (any of the) passed value(s) exists in array, or optionally an index") * [arr-map](https://www.npmjs.com/package/arr-map): Faster, node.js focused alternative to JavaScript's native array map. | [homepage](https://github.com/jonschlinkert/arr-map "Faster, node.js focused alternative to JavaScript's native array map.") * [get-fn-name](https://www.npmjs.com/package/get-fn-name): Get function name with strictness and correctness in mind. Also… [more](https://github.com/tunnckocore/get-fn-name#readme) | [homepage](https://github.com/tunnckocore/get-fn-name#readme "Get function name with strictness and correctness in mind. Also works for arrow functions and getting correct name of bounded functions. Powered by [fn-name][].") * [in-array](https://www.npmjs.com/package/in-array): Return true if a value exists in an array. Faster… [more](https://github.com/jonschlinkert/in-array) | [homepage](https://github.com/jonschlinkert/in-array "Return true if a value exists in an array. Faster than using indexOf and won't blow up on null values.") * [ip-filter](https://www.npmjs.com/package/ip-filter): Validates valid IPs (IPv4 and IPv6) using [micromatch](https://github.com/micromatch/micromatch) - glob… [more](https://tunnckocore.com/opensource) | [homepage](https://tunnckocore.com/opensource "Validates valid IPs (IPv4 and IPv6) using [micromatch][] - glob patterns, RegExp, string or array of globs. If match returns the IP, otherwise null.") * [to-object-path](https://www.npmjs.com/package/to-object-path): Create an object path from a list or array of… [more](https://github.com/jonschlinkert/to-object-path) | [homepage](https://github.com/jonschlinkert/to-object-path "Create an object path from a list or array of strings.") **[back to top](#readme)** Contributing --- ### Guides and Community Please read the [Contributing Guide](https://github.com/tunnckoCore/opensource/blob/master/CONTRIBUTING.md) and [Code of Conduct](https://github.com/tunnckoCore/opensource/blob/master/CODE_OF_CONDUCT.md) documents for advices. For bug reports and feature requests, please join our [community](https://github.com/tunnckocorehq/community) forum and open a thread there with prefixing the title of the thread with the name of the project if there's no separate channel for it. Consider reading the [Support and Release Policy](https://github.com/tunnckoCoreLabs/support-release-policy) guide if you are interested in what are the supported Node.js versions and how we proceed. In short, we support latest two even-numbered Node.js release lines. ### Support the project [Become a Partner or Sponsor?](https://ko-fi.com/tunnckoCore) 💵 Check the **OpenSource** Commision (tier). 🎉 You can get your company logo, link & name on this file. It's also rendered on package's page in [npmjs.com](https://www.npmjs.com/package/to-file-path) and [yarnpkg.com](https://yarnpkg.com/en/package/to-file-path) sites too! 🚀 Not financial support? Okey! [Pull requests](https://github.com/tunnckoCoreLabs/contributing#opening-a-pull-request), stars and all kind of [contributions](https://opensource.guide/how-to-contribute/#what-it-means-to-contribute) are always welcome. ✨ Contributors --- This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome! Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)), consider showing your [support](#support-the-project) to them: | | | --- | | [**Charlike Mike Reagent**](https://tunnckoCore.com)[🚇](#infra-tunnckoCore "Infrastructure (Hosting, Build-Tools, etc)") [💻](https://github.com/node-formidable/node-formidable/commits?author=tunnckoCore "Code") [📖](https://github.com/node-formidable/node-formidable/commits?author=tunnckoCore "Documentation") [🤔](#ideas-tunnckoCore "Ideas, Planning, & Feedback") [🚧](#maintenance-tunnckoCore "Maintenance") [⚠️](https://github.com/node-formidable/node-formidable/commits?author=tunnckoCore "Tests") | **[back to top](#readme)** License --- Copyright (c) 2016-present, [Charlike Mike Reagent](https://tunnckocore.com) `<<EMAIL>>` & [contributors](#wonderful-contributors). Released under the [MPL-2.0 License](https://github.com/tunnckoCore/opensource/blob/master/packages/to-file-path/LICENSE). Readme --- ### Keywords * args * arguments * dot * dot-notation * file * filepath * fp * list * notation * obj * object * path * to * to-file * to-file-path * to-filepath * to-path * util * utility * tunnckocore-oss * tunnckocorehq * valid * validate
ring-cors
hex
Erlang
ring.middleware.cors === Ring middleware for Cross-Origin Resource Sharing. ``` Ring middleware for Cross-Origin Resource Sharing. ``` [raw docstring](#) --- #### add-access-controlclj ``` (add-access-control request access-control response) ``` Add the access-control headers to the response based on the rules and what came on the header. ``` Add the access-control headers to the response based on the rules and what came on the header. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L138)[raw docstring](#) --- #### add-allowed-headersclj ``` (add-allowed-headers request allowed-headers response) ``` Adds the allowed headers to the request ``` Adds the allowed headers to the request ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L123)[raw docstring](#) --- #### add-headersclj ``` (add-headers request access-control response) ``` Add the access control headers using the request's origin to the response. ``` Add the access control headers using the request's origin to the response. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L115)[raw docstring](#) --- #### allow-method?clj ``` (allow-method? request allowed-methods) ``` In the case of regular requests it checks if the request-method is allowed. In the case of preflight requests it checks if the access-control-request-method is allowed. ``` In the case of regular requests it checks if the request-method is allowed. In the case of preflight requests it checks if the access-control-request-method is allowed. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L57)[raw docstring](#) --- #### allow-preflight-headers?clj ``` (allow-preflight-headers? request allowed-headers) ``` Returns true if the request is a preflight request and all the headers that it's going to use are allowed. Returns false otherwise. ``` Returns true if the request is a preflight request and all the headers that it's going to use are allowed. Returns false otherwise. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L47)[raw docstring](#) --- #### allow-request?clj ``` (allow-request? request access-control) ``` Returns true if the request's origin matches the access control origin, otherwise false. ``` Returns true if the request's origin matches the access control origin, otherwise false. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L69)[raw docstring](#) --- #### handle-corsclj ``` (handle-cors handler request access-control response-handler) ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L160) --- #### header-nameclj ``` (header-name header) ``` Returns the capitalized header name as a string. ``` Returns the capitalized header name as a string. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L93)[raw docstring](#) --- #### lower-case-setclj ``` (lower-case-set s) ``` Converts strings in a sequence to lower-case, and put them into a set ``` Converts strings in a sequence to lower-case, and put them into a set ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L32)[raw docstring](#) --- #### normalize-configclj ``` (normalize-config access-control) ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L150) --- #### normalize-headersclj ``` (normalize-headers headers) ``` Normalize the headers by converting them to capitalized strings. ``` Normalize the headers by converting them to capitalized strings. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L101)[raw docstring](#) --- #### originclj ``` (origin request) ``` Returns the Origin request header. ``` Returns the Origin request header. ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L23)[raw docstring](#) --- #### parse-headersclj ``` (parse-headers s) ``` Transforms a comma-separated string to a set ``` Transforms a comma-separated string to a set ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L40)[raw docstring](#) --- #### preflight?clj ``` (preflight? request) ``` Returns true if the request is a preflight request ``` Returns true if the request is a preflight request ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L27)[raw docstring](#) --- #### wrap-corsclj ``` (wrap-cors handler & access-control) ``` Middleware that adds Cross-Origin Resource Sharing headers. (def handler (-> routes (wrap-cors :access-control-allow-origin #"<http://example.com>" :access-control-allow-methods [:get :put :post :delete]))) ``` Middleware that adds Cross-Origin Resource Sharing headers. (def handler (-> routes (wrap-cors :access-control-allow-origin #"http://example.com" :access-control-allow-methods [:get :put :post :delete]))) ``` [source](https://github.com/r0man/ring-cors/blob/0.1.12/src/ring/middleware/cors.clj#L173)[raw docstring](#)
github.com/libp2p/go-libp2p-blankhost
go
Go
README [¶](#section-readme) --- ### DEPRECATION NOTICE This package has moved into go-libp2p as a sub-package, `github.com/libp2p/go-libp2p/p2p/host/blank`. ### go-libp2p-blankhost [![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://protocol.ai) [![](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/) [![](https://img.shields.io/badge/freenode-%23libp2p-yellow.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23libp2p) [![Travis CI](https://travis-ci.org/libp2p/go-libp2p-blankhost.svg?branch=master)](https://travis-ci.org/libp2p/go-libp2p-blankhost) [![Discourse posts](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg)](https://discuss.libp2p.io) A very thin implementation of go-libp2p-host. Does not contain any identify, relay, or NAT traversal code. #### Table of Contents * [Install](#readme-install) * [Contribute](#readme-contribute) * [License](#readme-license) #### Install ``` make install ``` #### Contribute PRs are welcome! Small note: If editing the Readme, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification. #### License MIT © <NAME> --- The last gx published version of this module was: 0.3.26: QmcBTHN7uAMBdkzRoQ3n9cE7tGu8Ubd9zmahjskjTRw4Uf Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Deprecated: This package has moved into go-libp2p as a sub-package, github.com/libp2p/go-libp2p/p2p/host/blank. ### Index [¶](#pkg-index) * [type BlankHost](#BlankHost) * + [func NewBlankHost(n network.Network, options ...Option) *BlankHost](#NewBlankHost)deprecated * [type Option](#Option)deprecated * + [func WithConnectionManager(cmgr connmgr.ConnManager) Option](#WithConnectionManager)deprecated + [func WithEventBus(eventBus event.Bus) Option](#WithEventBus)deprecated ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) This section is empty. ### Types [¶](#pkg-types) #### type [BlankHost](https://github.com/libp2p/go-libp2p-blankhost/blob/v0.4.0/blank.go#L14) [¶](#BlankHost) ``` type BlankHost = [blankhost](/github.com/libp2p/go-libp2p/p2p/host/blank).[BlankHost](/github.com/libp2p/go-libp2p/p2p/host/blank#BlankHost) ``` BlankHost is the thinnest implementation of the host.Host interface Deprecated: use github.com/libp2p/go-libp2p/p2p/host/blank.BlankHost instead. #### func [NewBlankHost](https://github.com/libp2p/go-libp2p-blankhost/blob/v0.4.0/blank.go#L30) deprecated ``` func NewBlankHost(n [network](/github.com/libp2p/go-libp2p-core/network).[Network](/github.com/libp2p/go-libp2p-core/network#Network), options ...[Option](#Option)) *[BlankHost](#BlankHost) ``` Deprecated: use github.com/libp2p/go-libp2p/p2p/host/blank.NewBlankHost instead. #### type [Option](https://github.com/libp2p/go-libp2p-blankhost/blob/v0.4.0/blank.go#L17) deprecated added in v0.1.5 ``` type Option = [blankhost](/github.com/libp2p/go-libp2p/p2p/host/blank).[Option](/github.com/libp2p/go-libp2p/p2p/host/blank#Option) ``` Deprecated: use github.com/libp2p/go-libp2p/p2p/host/blank.Option instead. #### func [WithConnectionManager](https://github.com/libp2p/go-libp2p-blankhost/blob/v0.4.0/blank.go#L20) deprecated added in v0.1.5 ``` func WithConnectionManager(cmgr [connmgr](/github.com/libp2p/go-libp2p-core/connmgr).[ConnManager](/github.com/libp2p/go-libp2p-core/connmgr#ConnManager)) [Option](#Option) ``` Deprecated: use github.com/libp2p/go-libp2p/p2p/host/blank.WithConnectionManager instead. #### func [WithEventBus](https://github.com/libp2p/go-libp2p-blankhost/blob/v0.4.0/blank.go#L25) deprecated added in v0.3.0 ``` func WithEventBus(eventBus [event](/github.com/libp2p/go-libp2p-core/event).[Bus](/github.com/libp2p/go-libp2p-core/event#Bus)) [Option](#Option) ``` Deprecated: use github.com/libp2p/go-libp2p/p2p/host/blank.WithEventBus instead.
lacm
cran
R
Package ‘lacm’ October 13, 2022 Version 0.1.1 Priority optional Title Latent Autoregressive Count Models Description Perform pairwise likelihood inference in latent autoregressive count mod- els. See Pedeli and Varin (2020) for details. Maintainer <NAME> <<EMAIL>> Depends R (>= 3.4.0) Imports graphics, numDeriv, statmod, stats License GPL (>= 2) NeedsCompilation yes Author <NAME> [aut], <NAME> [aut, cre] Repository CRAN Date/Publication 2020-06-20 22:00:02 UTC R topics documented: CLI... 1 lac... 3 poli... 6 summary.lac... 7 CLIC Composite Likelihood Information Criterion Description Calculates the composite likelihood information criterion for a latent autoregressive count model fitted through maximum pairwise likelihood. Usage CLIC(object, ...) Arguments object a fitted model object of class "lacm". ... optional arguments. Details Function CLIC computes the composite likelihood information criterion (Varin and Vidoni, 2005) for a latent autoregressive count model estimated by maximum pairwise likelihood. See Pedeli and Varin (2020) for details. When comparing models fitted by maximum pairwise likelihood to the same data, the smaller the CLIC, the better the fit. Value a numeric value with the corresponding CLIC. Author(s) <NAME> and <NAME>. References <NAME>. and <NAME>. (2020). Pairwise likelihood estimation of latent autoregressive count mod- els. Statistical Methods in Medical Research.doi: 10.1177/0962280220924068. <NAME>. and <NAME>. (2005). A note on composite likelihood inference and model selection. Biometrika, 92, 519–528. See Also lacm. Examples data("polio", package = "lacm") ## model components trend <- 1:length(polio) sin.term <- sin(2 * pi * trend / 12) cos.term <- cos(2 * pi * trend / 12) sin2.term <- sin(2 * pi * trend / 6) cos2.term <- cos(2 * pi * trend / 6) ## fit model with pairwise likelihood of order 1 mod1 <- lacm(polio ~ I(trend * 10^(-3)) + sin.term + cos.term + sin2.term + cos2.term) CLIC(mod1) lacm Fitting Latent Autoregressive Count Models by Maximum Pairwise Likelihood Description Fits latent autoregressive count models by maximum pairwise likelihood. Usage lacm(formula, data, subset, offset, contrasts = NULL, start.theta = NULL, fixed, d = 1, kernel.type = c("Rectangular", "Trapezoidal"), fit = TRUE, gh.num = 20, reltol.opt = 1e-06, opt.method = c("BFGS", "Nelder-Mead"), maxit.opt = 1000, sandwich.lag = NULL, bread.method = c("Outer-product", "Hessian"), ...) Arguments formula an object of class "formula" (or one that can be coerced to that class): a sym- bolic description of the model to be fitted. The details of model specification are given under ‘Details’. data an optional data frame, list or environment (or object coercible by as.data.frame to a data frame) containing the variables in the model. If not found in data, the variables are taken from environment(formula), typically the environment from which lacm is called. subset an optional vector specifying a subset of observations to be used in the fitting process. offset this can be used to specify an a priori known component to be included in the linear predictor during fitting. This should be NULL or a numeric vector of length equal to the number of cases. One or more offset terms can be included in the formula instead or as well, and if more than one is specified their sum is used. See model.offset. contrasts an optional list. See the contrasts.arg of model.matrix.default. start.theta optional numeric vector with starting values for the model parameters. fixed optional numeric vector of the same length as the total number of parameters. If supplied, only NA entries in fixed will be varied. d order of the pairwise likelihood. Defaults to 1. kernel.type one of "Rectangular", "Trapezoidal" indicating the type of kernel weights to be used in the weighted pairwise likelihood specification. The default "Rectangular" corresponds to equal contribution from all pairs of observations that are distant apart up to lag d. Can be abbreviated. fit a logical value indicating whether to compute the maximum pairwise likelihood estimates or not. gh.num number of the Gauss-Hermite quadrature nodes. Defaults to 20. reltol.opt relative convergence tolerance to be passed to optim. Defaults to 1e-6. opt.method one of "BFGS" or "Nelder-Mead" indicating the optimization method to be passed to optim. Can be abbreviated. See optim for details. maxit.opt the maximum number of iterations to be passed to optim. Defaults to 1000. sandwich.lag the lag length used for computing the bandwith of the sandwich variance. See ‘Details’. bread.method one of "Outer-product" or "Hessian" indicating whether the bread matrix of the sandwich variance is estimated with the outer-product of the individual gradients or with a numerical approximation of the Hessian matrix. Can be abbreviated. See ‘Details’. ... further arguments passed to or from other methods. Details Function lacm performs maximum pairwise likelihood estimation in latent autoressive count mod- els, see Pedeli and Varin (2020) for details. Evaluation of the pairwise likelihood is performed through double Gauss-Hermite quadrature with the gh.num nodes and weights calculated by gauss.quad. Standard formula y ~ x1 + x2 indicates that the mean response is modelled as a function of covari- ates x1 and x2 through a log link function. Starting values supplied by the user can be specified through start.theta. If start.theta=NULL, then starting values are obtained using the method-of-moments as discussed in Ng et al. (2011). Sandwich standard errors that are robust to heteroschedasticity and autocorrelation (HAC-type) are computed. The "meat matrix" is estimated using a lag length equal to sandwich.lag. If sandwich.lag is NULL, then L is set equal to 10 * log10(n), where n is the time series length and d is the pairwise likelihood order. The "bread matrix" is computed with the average of outer products of the individual grandients (bread.matrix = "Outer-product") or with a numerical ap- proximation of the Hessian (bread.method = "Hessian"). Details are given in Pedeli and Varin (2020). Value An object of class "lacm" with the following components: nobs the number of observations. p the number of regressors, including the intercept. d the order of the pairwise likelihood. npar the number of parameters. Y the response used. X the model matrix used for the mean response. offset the offset used. sandwich.lag the lag length used for the bandwith of the HAC-type standard errors. fit logical. Was the model fitted or not? gh.num number of Gauss-Hermite nodes used. call the matched call. terms the terms object used. latent logical. Does the model include the latent part? fixed the numeric vector indicating which parameters are constants. ifree indeces of the free parameters. kweights the kernel weights used. start.theta the starting values. objfun function computing the logarithm of the pairwise likelihood of order d. grad function computing the gradient of the pairwise likelihood of order d. gh Gauss-Hermite nodes and weights used. opt.method a character string specifying the method argument passed to optim. The de- fault optimization routine is the quasi-Newton algorithm BFGS. See optim for details. convergence an integer code indicating convergence of the optimizer. See link{optim} for details. gh a list with components the Gauss-Hermite nodes and the weights used for ap- proximating the pairwise likelihood. plik the maximum pairwise likelihood value. theta the maximum pairwise likelihood estimate. jacobian the jacobian of the individual pairwise likelihood terms. outer-product logical. Was the bread matrix of the sandwich variance computed with the outer product of the individual scores? H the bread matrix. J the meat matrix. vcov the variance-covariance matrix of the maximum pairwise likelihood estimate. CLIC the composite likelihood information criterion. Functions summary.lacm, coefficients and vcov.lacm can be used to obtain or print a summary of the results, extract coefficients and their estimated variance-covariance matrix of the model fitted by lacm. Author(s) <NAME> and <NAME>. References <NAME>., <NAME>., <NAME>., and <NAME>. (2011). Composite likelihood for time series models with a latent autoregressive process. Statistica Sinica, 21, 279–305. <NAME>. and <NAME>. (2020). Pairwise likelihood estimation of latent autoregressive count mod- els. Statistical Methods in Medical Research.doi: 10.1177/0962280220924068. See Also CLIC. Examples data("polio", package = "lacm") ## model components trend <- 1:length(polio) sin.term <- sin(2 * pi * trend / 12) cos.term <- cos(2 * pi * trend / 12) sin2.term <- sin(2 * pi * trend / 6) cos2.term <- cos(2 * pi * trend / 6) ## fit model with pairwise likelihood of order 1 mod1 <- lacm(polio ~ I(trend * 10^(-3)) + sin.term + cos.term + sin2.term + cos2.term) mod1 summary(mod1) ## refit with d = 3 mod3 <- update(mod1, d = 3) summary(mod3) polio Polio Time Series Description Time series of Polio incidences in USA from 1970 to 1983. Usage data(polio) Format Time series of monthly Polio cases in USA from January 1970 to December 1983. Source <NAME>.L. (1988). A regression model for time series of counts. Biometrika 75, 822–835. Examples data(polio, package = "lacm") summary.lacm Methods for lacm Objects Description Methods for fitted latent autoregressive count model objects of class "lacm" Usage ## S3 method for class 'lacm' summary(object, ...) ## S3 method for class 'lacm' print(x, digits = max(3L, getOption("digits") - 3L), ...) ## S3 method for class 'lacm' coef(object, ...) ## S3 method for class 'lacm' vcov(object, ...) ## S3 method for class 'lacm' simulate(object, nsim = 1, seed = NULL, ...) Arguments object, x a fitted model object of class "lacm". digits the number of significant digits to use when printing. nsim number of response vectors to simulate. Defaults to 1. seed an object specifying if and how the random number generator should be initial- ized (’seeded’). See simulate. ... additional optional arguments. Value The function summary.lacm returns an object of class "summary.lacm", a list of some components of the "lacm" object, plus coefficients a summary of the parameter estimates, standard errors, z-values and correspond- ing p-values. clic the composite likelihood information criterion. The function simulate.lacm returns a list of simulated responses. The function print returns the call and coefficients, coef returns the estimated coefficients and vcov the corresponding variance-covariance matrix. Author(s) <NAME> and <NAME>. References <NAME>. and <NAME>. (2020). Pairwise likelihood estimation of latent autoregressive count mod- els. Statistical Methods in Medical Research.doi: 10.1177/0962280220924068. See Also CLIC. Examples data("polio", package = "lacm") ## model components trend <- 1:length(polio) sin.term <- sin(2 * pi * trend / 12) cos.term <- cos(2 * pi * trend / 12) sin2.term <- sin(2 * pi * trend / 6) cos2.term <- cos(2 * pi * trend / 6) ## fit model with pairwise likelihood of order 1 mod1 <- lacm(polio ~ I(trend * 10^(-3)) + sin.term + cos.term + sin2.term + cos2.term) mod1 summary(mod1) ## refit with d = 3 mod3 <- update(mod1, d = 3) summary(mod3)
github.com/howeyc/ledger
go
Go
README [¶](#section-readme) --- [![license](https://img.shields.io/badge/license-ISC-brightgreen.svg)](https://en.wikipedia.org/wiki/ISC_license) [![GitHub releases](https://img.shields.io/github/tag/howeyc/ledger.svg)](https://github.com/howeyc/ledger/releases) [![GitHub downloads](https://img.shields.io/github/downloads/howeyc/ledger/total.svg?logo=github&logoColor=lime)](https://github.com/howeyc/ledger/releases) [![Chat on Libera](https://img.shields.io/badge/chat-libera-blue.svg)](https://matrix.to/#/%23plaintextaccounting:libera.chat) [![Go Report Card](https://goreportcard.com/badge/github.com/howeyc/ledger)](https://goreportcard.com/report/github.com/howeyc/ledger) [![Go Reference](https://pkg.go.dev/badge/github.com/howeyc/ledger.svg)](https://pkg.go.dev/github.com/howeyc/ledger) [![Coverage Status](https://coveralls.io/repos/github/howeyc/ledger/badge.svg?branch=master)](https://coveralls.io/github/howeyc/ledger?branch=master) ![ledger-logo](https://github.com/howeyc/ledger/raw/v1.15.1/logo.png) ### Purpose Ledger is a command line application for plain text accounting. Providing commands to view balances, register of transactions, importing of CSV files, exporting of CSV files, and a web interface to view reports, and track investments. ### Documentation Head over to <https://howeyc.github.io/ledger/Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [func NewLedgerReader(filename string) (io.Reader, error)](#NewLedgerReader)deprecated * [func ParseLedgerAsync(ledgerReader io.Reader) (c chan *Transaction, e chan error)](#ParseLedgerAsync) * [type Account](#Account) * + [func GetBalances(generalLedger []*Transaction, filterArr []string) []*Account](#GetBalances) * [type Period](#Period) * [type RangeBalance](#RangeBalance) * + [func BalancesByPeriod(trans []*Transaction, per Period, rType RangeType) []*RangeBalance](#BalancesByPeriod) * [type RangeTransactions](#RangeTransactions) * + [func TransactionsByPeriod(trans []*Transaction, per Period) []*RangeTransactions](#TransactionsByPeriod) * [type RangeType](#RangeType) * [type Transaction](#Transaction) * + [func ParseLedger(ledgerReader io.Reader) (generalLedger []*Transaction, err error)](#ParseLedger) + [func ParseLedgerFile(filename string) (generalLedger []*Transaction, err error)](#ParseLedgerFile) + [func TransactionsInDateRange(trans []*Transaction, start, end time.Time) []*Transaction](#TransactionsInDateRange) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) #### func [NewLedgerReader](https://github.com/howeyc/ledger/blob/v1.15.1/ledgerReader.go#L13) deprecated added in v0.2.0 ``` func NewLedgerReader(filename [string](/builtin#string)) ([io](/io).[Reader](/io#Reader), [error](/builtin#error)) ``` NewLedgerReader reads a file and includes any files with include directives and returns the whole combined ledger as a buffer for parsing. Deprecated: use ParseLedgerFile #### func [ParseLedgerAsync](https://github.com/howeyc/ledger/blob/v1.15.1/parse.go#L60) [¶](#ParseLedgerAsync) ``` func ParseLedgerAsync(ledgerReader [io](/io).[Reader](/io#Reader)) (c chan *[Transaction](#Transaction), e chan [error](/builtin#error)) ``` ParseLedgerAsync parses a ledger file and returns a Transaction and error channels . ### Types [¶](#pkg-types) #### type [Account](https://github.com/howeyc/ledger/blob/v1.15.1/types.go#L10) [¶](#Account) ``` type Account struct { Name [string](/builtin#string) Balance [decimal](/github.com/howeyc/[email protected]/decimal).[Decimal](/github.com/howeyc/[email protected]/decimal#Decimal) Comment [string](/builtin#string) } ``` Account holds the name and balance #### func [GetBalances](https://github.com/howeyc/ledger/blob/v1.15.1/balances.go#L15) [¶](#GetBalances) ``` func GetBalances(generalLedger []*[Transaction](#Transaction), filterArr [][string](/builtin#string)) []*[Account](#Account) ``` GetBalances provided a list of transactions and filter strings, returns account balances of all accounts that have any filter as a substring of the account name. Also returns balances for each account level depth as a separate record. Accounts are sorted by name. #### type [Period](https://github.com/howeyc/ledger/blob/v1.15.1/date.go#L23) [¶](#Period) ``` type Period [string](/builtin#string) ``` Period is used to specify the length of a date range or frequency ``` const ( PeriodDay [Period](#Period) = "Daily" PeriodWeek [Period](#Period) = "Weekly" Period2Week [Period](#Period) = "BiWeekly" PeriodMonth [Period](#Period) = "Monthly" Period2Month [Period](#Period) = "BiMonthly" PeriodQuarter [Period](#Period) = "Quarterly" PeriodSemiYear [Period](#Period) = "SemiYearly" PeriodYear [Period](#Period) = "Yearly" ) ``` Periods supported by ledger #### type [RangeBalance](https://github.com/howeyc/ledger/blob/v1.15.1/date.go#L161) [¶](#RangeBalance) ``` type RangeBalance struct { Start, End [time](/time).[Time](/time#Time) Balances []*[Account](#Account) } ``` RangeBalance contains the account balances and the start and end time of the date range #### func [BalancesByPeriod](https://github.com/howeyc/ledger/blob/v1.15.1/date.go#L167) [¶](#BalancesByPeriod) ``` func BalancesByPeriod(trans []*[Transaction](#Transaction), per [Period](#Period), rType [RangeType](#RangeType)) []*[RangeBalance](#RangeBalance) ``` BalancesByPeriod will return the account balances for each period. #### type [RangeTransactions](https://github.com/howeyc/ledger/blob/v1.15.1/date.go#L109) [¶](#RangeTransactions) ``` type RangeTransactions struct { Start, End [time](/time).[Time](/time#Time) Transactions []*[Transaction](#Transaction) } ``` RangeTransactions contains the transactions and the start and end time of the date range #### func [TransactionsByPeriod](https://github.com/howeyc/ledger/blob/v1.15.1/date.go#L139) [¶](#TransactionsByPeriod) ``` func TransactionsByPeriod(trans []*[Transaction](#Transaction), per [Period](#Period)) []*[RangeTransactions](#RangeTransactions) ``` TransactionsByPeriod will return the transactions for each period. #### type [RangeType](https://github.com/howeyc/ledger/blob/v1.15.1/date.go#L98) [¶](#RangeType) ``` type RangeType [string](/builtin#string) ``` RangeType is used to specify how the data is "split" into sections ``` const ( // RangeSnapshot will have each section be the running total at the time of the snapshot RangeSnapshot [RangeType](#RangeType) = "Snapshot" // RangePartition will have each section be the accumulated value of the transactions within that partition's date range RangePartition [RangeType](#RangeType) = "Partition" ) ``` #### type [Transaction](https://github.com/howeyc/ledger/blob/v1.15.1/types.go#L20) [¶](#Transaction) ``` type Transaction struct { Date [time](/time).[Time](/time#Time) Payee [string](/builtin#string) PayeeComment [string](/builtin#string) AccountChanges [][Account](#Account) Comments [][string](/builtin#string) } ``` Transaction is the basis of a ledger. The ledger holds a list of transactions. A Transaction has a Payee, Date (with no time, or to put another way, with hours,minutes,seconds values that probably doesn't make sense), and a list of Account values that hold the value of the transaction for each account. #### func [ParseLedger](https://github.com/howeyc/ledger/blob/v1.15.1/parse.go#L44) [¶](#ParseLedger) ``` func ParseLedger(ledgerReader [io](/io).[Reader](/io#Reader)) (generalLedger []*[Transaction](#Transaction), err [error](/builtin#error)) ``` ParseLedger parses a ledger file and returns a list of Transactions. #### func [ParseLedgerFile](https://github.com/howeyc/ledger/blob/v1.15.1/parse.go#L20) [¶](#ParseLedgerFile) added in v1.7.0 ``` func ParseLedgerFile(filename [string](/builtin#string)) (generalLedger []*[Transaction](#Transaction), err [error](/builtin#error)) ``` ParseLedgerFile parses a ledger file and returns a list of Transactions. #### func [TransactionsInDateRange](https://github.com/howeyc/ledger/blob/v1.15.1/date.go#L8) [¶](#TransactionsInDateRange) ``` func TransactionsInDateRange(trans []*[Transaction](#Transaction), start, end [time](/time).[Time](/time#Time)) []*[Transaction](#Transaction) ``` TransactionsInDateRange returns a new array of transactions that are in the date range specified by start and end. The returned list contains transactions on the same day as start but does not include any transactions on the day of end.
murmur
hex
Erlang
Murmur === [![Build Status](https://img.shields.io/github/workflow/status/gmcabrita/murmur/CI/master.svg)](https://github.com/gmcabrita/murmur/actions) [![Coverage Status](https://img.shields.io/coveralls/gmcabrita/murmur.svg?style=flat)](https://coveralls.io/r/gmcabrita/murmur?branch=master) [![Hex docs](http://img.shields.io/badge/hex.pm-docs-green.svg?style=flat)](https://hexdocs.pm/murmur) [![Hex Version](http://img.shields.io/hexpm/v/murmur.svg?style=flat)](https://hex.pm/packages/murmur) [![License](http://img.shields.io/hexpm/l/murmur.svg?style=flat)](https://github.com/gmcabrita/murmur/blob/master/LICENSE) Murmur is a pure Elixir implementation of the non-cryptographic hash [Murmur3](https://code.google.com/p/smhasher/wiki/MurmurHash3). It aims to implement the x86_32bit, x86_128bit and x64_128bit variants. Usage === Add Murmur as a dependency in your mix.exs file. ``` def deps do [{:murmur, "~> 1.0"}] end ``` When you are done, run [`mix deps.get`](https://hexdocs.pm/mix/Mix.Tasks.Deps.Get.html) in your shell to fetch and compile Murmur. Examples === ``` iex> Murmur.hash_x86_32("b2622f5e1310a0aa14b7f957fe4246fa", 2147368987) 3297211900 iex> Murmur.hash_x86_128("some random data") 5586633072055552000169173700229798482 iex> Murmur.hash_x64_128([:yes, :you, :can, :use, :any, :erlang, :term!]) 300414073828138369336317731503972665325 ``` [API Reference](api-reference.html) Murmur === This module implements the x86_32, x86_128 and x64_128 variants of the non-cryptographic hash Murmur3. Examples --- ``` iex> Murmur.hash_x86_32("b2622f5e1310a0aa14b7f957fe4246fa", 2147368987) 3297211900 iex> Murmur.hash_x86_128("some random data") 5586633072055552000169173700229798482 iex> Murmur.hash_x64_128([:yes, :you, :can, :use, :any, :erlang, :term!]) 300414073828138369336317731503972665325 ``` [Link to this section](#summary) Summary === [Functions](#functions) --- [hash_x64_128(data, seed \\ 0)](#hash_x64_128/2) Returns the hashed erlang term `data` using an optional `seed` which defaults to `0`. [hash_x86_128(data, seed \\ 0)](#hash_x86_128/2) Returns the hashed erlang term `data` using an optional `seed` which defaults to `0`. [hash_x86_32(data, seed \\ 0)](#hash_x86_32/2) Returns the hashed erlang term `data` using an optional `seed` which defaults to `0`. [Link to this section](#functions) Functions === API Reference === Modules --- [Murmur](Murmur.html) This module implements the x86_32, x86_128 and x64_128 variants of the non-cryptographic hash Murmur3. [Murmur](readme.html)
ethereum-types
rust
Rust
Macro ethereum_types::if_ethbloom === ``` macro_rules! if_ethbloom { ($($tt:tt)*) => { ... }; } ``` Conditional compilation depending on whether ethereum-types is built with ethbloom support. Struct ethereum_types::Bloom === ``` pub struct Bloom(pub [u8; 256]); ``` Bloom hash type with 256 bytes (2048 bits) size. Tuple Fields --- `0: [u8; 256]`Implementations --- ### impl Bloom #### pub const fn repeat_byte(byte: u8) -> Bloom Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> Bloom Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 256] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 256] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 256] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> Bloom Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &Bloom) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl Bloom Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> Bloom Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> Bloom Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> Bloom Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl Bloom Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> Bloomwhere    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> Bloom Create a new hash with cryptographically random content. ### impl Bloom #### pub fn is_empty(&self) -> bool #### pub fn contains_input(&self, input: Input<'_>) -> bool #### pub fn contains_bloom<'a, B>(&self, bloom: B) -> boolwhere    BloomRef<'a>: From<B>, #### pub fn accrue(&mut self, input: Input<'_>) #### pub fn accrue_bloom<'a, B>(&mut self, bloom: B)where    BloomRef<'a>: From<B>, #### pub fn data(&self) -> &[u8; 256] Trait Implementations --- ### impl AsMut<[u8]> for Bloom #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for Bloom #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl<'l, 'r> BitAnd<&'r Bloom> for &'l Bloom #### type Output = Bloom The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r Bloom) -> <&'l Bloom as BitAnd<&'r Bloom>>::Output Performs the `&` operation. #### type Output = Bloom The resulting type after applying the `&` operator.#### fn bitand(self, rhs: Bloom) -> <Bloom as BitAnd<Bloom>>::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r Bloom) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: Bloom) Performs the `&=` operation. #### type Output = Bloom The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r Bloom) -> <&'l Bloom as BitOr<&'r Bloom>>::Output Performs the `|` operation. #### type Output = Bloom The resulting type after applying the `|` operator.#### fn bitor(self, rhs: Bloom) -> <Bloom as BitOr<Bloom>>::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r Bloom) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: Bloom) Performs the `|=` operation. #### type Output = Bloom The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r Bloom) -> <&'l Bloom as BitXor<&'r Bloom>>::Output Performs the `^` operation. #### type Output = Bloom The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: Bloom) -> <Bloom as BitXor<Bloom>>::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r Bloom) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: Bloom) Performs the `^=` operation. #### fn clone(&self) -> Bloom Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<Bloom, DecoderErrorDecode a value from RLP bytes### impl Default for Bloom #### fn default() -> Bloom Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<Bloom, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 256]> for Bloom #### fn from(bytes: &'a [u8; 256]) -> Bloom Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a Bloom> for BloomRef<'a#### fn from(bloom: &'a Bloom) -> BloomRef<'aConverts to this type from the input type.### impl<'a> From<&'a mut [u8; 256]> for Bloom #### fn from(bytes: &'a mut [u8; 256]) -> Bloom Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 256]> for Bloom #### fn from(bytes: [u8; 256]) -> Bloom Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<Input<'a>> for Bloom #### fn from(input: Input<'a>) -> Bloom Converts to this type from the input type.### impl FromStr for Bloom #### fn from_str(input: &str) -> Result<Bloom, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for Bloom #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &<I as SliceIndex<[u8]>>::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<[u8]>>::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Ord for Bloom #### fn cmp(&self, other: &Bloom) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Bloom) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn eq(&self, other: &BloomRef<'a>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &Bloom) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for Bloom ### impl Eq for Bloom Auto Trait Implementations --- ### impl RefUnwindSafe for Bloom ### impl Send for Bloom ### impl Sync for Bloom ### impl Unpin for Bloom ### impl UnwindSafe for Bloom Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::BloomRef === ``` pub struct BloomRef<'a>(_); ``` Implementations --- ### impl<'a> BloomRef<'a#### pub fn is_empty(&self) -> bool #### pub fn contains_input(&self, input: Input<'_>) -> bool #### pub fn contains_bloom<'b, B>(&self, bloom: B) -> boolwhere    BloomRef<'b>: From<B>, #### pub fn data(&self) -> &'a [u8; 256] Trait Implementations --- ### impl<'a> Clone for BloomRef<'a#### fn clone(&self) -> BloomRef<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn eq(&self, other: &BloomRef<'a>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. --- ### impl<'a> RefUnwindSafe for BloomRef<'a### impl<'a> Send for BloomRef<'a### impl<'a> Sync for BloomRef<'a### impl<'a> Unpin for BloomRef<'a### impl<'a> UnwindSafe for BloomRef<'aBlanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct ethereum_types::FromStrRadixErr === ``` pub struct FromStrRadixErr { /* private fields */ } ``` The error type for parsing numbers from strings. Implementations --- ### impl FromStrRadixErr #### pub fn kind(&self) -> FromStrRadixErrKind Returns the corresponding `FromStrRadixErrKind` for this error. Trait Implementations --- ### impl Debug for FromStrRadixErr #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(e: FromDecStrErr) -> FromStrRadixErr Converts to this type from the input type.### impl From<FromHexError> for FromStrRadixErr #### fn from(e: FromHexError) -> FromStrRadixErr Converts to this type from the input type.Auto Trait Implementations --- ### impl RefUnwindSafe for FromStrRadixErr ### impl Send for FromStrRadixErr ### impl Sync for FromStrRadixErr ### impl Unpin for FromStrRadixErr ### impl UnwindSafe for FromStrRadixErr Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<E> Provider for Ewhere    E: Error + ?Sized, #### fn provide<'a>(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any`)Data providers should implement this method to provide *all* values they are able to provide by using `demand`. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct ethereum_types::H32 === ``` #[repr(C)]pub struct H32(pub [u8; 4]); ``` Tuple Fields --- `0: [u8; 4]`Implementations --- ### impl H32 #### pub const fn repeat_byte(byte: u8) -> H32 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H32 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 4] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 4] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 4] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> Self Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &Self) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H32 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H32 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> Selfwhere    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> Self Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H32 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H32 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl<'l, 'r> BitAnd<&'r H32> for &'l H32 #### type Output = H32 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H32) -> Self::Output Performs the `&` operation. #### type Output = H32 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: Self) -> Self::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H32) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H32) Performs the `&=` operation. #### type Output = H32 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H32) -> Self::Output Performs the `|` operation. #### type Output = H32 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: Self) -> Self::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H32) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H32) Performs the `|=` operation. #### type Output = H32 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H32) -> Self::Output Performs the `^` operation. #### type Output = H32 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: Self) -> Self::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H32) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H32) Performs the `^=` operation. #### fn clone(&self) -> H32 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<Self, DecoderErrorDecode a value from RLP bytes### impl Default for H32 #### fn default() -> Self Returns the “default value” for a type. #### fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn sample<R: Rng + ?Sized>(&self, rng: &mutR) -> H32 Generate a random value of `T`, using `rng` as the source of randomness.#### fn sample_iter<R>(self, rng: R) -> DistIter<Self, R, T>where    R: Rng,    Self: Sized, Create an iterator that generates random values of `T`, using `rng` as the source of randomness. Create a distribution of values of ‘S’ by mapping the output of `Self` through the closure `F` #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 4]> for H32 #### fn from(bytes: &'a [u8; 4]) -> Self Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 4]> for H32 #### fn from(bytes: &'a mut [u8; 4]) -> Self Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 4]> for H32 #### fn from(bytes: [u8; 4]) -> Self Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<H32> for [u8; 4] #### fn from(s: H32) -> Self Converts to this type from the input type.### impl FromStr for H32 #### fn from_str(input: &str) -> Result<H32, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H32 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &I::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut I::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Ord for H32 #### fn cmp(&self, other: &Self) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &Self) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Copy for H32 ### impl Eq for H32 Auto Trait Implementations --- ### impl RefUnwindSafe for H32 ### impl Send for H32 ### impl Sync for H32 ### impl Unpin for H32 ### impl UnwindSafe for H32 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::H64 === ``` #[repr(C)]pub struct H64(pub [u8; 8]); ``` Tuple Fields --- `0: [u8; 8]`Implementations --- ### impl H64 #### pub const fn repeat_byte(byte: u8) -> H64 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H64 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 8] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 8] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 8] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> Self Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &Self) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H64 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H64 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> Selfwhere    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> Self Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H64 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H64 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl BigEndianHash for H64 #### type Uint = U64 #### fn from_uint(value: &U64) -> Self #### fn into_uint(&self) -> U64 ### impl<'l, 'r> BitAnd<&'r H64> for &'l H64 #### type Output = H64 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H64) -> Self::Output Performs the `&` operation. #### type Output = H64 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: Self) -> Self::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H64) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H64) Performs the `&=` operation. #### type Output = H64 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H64) -> Self::Output Performs the `|` operation. #### type Output = H64 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: Self) -> Self::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H64) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H64) Performs the `|=` operation. #### type Output = H64 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H64) -> Self::Output Performs the `^` operation. #### type Output = H64 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: Self) -> Self::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H64) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H64) Performs the `^=` operation. #### fn clone(&self) -> H64 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<Self, DecoderErrorDecode a value from RLP bytes### impl Default for H64 #### fn default() -> Self Returns the “default value” for a type. #### fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn sample<R: Rng + ?Sized>(&self, rng: &mutR) -> H64 Generate a random value of `T`, using `rng` as the source of randomness.#### fn sample_iter<R>(self, rng: R) -> DistIter<Self, R, T>where    R: Rng,    Self: Sized, Create an iterator that generates random values of `T`, using `rng` as the source of randomness. Create a distribution of values of ‘S’ by mapping the output of `Self` through the closure `F` #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 8]> for H64 #### fn from(bytes: &'a [u8; 8]) -> Self Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 8]> for H64 #### fn from(bytes: &'a mut [u8; 8]) -> Self Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 8]> for H64 #### fn from(bytes: [u8; 8]) -> Self Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<H64> for [u8; 8] #### fn from(s: H64) -> Self Converts to this type from the input type.### impl FromStr for H64 #### fn from_str(input: &str) -> Result<H64, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H64 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &I::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut I::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Ord for H64 #### fn cmp(&self, other: &Self) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &Self) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Copy for H64 ### impl Eq for H64 Auto Trait Implementations --- ### impl RefUnwindSafe for H64 ### impl Send for H64 ### impl Sync for H64 ### impl Unpin for H64 ### impl UnwindSafe for H64 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::H128 === ``` pub struct H128(pub [u8; 16]); ``` Fixed-size uninterpreted hash type with 16 bytes (128 bits) size. Tuple Fields --- `0: [u8; 16]`Implementations --- ### impl H128 #### pub const fn repeat_byte(byte: u8) -> H128 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H128 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 16] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 16] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 16] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> H128 Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &H128) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H128 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> H128 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> H128 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> H128 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H128 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> H128where    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> H128 Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H128 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H128 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl BigEndianHash for H128 #### type Uint = U128 #### fn from_uint(value: &U128) -> Self #### fn into_uint(&self) -> U128 ### impl<'l, 'r> BitAnd<&'r H128> for &'l H128 #### type Output = H128 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H128) -> <&'l H128 as BitAnd<&'r H128>>::Output Performs the `&` operation. #### type Output = H128 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: H128) -> <H128 as BitAnd<H128>>::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H128) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H128) Performs the `&=` operation. #### type Output = H128 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H128) -> <&'l H128 as BitOr<&'r H128>>::Output Performs the `|` operation. #### type Output = H128 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: H128) -> <H128 as BitOr<H128>>::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H128) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H128) Performs the `|=` operation. #### type Output = H128 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H128) -> <&'l H128 as BitXor<&'r H128>>::Output Performs the `^` operation. #### type Output = H128 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: H128) -> <H128 as BitXor<H128>>::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H128) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H128) Performs the `^=` operation. #### fn clone(&self) -> H128 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<H128, DecoderErrorDecode a value from RLP bytes### impl Default for H128 #### fn default() -> H128 Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<H128, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 16]> for H128 #### fn from(bytes: &'a [u8; 16]) -> H128 Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 16]> for H128 #### fn from(bytes: &'a mut [u8; 16]) -> H128 Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 16]> for H128 #### fn from(bytes: [u8; 16]) -> H128 Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl FromStr for H128 #### fn from_str(input: &str) -> Result<H128, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H128 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &<I as SliceIndex<[u8]>>::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<[u8]>>::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Ord for H128 #### fn cmp(&self, other: &H128) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &H128) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &H128) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for H128 ### impl Eq for H128 Auto Trait Implementations --- ### impl RefUnwindSafe for H128 ### impl Send for H128 ### impl Sync for H128 ### impl Unpin for H128 ### impl UnwindSafe for H128 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::H160 === ``` pub struct H160(pub [u8; 20]); ``` Fixed-size uninterpreted hash type with 20 bytes (160 bits) size. Tuple Fields --- `0: [u8; 20]`Implementations --- ### impl H160 #### pub const fn repeat_byte(byte: u8) -> H160 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H160 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 20] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 20] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 20] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> H160 Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &H160) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H160 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> H160 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> H160 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> H160 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H160 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> H160where    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> H160 Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H160 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H160 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl<'l, 'r> BitAnd<&'r H160> for &'l H160 #### type Output = H160 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H160) -> <&'l H160 as BitAnd<&'r H160>>::Output Performs the `&` operation. #### type Output = H160 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: H160) -> <H160 as BitAnd<H160>>::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H160) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H160) Performs the `&=` operation. #### type Output = H160 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H160) -> <&'l H160 as BitOr<&'r H160>>::Output Performs the `|` operation. #### type Output = H160 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: H160) -> <H160 as BitOr<H160>>::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H160) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H160) Performs the `|=` operation. #### type Output = H160 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H160) -> <&'l H160 as BitXor<&'r H160>>::Output Performs the `^` operation. #### type Output = H160 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: H160) -> <H160 as BitXor<H160>>::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H160) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H160) Performs the `^=` operation. #### fn clone(&self) -> H160 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<H160, DecoderErrorDecode a value from RLP bytes### impl Default for H160 #### fn default() -> H160 Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<H160, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 20]> for H160 #### fn from(bytes: &'a [u8; 20]) -> H160 Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 20]> for H160 #### fn from(bytes: &'a mut [u8; 20]) -> H160 Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 20]> for H160 #### fn from(bytes: [u8; 20]) -> H160 Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<H160> for H256 #### fn from(value: H160) -> H256 Converts to this type from the input type.### impl From<H256> for H160 #### fn from(value: H256) -> H160 Converts to this type from the input type.### impl FromStr for H160 #### fn from_str(input: &str) -> Result<H160, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H160 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &<I as SliceIndex<[u8]>>::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<[u8]>>::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Ord for H160 #### fn cmp(&self, other: &H160) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &H160) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &H160) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for H160 ### impl Eq for H160 Auto Trait Implementations --- ### impl RefUnwindSafe for H160 ### impl Send for H160 ### impl Sync for H160 ### impl Unpin for H160 ### impl UnwindSafe for H160 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::H256 === ``` pub struct H256(pub [u8; 32]); ``` Fixed-size uninterpreted hash type with 32 bytes (256 bits) size. Tuple Fields --- `0: [u8; 32]`Implementations --- ### impl H256 #### pub const fn repeat_byte(byte: u8) -> H256 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H256 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 32] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 32] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 32] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> H256 Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &H256) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H256 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> H256 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> H256 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> H256 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H256 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> H256where    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> H256 Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H256 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H256 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl BigEndianHash for H256 #### type Uint = U256 #### fn from_uint(value: &U256) -> Self #### fn into_uint(&self) -> U256 ### impl<'l, 'r> BitAnd<&'r H256> for &'l H256 #### type Output = H256 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H256) -> <&'l H256 as BitAnd<&'r H256>>::Output Performs the `&` operation. #### type Output = H256 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: H256) -> <H256 as BitAnd<H256>>::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H256) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H256) Performs the `&=` operation. #### type Output = H256 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H256) -> <&'l H256 as BitOr<&'r H256>>::Output Performs the `|` operation. #### type Output = H256 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: H256) -> <H256 as BitOr<H256>>::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H256) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H256) Performs the `|=` operation. #### type Output = H256 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H256) -> <&'l H256 as BitXor<&'r H256>>::Output Performs the `^` operation. #### type Output = H256 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: H256) -> <H256 as BitXor<H256>>::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H256) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H256) Performs the `^=` operation. #### fn clone(&self) -> H256 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<H256, DecoderErrorDecode a value from RLP bytes### impl Default for H256 #### fn default() -> H256 Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<H256, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 32]> for H256 #### fn from(bytes: &'a [u8; 32]) -> H256 Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 32]> for H256 #### fn from(bytes: &'a mut [u8; 32]) -> H256 Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 32]> for H256 #### fn from(bytes: [u8; 32]) -> H256 Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<H160> for H256 #### fn from(value: H160) -> H256 Converts to this type from the input type.### impl From<H256> for H160 #### fn from(value: H256) -> H160 Converts to this type from the input type.### impl FromStr for H256 #### fn from_str(input: &str) -> Result<H256, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H256 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &<I as SliceIndex<[u8]>>::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<[u8]>>::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Ord for H256 #### fn cmp(&self, other: &H256) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &H256) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &H256) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for H256 ### impl Eq for H256 Auto Trait Implementations --- ### impl RefUnwindSafe for H256 ### impl Send for H256 ### impl Sync for H256 ### impl Unpin for H256 ### impl UnwindSafe for H256 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::H264 === ``` #[repr(C)]pub struct H264(pub [u8; 33]); ``` Tuple Fields --- `0: [u8; 33]`Implementations --- ### impl H264 #### pub const fn repeat_byte(byte: u8) -> H264 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H264 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 33] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 33] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 33] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> Self Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &Self) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H264 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H264 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> Selfwhere    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> Self Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H264 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H264 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl<'l, 'r> BitAnd<&'r H264> for &'l H264 #### type Output = H264 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H264) -> Self::Output Performs the `&` operation. #### type Output = H264 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: Self) -> Self::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H264) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H264) Performs the `&=` operation. #### type Output = H264 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H264) -> Self::Output Performs the `|` operation. #### type Output = H264 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: Self) -> Self::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H264) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H264) Performs the `|=` operation. #### type Output = H264 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H264) -> Self::Output Performs the `^` operation. #### type Output = H264 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: Self) -> Self::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H264) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H264) Performs the `^=` operation. #### fn clone(&self) -> H264 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<Self, DecoderErrorDecode a value from RLP bytes### impl Default for H264 #### fn default() -> Self Returns the “default value” for a type. #### fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn sample<R: Rng + ?Sized>(&self, rng: &mutR) -> H264 Generate a random value of `T`, using `rng` as the source of randomness.#### fn sample_iter<R>(self, rng: R) -> DistIter<Self, R, T>where    R: Rng,    Self: Sized, Create an iterator that generates random values of `T`, using `rng` as the source of randomness. Create a distribution of values of ‘S’ by mapping the output of `Self` through the closure `F` #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 33]> for H264 #### fn from(bytes: &'a [u8; 33]) -> Self Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 33]> for H264 #### fn from(bytes: &'a mut [u8; 33]) -> Self Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 33]> for H264 #### fn from(bytes: [u8; 33]) -> Self Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<H264> for [u8; 33] #### fn from(s: H264) -> Self Converts to this type from the input type.### impl FromStr for H264 #### fn from_str(input: &str) -> Result<H264, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H264 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &I::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut I::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Ord for H264 #### fn cmp(&self, other: &Self) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &Self) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Copy for H264 ### impl Eq for H264 Auto Trait Implementations --- ### impl RefUnwindSafe for H264 ### impl Send for H264 ### impl Sync for H264 ### impl Unpin for H264 ### impl UnwindSafe for H264 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::H512 === ``` pub struct H512(pub [u8; 64]); ``` Fixed-size uninterpreted hash type with 64 bytes (512 bits) size. Tuple Fields --- `0: [u8; 64]`Implementations --- ### impl H512 #### pub const fn repeat_byte(byte: u8) -> H512 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H512 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 64] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 64] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 64] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> H512 Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &H512) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H512 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> H512 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> H512 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> H512 Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H512 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> H512where    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> H512 Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H512 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H512 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl BigEndianHash for H512 #### type Uint = U512 #### fn from_uint(value: &U512) -> Self #### fn into_uint(&self) -> U512 ### impl<'l, 'r> BitAnd<&'r H512> for &'l H512 #### type Output = H512 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H512) -> <&'l H512 as BitAnd<&'r H512>>::Output Performs the `&` operation. #### type Output = H512 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: H512) -> <H512 as BitAnd<H512>>::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H512) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H512) Performs the `&=` operation. #### type Output = H512 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H512) -> <&'l H512 as BitOr<&'r H512>>::Output Performs the `|` operation. #### type Output = H512 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: H512) -> <H512 as BitOr<H512>>::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H512) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H512) Performs the `|=` operation. #### type Output = H512 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H512) -> <&'l H512 as BitXor<&'r H512>>::Output Performs the `^` operation. #### type Output = H512 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: H512) -> <H512 as BitXor<H512>>::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H512) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H512) Performs the `^=` operation. #### fn clone(&self) -> H512 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<H512, DecoderErrorDecode a value from RLP bytes### impl Default for H512 #### fn default() -> H512 Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<H512, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 64]> for H512 #### fn from(bytes: &'a [u8; 64]) -> H512 Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 64]> for H512 #### fn from(bytes: &'a mut [u8; 64]) -> H512 Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 64]> for H512 #### fn from(bytes: [u8; 64]) -> H512 Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl FromStr for H512 #### fn from_str(input: &str) -> Result<H512, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H512 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &<I as SliceIndex<[u8]>>::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<[u8]>>::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Ord for H512 #### fn cmp(&self, other: &H512) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &H512) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &H512) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for H512 ### impl Eq for H512 Auto Trait Implementations --- ### impl RefUnwindSafe for H512 ### impl Send for H512 ### impl Sync for H512 ### impl Unpin for H512 ### impl UnwindSafe for H512 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::H520 === ``` #[repr(C)]pub struct H520(pub [u8; 65]); ``` Tuple Fields --- `0: [u8; 65]`Implementations --- ### impl H520 #### pub const fn repeat_byte(byte: u8) -> H520 Returns a new fixed hash where all bits are set to the given byte. #### pub const fn zero() -> H520 Returns a new zero-initialized fixed hash. #### pub const fn len_bytes() -> usize Returns the size of this hash in bytes. #### pub fn as_bytes(&self) -> &[u8] Extracts a byte slice containing the entire fixed hash. #### pub fn as_bytes_mut(&mut self) -> &mut [u8] Extracts a mutable byte slice containing the entire fixed hash. #### pub const fn as_fixed_bytes(&self) -> &[u8; 65] Extracts a reference to the byte array containing the entire fixed hash. #### pub fn as_fixed_bytes_mut(&mut self) -> &mut [u8; 65] Extracts a reference to the byte array containing the entire fixed hash. #### pub const fn to_fixed_bytes(self) -> [u8; 65] Returns the inner bytes array. #### pub fn as_ptr(&self) -> *constu8 Returns a constant raw pointer to the value. #### pub fn as_mut_ptr(&mut self) -> *mutu8 Returns a mutable raw pointer to the value. #### pub fn assign_from_slice(&mut self, src: &[u8]) Assign the bytes from the byte slice `src` to `self`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `self` do not match. #### pub fn from_slice(src: &[u8]) -> Self Create a new fixed-hash from the given slice `src`. ##### Note The given bytes are interpreted in big endian order. ##### Panics If the length of `src` and the number of bytes in `Self` do not match. #### pub fn covers(&self, b: &Self) -> bool Returns `true` if all bits set in `b` are also set in `self`. #### pub fn is_zero(&self) -> bool Returns `true` if no bits are set. ### impl H520 Utilities using the `byteorder` crate. #### pub fn to_low_u64_be(&self) -> u64 Returns the lowest 8 bytes interpreted as big-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_le(&self) -> u64 Returns the lowest 8 bytes interpreted as little-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn to_low_u64_ne(&self) -> u64 Returns the lowest 8 bytes interpreted as native-endian. ##### Note For hash type with less than 8 bytes the missing bytes are interpreted as being zero. #### pub fn from_low_u64_be(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as big endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_le(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as little endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. #### pub fn from_low_u64_ne(val: u64) -> Self Creates a new hash type from the given `u64` value. ##### Note * The given `u64` value is interpreted as native endian. * Ignores the most significant bits of the given value if the hash type has less than 8 bytes. ### impl H520 Utilities using the `rand` crate. #### pub fn randomize_using<R>(&mut self, rng: &mutR)where    R: Rng + ?Sized, Assign `self` to a cryptographically random value using the given random number generator. #### pub fn randomize(&mut self) Assign `self` to a cryptographically random value. #### pub fn random_using<R>(rng: &mutR) -> Selfwhere    R: Rng + ?Sized, Create a new hash with cryptographically random content using the given random number generator. #### pub fn random() -> Self Create a new hash with cryptographically random content. Trait Implementations --- ### impl AsMut<[u8]> for H520 #### fn as_mut(&mut self) -> &mut [u8] Converts this type into a mutable reference of the (usually inferred) input type.### impl AsRef<[u8]> for H520 #### fn as_ref(&self) -> &[u8] Converts this type into a shared reference of the (usually inferred) input type.### impl<'l, 'r> BitAnd<&'r H520> for &'l H520 #### type Output = H520 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: &'r H520) -> Self::Output Performs the `&` operation. #### type Output = H520 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: Self) -> Self::Output Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: &'r H520) Performs the `&=` operation. #### fn bitand_assign(&mut self, rhs: H520) Performs the `&=` operation. #### type Output = H520 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: &'r H520) -> Self::Output Performs the `|` operation. #### type Output = H520 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: Self) -> Self::Output Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: &'r H520) Performs the `|=` operation. #### fn bitor_assign(&mut self, rhs: H520) Performs the `|=` operation. #### type Output = H520 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: &'r H520) -> Self::Output Performs the `^` operation. #### type Output = H520 The resulting type after applying the `^` operator.#### fn bitxor(self, rhs: Self) -> Self::Output Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: &'r H520) Performs the `^=` operation. #### fn bitxor_assign(&mut self, rhs: H520) Performs the `^=` operation. #### fn clone(&self) -> H520 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<Self, DecoderErrorDecode a value from RLP bytes### impl Default for H520 #### fn default() -> Self Returns the “default value” for a type. #### fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn sample<R: Rng + ?Sized>(&self, rng: &mutR) -> H520 Generate a random value of `T`, using `rng` as the source of randomness.#### fn sample_iter<R>(self, rng: R) -> DistIter<Self, R, T>where    R: Rng,    Self: Sized, Create an iterator that generates random values of `T`, using `rng` as the source of randomness. Create a distribution of values of ‘S’ by mapping the output of `Self` through the closure `F` #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 65]> for H520 #### fn from(bytes: &'a [u8; 65]) -> Self Constructs a hash type from the given reference to the bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl<'a> From<&'a mut [u8; 65]> for H520 #### fn from(bytes: &'a mut [u8; 65]) -> Self Constructs a hash type from the given reference to the mutable bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<[u8; 65]> for H520 #### fn from(bytes: [u8; 65]) -> Self Constructs a hash type from the given bytes array of fixed length. ##### Note The given bytes are interpreted in big endian order. ### impl From<H520> for [u8; 65] #### fn from(s: H520) -> Self Converts to this type from the input type.### impl FromStr for H520 #### fn from_str(input: &str) -> Result<H520, FromHexErrorCreates a hash type instance from the given string. ##### Note The given input string is interpreted in big endian. ##### Errors * When encountering invalid non hex-digits * Upon empty string input or invalid input length in general #### type Err = FromHexError The associated error which can be returned from parsing.### impl Hash for H520 #### fn hash<H>(&self, state: &mutH)where    H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = <I as SliceIndex<[u8]>>::Output The returned type after indexing.#### fn index(&self, index: I) -> &I::Output Performs the indexing (`container[index]`) operation. #### fn index_mut(&mut self, index: I) -> &mut I::Output Performs the mutable indexing (`container[index]`) operation. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Ord for H520 #### fn cmp(&self, other: &Self) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &Self) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Copy for H520 ### impl Eq for H520 Auto Trait Implementations --- ### impl RefUnwindSafe for H520 ### impl Send for H520 ### impl Sync for H520 ### impl Unpin for H520 ### impl UnwindSafe for H520 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToHex for Twhere    T: AsRef<[u8]>, #### fn encode_hex<U>(&self) -> Uwhere    U: FromIterator<char>, Encode the hex strict representing `self` into the result. Lower case letters are used (e.g. `f9b4ca`) Encode the hex strict representing `self` into the result. Upper case letters are used (e.g. `F9B4CA`) #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre class=\"content\"><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct ethereum_types::U64 === ``` #[repr(C)]pub struct U64(pub [u64; 1]); ``` Little-endian large integer type Unsigned 64-bit integer. Tuple Fields --- `0: [u64; 1]`Implementations --- ### impl U64 #### pub const MAX: U64 = _ Maximum value. #### pub fn from_str_radix(txt: &str, radix: u32) -> Result<Self, FromStrRadixErrConverts a string slice in a given base to an integer. Only supports radixes of 10 and 16. #### pub fn from_dec_str(value: &str) -> Result<Self, FromDecStrErrConvert from a decimal string. #### pub const fn low_u32(&self) -> u32 Conversion to u32 #### pub const fn low_u64(&self) -> u64 Low word (u64) #### pub fn as_u32(&self) -> u32 Conversion to u32 with overflow checking ##### Panics Panics if the number is larger than 2^32. #### pub fn as_u64(&self) -> u64 Conversion to u64 with overflow checking ##### Panics Panics if the number is larger than u64::max_value(). #### pub fn as_usize(&self) -> usize Conversion to usize with overflow checking ##### Panics Panics if the number is larger than usize::max_value(). #### pub const fn is_zero(&self) -> bool Whether this is zero. #### pub fn bits(&self) -> usize Return the least number of bits needed to represent the number #### pub const fn bit(&self, index: usize) -> bool Return if specific bit is set. ##### Panics Panics if `index` exceeds the bit width of the number. #### pub fn leading_zeros(&self) -> u32 Returns the number of leading zeros in the binary representation of self. #### pub fn trailing_zeros(&self) -> u32 Returns the number of trailing zeros in the binary representation of self. #### pub const fn byte(&self, index: usize) -> u8 Return specific byte. ##### Panics Panics if `index` exceeds the byte width of the number. #### pub fn to_big_endian(&self, bytes: &mut [u8]) Write to the slice in big-endian format. #### pub fn to_little_endian(&self, bytes: &mut [u8]) Write to the slice in little-endian format. #### pub fn exp10(n: usize) -> Self Create `10**n` as this type. ##### Panics Panics if the result overflows the type. #### pub const fn zero() -> Self Zero (additive identity) of this type. #### pub const fn one() -> Self One (multiplicative identity) of this type. #### pub const fn max_value() -> Self The maximum value which can be inhabited by this type. #### pub fn div_mod(self, other: Self) -> (Self, Self) Returns a pair `(self / other, self % other)`. ##### Panics Panics if `other` is zero. #### pub fn integer_sqrt(&self) -> Self Compute the highest `n` such that `n * n <= self`. #### pub fn pow(self, expon: Self) -> Self Fast exponentiation by squaring https://en.wikipedia.org/wiki/Exponentiation_by_squaring ##### Panics Panics if the result overflows the type. #### pub fn overflowing_pow(self, expon: Self) -> (Self, bool) Fast exponentiation by squaring. Returns result and overflow flag. #### pub fn checked_pow(self, expon: U64) -> Option<U64Checked exponentiation. Returns `None` if overflow occurred. #### pub fn overflowing_add(self, other: U64) -> (U64, bool) Addition which overflows and returns a flag if it does. #### pub fn saturating_add(self, other: U64) -> U64 Addition which saturates at the maximum value (Self::MAX). #### pub fn checked_add(self, other: U64) -> Option<U64Checked addition. Returns `None` if overflow occurred. #### pub fn overflowing_sub(self, other: U64) -> (U64, bool) Subtraction which underflows and returns a flag if it does. #### pub fn saturating_sub(self, other: U64) -> U64 Subtraction which saturates at zero. #### pub fn checked_sub(self, other: U64) -> Option<U64Checked subtraction. Returns `None` if overflow occurred. #### pub fn abs_diff(self, other: U64) -> U64 Computes the absolute difference between self and other. #### pub fn overflowing_mul(self, other: U64) -> (U64, bool) Multiply with overflow, returning a flag if it does. #### pub fn saturating_mul(self, other: U64) -> U64 Multiplication which saturates at the maximum value.. #### pub fn checked_mul(self, other: U64) -> Option<U64Checked multiplication. Returns `None` if overflow occurred. #### pub fn checked_div(self, other: U64) -> Option<U64Checked division. Returns `None` if `other == 0`. #### pub fn checked_rem(self, other: U64) -> Option<U64Checked modulus. Returns `None` if `other == 0`. #### pub fn overflowing_neg(self) -> (U64, bool) Negation with overflow. #### pub fn checked_neg(self) -> Option<U64Checked negation. Returns `None` unless `self == 0`. #### pub fn from_big_endian(slice: &[u8]) -> Self Converts from big endian representation bytes in memory. #### pub fn from_little_endian(slice: &[u8]) -> Self Converts from little endian representation bytes in memory. Trait Implementations --- ### impl<'a, T> Add<T> for &'a U64where    T: Into<U64>, #### type Output = U64 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U64 Performs the `+` operation. #### type Output = U64 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U64 Performs the `+` operation. #### fn add_assign(&mut self, other: U64) Performs the `+=` operation. Get a reference to the underlying little-endian words. #### fn as_ref(&self) -> &[u64] Converts this type into a shared reference of the (usually inferred) input type.### impl BitAnd<U64> for U64 #### type Output = U64 The resulting type after applying the `&` operator.#### fn bitand(self, other: U64) -> U64 Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: U64) Performs the `&=` operation. #### type Output = U64 The resulting type after applying the `|` operator.#### fn bitor(self, other: U64) -> U64 Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: U64) Performs the `|=` operation. #### type Output = U64 The resulting type after applying the `^` operator.#### fn bitxor(self, other: U64) -> U64 Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: U64) Performs the `^=` operation. #### fn clone(&self) -> U64 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<Self, DecoderErrorDecode a value from RLP bytes### impl Default for U64 #### fn default() -> Self Returns the “default value” for a type. #### fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### type Output = U64 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U64 Performs the `/` operation. #### type Output = U64 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U64 Performs the `/` operation. #### fn div_assign(&mut self, other: T) Performs the `/=` operation. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 8]> for U64 #### fn from(bytes: &[u8; 8]) -> Self Converts to this type from the input type.### impl<'a> From<&'a [u8]> for U64 #### fn from(bytes: &[u8]) -> U64 Converts to this type from the input type.### impl<'a> From<&'a U64> for U64 #### fn from(x: &'a U64) -> U64 Converts to this type from the input type.### impl From<&'static str> for U64 #### fn from(s: &'static str) -> Self Converts to this type from the input type.### impl From<[u8; 8]> for U64 #### fn from(bytes: [u8; 8]) -> Self Converts to this type from the input type.### impl From<U64> for [u8; 8] #### fn from(number: U64) -> Self Converts to this type from the input type.### impl From<i16> for U64 #### fn from(value: i16) -> U64 Converts to this type from the input type.### impl From<i32> for U64 #### fn from(value: i32) -> U64 Converts to this type from the input type.### impl From<i64> for U64 #### fn from(value: i64) -> U64 Converts to this type from the input type.### impl From<i8> for U64 #### fn from(value: i8) -> U64 Converts to this type from the input type.### impl From<isize> for U64 #### fn from(value: isize) -> U64 Converts to this type from the input type.### impl From<u16> for U64 #### fn from(value: u16) -> U64 Converts to this type from the input type.### impl From<u32> for U64 #### fn from(value: u32) -> U64 Converts to this type from the input type.### impl From<u64> for U64 #### fn from(value: u64) -> U64 Converts to this type from the input type.### impl From<u8> for U64 #### fn from(value: u8) -> U64 Converts to this type from the input type.### impl From<usize> for U64 #### fn from(value: usize) -> U64 Converts to this type from the input type.### impl FromStr for U64 #### type Err = FromHexError The associated error which can be returned from parsing.#### fn from_str(value: &str) -> Result<U64, Self::ErrParses a string `s` to return a value of this type. #### fn hash<__H: Hasher>(&self, state: &mut__H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl<'a> Mul<&'a U64> for &'a U64 #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: U64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: U64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U64 Performs the `*` operation. #### type Output = U64 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U64 Performs the `*` operation. #### fn mul_assign(&mut self, other: U64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: isize) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: usize) Performs the `*=` operation. #### type Output = U64 The resulting type after applying the `!` operator.#### fn not(self) -> U64 Performs the unary `!` operation. #### fn cmp(&self, other: &U64) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &U64) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &U64) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### type Output = U64 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U64 Performs the `%` operation. #### type Output = U64 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U64 Performs the `%` operation. #### fn rem_assign(&mut self, other: T) Performs the `%=` operation. #### fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### type Output = U64 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U64 Performs the `<<` operation. #### type Output = U64 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U64 Performs the `<<` operation. #### fn shl_assign(&mut self, shift: T) Performs the `<<=` operation. #### type Output = U64 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U64 Performs the `>>` operation. #### type Output = U64 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U64 Performs the `>>` operation. #### fn shr_assign(&mut self, shift: T) Performs the `>>=` operation. #### type Output = U64 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U64 Performs the `-` operation. #### type Output = U64 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U64 Performs the `-` operation. #### fn sub_assign(&mut self, other: U64) Performs the `-=` operation. #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<i16, &'static strPerforms the conversion.### impl TryFrom<U64> for i32 #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<i32, &'static strPerforms the conversion.### impl TryFrom<U64> for i64 #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<i64, &'static strPerforms the conversion.### impl TryFrom<U64> for i8 #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<i8, &'static strPerforms the conversion.### impl TryFrom<U64> for isize #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<isize, &'static strPerforms the conversion.### impl TryFrom<U64> for u16 #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<u16, &'static strPerforms the conversion.### impl TryFrom<U64> for u32 #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<u32, &'static strPerforms the conversion.### impl TryFrom<U64> for u64 #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<u64, &'static strPerforms the conversion.### impl TryFrom<U64> for u8 #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<u8, &'static strPerforms the conversion.### impl TryFrom<U64> for usize #### type Error = &'static str The type returned in the event of a conversion error.#### fn try_from(u: U64) -> Result<usize, &'static strPerforms the conversion.### impl UpperHex for U64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter.### impl Copy for U64 ### impl Eq for U64 ### impl StructuralEq for U64 ### impl StructuralPartialEq for U64 Auto Trait Implementations --- ### impl RefUnwindSafe for U64 ### impl Send for U64 ### impl Sync for U64 ### impl Unpin for U64 ### impl UnwindSafe for U64 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, Struct ethereum_types::U128 === ``` pub struct U128(pub [u64; 2]); ``` Little-endian large integer type 128-bit unsigned integer. Tuple Fields --- `0: [u64; 2]`Implementations --- ### impl U128 #### pub const MAX: U128 = U128([u64::max_value(); 2]) Maximum value. #### pub fn from_str_radix(txt: &str, radix: u32) -> Result<U128, FromStrRadixErrConverts a string slice in a given base to an integer. Only supports radixes of 10 and 16. #### pub fn from_dec_str(value: &str) -> Result<U128, FromDecStrErrConvert from a decimal string. #### pub const fn low_u32(&self) -> u32 Conversion to u32 #### pub const fn low_u64(&self) -> u64 Low word (u64) #### pub fn as_u32(&self) -> u32 Conversion to u32 with overflow checking ##### Panics Panics if the number is larger than 2^32. #### pub fn as_u64(&self) -> u64 Conversion to u64 with overflow checking ##### Panics Panics if the number is larger than u64::max_value(). #### pub fn as_usize(&self) -> usize Conversion to usize with overflow checking ##### Panics Panics if the number is larger than usize::max_value(). #### pub const fn is_zero(&self) -> bool Whether this is zero. #### pub fn bits(&self) -> usize Return the least number of bits needed to represent the number #### pub const fn bit(&self, index: usize) -> bool Return if specific bit is set. ##### Panics Panics if `index` exceeds the bit width of the number. #### pub fn leading_zeros(&self) -> u32 Returns the number of leading zeros in the binary representation of self. #### pub fn trailing_zeros(&self) -> u32 Returns the number of trailing zeros in the binary representation of self. #### pub const fn byte(&self, index: usize) -> u8 Return specific byte. ##### Panics Panics if `index` exceeds the byte width of the number. #### pub fn to_big_endian(&self, bytes: &mut [u8]) Write to the slice in big-endian format. #### pub fn to_little_endian(&self, bytes: &mut [u8]) Write to the slice in little-endian format. #### pub fn exp10(n: usize) -> U128 Create `10**n` as this type. ##### Panics Panics if the result overflows the type. #### pub const fn zero() -> U128 Zero (additive identity) of this type. #### pub const fn one() -> U128 One (multiplicative identity) of this type. #### pub const fn max_value() -> U128 The maximum value which can be inhabited by this type. #### pub fn div_mod(self, other: U128) -> (U128, U128) Returns a pair `(self / other, self % other)`. ##### Panics Panics if `other` is zero. #### pub fn integer_sqrt(&self) -> U128 Compute the highest `n` such that `n * n <= self`. #### pub fn pow(self, expon: U128) -> U128 Fast exponentiation by squaring https://en.wikipedia.org/wiki/Exponentiation_by_squaring ##### Panics Panics if the result overflows the type. #### pub fn overflowing_pow(self, expon: U128) -> (U128, bool) Fast exponentiation by squaring. Returns result and overflow flag. #### pub fn checked_pow(self, expon: U128) -> Option<U128Checked exponentiation. Returns `None` if overflow occurred. #### pub fn overflowing_add(self, other: U128) -> (U128, bool) Addition which overflows and returns a flag if it does. #### pub fn saturating_add(self, other: U128) -> U128 Addition which saturates at the maximum value (Self::MAX). #### pub fn checked_add(self, other: U128) -> Option<U128Checked addition. Returns `None` if overflow occurred. #### pub fn overflowing_sub(self, other: U128) -> (U128, bool) Subtraction which underflows and returns a flag if it does. #### pub fn saturating_sub(self, other: U128) -> U128 Subtraction which saturates at zero. #### pub fn checked_sub(self, other: U128) -> Option<U128Checked subtraction. Returns `None` if overflow occurred. #### pub fn abs_diff(self, other: U128) -> U128 Computes the absolute difference between self and other. #### pub fn overflowing_mul(self, other: U128) -> (U128, bool) Multiply with overflow, returning a flag if it does. #### pub fn saturating_mul(self, other: U128) -> U128 Multiplication which saturates at the maximum value.. #### pub fn checked_mul(self, other: U128) -> Option<U128Checked multiplication. Returns `None` if overflow occurred. #### pub fn checked_div(self, other: U128) -> Option<U128Checked division. Returns `None` if `other == 0`. #### pub fn checked_rem(self, other: U128) -> Option<U128Checked modulus. Returns `None` if `other == 0`. #### pub fn overflowing_neg(self) -> (U128, bool) Negation with overflow. #### pub fn checked_neg(self) -> Option<U128Checked negation. Returns `None` unless `self == 0`. #### pub fn from_big_endian(slice: &[u8]) -> U128 Converts from big endian representation bytes in memory. #### pub fn from_little_endian(slice: &[u8]) -> U128 Converts from little endian representation bytes in memory. ### impl U128 #### pub const fn low_u128(&self) -> u128 Low 2 words (u128) #### pub fn as_u128(&self) -> u128 Conversion to u128 with overflow checking ##### Panics Panics if the number is larger than 2^128. ### impl U128 #### pub fn full_mul(self, other: U128) -> U256 Multiplies two 128-bit integers to produce full 256-bit integer. Overflow is not possible. Trait Implementations --- ### impl<'a, T> Add<T> for &'a U128where    T: Into<U128>, #### type Output = U128 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U128 Performs the `+` operation. #### type Output = U128 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U128 Performs the `+` operation. #### fn add_assign(&mut self, other: U128) Performs the `+=` operation. Get a reference to the underlying little-endian words. #### fn as_ref(&self) -> &[u64] Converts this type into a shared reference of the (usually inferred) input type.### impl BitAnd<U128> for U128 #### type Output = U128 The resulting type after applying the `&` operator.#### fn bitand(self, other: U128) -> U128 Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: U128) Performs the `&=` operation. #### type Output = U128 The resulting type after applying the `|` operator.#### fn bitor(self, other: U128) -> U128 Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: U128) Performs the `|=` operation. #### type Output = U128 The resulting type after applying the `^` operator.#### fn bitxor(self, other: U128) -> U128 Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: U128) Performs the `^=` operation. #### fn clone(&self) -> U128 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<U128, DecoderErrorDecode a value from RLP bytes### impl Default for U128 #### fn default() -> U128 Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<U128, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Output = U128 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U128 Performs the `/` operation. #### type Output = U128 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U128 Performs the `/` operation. #### fn div_assign(&mut self, other: T) Performs the `/=` operation. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 16]> for U128 #### fn from(bytes: &[u8; 16]) -> U128 Converts to this type from the input type.### impl<'a> From<&'a [u8]> for U128 #### fn from(bytes: &[u8]) -> U128 Converts to this type from the input type.### impl<'a> From<&'a U128> for U128 #### fn from(x: &'a U128) -> U128 Converts to this type from the input type.### impl From<&'static str> for U128 #### fn from(s: &'static str) -> U128 Converts to this type from the input type.### impl From<[u8; 16]> for U128 #### fn from(bytes: [u8; 16]) -> U128 Converts to this type from the input type.### impl From<U128> for U256 #### fn from(value: U128) -> U256 Converts to this type from the input type.### impl From<U128> for U512 #### fn from(value: U128) -> U512 Converts to this type from the input type.### impl From<i128> for U128 #### fn from(value: i128) -> U128 Converts to this type from the input type.### impl From<i16> for U128 #### fn from(value: i16) -> U128 Converts to this type from the input type.### impl From<i32> for U128 #### fn from(value: i32) -> U128 Converts to this type from the input type.### impl From<i64> for U128 #### fn from(value: i64) -> U128 Converts to this type from the input type.### impl From<i8> for U128 #### fn from(value: i8) -> U128 Converts to this type from the input type.### impl From<isize> for U128 #### fn from(value: isize) -> U128 Converts to this type from the input type.### impl From<u128> for U128 #### fn from(value: u128) -> U128 Converts to this type from the input type.### impl From<u16> for U128 #### fn from(value: u16) -> U128 Converts to this type from the input type.### impl From<u32> for U128 #### fn from(value: u32) -> U128 Converts to this type from the input type.### impl From<u64> for U128 #### fn from(value: u64) -> U128 Converts to this type from the input type.### impl From<u8> for U128 #### fn from(value: u8) -> U128 Converts to this type from the input type.### impl From<usize> for U128 #### fn from(value: usize) -> U128 Converts to this type from the input type.### impl FromStr for U128 #### type Err = FromHexError The associated error which can be returned from parsing.#### fn from_str(value: &str) -> Result<U128, <U128 as FromStr>::ErrParses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut__H)where    __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl<'a> Mul<&'a U128> for &'a U128 #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U128) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U128) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: U128) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: U128) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U128 Performs the `*` operation. #### type Output = U128 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U128 Performs the `*` operation. #### fn mul_assign(&mut self, other: U128) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: isize) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: usize) Performs the `*=` operation. #### type Output = U128 The resulting type after applying the `!` operator.#### fn not(self) -> U128 Performs the unary `!` operation. #### fn cmp(&self, other: &U128) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &U128) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &U128) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### type Output = U128 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U128 Performs the `%` operation. #### type Output = U128 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U128 Performs the `%` operation. #### fn rem_assign(&mut self, other: T) Performs the `%=` operation. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### type Output = U128 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U128 Performs the `<<` operation. #### type Output = U128 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U128 Performs the `<<` operation. #### fn shl_assign(&mut self, shift: T) Performs the `<<=` operation. #### type Output = U128 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U128 Performs the `>>` operation. #### type Output = U128 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U128 Performs the `>>` operation. #### fn shr_assign(&mut self, shift: T) Performs the `>>=` operation. #### type Output = U128 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U128 Performs the `-` operation. #### type Output = U128 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U128 Performs the `-` operation. #### fn sub_assign(&mut self, other: U128) Performs the `-=` operation. #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: U256) -> Result<U128, ErrorPerforms the conversion.### impl TryFrom<U512> for U128 #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: U512) -> Result<U128, ErrorPerforms the conversion.### impl UpperHex for U128 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for U128 ### impl Eq for U128 ### impl StructuralEq for U128 ### impl StructuralPartialEq for U128 Auto Trait Implementations --- ### impl RefUnwindSafe for U128 ### impl Send for U128 ### impl Sync for U128 ### impl Unpin for U128 ### impl UnwindSafe for U128 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, Struct ethereum_types::U256 === ``` pub struct U256(pub [u64; 4]); ``` Little-endian large integer type 256-bit unsigned integer. Tuple Fields --- `0: [u64; 4]`Implementations --- ### impl U256 #### pub const MAX: U256 = U256([u64::max_value(); 4]) Maximum value. #### pub fn from_str_radix(txt: &str, radix: u32) -> Result<U256, FromStrRadixErrConverts a string slice in a given base to an integer. Only supports radixes of 10 and 16. #### pub fn from_dec_str(value: &str) -> Result<U256, FromDecStrErrConvert from a decimal string. #### pub const fn low_u32(&self) -> u32 Conversion to u32 #### pub const fn low_u64(&self) -> u64 Low word (u64) #### pub fn as_u32(&self) -> u32 Conversion to u32 with overflow checking ##### Panics Panics if the number is larger than 2^32. #### pub fn as_u64(&self) -> u64 Conversion to u64 with overflow checking ##### Panics Panics if the number is larger than u64::max_value(). #### pub fn as_usize(&self) -> usize Conversion to usize with overflow checking ##### Panics Panics if the number is larger than usize::max_value(). #### pub const fn is_zero(&self) -> bool Whether this is zero. #### pub fn bits(&self) -> usize Return the least number of bits needed to represent the number #### pub const fn bit(&self, index: usize) -> bool Return if specific bit is set. ##### Panics Panics if `index` exceeds the bit width of the number. #### pub fn leading_zeros(&self) -> u32 Returns the number of leading zeros in the binary representation of self. #### pub fn trailing_zeros(&self) -> u32 Returns the number of trailing zeros in the binary representation of self. #### pub const fn byte(&self, index: usize) -> u8 Return specific byte. ##### Panics Panics if `index` exceeds the byte width of the number. #### pub fn to_big_endian(&self, bytes: &mut [u8]) Write to the slice in big-endian format. #### pub fn to_little_endian(&self, bytes: &mut [u8]) Write to the slice in little-endian format. #### pub fn exp10(n: usize) -> U256 Create `10**n` as this type. ##### Panics Panics if the result overflows the type. #### pub const fn zero() -> U256 Zero (additive identity) of this type. #### pub const fn one() -> U256 One (multiplicative identity) of this type. #### pub const fn max_value() -> U256 The maximum value which can be inhabited by this type. #### pub fn div_mod(self, other: U256) -> (U256, U256) Returns a pair `(self / other, self % other)`. ##### Panics Panics if `other` is zero. #### pub fn integer_sqrt(&self) -> U256 Compute the highest `n` such that `n * n <= self`. #### pub fn pow(self, expon: U256) -> U256 Fast exponentiation by squaring https://en.wikipedia.org/wiki/Exponentiation_by_squaring ##### Panics Panics if the result overflows the type. #### pub fn overflowing_pow(self, expon: U256) -> (U256, bool) Fast exponentiation by squaring. Returns result and overflow flag. #### pub fn checked_pow(self, expon: U256) -> Option<U256Checked exponentiation. Returns `None` if overflow occurred. #### pub fn overflowing_add(self, other: U256) -> (U256, bool) Addition which overflows and returns a flag if it does. #### pub fn saturating_add(self, other: U256) -> U256 Addition which saturates at the maximum value (Self::MAX). #### pub fn checked_add(self, other: U256) -> Option<U256Checked addition. Returns `None` if overflow occurred. #### pub fn overflowing_sub(self, other: U256) -> (U256, bool) Subtraction which underflows and returns a flag if it does. #### pub fn saturating_sub(self, other: U256) -> U256 Subtraction which saturates at zero. #### pub fn checked_sub(self, other: U256) -> Option<U256Checked subtraction. Returns `None` if overflow occurred. #### pub fn abs_diff(self, other: U256) -> U256 Computes the absolute difference between self and other. #### pub fn overflowing_mul(self, other: U256) -> (U256, bool) Multiply with overflow, returning a flag if it does. #### pub fn saturating_mul(self, other: U256) -> U256 Multiplication which saturates at the maximum value.. #### pub fn checked_mul(self, other: U256) -> Option<U256Checked multiplication. Returns `None` if overflow occurred. #### pub fn checked_div(self, other: U256) -> Option<U256Checked division. Returns `None` if `other == 0`. #### pub fn checked_rem(self, other: U256) -> Option<U256Checked modulus. Returns `None` if `other == 0`. #### pub fn overflowing_neg(self) -> (U256, bool) Negation with overflow. #### pub fn checked_neg(self) -> Option<U256Checked negation. Returns `None` unless `self == 0`. #### pub fn from_big_endian(slice: &[u8]) -> U256 Converts from big endian representation bytes in memory. #### pub fn from_little_endian(slice: &[u8]) -> U256 Converts from little endian representation bytes in memory. ### impl U256 #### pub const fn low_u128(&self) -> u128 Low 2 words (u128) #### pub fn as_u128(&self) -> u128 Conversion to u128 with overflow checking ##### Panics Panics if the number is larger than 2^128. ### impl U256 #### pub fn full_mul(self, other: U256) -> U512 Multiplies two 256-bit integers to produce full 512-bit integer. Overflow is not possible. Trait Implementations --- ### impl<'a, T> Add<T> for &'a U256where    T: Into<U256>, #### type Output = U256 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U256 Performs the `+` operation. #### type Output = U256 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U256 Performs the `+` operation. #### fn add_assign(&mut self, other: U256) Performs the `+=` operation. Get a reference to the underlying little-endian words. #### fn as_ref(&self) -> &[u64] Converts this type into a shared reference of the (usually inferred) input type.### impl BitAnd<U256> for U256 #### type Output = U256 The resulting type after applying the `&` operator.#### fn bitand(self, other: U256) -> U256 Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: U256) Performs the `&=` operation. #### type Output = U256 The resulting type after applying the `|` operator.#### fn bitor(self, other: U256) -> U256 Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: U256) Performs the `|=` operation. #### type Output = U256 The resulting type after applying the `^` operator.#### fn bitxor(self, other: U256) -> U256 Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: U256) Performs the `^=` operation. #### fn clone(&self) -> U256 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<U256, DecoderErrorDecode a value from RLP bytes### impl Default for U256 #### fn default() -> U256 Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<U256, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Output = U256 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U256 Performs the `/` operation. #### type Output = U256 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U256 Performs the `/` operation. #### fn div_assign(&mut self, other: T) Performs the `/=` operation. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 32]> for U256 #### fn from(bytes: &[u8; 32]) -> U256 Converts to this type from the input type.### impl<'a> From<&'a [u8]> for U256 #### fn from(bytes: &[u8]) -> U256 Converts to this type from the input type.### impl<'a> From<&'a U256> for U256 #### fn from(x: &'a U256) -> U256 Converts to this type from the input type.### impl<'a> From<&'a U256> for U512 #### fn from(value: &'a U256) -> U512 Converts to this type from the input type.### impl From<&'static str> for U256 #### fn from(s: &'static str) -> U256 Converts to this type from the input type.### impl From<[u8; 32]> for U256 #### fn from(bytes: [u8; 32]) -> U256 Converts to this type from the input type.### impl From<U128> for U256 #### fn from(value: U128) -> U256 Converts to this type from the input type.### impl From<U256> for U512 #### fn from(value: U256) -> U512 Converts to this type from the input type.### impl From<i128> for U256 #### fn from(value: i128) -> U256 Converts to this type from the input type.### impl From<i16> for U256 #### fn from(value: i16) -> U256 Converts to this type from the input type.### impl From<i32> for U256 #### fn from(value: i32) -> U256 Converts to this type from the input type.### impl From<i64> for U256 #### fn from(value: i64) -> U256 Converts to this type from the input type.### impl From<i8> for U256 #### fn from(value: i8) -> U256 Converts to this type from the input type.### impl From<isize> for U256 #### fn from(value: isize) -> U256 Converts to this type from the input type.### impl From<u128> for U256 #### fn from(value: u128) -> U256 Converts to this type from the input type.### impl From<u16> for U256 #### fn from(value: u16) -> U256 Converts to this type from the input type.### impl From<u32> for U256 #### fn from(value: u32) -> U256 Converts to this type from the input type.### impl From<u64> for U256 #### fn from(value: u64) -> U256 Converts to this type from the input type.### impl From<u8> for U256 #### fn from(value: u8) -> U256 Converts to this type from the input type.### impl From<usize> for U256 #### fn from(value: usize) -> U256 Converts to this type from the input type.### impl FromStr for U256 #### type Err = FromHexError The associated error which can be returned from parsing.#### fn from_str(value: &str) -> Result<U256, <U256 as FromStr>::ErrParses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut__H)where    __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl<'a> Mul<&'a U256> for &'a U256 #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U256) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U256) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: U256) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: U256) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U256 Performs the `*` operation. #### type Output = U256 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U256 Performs the `*` operation. #### fn mul_assign(&mut self, other: U256) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: isize) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: usize) Performs the `*=` operation. #### type Output = U256 The resulting type after applying the `!` operator.#### fn not(self) -> U256 Performs the unary `!` operation. #### fn cmp(&self, other: &U256) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &U256) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &U256) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### type Output = U256 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U256 Performs the `%` operation. #### type Output = U256 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U256 Performs the `%` operation. #### fn rem_assign(&mut self, other: T) Performs the `%=` operation. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### type Output = U256 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U256 Performs the `<<` operation. #### type Output = U256 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U256 Performs the `<<` operation. #### fn shl_assign(&mut self, shift: T) Performs the `<<=` operation. #### type Output = U256 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U256 Performs the `>>` operation. #### type Output = U256 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U256 Performs the `>>` operation. #### fn shr_assign(&mut self, shift: T) Performs the `>>=` operation. #### type Output = U256 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U256 Performs the `-` operation. #### type Output = U256 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U256 Performs the `-` operation. #### fn sub_assign(&mut self, other: U256) Performs the `-=` operation. #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: &'a U512) -> Result<U256, ErrorPerforms the conversion.### impl TryFrom<U256> for U128 #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: U256) -> Result<U128, ErrorPerforms the conversion.### impl TryFrom<U512> for U256 #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: U512) -> Result<U256, ErrorPerforms the conversion.### impl UpperHex for U256 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for U256 ### impl Eq for U256 ### impl StructuralEq for U256 ### impl StructuralPartialEq for U256 Auto Trait Implementations --- ### impl RefUnwindSafe for U256 ### impl Send for U256 ### impl Sync for U256 ### impl Unpin for U256 ### impl UnwindSafe for U256 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, Struct ethereum_types::U512 === ``` pub struct U512(pub [u64; 8]); ``` Little-endian large integer type 512-bits unsigned integer. Tuple Fields --- `0: [u64; 8]`Implementations --- ### impl U512 #### pub const MAX: U512 = U512([u64::max_value(); 8]) Maximum value. #### pub fn from_str_radix(txt: &str, radix: u32) -> Result<U512, FromStrRadixErrConverts a string slice in a given base to an integer. Only supports radixes of 10 and 16. #### pub fn from_dec_str(value: &str) -> Result<U512, FromDecStrErrConvert from a decimal string. #### pub const fn low_u32(&self) -> u32 Conversion to u32 #### pub const fn low_u64(&self) -> u64 Low word (u64) #### pub fn as_u32(&self) -> u32 Conversion to u32 with overflow checking ##### Panics Panics if the number is larger than 2^32. #### pub fn as_u64(&self) -> u64 Conversion to u64 with overflow checking ##### Panics Panics if the number is larger than u64::max_value(). #### pub fn as_usize(&self) -> usize Conversion to usize with overflow checking ##### Panics Panics if the number is larger than usize::max_value(). #### pub const fn is_zero(&self) -> bool Whether this is zero. #### pub fn bits(&self) -> usize Return the least number of bits needed to represent the number #### pub const fn bit(&self, index: usize) -> bool Return if specific bit is set. ##### Panics Panics if `index` exceeds the bit width of the number. #### pub fn leading_zeros(&self) -> u32 Returns the number of leading zeros in the binary representation of self. #### pub fn trailing_zeros(&self) -> u32 Returns the number of trailing zeros in the binary representation of self. #### pub const fn byte(&self, index: usize) -> u8 Return specific byte. ##### Panics Panics if `index` exceeds the byte width of the number. #### pub fn to_big_endian(&self, bytes: &mut [u8]) Write to the slice in big-endian format. #### pub fn to_little_endian(&self, bytes: &mut [u8]) Write to the slice in little-endian format. #### pub fn exp10(n: usize) -> U512 Create `10**n` as this type. ##### Panics Panics if the result overflows the type. #### pub const fn zero() -> U512 Zero (additive identity) of this type. #### pub const fn one() -> U512 One (multiplicative identity) of this type. #### pub const fn max_value() -> U512 The maximum value which can be inhabited by this type. #### pub fn div_mod(self, other: U512) -> (U512, U512) Returns a pair `(self / other, self % other)`. ##### Panics Panics if `other` is zero. #### pub fn integer_sqrt(&self) -> U512 Compute the highest `n` such that `n * n <= self`. #### pub fn pow(self, expon: U512) -> U512 Fast exponentiation by squaring https://en.wikipedia.org/wiki/Exponentiation_by_squaring ##### Panics Panics if the result overflows the type. #### pub fn overflowing_pow(self, expon: U512) -> (U512, bool) Fast exponentiation by squaring. Returns result and overflow flag. #### pub fn checked_pow(self, expon: U512) -> Option<U512Checked exponentiation. Returns `None` if overflow occurred. #### pub fn overflowing_add(self, other: U512) -> (U512, bool) Addition which overflows and returns a flag if it does. #### pub fn saturating_add(self, other: U512) -> U512 Addition which saturates at the maximum value (Self::MAX). #### pub fn checked_add(self, other: U512) -> Option<U512Checked addition. Returns `None` if overflow occurred. #### pub fn overflowing_sub(self, other: U512) -> (U512, bool) Subtraction which underflows and returns a flag if it does. #### pub fn saturating_sub(self, other: U512) -> U512 Subtraction which saturates at zero. #### pub fn checked_sub(self, other: U512) -> Option<U512Checked subtraction. Returns `None` if overflow occurred. #### pub fn abs_diff(self, other: U512) -> U512 Computes the absolute difference between self and other. #### pub fn overflowing_mul(self, other: U512) -> (U512, bool) Multiply with overflow, returning a flag if it does. #### pub fn saturating_mul(self, other: U512) -> U512 Multiplication which saturates at the maximum value.. #### pub fn checked_mul(self, other: U512) -> Option<U512Checked multiplication. Returns `None` if overflow occurred. #### pub fn checked_div(self, other: U512) -> Option<U512Checked division. Returns `None` if `other == 0`. #### pub fn checked_rem(self, other: U512) -> Option<U512Checked modulus. Returns `None` if `other == 0`. #### pub fn overflowing_neg(self) -> (U512, bool) Negation with overflow. #### pub fn checked_neg(self) -> Option<U512Checked negation. Returns `None` unless `self == 0`. #### pub fn from_big_endian(slice: &[u8]) -> U512 Converts from big endian representation bytes in memory. #### pub fn from_little_endian(slice: &[u8]) -> U512 Converts from little endian representation bytes in memory. ### impl U512 #### pub const fn low_u128(&self) -> u128 Low 2 words (u128) #### pub fn as_u128(&self) -> u128 Conversion to u128 with overflow checking ##### Panics Panics if the number is larger than 2^128. Trait Implementations --- ### impl<'a, T> Add<T> for &'a U512where    T: Into<U512>, #### type Output = U512 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U512 Performs the `+` operation. #### type Output = U512 The resulting type after applying the `+` operator.#### fn add(self, other: T) -> U512 Performs the `+` operation. #### fn add_assign(&mut self, other: U512) Performs the `+=` operation. Get a reference to the underlying little-endian words. #### fn as_ref(&self) -> &[u64] Converts this type into a shared reference of the (usually inferred) input type.### impl BitAnd<U512> for U512 #### type Output = U512 The resulting type after applying the `&` operator.#### fn bitand(self, other: U512) -> U512 Performs the `&` operation. #### fn bitand_assign(&mut self, rhs: U512) Performs the `&=` operation. #### type Output = U512 The resulting type after applying the `|` operator.#### fn bitor(self, other: U512) -> U512 Performs the `|` operation. #### fn bitor_assign(&mut self, rhs: U512) Performs the `|=` operation. #### type Output = U512 The resulting type after applying the `^` operator.#### fn bitxor(self, other: U512) -> U512 Performs the `^` operation. #### fn bitxor_assign(&mut self, rhs: U512) Performs the `^=` operation. #### fn clone(&self) -> U512 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn decode(rlp: &Rlp<'_>) -> Result<U512, DecoderErrorDecode a value from RLP bytes### impl Default for U512 #### fn default() -> U512 Returns the “default value” for a type. #### fn deserialize<D>(    deserializer: D) -> Result<U512, <D as Deserializer<'de>>::Error>where    D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Output = U512 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U512 Performs the `/` operation. #### type Output = U512 The resulting type after applying the `/` operator.#### fn div(self, other: T) -> U512 Performs the `/` operation. #### fn div_assign(&mut self, other: T) Performs the `/=` operation. #### fn rlp_append(&self, s: &mut RlpStream) Append a value to the stream#### fn rlp_bytes(&self) -> BytesMut Get rlp-encoded bytes for this instance### impl<'a> From<&'a [u8; 64]> for U512 #### fn from(bytes: &[u8; 64]) -> U512 Converts to this type from the input type.### impl<'a> From<&'a [u8]> for U512 #### fn from(bytes: &[u8]) -> U512 Converts to this type from the input type.### impl<'a> From<&'a U256> for U512 #### fn from(value: &'a U256) -> U512 Converts to this type from the input type.### impl<'a> From<&'a U512> for U512 #### fn from(x: &'a U512) -> U512 Converts to this type from the input type.### impl From<&'static str> for U512 #### fn from(s: &'static str) -> U512 Converts to this type from the input type.### impl From<[u8; 64]> for U512 #### fn from(bytes: [u8; 64]) -> U512 Converts to this type from the input type.### impl From<U128> for U512 #### fn from(value: U128) -> U512 Converts to this type from the input type.### impl From<U256> for U512 #### fn from(value: U256) -> U512 Converts to this type from the input type.### impl From<i128> for U512 #### fn from(value: i128) -> U512 Converts to this type from the input type.### impl From<i16> for U512 #### fn from(value: i16) -> U512 Converts to this type from the input type.### impl From<i32> for U512 #### fn from(value: i32) -> U512 Converts to this type from the input type.### impl From<i64> for U512 #### fn from(value: i64) -> U512 Converts to this type from the input type.### impl From<i8> for U512 #### fn from(value: i8) -> U512 Converts to this type from the input type.### impl From<isize> for U512 #### fn from(value: isize) -> U512 Converts to this type from the input type.### impl From<u128> for U512 #### fn from(value: u128) -> U512 Converts to this type from the input type.### impl From<u16> for U512 #### fn from(value: u16) -> U512 Converts to this type from the input type.### impl From<u32> for U512 #### fn from(value: u32) -> U512 Converts to this type from the input type.### impl From<u64> for U512 #### fn from(value: u64) -> U512 Converts to this type from the input type.### impl From<u8> for U512 #### fn from(value: u8) -> U512 Converts to this type from the input type.### impl From<usize> for U512 #### fn from(value: usize) -> U512 Converts to this type from the input type.### impl FromStr for U512 #### type Err = FromHexError The associated error which can be returned from parsing.#### fn from_str(value: &str) -> Result<U512, <U512 as FromStr>::ErrParses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut__H)where    __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl<'a> Mul<&'a U512> for &'a U512 #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U512) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a U512) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a i8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a isize) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a u8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: &'a usize) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: U512) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: U512) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: i8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: isize) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u16) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u64) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: u8) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U512 Performs the `*` operation. #### type Output = U512 The resulting type after applying the `*` operator.#### fn mul(self, other: usize) -> U512 Performs the `*` operation. #### fn mul_assign(&mut self, other: U512) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: i8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: isize) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u16) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u32) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u64) Performs the `*=` operation. #### fn mul_assign(&mut self, other: u8) Performs the `*=` operation. #### fn mul_assign(&mut self, other: usize) Performs the `*=` operation. #### type Output = U512 The resulting type after applying the `!` operator.#### fn not(self) -> U512 Performs the unary `!` operation. #### fn cmp(&self, other: &U512) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere    Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere    Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &U512) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### fn partial_cmp(&self, other: &U512) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### type Output = U512 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U512 Performs the `%` operation. #### type Output = U512 The resulting type after applying the `%` operator.#### fn rem(self, other: T) -> U512 Performs the `%` operation. #### fn rem_assign(&mut self, other: T) Performs the `%=` operation. #### fn serialize<S>(    &self,    serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where    S: Serializer, Serialize this value into the given Serde serializer. #### type Output = U512 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U512 Performs the `<<` operation. #### type Output = U512 The resulting type after applying the `<<` operator.#### fn shl(self, shift: T) -> U512 Performs the `<<` operation. #### fn shl_assign(&mut self, shift: T) Performs the `<<=` operation. #### type Output = U512 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U512 Performs the `>>` operation. #### type Output = U512 The resulting type after applying the `>>` operator.#### fn shr(self, shift: T) -> U512 Performs the `>>` operation. #### fn shr_assign(&mut self, shift: T) Performs the `>>=` operation. #### type Output = U512 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U512 Performs the `-` operation. #### type Output = U512 The resulting type after applying the `-` operator.#### fn sub(self, other: T) -> U512 Performs the `-` operation. #### fn sub_assign(&mut self, other: U512) Performs the `-=` operation. #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: &'a U512) -> Result<U256, ErrorPerforms the conversion.### impl TryFrom<U512> for U128 #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: U512) -> Result<U128, ErrorPerforms the conversion.### impl TryFrom<U512> for U256 #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: U512) -> Result<U256, ErrorPerforms the conversion.### impl UpperHex for U512 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Copy for U512 ### impl Eq for U512 ### impl StructuralEq for U512 ### impl StructuralPartialEq for U512 Auto Trait Implementations --- ### impl RefUnwindSafe for U512 ### impl Send for U512 ### impl Sync for U512 ### impl Unpin for U512 ### impl UnwindSafe for U512 Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere    T: for<'de> Deserialize<'de>, Enum ethereum_types::BloomInput === ``` pub enum BloomInput<'a> { Raw(&'a [u8]), Hash(&'a [u8; 32]), } ``` Variants --- ### Raw(&'a [u8]) ### Hash(&'a [u8; 32]) Trait Implementations --- ### impl<'a> From<Input<'a>> for Bloom #### fn from(input: Input<'a>) -> Bloom Converts to this type from the input type.Auto Trait Implementations --- ### impl<'a> RefUnwindSafe for Input<'a### impl<'a> Send for Input<'a### impl<'a> Sync for Input<'a### impl<'a> Unpin for Input<'a### impl<'a> UnwindSafe for Input<'aBlanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum ethereum_types::FromDecStrErr === ``` pub enum FromDecStrErr { InvalidCharacter, InvalidLength, } ``` Conversion from decimal string error Variants --- ### InvalidCharacter Char not from range 0-9 ### InvalidLength Value does not fit into type Trait Implementations --- ### impl Debug for FromDecStrErr #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(e: FromDecStrErr) -> FromStrRadixErr Converts to this type from the input type.### impl PartialEq<FromDecStrErr> for FromDecStrErr #### fn eq(&self, other: &FromDecStrErr) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. Auto Trait Implementations --- ### impl RefUnwindSafe for FromDecStrErr ### impl Send for FromDecStrErr ### impl Sync for FromDecStrErr ### impl Unpin for FromDecStrErr ### impl UnwindSafe for FromDecStrErr Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<E> Provider for Ewhere    E: Error + ?Sized, #### fn provide<'a>(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any`)Data providers should implement this method to provide *all* values they are able to provide by using `demand`. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum ethereum_types::FromStrRadixErrKind === ``` #[non_exhaustive] pub enum FromStrRadixErrKind { InvalidCharacter, InvalidLength, UnsupportedRadix, } ``` A list of error categories encountered when parsing numbers. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### InvalidCharacter A character in the input string is not valid for the given radix. ### InvalidLength The input length is not valid for the given radix. ### UnsupportedRadix The given radix is not supported. Trait Implementations --- ### impl Clone for FromStrRadixErrKind #### fn clone(&self) -> FromStrRadixErrKind Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn hash<__H>(&self, state: &mut__H)where    __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &FromStrRadixErrKind) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ### impl Eq for FromStrRadixErrKind ### impl StructuralEq for FromStrRadixErrKind ### impl StructuralPartialEq for FromStrRadixErrKind Auto Trait Implementations --- ### impl RefUnwindSafe for FromStrRadixErrKind ### impl Send for FromStrRadixErrKind ### impl Sync for FromStrRadixErrKind ### impl Unpin for FromStrRadixErrKind ### impl UnwindSafe for FromStrRadixErrKind Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.
graby
rust
Rust
Struct graby::Config === ``` pub struct Config { pub query: String, pub regex_match: bool, pub file_path: PathBuf, pub ignore_case: bool, pub invert_match: bool, } ``` Structure to store the given arguments from the terminal. Fields --- `query: String`Pattern to search in the file. `regex_match: bool`Take pattern as regular expression. `file_path: PathBuf`Path to the file. `ignore_case: bool`Ignore case distinctions while searching QUERY in FILE_PATH. `invert_match: bool`Print the lines without QUERY pattern in the FILE_PATH. Trait Implementations --- ### impl Args for Config #### fn group_id() -> Option<IdReport the [`ArgGroup::id`][crate::ArgGroup::id] for this set of arguments#### fn augment_args<'b>(__clap_app: Command) -> Command Append to [`Command`] so it can instantiate `Self`. Append to [`Command`] so it can update `self`. #### fn command<'b>() -> Command Build a [`Command`] that can instantiate `Self`. Build a [`Command`] that can update `self`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from_arg_matches(__clap_arg_matches: &ArgMatches) -> Result<Self, ErrorInstantiate `Self` from [`ArgMatches`], parsing the arguments as needed. __clap_arg_matches: &mut ArgMatches ) -> Result<Self, ErrorInstantiate `Self` from [`ArgMatches`], parsing the arguments as needed. &mut self, __clap_arg_matches: &ArgMatches ) -> Result<(), ErrorAssign values from `ArgMatches` to `self`.#### fn update_from_arg_matches_mut( &mut self, __clap_arg_matches: &mut ArgMatches ) -> Result<(), ErrorAssign values from `ArgMatches` to `self`.### impl Parser for Config #### fn parse() -> Self Parse from `std::env::args_os()`, exit on error#### fn try_parse() -> Result<Self, Error<RichFormatter>Parse from `std::env::args_os()`, return Err on error.#### fn parse_from<I, T>(itr: I) -> Selfwhere I: IntoIterator<Item = T>, T: Into<OsString> + Clone, Parse from iterator, exit on error#### fn try_parse_from<I, T>(itr: I) -> Result<Self, Error<RichFormatter>>where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, Parse from iterator, return Err on error.#### fn update_from<I, T>(&mut self, itr: I)where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, Update from iterator, exit on error#### fn try_update_from<I, T>(&mut self, itr: I) -> Result<(), Error<RichFormatter>>where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, Update from iterator, return Err on error.Auto Trait Implementations --- ### impl RefUnwindSafe for Config ### impl Send for Config ### impl Sync for Config ### impl Unpin for Config ### impl UnwindSafe for Config Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Function graby::run === ``` pub fn run(config: Config) -> Result<()> ``` Checks if pattern is regular expression or not. Function graby::run_string === ``` pub fn run_string(config: Config) -> Result<()> ``` Search for the string query in the given file and display the lines that contain it. Function graby::search === ``` pub fn search<'a>(query: &str, contents: &'a str, invert: bool) -> Vec<&'a str> ``` This function search for the query string with exact case. Function graby::search_case_insensitive === ``` pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, invert: bool ) -> Vec<&'a str> ``` This function search for the query string without case distinction.
textwrap
hex
Erlang
Textwrap === [`Textwrap`](Textwrap.html#content) provides a set of functions for wrapping, indenting, and dedenting text. It wraps the Rust [`textwrap`](https://lib.rs/textwrap) crate. Wrapping --- Use [`wrap/2`](#wrap/2) to turn a [`String`](https://hexdocs.pm/elixir/String.html) into a list of [`String`](https://hexdocs.pm/elixir/String.html)s each no more than `width` characters long. ``` iex> Textwrap.wrap("foo bar baz", 3) ["foo", "bar", "baz"] iex> Textwrap.wrap("foo bar baz", 7) ["foo bar", "baz"] ``` [`fill/2`](#fill/2) is like [`wrap/2`](#wrap/2), except that it retuns the wrapped text as a single [`String`](https://hexdocs.pm/elixir/String.html). ``` iex> Textwrap.fill("foo bar baz", 3) "foo\nbar\nbaz" iex> Textwrap.fill("foo bar baz", 7) "foo bar\nbaz" ``` Both [`wrap/2`](#wrap/2) and [`fill/2`](#fill/2) can either take the width to wrap too as their second argument, or take a keyword list including a `:width` key and any number of other options. See the docs for [`wrap/2`](#wrap/2) for details. Displayed Width vs Byte Width --- [`Textwrap`](Textwrap.html#content) wraps text based on measured display width, not simply counting bytes. For ascii text this gives exactly the same result, but many non-ASCII characters take up more than one byte in the UTF-8 encoding. See the documentation of the [`textwrap` crate](https://docs.rs/textwrap/0.13.2/textwrap/index.html#displayed-width-vs-byte-size) for more details. Terminal Width --- The `width` passed to [`wrap/2`](#wrap/2) or [`fill/2`](#fill/2) can either by a positive integer, or the atom `:termwidth`. When standard output is connected to a terminal, passing `:termwidth` will wrap the text to the width of the terminal. Otherwise, it will use a width of 80 characters as a fallback. Indenting and Dedenting --- Use [`indent/2`](#indent/2) and [`dedent/1`](#dedent/1) to indent and dedent text: ``` iex> Textwrap.indent("hello\nworld\n", " ") " hello\n world\n" iex> Textwrap.dedent(" hello\n world\n") "hello\nworld\n" ``` [Link to this section](#summary) Summary === [Types](#types) --- [wrap_algorithm()](#t:wrap_algorithm/0) [wrap_opt()](#t:wrap_opt/0) [wrap_opts()](#t:wrap_opts/0) [Functions](#functions) --- [dedent(text)](#dedent/1) Removes as much common leading whitespace as possible from each line. [fill(text, width_or_opts)](#fill/2) Fills text to the given width. [indent(text, prefix)](#indent/2) Adds a given prefix to each non-empty line. [wrap(text, width_or_opts)](#wrap/2) Wraps text to the given width. [Link to this section](#types) Types === [Link to this section](#functions) Functions === API Reference === Modules --- [Textwrap](Textwrap.html) [`Textwrap`](Textwrap.html#content) provides a set of functions for wrapping, indenting, and dedenting text. It wraps the Rust [`textwrap`](https://lib.rs/textwrap) crate.
brainiak
readthedoc
JSON
brainiak documentation [brainiak](index.html#document-index) --- Brainiak API documentation![¶](#brainiak-api-documentation) === Linked data offers a set of best practices for publishing, sharing and linking data and information on the web. It is based on use of http URIs and semantic web standards such as [RDF](http://www.w3.org/RDF/). What is Linked Data? Please refer to this [great introduction video](http://www.youtube.com/watch?v=TJfrNo3Z-DU), by Metaweb (acquired by Google). For some web developers the need to understand the RDF data model and associated serializations and query language ([SPARQL](http://www.cambridgesemantics.com/semantic-university/sparql-by-example)) has proved a barrier to adoption of Linked Data. This project seeks to build APIs, data formats and supporting tools to overcome this barrier. Including, but not limited to, accessing Linked Data via a developer-friendly JSON format. The Brainiak API provides a configurable way to access RDF data using simple RESTful URLs that are translated into queries to a SPARQL endpoint, where basic RDF manipulation, such as manipulating instances is easy with just some configuration. Of course, SPARQL is more expressive than an API built on top of HTTP, therefore, we also support ad-hoc SPARQL queries for fast execution (see [*Stored Queries*](index.html#document-services/stored_query/stored_query)). Concepts[¶](#concepts) --- Prior to use the API is advisable to master the following concepts: ### Ubiquitous Language[¶](#ubiquitous-language) Here we explain the main concepts of the API, i.e. this is our [ubiquitous language](http://martinfowler.com/bliki/UbiquitousLanguage.html). #### Context[¶](#context) Context is an isolated data space, defined by some unique context_id. This context_id will be used as a namespace. Each context can hold classes and instance definitions. A context can be used to represent, for example, some product or some app being developed. Inside the triplestore, the context is materialized as [a graph](http://www.w3.org/TR/rdf-sparql-query/#GraphPattern). This graph is represented internally by an [URI](http://www.ietf.org/rfc/rfc3986.txt). This URI is composed by adding a configurable (server-wide) URI_PREFIX to the context_id For example, inside Globo.com, the Brainiak server is configured with URI_PREFIX=”<http://semantica.globo.com/>”. Thus, the graph URI implicitly associated with context “app1” would be: “<http://semantica.globo.com/app1/>”. The default prefix can be overridden if necessary using the parameter graph_uri, see more details in [*Overriding URIs*](index.html#parametrization). #### Class[¶](#class) Usually database models work with a clear distinction between instances (data) and classes (metadata). We also make this distinction on the API interface. A *Class* is a priviledged instance that defines the structure of the data (non-class instances) being stored. To avoid confusion, we avoid referring to classes calling them *instances*, a term we reserve for *non-class* instances. Although we prefer class, sometimes we use the term schema as a synonym. Class is preferable to schema in order to avoid the confusion with the listings schemas rendered in json-schema format. Classes are defined in the RDF/OWL Model, given its high expressivity and flexibility. Therefore, it will be possible to represent classes in different database models or even translations between them in a common language. Likewise, we expect a class to be easily written, by using the [Turtle](http://en.wikipedia.org/wiki/Turtle_(syntax)) format, the most compact serialization for ontologies developed in the RDF/OWL model. ``` :City a owl:Class ; rdfs:subClassOf :Place . ``` The class is associated with a class_id that is unique in the particular context where it was declared. Therefore, the class definition belongs to a graph in the triplestore, where it is identified by an URI. By convention, the class URI is composed by the context’s graph URI and the class_id. For example, consider the class for Person declared in the context person whose graph_uri is http://semantica.globo.com/person. The default URI for this class would be generated as http://semantica.globo.com/person/Person. The class’ URI can be overriden if necessary using the parameter class_uri, see more details in [*Overriding URIs*](index.html#parametrization). #### Collection[¶](#collection) We need to distinguish the structure of an instance (class) from a group of instances with the same structure (collection). Therefore, for each class corresponds a unique collection and vice-versa. The collection name and the class name are the same. #### Instance[¶](#instance) An instance is a set of data that is treated as a unit, whose structure is described by a class. The group of instances that share the same class form a collection. A collection subset or the whole collection is stored in a context. Instances must be easily retrieved. Morevoer, “instance queries” must be really simple for developers to understand as they will do way more requests on instances than on classes. As such, the interface for manipulating instances accepts JSON content_type as most of the RESTful APIs do. ### Using HTTP methods in a RESTful way[¶](#using-http-methods-in-a-restful-way) The HTTP verbs comprise a major portion of our “uniform interface” goal. They represent the actions applied over the resources provided by the interface. The primary or most commonly used HTTP verbs (or methods) are POST, GET, PUT, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently such as OPTIONS, HEAD and PURGE. Below is a table summarizing recommended return values of the primary HTTP methods in combination with the resource URIs: | HTTP Verb | Collection (e.g. /place/City) | Item (e.g. /place/City/{id}) | | --- | --- | --- | | HEAD HTTP header info | | | | GET retrieving resources | 200 OK, list of cities. Use pagination, sorting and filtering to navigate. | 200 *OK*, single city. 404 *Not Found* for missing {id} | | PUT replacing resources | 404 *Not Found* | 200 *OK*. 404 *Not Found* for missing {id} | | POST for creating resources | 201 *Created*, Location header with link to /place/City/{id} containing new ID. | 404 *Not Found*. | | DELETE for deleting resources | 404 *Not Found* | 204 *No Content*, resource deleted. 404 *Not Found* | ### Hypermedia Support[¶](#hypermedia-support) In the words of <NAME>, HATEOAS - Hypermedia as the engine of application state is: ``` You do stuff by reading pages and then either following links or submitting forms. ``` Any resource may have one or more properties linking to other resources, represented in the resource’s link section. These links are meant to provide explicit URLs so that proper API clients don’t need to hardcode URLs to API services. In hypermedia APIs you should be able to navigate through API services from the root /. It is highly recommended that API clients use these links, because API service URLs may change in production without previous notice to clients. The links are not embedded in the resource, they are present in the schema that described such resource. In order to obtain the list of links for a given resource, one should follow the profile URL present in the Content-Type response header. For example: ``` $ curl -i http://brainiak.semantica.dev.globoi.com HTTP/1.1 200 OK Content-Type: application/json; profile=http://brainiak.semantica.dev.globoi.com/_schema_list Content-Length: 1007 ... ``` All URLs are expected to be proper RFC 6570 URI templates. Each link is described by attributes, typically: rel, href and method. The rel attribute describes the purpose of the link. The method attribute describes which HTTP verb should be used to follow the ink. The href attribute describes the URL of the link. The href value can be an exact string, or a string template whose variable placeholders are given from the items section. We give an example of a link section below: ``` { "links": [ { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Male", "rel": "self" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/_schema", "rel": "describedBy" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Male", "method": "PUT", "rel": "update" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Male", "method": "DELETE", "rel": "delete" } ] } ``` A complete documentation of rel values is given in the section [*Hypermap of Resources*](index.html#links-spec). ### Modeling and Ontology Engineering[¶](#modeling-and-ontology-engineering) The Brainiak API impose on its client applications some ontology modeling restricitons. In this section we discuss the rationale, limits and benefits related to those decisions. #### The need for rdfs:label[¶](#the-need-for-rdfs-label) We use rdfs:label or any of its derived property as an ubiquitous property, that we can rely on for indexing and for showing in user interfaces. Brainiak uses that property in several queries over the triplestore, and if an instance does not have this property defined it may not appear in the results produced by Brainiak API. #### Restrictions on subproperties[¶](#restrictions-on-subproperties) While presenting a class definition, all its direct properties are rendered. Even the properties inherited from ancestor classes are rendered. However, if a direct property is derived from another property declared in an ancestor class, only the most specific property will be rendered in the class definition. This is done to avoid duplicated properties in a class definiton. For example, in the example below subRegionOf is a sub-property of isPartOf, but only subRegionOf will appear when retrieving the schema for class Region. ``` :subRegionOf a owl:ObjectProperty ; rdfs:subPropertyOf other:isPartOf ; rdfs:domain :Region . ``` Moreover, if the class Region had two properties prop1 and prop2 where prop2 is a subproperty of prop1, only prop2 will show up in the class Region definiton. ``` :prop1 a owl:ObjectProperty ; rdfs:domain :Region . :prop2 a owl:ObjectProperty ; rdfs:subPropertyOf :prop1 ; rdfs:domain :Region . ``` So, if the original intention was to show prop1 and prop2 as direct properties in class Region, then both should be sub-properties of a more generic property with domain and ranges pointing to some ancestor class of the ones referred by the sub-property. The example below illustrates that approach. ``` :superprop a owl:ObjectProperty ; rdfs:domain :Place . :Region a owl:Class ; rdfs:subClassOf :Place . :prop1 a owl:ObjectProperty ; rdfs:subPropertyOf :superprop ; rdfs:domain :Region . :prop2 a owl:ObjectProperty ; rdfs:subPropertyOf :superprop ; rdfs:domain :Region . ``` Tutorials[¶](#tutorials) --- New to Brainiak? This tutorials might help you getting started: ### How to read this documentation[¶](#how-to-read-this-documentation) #### Simplified response examples[¶](#simplified-response-examples) Fear no evil if response examples in documentation are a subset of real output from Brainiak. We did this intentionally in documentation for legibility purposes. For example, hypermedia commands (like the links section) or metadata for hypernavigation (_attributes) are sometimes hidden in examples. For a list of hypermedia commands, check [*Hypermap of Resources*](index.html#document-services/links). ### Building Brainiak in your local environment[¶](#building-brainiak-in-your-local-environment) Brainiak is developed using [Python](http://python.org) 2.7 and the web framework [Tornado](http://www.tornadoweb.org/en/stable/), on top of [Virtuoso](http://virtuoso.openlinksw.com/). #### Source-code[¶](#source-code) Clone Brainiak repository using [Git](http://git-scm.com/): ``` git clone git://ngit.globoi.com/brainiak/brainiak.git ``` Or, if you have super-powers: ``` git clone <EMAIL>:brainiak/brainiak.git ``` #### Python dependencies[¶](#python-dependencies) ##### Python 2.7[¶](#python-2-7) Most recent GNU Linux and MacOS distributions have [Python](http://python.org) installed by default. If this is not your case, [download and install it](http://www.python.org/download/releases/2.7/). ##### Python libs[¶](#python-libs) We strongly suggest you use [VirtualEnv](http://www.virtualenv.org/) and [VirtualEnvWrapper](http://virtualenvwrapper.readthedocs.org/en/latest/), to isolate dependencies of each Python project you run locally: ``` $ sudo python easy_install setuptools $ sudo python easy_install pip $ sudo pip install virtualenv virtualenvwrapper $ source `which virtualenvwrapper.sh` $ mkvirtualenv brainiak ``` To install other python packages, make sure you enter Brainiak root directory and run: ``` $ make install ``` #### Non-python dependencies[¶](#non-python-dependencies) When running Brainiak locally, you can refer a local or remote [Virtuoso](http://virtuoso.openlinksw.com/) server. Brainiak access to [Virtuoso](http://virtuoso.openlinksw.com/) is defined in the settings.py file, at brainiak/src/brainiak directory, by the lines: ``` SPARQL_ENDPOINT = 'http://localhost:8890/sparql-auth' SPARQL_ENDPOINT_USER = "api-semantica" SPARQL_ENDPOINT_PASSWORD = "api-semantica" SPARQL_ENDPOINT_AUTH_MODE = "digest" SPARQL_ENDPOINT_REALM = "SPARQL" ``` In order to point your local Brainiak to DEV’s Virtuoso, for instance, SPARQL_ENDPOINT could be changed to: ``` SPARQL_ENDPOINT = "http://dev.virtuoso.globoi.com:8890/sparql-auth" ``` Note that **digest authentication is mandatory** for Brainiak’s access to Virtuoso. Therefore, make sure SPARQL_ENDPOINT_USER and SPARQL_ENDPOINT_PASSWORD are appropriately set. The steps below should be followed just if you are installing Virtuoso locally. ##### OpenLink Virtuoso[¶](#openlink-virtuoso) [Virtuoso](http://virtuoso.openlinksw.com/) is a middleware and hybrid database engine that combines the functionalities of RDBMS, ORDBMS, virtual database, RDF, XML, free-text, web application server and file server. Internally, Brainiak uses [Virtuoso](http://virtuoso.openlinksw.com/) as an Object-relational database (throught [RDF](http://en.wikipedia.org/wiki/Resource_Description_Framework)). *Version*: Virtuoso Open Source Edition (multi threaded) 6.1 ###### Install in MacOS X[¶](#install-in-macos-x) Using [HomeBrew](http://mxcl.github.com/homebrew/): ``` $ sudo brew install virtuoso ``` ###### Install in Fedora[¶](#install-in-fedora) ``` $ sudo yum install virtuoso ``` ##### After-installing Virtuoso[¶](#after-installing-virtuoso) Run isql (OpenLink Interactive SQL) prompt: ``` $ isql OpenLink Interactive SQL (Virtuoso), version 0.9849b. Type HELP; for help and EXIT; to exit. SQL> ``` And execute the steps bellow from it. ###### Add authenticated user[¶](#add-authenticated-user) Create an user api-semantica with password api-semantica, and grant it update permissions, using the following commands: ``` SQL> DB.DBA.USER_CREATE ('api-semantica', 'api-semantica'); SQL> grant SPARQL_UPDATE to "api-semantica"; ``` ###### Activate inference in graphs[¶](#activate-inference-in-graphs) Some Brainiak primitives make queries to Virtuoso using inference. To make sure this primitives will work appropriatelly, you have to enable associate Brainiak ruleset for all your graphs, **after loading instances to your graphs**. Brainiak, by default, uses inference in all graphs that are mapped to the rule named ‘<http://semantica.globo.com/ruleset>‘. For instance, to apply Brainiak ruleset ‘<http://semantica.globo.com/ruleset>‘ to the graph http://semantica.globo.com/new_graph, run: ``` SQL> rdfs_rule_set('http://semantica.globo.com/ruleset', 'http://semantica.globo.com/new_graph'); ``` For more information about this function, read [fn_rdfs_rule_set](http://docs.openlinksw.com/virtuoso/fn_rdfs_rule_set.html) documentation at OpenLink’s website. ### Authorization[¶](#authorization) To use Brainiak in Globo.com infra one does not simply walk into production with no authentication. Talk to the team. Services[¶](#services) --- The API services should be easy to remember, easy to use, and extensible. We follow the principles of [REST](http://en.wikipedia.org/wiki/Representational_state_transfer) and [HATEOAS](http://en.wikipedia.org/wiki/HATEOAS). For the meaning and rationale of these concepts in our API, see [*Context*](index.html#concept-context), [*Class*](index.html#concept-schema), [*Collection*](index.html#concept-collection), and [*Instance*](index.html#concept-instance). **API Services** ### Managing Contexts[¶](#managing-contexts) Graphs (or contexts) can be retrieved, added, edited, removed, and so on. Services available for managing contexts: #### List of Contexts[¶](#list-of-contexts) This primitive retrieves a list of contexts where one can define classes and/or instances. Contexts that contain no data are not listed. This resource is **cached**. Read [*Caching*](index.html#document-services/cache) for more information. **Basic usage** ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/' ``` ##### Optional parameters[¶](#optional-parameters) **page**: The page to be retrieved. The default value is 1, i.e. the first page. **per_page**: Defines how many items are retrieved per page. The default value is 10 > By default, the first page containing 10 items is returned. It could also be retrieved by: ``` GET 'http://brainiak.semantica.dev.globoi.com/?page=1&per_page=10' ``` **do_item_count**: If set to 1 determines that the resulting page will compute the property ìtem_count with total number of items. When set, this parameter also has the side effect of including the URL for the last page in the links section. By default do_item_count is set to 0 for performance’s sake and can be omitted. ##### Possible responses[¶](#possible-responses) **Status 200** If there are contexts, the response body is a JSON containing contexts’ titles, resources_id and @ids (URIs). ``` { "_base_url": "http://brainiak.semantica.dev.globoi.com", "_first_args": "page=1", "_next_args": "page=2", "items": [ { "@id": "http://semantica.globo.com/graph1/", "resource_id": "graph1", "title": "graph1" }, { "@id": "http://semantica.globo.com/sports/", "resource_id": "sports", "title": "sports" } ] } ``` **Status 400** If there are unknown parameters in the request query string, the response status code is 400. A JSON containing both the wrong parameters and the accepted ones is returned. ``` { "errors": [ "HTTP error: 400\nArgument invalid_param is not supported. The supported querystring arguments are: do_item_count, expand_uri, graph_uri, lang, page, per_page, sort_by, sort_include_empty, sort_order." ] } ``` **Status 404** If there are no contexts, the response status code is a 404. ``` { "errors": ["HTTP error: 404\nNo contexts were found."] } ``` **Status 500** If there was some internal problem, the response status code is a 500. Please, contact [<EMAIL>](mailto:semantica%40corp.globo.com) informing the URL and the JSON returned. ### Managing Prefixes[¶](#managing-prefixes) Prefixes are names for contexts (e.g. person and place) and common namespaces like owl or rdf. They are used to shorten URIs in the communication with the API. Services available for managing prefixes: #### List of Prefixes[¶](#list-of-prefixes) This service retrieves registered prefixes, used in compact communication with the API. **Basic usage** ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/_prefixes' ``` ##### Optional parameters[¶](#optional-parameters) **page**: The page to be retrieved. The default value is 1, i.e. the first page. **per_page**: Defines how many items are retrieved per page. The default value is 10 > By default, the first page containing 10 items is returned. It could also be retrieved by: ``` GET 'http://brainiak.semantica.dev.globoi.com/?page=1&per_page=10' ``` ##### Possible responses[¶](#possible-responses) **Status 200** The response body is a JSON containing the prefixes in a “@context” section and the root context, which is a context whose name is not in the prefix URI. ``` { "@context": { "dbpedia": "http://dbpedia.org/ontology/", "dc": "http://purl.org/dc/elements/1.1/" } } ``` **Status 400** If there are unknown parameters in the request query string, the response status code is 400. A JSON containing both the wrong parameters and the accepted ones is returned. ``` { "errors": [ "HTTP error: 400\nO argumento invalid_param não é suportado. Os argumentos de querystring suportados são: do_item_count, expand_uri, graph_uri, lang, page, per_page, sort_by, sort_include_empty, sort_order."] } ``` **Status 500** If there was some internal problem, the response status code is a 500. Please, contact [<EMAIL>](mailto:semantica%40corp.globo.com) informing the URL and the JSON returned. ### Managing Collections[¶](#managing-collections) Classes (or collections) can be retrieved, added, edited, removed, and so on. Here we list the available services for managing them. #### List of Collections[¶](#list-of-collections) This service retrieves all classes of a specific context (i.e. graph). The results are paginated. **Basic usage** ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/place/' ``` This will retrieve all classes in the place graph. ``` { "@context": { "@language": "pt" }, "@id": "http://semantica.globo.com/place/", "_base_url": "http://brainiak.semantica.dev.globoi.com/place", "_first_args": "page=1", "_next_args": "page=2", "items": [ { "@id": "http://semantica.globo.com/place/City", "class_prefix": "http://semantica.globo.com/place/", "resource_id": "City", "title": "Cidade" }, { "@id": "http://semantica.globo.com/place/Country", "class_prefix": "http://semantica.globo.com/place/", "resource_id": "Country", "title": "Pa\u00eds" } ] } ``` ##### Optional parameters[¶](#optional-parameters) **lang**: Specify language of labels. Options: pt, en, undefined (do not filter labels) **expand_uri**: The URIs that represent names and values of properties in the response are either compressed (0) or expanded (1) by this parameter. By default, this parameter is set to 0, meaning that URIs are compressed for keys and values. This is going to change in future versions, and the default will be URI expansion. So, we ask you to use this parameter explicitly and not rely on the default behaviour. For example, rdfs:label is the compressed form, while http://www.w3.org/2000/01/rdf-schema#label is the respective expanded form. Warning For the time being, URI expansion is not supported in resource listings. It is only supported while retrieving instances and class definition. **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **page**: The page to be retrieved. The default value is 1, i.e. the first page. **per_page**: Defines how many items are retrieved per page. The default value is 10 > By default, the first page containing 10 items is returned. It could also be retrieved by: ``` GET 'http://brainiak.semantica.dev.globoi.com/?page=1&per_page=10' ``` **do_item_count**: If set to 1 determines that the resulting page will compute the property ìtem_count with total number of items. When set, this parameter also has the side effect of including the URL for the last page in the links section. By default do_item_count is set to 0 for performance’s sake and can be omitted. ##### Possible responses[¶](#possible-responses) **Status 200** If there are classes in this graph, the response body is a JSON containing classes’ titles and @ids (URIs). By default, the first page containing 10 items is returned (?page=1&per_page=10). ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/place/?page=1&per_page=10' ``` ``` { "@context": { "@language": "pt" }, "@id": "http://semantica.globo.com/place/", "_base_url": "http://brainiak.semantica.dev.globoi.com/place", "_first_args": "page=1", "_next_args": "page=2", "items": [ { "@id": "http://semantica.globo.com/place/City", "class_prefix": "http://semantica.globo.com/place/", "resource_id": "City", "title": "Cidade" }, { "@id": "http://semantica.globo.com/place/Country", "class_prefix": "http://semantica.globo.com/place/", "resource_id": "Country", "title": "Pa\u00eds" } ] } ``` If there are no classes for this graph, the response will contain a warning and a items list empty. ``` { "items": [], "warning": "No classes found for context graph_example in page 1." } ``` **Status 400** If there are unknown parameters in the request query string, the response status code is 400. A JSON containing both the wrong parameters and the accepted ones is returned. ``` { "errors": [ "HTTP error: 400\nArgument invalid_param is not supported. The supported querystring arguments are: do_item_count, expand_uri, graph_uri, lang, page, per_page, sort_by, sort_include_empty, sort_order." ] } ``` **Status 404** If the graph does not exist, the response status code is 404. ``` { "errors": ["HTTP error: 404\nContext example_graph does not exist."] } ``` **Status 500** If there was some internal problem, the response status code is a 500. Please, contact [<EMAIL>](mailto:<EMAIL>) informing the URL and the JSON returned. ### Managing Classes[¶](#managing-classes) Here are the services for manipulating classes #### Get a Class[¶](#get-a-class) A class is where the definition of the data structure resides. In this service, we can get a class defined in some context. **Basic usage** ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/place/City/_schema' ``` ``` { "$schema": "http://json-schema.org/draft-04/schema#", "@context": { "@language": "pt" }, "description": "Lugar perene e urbanizado onde pessoas habitam.", "id": "http://semantica.globo.com/place/City", "links": [ { "href": "{+_base_url}", "method": "GET", "rel": "self" }, { "href": "/place/City/_schema", "method": "GET", "rel": "class" }, { "href": "/place/City?class_prefix=http://semantica.globo.com/place/", "method": "POST", "rel": "create", "schema": { "$ref": "{+_base_url}" } }] "properties": { "http://semantica.globo.com/place/latitude": { "class": "http://semantica.globo.com/place/Place", "datatype": "http://www.w3.org/2001/XMLSchema#float", "description": "Coordenada de latitude de acordo com WGS84.", "graph": "http://semantica.globo.com/place/", "title": "Latitude", "type": "number" }, "http://semantica.globo.com/place/longitude": { "class": "http://semantica.globo.com/place/Place", "datatype": "http://www.w3.org/2001/XMLSchema#float", "description": "Coordenada de longitude de acordo com WGS84.", "graph": "http://semantica.globo.com/place/", "title": "Longitude", "type": "number" }, }, "title": "Cidade", "type": "object" } ``` Why _schema? In our data model we have a clear distinction between class (structure of data) and instances (the data content itself), and by using a request like GET <context>/<class> we could not have a clear distinction whether we want the whole collection of instances or we want the definition of this class. Thus, the _schema suffix is used to distinguish the latter case from the former. It also serves to inform that the class definition will be given in json-schema format. ##### Optional parameters[¶](#optional-parameters) **lang**: Specify language of labels. Options: pt, en, undefined (do not filter labels) **expand_uri**: The URIs that represent names and values of properties in the response are either compressed (0) or expanded (1) by this parameter. By default, this parameter is set to 0, meaning that URIs are compressed for keys and values. This is going to change in future versions, and the default will be URI expansion. So, we ask you to use this parameter explicitly and not rely on the default behaviour. For example, rdfs:label is the compressed form, while http://www.w3.org/2000/01/rdf-schema#label is the respective expanded form. Warning For the time being, URI expansion is not supported in resource listings. It is only supported while retrieving instances and class definition. **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **class_uri**: Set the class URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME **class_prefix**: by default, the class URI is defined by the API’s convention (context_uri/class_name). If the convention doesn’t apply, provide class_prefix so the URI will be: class_prefix/class_name. Example: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/?class_prefix=http%3A//dbpedia.org/' ``` If no **class_prefix** had been provided, the class URI above would be resolved as: <http://semantica.globo.com/place/City>. As **class_prefix** was defined, the class URI will be: <http://dbpedia.org/City>. ##### Possible responses[¶](#possible-responses) **Status 200** If the class exists, the response body is a JSON representing the class definition. ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/place/Country/_schema' ``` ``` { "$schema": "http://json-schema.org/draft-04/schema#", "@context": { "@language": "pt" }, "description": "A relatively large and permanent settlement, particularly a large urban settlement.", "id": "http://semantica.globo.com/place/City", "links": [ { "href": "{+_base_url}", "method": "GET", "rel": "self" }, { "href": "/place/City/_schema", "method": "GET", "rel": "class" }, { "href": "/place/City", "method": "POST", "rel": "create", "schema": { "$ref": "{+_base_url}" } } ], "properties": { "http://semantica.globo.com/place/latitude": { "class": "http://semantica.globo.com/place/Place", "datatype": "http://www.w3.org/2001/XMLSchema#float", "description": "Coordenada de latitude de acordo com WGS84.", "graph": "http://semantica.globo.com/place/", "title": "Latitude", "type": "number" }, "http://semantica.globo.com/place/longitude": { "class": "http://semantica.globo.com/place/Place", "datatype": "http://www.w3.org/2001/XMLSchema#float", "description": "Coordenada de longitude de acordo com WGS84.", "graph": "http://semantica.globo.com/place/", "title": "Longitude", "type": "number" } }, "title": "City", "type": "object" } ``` **Status 400** If there are unknown parameters in the request, the response is a 400 with a JSON informing the wrong parameters and the accepted ones. ``` { "errors": ["HTTP error: 400\nArgument 'wrong_param' is not supported"] } ``` **Status 404** If the class does not exist, the response is a 404 with a JSON informing the error ``` { "errors": ["HTTP error: 404\nClass not found in triplestore."] } ``` ### Managing Instances[¶](#managing-instances) Instances can be retrieved, added, edited, removed and so on. Here we list the available services for managing them. #### Create an Instance[¶](#create-an-instance) This service allows the creation of a new instance, provided its context, class name and JSON. **Basic usage** ``` $ curl -i -X POST -T "new_york_city.json" http://brainiak.semantica.dev.globoi.com/place/City HTTP/1.1 201 Created Server: nginx Date: Mon, 14 Jul 2014 14:09:27 GMT Content-Type: application/json; profile=http://brainiak.semantica.dev.globoi.com/place/City/_schema_list Content-Length: 0 Connection: keep-alive X-Brainiak-Resource-Uri: http://semantica.globo.com/place/City/38cea15a-d122-4e53-9214-13c00aec9969 Location: http://brainiak.semantica.dev.globoi.com/place/City/38cea15a-d122-4e53-9214-13c00aec9969 Access-Control-Allow-Origin: * ``` Warning When using curl, the “-T” param will append the filename to the actual URL, if the URL parameter ends with a “/”. In order to avoid that, either remove the last “/” or use ‘-d @new_york_city.json’ to expand the file contents. Sample JSON “new_city.json” for the class [City](http://brainiak.semantica.dev.globoi.com/place/City/_schema): ``` { "upper:name": "Globoland", "upper:fullName": "Globoland (RJ)", "rdfs:comment": "City of Globo's companies. Historically known as PROJAC.", "place:partOfState": "base:UF_RJ", "place:latitude": -22.958314, "place:longitude": -43.407133 } ``` Warning Note that prefixes are defined in the “@context” section. [Default prefixes](http://brainiak.semantica.dev.globoi.com/_prefixes) are implicit and don’t need to be declared. Besides using POST to create new instances, it is also possible to use PUT (for more information, see [*Edit a Instance*](index.html#edit-instance)). In this case, the instance_id should be provided, which must be unique in the specified context. The recommended policy is to use POST, as it will assure uniqueness of the identifiers. ##### Optional query string parameters[¶](#optional-query-string-parameters) **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **class_uri**: Set the class URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME **class_prefix**: by default, the class URI is defined by the API’s convention (context_uri/class_name). If the convention doesn’t apply, provide class_prefix so the URI will be: class_prefix/class_name. Example: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/?class_prefix=http%3A//dbpedia.org/' ``` If no **class_prefix** had been provided, the class URI above would be resolved as: <http://semantica.globo.com/place/City>. As **class_prefix** was defined, the class URI will be: <http://dbpedia.org/City>. ##### Possible responses[¶](#possible-responses) **Status 201** The instance was created successfully, the response body is empty. The URI of the new instance is identified by the “Location” header in the HTTP response. Note that the URI of a instance is not the same as the URL to retrieve a instance from the API. For retrieving it, use the retrieve instance primitive <>. **Status 400** If there are unknown parameters in the request, the response status code is 400. The 400 status may also happen when the JSON provided is invalid: ``` { "errors": ["HTTP error: 400\nNo JSON object could be decoded"] } ``` **Status 404** If the class does not exist, the response status code is 404. ``` $ curl -i -X POST -T "new_york_city.json" http://brainiak.semantica.dev.globoi.com/place/Person ``` ``` { "errors": [ "HTTP error: 404\nClass http://semantica.globo.com/place/Person doesn't exist in context http://semantica.globo.com/place/." ] } ``` **Status 500** Internal server error. Please, contact the team <[<EMAIL>](mailto:<EMAIL>)> and provide the URL, JSON and error message. #### List of Instances[¶](#list-of-instances) This service retrieves all instances of a specific class or Instances according a propert/value filter. The results are paginated. **Basic usage** ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/place/Continent' ``` This will retrieve all instances of Continent in the graph place ##### Optional parameters[¶](#optional-parameters) **lang**: Specify language of labels. Options: pt, en, undefined (do not filter labels) **expand_uri**: The URIs that represent names and values of properties in the response are either compressed (0) or expanded (1) by this parameter. By default, this parameter is set to 0, meaning that URIs are compressed for keys and values. This is going to change in future versions, and the default will be URI expansion. So, we ask you to use this parameter explicitly and not rely on the default behaviour. For example, rdfs:label is the compressed form, while http://www.w3.org/2000/01/rdf-schema#label is the respective expanded form. Warning For the time being, URI expansion is not supported in resource listings. It is only supported while retrieving instances and class definition. **page**: The page to be retrieved. The default value is 1, i.e. the first page. **per_page**: Defines how many items are retrieved per page. The default value is 10 > By default, the first page containing 10 items is returned. It could also be retrieved by: ``` GET 'http://brainiak.semantica.dev.globoi.com/?page=1&per_page=10' ``` **do_item_count**: If set to 1 determines that the resulting page will compute the property ìtem_count with total number of items. When set, this parameter also has the side effect of including the URL for the last page in the links section. By default do_item_count is set to 0 for performance’s sake and can be omitted. **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **class_uri**: Set the class URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME **class_prefix**: by default, the class URI is defined by the API’s convention (context_uri/class_name). If the convention doesn’t apply, provide class_prefix so the URI will be: class_prefix/class_name. Example: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/?class_prefix=http%3A//dbpedia.org/' ``` If no **class_prefix** had been provided, the class URI above would be resolved as: <http://semantica.globo.com/place/City>. As **class_prefix** was defined, the class URI will be: <http://dbpedia.org/City>. **sort_by**: Defines predicate used to order instances. The sorting can also behave as a **p** filter, read **sort_include_empty**. Usage: sort_by=rdfs:label or sort_by=dbprop:stadium. **sort_order**: Defines if ordering will be ascending or descending. The default is ascending. E.g: sort_order=asc or sort_order=desc. **sort_include_empty**: By default, items that don’t define **sort_by** property are also listed (sort_include_empty=1). If it is desired to exclude such items, set sort_include_empty=0. **direct_instances_only**: If set to 1 determines that the response will only contain instances of a certain class (ignoring sub-classes’ instances). Otherwise, if it is set to 0, it returns both direct class’ and subclasses’ instances. The default value for direct_instances_only is 1. ##### Special filters ?p ?o[¶](#special-filters-p-o) **p**: Filters the instances that have the (**p**)redicate specified used in a triple. **o**: Filters the instances that have the (**o**)bject specified used in a triple. By combining p and/or o parameters you can specify a filter for instances that have this property and/or object values. For example: ``` GET 'http://brainiak.semantica.dev.globoi.com/place/Country/?p=place:partOfContinent&o=http://semantica.globo.com/place/Continent/America' ``` It is also possible to set multiple p's and/or o's, adding a number after them (p1, o1, p2, o2, etc). Example: ``` GET 'http://brainiak.semantica.dev.globoi.com/place/City/?o=place:UF_RJ&p1=place:longitude&p2=place:latitude&per_page=1' ``` ``` { "@context": { "@language": "pt" }, "@id": "http://semantica.globo.com/place/City", "_base_url": "http://brainiak.semantica.dev.globoi.com/place/City", "_class_prefix": "http://semantica.globo.com/place/", "_first_args": "p2=place:latitude&per_page=1&p1=place:longitude&page=1&o=base:UF_RJ", "_next_args": "p2=place:latitude&per_page=1&p1=place:longitude&page=2&o=base:UF_RJ", "_schema_url": "http://brainiak.semantica.dev.globoi.com/place/City/_schema", "items": [ { "@id": "http://semantica.globo.com/place/City/Globoland", "class_prefix": "http://semantica.globo.com/place/", "instance_prefix": "http://semantica.globo.com/place/City/", "p": "http://semantica.globo.com/place/partOfState", "place:latitude": -22.9583, "place:longitude": -43.4071, "resource_id": "673caaed-9ebb-4677-b200-0eccac65a3e5", "title": "Globoland" } ], "pattern": "" } ``` What happened where? Querystring p/o parameters are matched using numbers. If the number is omitted consider p0. Therefore, for parameters o=place:UF_RJ&p1=place:longitude&p2=place:latitude, we have. | Number | P | O | | --- | --- | --- | | 0 | * | place:UF_RJ | | 1 | place:latitude | * | | 2 | place:longitude | * | Places in blank will match everything in base. The query above will be translated to this (simplified) query: ``` SELECT * { ?s a place:City . ?s ?p0 place:UF_RJ . ?s place:longitude ?o1 . ?s place:latitude ?o2 . } ``` By fixing a ?o=place:UF_RJ without a matching ?p, for example, we set that instances of class City must have some property with value ?o=place:UF_RJ. In the ontology tested, the property to be matched with this object value is isPartOf, meaning that Globoland is part of state ([Unidade Federativa](http://en.wikipedia.org/wiki/States_of_Brazil)) o=place:UF_RJ. Fixing predicates like in p1=place:longitude&p2=place:latitude will only present instances that have this predicate, and the values for this properties will appear in the filtered collection result. ##### Possible responses[¶](#possible-responses) **Status 200** If there are instances that match the query, the response body is a JSON containing instances’ titles, resources_id and @ids (URIs). By default, the first page containing 10 items is returned (?page=1&per_page=10). ``` { "@context": { "@language": "pt" }, "@id": "place:Continent", "_base_url": "http://brainiak.semantica.dev.globoi.com/place/Continent", "_class_prefix": "place", "_first_args": "per_page=10&page=1", "_next_args": "per_page=10&page=2", "_schema_url": "http://brainiak.semantica.dev.globoi.com/place/Continent/_schema", "items": [ { "@id": "http://semantica.globo.com/place/Continent/Africa", "class_prefix": "place", "instance_prefix": "http://semantica.globo.com/place/Continent/", "resource_id": "Africa", "title": "\u00c1frica" }, { "@id": "http://semantica.globo.com/place/Continent/Antarctica", "class_prefix": "place", "instance_prefix": "http://semantica.globo.com/place/Continent/", "resource_id": "Antarctica", "title": "Oceania" }, { "@id": "http://semantica.globo.com/place/Continent/Europe", "class_prefix": "place", "instance_prefix": "http://semantica.globo.com/place/Continent/", "resource_id": "Europe", "title": "Europa" }, { "@id": "http://semantica.globo.com/place/Continent/Asia", "class_prefix": "place", "instance_prefix": "http://semantica.globo.com/place/Continent/", "resource_id": "Asia", "title": "\u00c1sia" }, { "@id": "http://semantica.globo.com/place/Continent/America", "class_prefix": "place", "instance_prefix": "http://semantica.globo.com/place/Continent/", "resource_id": "America", "title": "Am\u00e9rica" } ], "pattern": "" } ``` If there are no instances for this class, the response will contain a warning and a items list empty. ``` { "items": [], "warning": "Instances of class (http://semantica.globo.com/place/Country) in graph (http://semantica.globo.com/place/) with filter predicate=<http://www.w3.org/2000/01/rdf-schema#label> object=\"lalalala\"@pt were not found."] } ``` **Status 400** If there are unknown parameters in the request query string, the response status code is 400. A JSON containing both the wrong parameters and the accepted ones is returned. ``` curl -s 'http://brainiak.semantica.dev.globoi.com/place/Continent?invalid_param=1' ``` ``` { "errors": [ "HTTP error: 400\nArgument invalid_param is not supported. The supported querystring arguments are: class_prefix, class_uri, direct_instances_only, do_item_count, expand_uri, graph_uri, lang, page, per_page, sort_by, sort_include_empty, sort_order." ] } ``` **Status 404** If the class does not exist, the response status code is a 404. ``` { "errors": "HTTP error: 404\nClass class_example in context person does not exist" } ``` **Status 500** If there was some internal problem, the response status code is a 500. Please, contact [<EMAIL>](mailto:semantica%40corp.globo.com) informing the URL and the JSON returned. #### Get an Instance[¶](#get-an-instance) This service retrieves all information about a instance, given its context, class name and instance id. **Basic usage** ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/person/Gender/Female' ``` **Fetching by instance URL** ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/_/_/_/?instance_uri=http%3A%2F%2Fsemantica.globo.com%2Fperson%2FGender%2FFemale' ``` This form has the same outcome as the one represented in basic usage. The difference is that you just specify the instance_uri, and all graphs are searched for this occurence. ##### Optional parameters[¶](#optional-parameters) **lang**: Specify language of labels. Options: pt, en, undefined (do not filter labels) **expand_uri**: The URIs that represent names and values of properties in the response are either compressed (0) or expanded (1) by this parameter. By default, this parameter is set to 0, meaning that URIs are compressed for keys and values. This is going to change in future versions, and the default will be URI expansion. So, we ask you to use this parameter explicitly and not rely on the default behaviour. For example, rdfs:label is the compressed form, while http://www.w3.org/2000/01/rdf-schema#label is the respective expanded form. Warning For the time being, URI expansion is not supported in resource listings. It is only supported while retrieving instances and class definition. **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **instance_prefix**: by default, the instance URI is defined by the API’s convention (context_uri/class_name/instance_name). If the convention doesn’t apply, provide instance_prefix so the URI will be: class_instance/instance_name. Example: examples: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/Campinas_SP?instance_prefix=http%3A//dbpedia.org/' ``` If no **instance_prefix** had been provided, the instance URI above would be resolved as: <http://semantica.globo.com/place/City/Campinas_SP>. As **instance_prefix** was defined, the instance URI will be: <http://dbpedia.org/Campinas_SP>. Other example: Instance URI is <http://semantica.globo.com/esportes/atleta/80801> ``` 'http://brainiak.semantica.dev.globoi.com/esportes/Atleta/80801?instance_prefix=http://semantica.globo.com/esportes/atleta/' ``` example: Instance URI is <http://semantica.globo.com/base/Pessoa_ImportacaoEleicoes2012TSE_10000001494> and Graph URI is <http://semantica.globo.com/> ``` 'http://brainiak.semantica.dev.globoi.com/base/Pessoa/Pessoa_ImportacaoEleicoes2012TSE_10000001494?instance_prefix=base&graph_uri=glb' ``` **instance_id**: Unique word identifier for an instance. This is composed with instance_prefix to form an equivalent of instance_uri. **instance_uri**: Set the instance URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME/INSTANCE_ID **expand_object_properties**: If set to 1 determines that the ObjectProperties of the response will map objects as {"@id": "object:uri", "title": "object label"}. The default value for expand_object_properties is 0 and the objects of ObjectProperties are represented as strings such as "object:uri". **meta_properties**: If set to 0 excludes from response JSON properties like _base_url, @id, @type, etc. The default value is 1. ##### Possible responses[¶](#possible-responses) **Status 200** If the instance exists, the response body is a JSON with all instance information and links to related actions. ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/place/Country/Brazil' | python -mjson.tool ``` ``` { "@id": "http://semantica.globo.com/place/Country/Brazil", "@type": "place:Country", "_base_url": "http://brainiak.semantica.dev.globoi.com/place/Country/Brazil/", "_instance_prefix": "http://semantica.globo.com/place/Country/", "_resource_id": "Brazil", "_type_title": "Pa\u00eds", "upper:description": "Representa o pa\u00eds Brasil.", "upper:name": "Brasil" } ``` **Status 400** If there are unknown parameters in the request, the response is a 400 with a JSON informing the wrong parameters and the accepted ones. ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/person/Gender/Female?invalid_param=1' ``` ``` { "errors": [ "HTTP error: 400\nArgument invalid_param is not supported. The supported querystring arguments are: class_prefix, class_uri, expand_object_properties, expand_uri, graph_uri, instance_prefix, instance_uri, lang, meta_properties." ] } ``` **Status 404** If the instance does not exist, the response is a 404 with a JSON informing the error ``` $ curl -s 'http://brainiak.semantica.dev.globoi.com/place/Country/NonExistent' ``` ``` { "errors": ["HTTP error: 404\nInstance (NonExistent) of class (Country) in graph (place) was not found."] } ``` #### Delete a Instance[¶](#delete-a-instance) This service deletes a instance, given its context, class name and instance id. **Basic usage** ``` DELETE 'http://brainiak.semantica.dev.globoi.com/place/Country/Brazil' ``` ##### Optional parameters[¶](#optional-parameters) **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **class_uri**: Set the class URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME **class_prefix**: by default, the class URI is defined by the API’s convention (context_uri/class_name). If the convention doesn’t apply, provide class_prefix so the URI will be: class_prefix/class_name. Example: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/?class_prefix=http%3A//dbpedia.org/' ``` If no **class_prefix** had been provided, the class URI above would be resolved as: <http://semantica.globo.com/place/City>. As **class_prefix** was defined, the class URI will be: <http://dbpedia.org/City>. **instance_prefix**: by default, the instance URI is defined by the API’s convention (context_uri/class_name/instance_name). If the convention doesn’t apply, provide instance_prefix so the URI will be: class_instance/instance_name. Example: examples: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/Campinas_SP?instance_prefix=http%3A//dbpedia.org/' ``` If no **instance_prefix** had been provided, the instance URI above would be resolved as: <http://semantica.globo.com/place/City/Campinas_SP>. As **instance_prefix** was defined, the instance URI will be: <http://dbpedia.org/Campinas_SP>. Other example: Instance URI is <http://semantica.globo.com/esportes/atleta/80801> ``` 'http://brainiak.semantica.dev.globoi.com/esportes/Atleta/80801?instance_prefix=http://semantica.globo.com/esportes/atleta/' ``` example: Instance URI is <http://semantica.globo.com/base/Pessoa_ImportacaoEleicoes2012TSE_10000001494> and Graph URI is <http://semantica.globo.com/> ``` 'http://brainiak.semantica.dev.globoi.com/base/Pessoa/Pessoa_ImportacaoEleicoes2012TSE_10000001494?instance_prefix=base&graph_uri=glb' ``` **instance_id**: Unique word identifier for an instance. This is composed with instance_prefix to form an equivalent of instance_uri. **instance_uri**: Set the instance URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME/INSTANCE_ID **expand_object_properties**: If set to 1 determines that the ObjectProperties of the response will map objects as {"@id": "object:uri", "title": "object label"}. The default value for expand_object_properties is 0 and the objects of ObjectProperties are represented as strings such as "object:uri". **meta_properties**: If set to 0 excludes from response JSON properties like _base_url, @id, @type, etc. The default value is 1. ##### Possible responses[¶](#possible-responses) **Status 204** If the [instance exists](#instance-exists) and there is no [conflict](#conflict), the response body is a 204 with no response body. **Status 400** If there are unknown parameters in the request, the response is a 400 with a JSON informing the wrong parameters and the accepted ones. ``` { "errors": ["HTTP error: 400\nArgument wrong_param is not supported"] } ``` **Status 404** If the instance does not exist, the response is a 404 with a JSON informing the error ``` { "errors": ["HTTP error: 404\nInstance (NonExistent) of class (Country) in graph (place) was not found."] } ``` **Status 409** When there is a conflict, i.e. the instance is refered by another, there is a dependency between them and therefore, the instance cannot be deleted, for consistency. To delete an instance you should first delete instances that depend on it. The response status is 409 and a JSON informing the dependants is returned. ``` { "errors": ["Cannot exclude instance because of the dependencies: http://semantica.globo.com/esportes/MateriaEsporte/239172, http://semantica.globo.com/esportes/MateriaEsporte/233213"] } ``` #### Edit a Instance[¶](#edit-a-instance) This service allows the edition of an instance, provided its context, class name, instance identifier and JSON. **Basic usage** ``` $ curl -i -X PUT -T "edit_female.json" http://brainiak.semantica.dev.globoi.com/person/Gender/Female ``` ``` HTTP/1.1 200 OK Server: nginx Date: Thu, 28 Mar 2013 15:51:59 GMT Content-Type: application/json; charset=UTF-8 Content-Length: 976 Connection: keep-alive Access-Control-Allow-Origin: * { "$schema": "http://brainiak.semantica.dev.globoi.com/person/Gender/_schema", "@context": { "person": "http://semantica.globo.com/person/", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#" }, "@id": "http://semantica.globo.com/person/Gender/Female", "@type": "person:Gender", "links": [ { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Female", "rel": "self" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/_schema", "rel": "describedBy" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Female", "method": "DELETE", "rel": "delete" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Female", "method": "PUT", "rel": "update" } ], "rdf:type": "person:Gender", "upper:name":"Feminino", } ``` Warning When using curl, the “-T” param will append the filename to the actual URL, if the URL parameter ends with a “/”. In order to avoid that, either remove the last “/” or use ‘-d @new_york_city.json’ to expand the file contents. Sample JSON “edit_female.json”: ``` { "@context": { "person": "http://semantica.globo.com/person/", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#" }, "$schema": "http://brainiak.semantica.dev.globoi.com/person/Gender/_schema", "rdfs:label": "Feminino 2", "rdf:type": "person:Gender", "@id": "http://semantica.globo.com/person/Gender/Female", "@type": "person:Gender" } ``` Note that prefixes are defined in the “@context” section. [Default prefixes](http://brainiak.semantica.dev.globoi.com/_prefixes) are implicit and don’t need to be declared. ##### Optional query string parameters[¶](#optional-query-string-parameters) **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **class_uri**: Set the class URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME **class_prefix**: by default, the class URI is defined by the API’s convention (context_uri/class_name). If the convention doesn’t apply, provide class_prefix so the URI will be: class_prefix/class_name. Example: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/?class_prefix=http%3A//dbpedia.org/' ``` If no **class_prefix** had been provided, the class URI above would be resolved as: <http://semantica.globo.com/place/City>. As **class_prefix** was defined, the class URI will be: <http://dbpedia.org/City>. **instance_prefix**: by default, the instance URI is defined by the API’s convention (context_uri/class_name/instance_name). If the convention doesn’t apply, provide instance_prefix so the URI will be: class_instance/instance_name. Example: examples: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/Campinas_SP?instance_prefix=http%3A//dbpedia.org/' ``` If no **instance_prefix** had been provided, the instance URI above would be resolved as: <http://semantica.globo.com/place/City/Campinas_SP>. As **instance_prefix** was defined, the instance URI will be: <http://dbpedia.org/Campinas_SP>. Other example: Instance URI is <http://semantica.globo.com/esportes/atleta/80801> ``` 'http://brainiak.semantica.dev.globoi.com/esportes/Atleta/80801?instance_prefix=http://semantica.globo.com/esportes/atleta/' ``` example: Instance URI is <http://semantica.globo.com/base/Pessoa_ImportacaoEleicoes2012TSE_10000001494> and Graph URI is <http://semantica.globo.com/> ``` 'http://brainiak.semantica.dev.globoi.com/base/Pessoa/Pessoa_ImportacaoEleicoes2012TSE_10000001494?instance_prefix=base&graph_uri=glb' ``` **instance_id**: Unique word identifier for an instance. This is composed with instance_prefix to form an equivalent of instance_uri. **instance_uri**: Set the instance URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME/INSTANCE_ID **expand_object_properties**: If set to 1 determines that the ObjectProperties of the response will map objects as {"@id": "object:uri", "title": "object label"}. The default value for expand_object_properties is 0 and the objects of ObjectProperties are represented as strings such as "object:uri". **meta_properties**: If set to 0 excludes from response JSON properties like _base_url, @id, @type, etc. The default value is 1. ##### Possible responses[¶](#possible-responses) **Status 200** The instance was edited successfully, the response body is the modified instance. **Status 400** If there are unknown parameters in the request, the response status code is 400. The 400 status may also happen when the JSON provided is invalid: ``` { "errors": ["HTTP error: 400\nNo JSON object could be decoded"] } ``` **Status 404** If the class does not exist, the response status code is 404. ``` $ curl -i -X PUT -T "edit_female.json" http://brainiak.semantica.dev.globoi.com/place/Person/Female ``` ``` { "errors": [ "HTTP error: 404\nClass http://semantica.globo.com/place/Person doesn't exist in context http://semantica.globo.com/place/." ] } ``` **Status 500** Internal server error. Please, contact the team <[<EMAIL>](mailto:semantica%40corp.globo.com)> and provide the URL, JSON and error messaage. #### Patch an Instance[¶](#patch-an-instance) Edit a part of an instance, providing: * context (graph) * class (schema) * instance identifier (id or uri) * patch body or payload (JSON) The body must be a **list** and it is based on RFC-6902: <http://tools.ietf.org/html/rfc6902>. Differently from the specification, we also use PATCH to create instances: provided that patch operations will create a valid instance. Currently the following operations are supported: 1. **replace**: change a property value 2. **add**: add a new property and its value 3. **remove**: remove some existing property (and therefore its value) ##### Basic usage[¶](#basic-usage) Consider you have an existing instance: ``` $ curl -s http://brainiak.semantica.dev.globoi.com/place/City/globoland ``` ``` { "@id": "http://semantica.globo.com/place/City/globoland", "@type": "place:City", "place:latitude": -22.9583, "place:longitude": -43.4071, "place:partOfState": "base:UF_RJ", "upper:fullName": "Globoland (RJ)", "upper:name": "Globoland" } ``` Note that prefixes, such as “upper”, are defined in the “@context” section: [Default prefixes](http://brainiak.semantica.dev.globoi.com/_prefixes) are implicit and don’t need to be declared. **Add** To patch this instance **adding** some property and value, do: ``` $ curl -i -s -X PATCH -d '[{"op": "add", "path": "place:latitude", "value": 11.785}]' http://brainiak.semantica.dev.globoi.com/place/City/globoland ``` **Replace** To patch this instance **replacing** some existing property’s value, do: ``` $ curl -i -s -X PATCH -d '[{"op": "replace", "path": "upper:name", "value": "New Globoland name"}]' http://brainiak.semantica.dev.globoi.com/place/City/globoland HTTP/1.1 200 OK Server: nginx Date: Mon, 14 Jul 2014 14:55:33 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 0 Connection: keep-alive Access-Control-Allow-Origin: * ``` Note that our implementation differs a bit from specification in the sense that replace have add semantics when the key is not present in target instance. **Remove** To patch this instance **removing** some property (and its existing values), do: ``` $ curl -i -s -X PATCH -d '[{"op": "remove", "path": "place:latitude"}]' http://brainiak.semantica.dev.globoi.com/place/City/globoland ``` ##### Optional query string parameters[¶](#optional-query-string-parameters) **graph_uri**: Set the graph URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME **class_uri**: Set the class URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME **class_prefix**: by default, the class URI is defined by the API’s convention (context_uri/class_name). If the convention doesn’t apply, provide class_prefix so the URI will be: class_prefix/class_name. Example: ``` 'http://brainiak.semantica.dev.globoi.com/place/City/?class_prefix=http%3A//dbpedia.org/' ``` If no **class_prefix** had been provided, the class URI above would be resolved as: <http://semantica.globo.com/place/City>. As **class_prefix** was defined, the class URI will be: <http://dbpedia.org/City>. **instance_id**: Unique word identifier for an instance. This is composed with instance_prefix to form an equivalent of instance_uri. **instance_uri**: Set the instance URI, for cases where the URI is not like http://semantica.globo.com/CONTEXT_NAME/CLASS_NAME/INSTANCE_ID ##### Possible responses[¶](#possible-responses) **Status 200** The instance was patched successfully, the response body is empty. **Status 400** If there are unknown parameters in the request, the response status code is 400 and the body contains a JSON containing valid and invalid parameters. The 400 status may also happen when the JSON provided is invalid: ``` $ curl -i -s -X PATCH -d '[{"op": "replace", "path": "inexistent:property", "value": "República Federativa do Brasil"}]' http://brainiak.semantica.dev.globoi.com/place/City/globoland HTTP/1.1 400 Bad Request Server: nginx Date: Mon, 14 Jul 2014 14:55:33 GMT Content-Type: application/json; charset=UTF-8 Content-Length: 196 Connection: keep-alive Access-Control-Allow-Origin: * {"errors": ["Inexistent property (inexistent:property) in the schema (http://semantica.globo.com/place/City), used to create instance (http://semantica.globo.com/place/City/globoland)"]} ``` **Status 404** If the instance does not exist, the response status code is 404. ``` $ curl -i -s -X PATCH -d '[{"op": "replace", "path": "upper:name", "value": "Some new name"}]' http://brainiak.semantica.dev.globoi.com/place/City/InexistentCity HTTP/1.1 404 Not Found Server: nginx Date: Mon, 14 Jul 2014 15:05:10 GMT Content-Type: application/json; charset=UTF-8 Content-Length: 52 Connection: keep-alive Access-Control-Allow-Origin: * {"errors": ["HTTP error: 404\nInexistent instance"]} ``` **Status 500** Internal server error. Please, contact the team <[<EMAIL>](mailto:semantica%40corp.globo.com)> and provide the URL, JSON and error message. ### Search[¶](#search) Given a target textual query expression, the search service tries to match the textual query expression with the label of the items that belong to the search scope. For the time being, Brainiak only supports textual searches over instances of a given class in a given graph, therefore both class and graph must be specified. The textual pattern provided by the user is tokenized and analyzed against a index that contains all the labels for instances. For example, the search for unido matches Estados Unidos, Reino Unido, and so on. The type of query used is a [Elastic Search match query](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-match-query.html). The mandatory parameters are: **pattern**: textual expression that will be matched or partially-matched against some instances in the search scope. **graph_uri**: Set the graph URI, defining a subset of classes belonging to the search scope. **class_uri**: Defines the URI of a given class, whose instances’ labels should be searched. **Basic usage** ``` $ curl -s -X GET 'http://brainiak.semantica.dev.globoi.com/_search?graph_uri=glb&class_uri=place:Country&pattern=united' ``` ``` { "items": [ { "id": "http://test.com/united-states", "title": "United States" }, { "id": "http://test.com/united-arab-emirates", "title": "United Arab Emirates" }, ], "pattern": "united" } ``` #### Possible responses[¶](#possible-responses) **Status 200** If the search is successfull, a response JSON is returned, showing the matched instances. For example, for the pattern brasil. ``` $ curl -s -X GET 'http://brainiak.semantica.dev.globoi.com/glb/Pais/_search?graph_uri=glb&class_uri=base:Pais&pattern=brasil' ``` If there are no matches found, the "items" dict will be empty. ``` { "@context": { "@language": "pt" }, "pattern": "brasil", "items": [ { "id": "http://semantica.globo.com/base/Pais_Brasil", "title": "Brasil" } ], "_base_url": "http://brainiak.semantica.dev.globoi.com/_search/", "_class_prefix": "http://semantica.globo.com/base/", "_graph_uri": "http://semantica.globo.com/", "_next_args": "pattern=brasil&graph_uri=glb&page=2&class_uri=base:Pais", "_first_args": "pattern=brasil&graph_uri=glb&page=1&class_uri=base:Pais", "_class_uri": "http://semantica.globo.com/base/Pais" } ``` **Status 400** If the request is malformed due to with invalid parameters, a 400 HTTP error is returned. This is due to the following reasons: * Missing required parameters. If the request body does not have the keys pattern, graph_uri or class_uri. ``` { "errors": ["HTTP error: 400\nRequired parameter (pattern) was not given."] } ``` **Status 500** Internal server error. Please, contact the team <[<EMAIL>](mailto:semantica%40corp.globo.com)> and provide the URL, JSON and error message. ### Suggest[¶](#suggest) Given a target predicate (an object property whose value is an object, i.e. an URI), the suggest service searches for instances that could be set as the predicate’s object. A JSON must be passed in the request’s body. This JSON may have the sections search and response: * search: is **obligatory** and is related to what will be searched * response: is **optional** and refers to what will be retrieved Two parameters must be defined in search: **target** The target parameter represents the target predicate. For example, the target in the example below is place:partOfCity. The range (types of possible values) of this predicate is place:City. Therefore, the _suggest service will only try to match instances of place:City set as the value of place:partOfCity. **pattern** The pattern parameter indicates the search expression used to match instances. Usually, the pattern is matched against the property rdfs:label of the instances, but one might want to search in other properties. The optional parameter fields serves to include other properties (see in [*Optional request body parameters*](index.html#optional-body-parameters)). Here is a minimal example of the request body: ``` { "search": { "pattern": "ronaldo", "target": "esportes:trata_da_entidade" }, "response": { "meta_fields": ["base:detalhe_da_cortina"] } } ``` **Basic usage** Considering example above as a file suggest_search.json (in -d parameter): ``` $ curl -s -XPOST 'http://brainiak.semantica.dev.globoi.com/_suggest' -d '{"search": {"united": "united", "target": "place:partOfCountry"}}' ``` ``` { "items": [ { "id": "http://test.com/united-states", "title": "United States" }, { "id": "http://test.com/united-arab-emirates", "title": "United Arab Emirates" } ] } ``` #### Optional request body parameters[¶](#optional-request-body-parameters) Some optional parameters can be passed in request body: ``` { "search": { "pattern": "united", "target": "http://semantica.globo.com/base/cita_a_entidade", "fields": ["http://semantica.globo.com/upper/name", "http://semantica.globo.com/upper/fullName", "base:dados_buscaveis"], "graphs": ["http://semantica.globo.com/esportes/"], "classes": [ "http://semantica.globo.com/esportes/Atleta", "http://semantica.globo.com/esportes/Equipe" ] }, "response": { "required_fields": false, "meta_fields": ["metadata:disambiguationProperty", "base:detalhe_da_cortina"], "class_fields": ["base:thumbnail"], "classes": [ { "@type": "http://semantica.globo.com/esportes/Atleta", "instance_fields": ["esportes:esta_no_time", "esportes:posicao"], }, { "@type": "http://semantica.globo.com/esportes/Equipe", "instance_fields": ["base:esta_na_cidade"] } ] } } ``` #### Optional search fields[¶](#optional-search-fields) fields list of optional fields to search on. Each field must be an URI or a CURIE. Without this parameter, only rdfs:label and its subproperties are matched. classes list of classes whose instances will be searched, thus restricting the result of the predicate range. Each class must be an URI or a CURIE. If this parameter has classes that are not in the predicate range, a 400 error is returned. graphs list of graphs in which we look for instances, thus restricting the result of the graphs. By default the graphs considered in the search are those in which the classes (present in the range of the target property) are declared. Each graph must be an URI or a CURIE. If this parameter has graphs that the classes in the predicate range are not in, a 400 error is returned. #### Optional response fields[¶](#optional-response-fields) required_fields boolean which indicates that fields which have owl:minQualifiedCardinality equal or larger than 1 should be returned. The default is true. meta_fields list of meta predicates. These meta predicates must be defined in the ontology and might map the most relevant predicates for disambiguation, for instance. Each meta predicate must be an URI or a CURIE. class_fields list of class predicates whose values should be retrieved, such as class description (rdfs:comment) or other properties. Each class field must be an URI or a CURIE. classes list of classes towards which the instances will be restricted. Each class must be an URI or a CURIE. #### Optional query string parameters[¶](#optional-query-string-parameters) **do_item_count**: If set to 1 determines that the resulting page will compute the property ìtem_count with total number of items. When set, this parameter also has the side effect of including the URL for the last page in the links section. By default do_item_count is set to 0 for performance’s sake and can be omitted. **page**: The page to be retrieved. The default value is 1, i.e. the first page. **per_page**: Defines how many items are retrieved per page. The default value is 10 > By default, the first page containing 10 items is returned. It could also be retrieved by: ``` GET 'http://brainiak.semantica.dev.globoi.com/?page=1&per_page=10' ``` **expand_uri**: The URIs that represent names and values of properties in the response are either compressed (0) or expanded (1) by this parameter. By default, this parameter is set to 0, meaning that URIs are compressed for keys and values. This is going to change in future versions, and the default will be URI expansion. So, we ask you to use this parameter explicitly and not rely on the default behaviour. For example, rdfs:label is the compressed form, while http://www.w3.org/2000/01/rdf-schema#label is the respective expanded form. #### Response body parameters[¶](#response-body-parameters) Example of response: ``` { "items": [ { "@id": "http://semantica.globo.com/esportes/Atleta/Ronaldo", "title": "<NAME>", "@type": "http://semantica.globo.com/esportes/Atleta", "type_title": "Atleta", "class_fields": { "base:thumbnail": "http://s-ct.glbimg.globoi.com/jo/eg/static/semantica/img/icones/ico_criatura.png" }, "instance_fields": [ { "predicate_id": "rdfs:label", "predicate_title": "Nome", "object_id": "http://semantica.globo.com/esportes/Atleta/Ronaldo", "object_title": "<NAME>", "required": true }, { "predicate_id": "esportes:esta_no_time", "predicate_title": "Pertence ao Time", "object_id": "http://semantica.globo.com/esportes/Equipe/Botafogo", "object_title": "Botafogo", "required": false }, { "predicate_id": "esportes:posicao", "predicate_title": "Posição", "object_title": "VOL", "required": false } ] } ], "item_count": 1, "@context": { "esportes": "http://semantica.globo.com/esportes/" } } ``` items list of instances (more details on the items on [*Response item details*](index.html#item-details)) item_count integer representing the total number of items @context JSON containing definitions of prefixes used in CURIEs. #### Response item details[¶](#response-item-details) Each item has several parameters: @id string containing the unique identifier (URI) of a certain instance title string that represents the instance label (rdfs:label) @type class from which the item was instantiated (rdf:type) type_title label (rdfs:label) associated to the instance’s class class_fields JSON that maps the class predicates declared in the request’s class_fields to their respective values for the instance instance_fields based on the fields defined in the request payload (fields, required_fields, meta_fields), return a list of JSONs composed by: * predicate_id string containing a URI or a CURIE of the predicate * predicate_title string containing the label (rdfs:label) of the predicate * object_id string containing a URI or a CURIE of the object mapped by the predicate for the given instance * object_title string containing the label (rdfs:label) of the object mapped by the predicate for the given instance * required boolean that represents if a certain predicate is obligatory for the provided class. In other words, if owl:minQualifiedCardinality equal or larger than 1. It is related to required_fields. #### Possible responses[¶](#possible-responses) **Status 200** If the search is successfull, a response JSON is returned, showing the matched instances. ``` $ curl -s -XPOST 'http://brainiak.semantica.dev.globoi.com/_suggest' -T "suggest_search.json" ``` ``` { "@context": { "@language": "pt" }, "_base_url": "http://localhost:5100/_range_search/", "_first_args": "page=1&do_item_count=1", "_last_args": "page=1&do_item_count=1", "item_count": 5, "items": [ { "@id": "http://semantica.globo.com/place/City/6c1aedb7-4526-4796-b8b8-ad2d87655572", "@type": "http://semantica.globo.com/place/City", "title": "Globoland", "type_title": "Cidade" }, { "@id": "http://semantica.globo.com/place/City/191ee05a-f53e-4880-a791-ff40d81c1edf", "@type": "http://semantica.globo.com/place/City", "title": "Globoland", "type_title": "Cidade" }, { "@id": "http://semantica.globo.com/place/City/c77de78a-b034-4664-a991-c85095c2e8cc", "@type": "http://semantica.globo.com/place/City", "title": "Globoland", "type_title": "Cidade" }, { "@id": "http://semantica.globo.com/place/City/0e4c671f-1b22-4ede-9023-716de095f2a5", "@type": "http://semantica.globo.com/place/City", "title": "Globoland", "type_title": "Cidade" }, { "@id": "http://semantica.globo.com/place/City/9d812e40-b726-4c2a-b43e-9ff1404c5481", "@type": "http://semantica.globo.com/place/City", "title": "Globolandia", "type_title": "Cidade" } ] } ``` **Status 400** If the request is malformed due to with invalid parameters, a 400 HTTP error is returned. This is due to the following reasons: * Missing required parameters. If the request body does not have the keys predicate or pattern. ``` { "errors": ["HTTP error: 400\nRequired parameter (pattern) was not given."] } ``` * Unknown predicate. If a predicate is not found in the ontology or does not have a declared rdfs:range. ``` { "errors": ["HTTP error: 400\nEither the predicate http://semantica.globo.com/base/unknownPredicate does not exists or it does not have any rdfs:range defined in the triplestore"] } ``` * Classes not in range. If the search_classes parameter has any class that is not in the range of predicate. For example, if we pass in the request body "predicate": "place:partOfContinent" and "search_classes": ["place:City"]. ``` { "errors": ["HTTP error: 400\nClasses ['http://semantica.globo.com/place/City'] are not in the range of predicate 'http://semantica.globo.com/place/partOfContinent'"] } ``` * Graphs not in range. If the search_graphs parameter has any graphs that classes in the range of predicate are not in. For example, if we pass in the request body "predicate": "place:partOfCity" and "search_graphs": ["http://semantica.globo.com/person/"]. ``` { "errors": ["HTTP error: 400\nClasses in the range of predicate 'http://semantica.globo.com/place/partOfCity' are not in graphs [u'http://semantica.globo.com/person/']"] } ``` * Graphs without instances. If the predicate’s ranges are only classes in graphs without instances, such as http://semantica.globo.com/upper/. For example, if we pass in the request body "predicate": "upper:isPartOf" and restrict graphs to "search_graphs": ["http://semantica.globo.com/upper/"]. ``` { "errors": ["HTTP error: 400\nClasses in the range of predicate 'http://semantica.globo.com/upper/isPartOf' are in graphs without instances, such as: ['http://semantica.globo.com/upper/']"] } ``` **Status 404** If there are no matches in the search engine, a 404 HTTP error is returned. ``` { "errors": ["HTTP error: 404\nThere were no search results."] } ``` **Status 500** Internal server error. Please, contact the team <[<EMAIL>](mailto:semantica%40corp.globo.com)> and provide the URL, JSON and error message. ### Stored Queries[¶](#stored-queries) Users of the Braniak API can define and store queries that do more than retrieve objects (instances or classes) or apply simple filters using p/o variables in querystring (see [*List of Instances*](index.html#document-services/instance/list_instance)). Stored queries give users flexibility to explore the model with complex relationships, graph traversal, etc. Stored queries gives users the flexibility to explore the model with all the power of SPARQL, including complex relationships and graph traversal. The first step is to register (store) a query. #### Creating or modifying a query definition[¶](#creating-or-modifying-a-query-definition) The service to register a query is the same used to update it. The X-Brainiak-Client-Id header is mandatory for access authentication. The client id used during query registration must be the same used during UPDATE and DELETE. Users can register a query by performing a request like: ``` $ curl -s -X PUT 'http://brainiak.semantica.dev.globoi.com/_query/my_query_id' -T payload.json -H "X-Brainiak-Client-Id: my_client_id" ``` The my_query_id attribute indicates the query identification to be used when executing it. The payload.json is a JSON object with the query definition and metadata: The required attributes are: sparql_template and description. ``` { "sparql_template": "SELECT %(class_uri)s FROM %(graph_uri)s {%(class_uri)s a owl:Class}", "description": "This query is so great, it does everything I need and it is used in apps such and such" } ``` When the request is successful for creating a query, a 201 status code is returned. For modifying existent queries, a 200 status code is returned. Notice that just read-only (e.g. SELECT) queries would be allowed to be registered. SPARQL 1.1 queries (most specifically, [SPARUL](http://en.wikipedia.org/wiki/SPARUL) ones) such as CONSTRUCT, MODIFY, INSERT, DELETE would be rejected with HTTP status code 403. Malformed queries with invalid JSON or missing required attributes (e.g sparql_template) would be rejected with HTTP status code 400. #### Listing registered queries[¶](#listing-registered-queries) We store the queries in Brainiak, but users might need to retrieve and/or modify a previously stored query. To list all queries registered, do: ``` $ curl -s -X GET 'http://brainiak.semantica.dev.globoi.com/_query' ``` The response for this query has the following format: ``` { "items": [ { "resource_id": "my_query_id", "description": "my query description", "sparql_template": "SELECT ?class_uri FROM %(graph_uri)s {?class_uri a owl:Class}" } ] } ``` The result can be navigated using [*Pagination*](index.html#document-services/pagination). #### Retrieving a specific query definition[¶](#retrieving-a-specific-query-definition) To retrieve a specific query definition, registered with my_query_id: ``` $ curl -s -X GET '/_query/my_query_id' ``` The response is the same JSON object that was used to register the query. ``` { "description": "my query description", "sparql_template": "SELECT ?class_uri FROM %(graph_uri)s {?class_uri a owl:Class}" } ``` If my_query_id was not registered previously, the request is invalid and will be rejected with HTTP status code 404. #### Deleting a query[¶](#deleting-a-query) To delete a stored query, registered with my_query_id: ``` $ curl -s -X DELETE '/_query/my_query_id' -H "X-Brainiak-Client-Id: my_client_id" ``` If the query exists and was successfuly deleted, a 204 status code is returned. If the query does not exists and there was an attempt to delete it, a 404 status code will be returned. #### Executing a query[¶](#executing-a-query) Consider the query described above for gettings classes in a graph. ``` SELECT ?class_uri FROM %(graph_uri)s {?class_uri a owl:Class} ``` To execute a query just use the _result modifier. ``` $ curl -s -X GET '/_query/my_query_id/_result?graph_uri=http%3A%2F%2Fsemantica.globo.com%2Fgraph%2F' ``` The response is a JSON with a list of dictionaries, each with all the matched variables in the query. ``` { "item_count": 2, "items": [ {"class_uri": "http://semantica.globo.com/graph/Class1"}, {"class_uri": "http://semantica.globo.com/graph/Class2"} ] } ``` ##### Counting in queries[¶](#counting-in-queries) When using the aggregator COUNT in SPARQL, for instance consider the following query: ``` SELECT DISTINCT COUNT(?o) {?s a ?o} ``` This would return a result with callret-N as variable name: ``` {"items": [{"callret-0": "42"}]} ``` In order to have a more descriptive result, use SPARQL AS modifier to create an alias. ``` SELECT DISTINCT COUNT(?o) AS ?count {?s a ?o} ``` This would return the more descriptive result: ``` {"items": [{"count": "42"}]} ``` #### Paging[¶](#paging) SPARQL uses LIMIT/OFFSET query modifiers for pagination. In Brainiak, we use page and per_page as reserved pagination parameters. We strongly recommend that variables in query templates **DO NOT USE** these reserved names. ### Overriding URIs[¶](#overriding-uris) The conventional patterns for assembling the URIs associated with resources are: > | Resources | URI | > | --- | --- | > | context | <URI_PREFIX><context_id>/ | > | collection | <URI_PREFIX><context_id>/<class_id> | > | class | <URI_PREFIX><context_id>/<class_id>/_schema | > | instance | <URI_PREFIX><context_id>/<class_id>/<instance_id> | These are described in [*Convention for URL Resources*](index.html#resource-url-convention). Specially for legacy systems, there are times when we need to override these. The following parameters are supported by all services: > | Parameter | Resource | URI | > | --- | --- | --- | > | graph_uri | context | <graph_uri> | > | graph_prefix | context | <graph_prefix><context_id> | > | class_uri | class | <class_uri> | > | class_prefix | class | <class_prefix><class_id> | > | instance_uri | instance | <instance_uri> | > | instance_prefix | instance | <instance_prefix><instance_id> | Notice that all prefixes should terminate with / #### Overriding the URI for the context[¶](#overriding-the-uri-for-the-context) The parameters graph_uri and graph_prefix can be used to define the URI for the context. The parameter graph_uri completely defines the URI for the context, specifying a particular graph in the triplestore. When specified, the context_id referred in the URL for the service is ignored. The parameter graph_prefix serves to override the global URI_PREFIX setting when composing the URI for the context. When specified, the URI for context becomes “<graph_prefix><context_id>/” . #### Overriding the URI for the collection+class[¶](#overriding-the-uri-for-the-collection-class) The parameters class_uri and class_prefix can be used to define the URI for the collection+class. The parameter class_uri completely defines the URI for the colelction+class. When specified, the class_id referred in the URL for the service is ignored. The parameter class_prefix serves to override the pattern “<URI_PREFIX><context_id>/” when composing the URI for the context. When specified, the URI for context becomes “<graph_prefix><class_id>/” . CAUTION: these parameters do not specify the graph where this class was defined, the latter follows the rules in [*Overriding the URI for the context*](index.html#override-context). #### Overriding the URI for the instance[¶](#overriding-the-uri-for-the-instance) The parameters instance_uri and instance_prefix can be used to define the URI for the instance. The parameter instance_uri completely defines the URI for the instance. When specified, the instance_id referred in the URL for the service is ignored. The parameter instance_prefix serves to override the pattern “<URI_PREFIX><context_id>/<class_id>/” when composing the URI for the instance. When specified, the URI for context becomes “<instance_prefix><instance_id>/” . CAUTION: these parameters do not specify neither the graph nor the class URIs, those follow the rules in [*Overriding the URI for the context*](index.html#override-context) and [*Overriding the URI for the collection+class*](index.html#override-schema) respectively. ### Hypermap of Resources[¶](#hypermap-of-resources) The image below depicts the map of hypermedia resources supported by Brainiak API. ### Links Specification[¶](#links-specification) In our API, successful responses have a links section that state possible actions for the resource being retrieved or access to other resources. For more about this concept, see [*Concepts*](index.html#document-concepts) and [*Hypermedia Support*](index.html#document-concepts/hypermedia). For example: ``` { "links": [ { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Male", "rel": "self" }, { href: "http://brainiak.semantica.dev.globoi.com/person/Gender", method: "GET", rel: "inCollection" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Male", "method": "PUT", "schema": {"$ref": "http://brainiak.semantica.dev.globoi.com/person/Gender/_schema"} "rel": "update" }, { "href": "http://brainiak.semantica.dev.globoi.com/person/Gender/Male", "method": "DELETE", "rel": "delete" } ] } ``` The URLs in href can be exact URLs or templates described by [URI template](http://tools.ietf.org/html/rfc6570). When they are templates, each placeholder variable of the template should have the respective variable defined in each entry of the items section. For example: ``` { "items": [ { "title": "Europa", "instance_prefix": "http://semantica.globo.com/place/Continent/", "@id": "http://semantica.globo.com/place/Continent/Europe", "resource_id": "Europe" } ], "links": [ { "href": "http://brainiak.semantica.dev.globoi.com/place/Continent/{resource_id}?instance_prefix={instance_prefix}", "method": "GET", "rel": "item" } ] } ``` ### Rel Vocabulary[¶](#rel-vocabulary) In the description below we use the term target to designate the resource retrieved that owns the link relations. Unless specified otherwise, GET is the default HTTP method used in each of the link relations. Defined by the rel key, the possible link relations are grouped in logically related links. We call this groups contracts. --- #### Mandatory contract[¶](#mandatory-contract) The mandatory contract is a group of links that need to be present in every response. ##### self[¶](#self) The target resource URL itself, i.e. a URL to the target resource that owns the links. --- #### CRUD contract[¶](#crud-contract) The CRUD contract is a group of links that represent the four basic data manipulation operations. ##### create[¶](#create) Refers to a resource that can be used to create other resources of the same type as the target. ##### edit[¶](#edit) Refers to a resource that can be used to edit incrementally the target. Method: PATCH ##### update[¶](#update) Refers to a resource that can be used to edit the target by entirely redefining its content. When using update, the target will be removed and inserted again. Method: PUT More about the [difference between HTTP PUT and PATCH](http://tools.ietf.org/html/rfc5789). ##### delete[¶](#delete) Delete the target. Method: DELETE ##### describedBy[¶](#describedby) Refers to a resource providing information about the target’s type in json-schema notation. --- #### Conceptual contract[¶](#conceptual-contract) The Conceptual contract is a group of links that represent the specific concepts provided by the Brainiak API. ##### root[¶](#root) The root link refers to the starting point of hypernavigation in the Brainiak API. The current implementation has chosen to represent a list of contexts in the root. ##### context[¶](#context) The context link refers to some context. This concept is explained in [*Context*](index.html#concept-context). Each context is a namespace that holds a list of collections. ##### collection[¶](#collection) The collection link refers to some collection. This concept is explained in [*Collection*](index.html#concept-collection). The collection is a list of instances that share the same type. ##### instance[¶](#instance) The instance link refers to the properties and values of an instance. This concept is explained in [*Instance*](index.html#concept-instance). ##### class[¶](#class) The class link refers to the type of an instance, defining its properties. This concept is explained in [*Class*](index.html#concept-schema). --- #### CMAaS contract[¶](#cmaas-contract) The CMAaS contract is a group of links that adhere to the Globo.com generic CMAaS or Content Management Application as a Service. ##### item[¶](#item) When the target is a list, the item refers to each resource within that list. Moreover, these items are guaranteed *not* to be lists. ##### instances[¶](#instances) When the target is a list, the instances refers to each resource within that list that represents a sub-list. Moreover, these resources are guaranteed to be also lists. --- #### Pagination contract[¶](#pagination-contract) The Pagination contract is a group of links that support the basic primitives to navigate through items organized in pages. ##### first[¶](#first) Refers to the first page of a list. ##### last[¶](#last) Refers to the last page of a list. This link is only present if the respective resource URL receives the do_item_count parameter set to 1. ##### previous[¶](#previous) Refers to the previous page in a list. ##### next[¶](#next) Refers to the next page in a list. Warning By default, the item_count attribute of a list is not computed. As a result, the URL given by the next link may not contain data beyond the last page. ### Pagination[¶](#pagination) Requests that return multiple items will be paginated to 20 items by default. You can specify further pages with the ?page parameter. For some resources, you can also set a custom page size up to 100 with the ?per_page parameter. Note that for technical reasons not all endpoints respect the ?per_page parameter, see events for example. ``` $ curl http://loclahost:5100/base/Acao?page=2&per_page=15 ``` The pagination info is included in the Link Session. It is important to follow these Link header values instead of constructing your own URLs. ``` "links": [{ "href": "http://10.2.180.27:5100/base/Acao?page=1", "method": "GET", "rel": "first" }, { "href": "http://10.2.180.27:5100/base/Acao?page=64", "method": "GET", "rel": "last" }, { "href": "http://10.2.180.27:5100/base/Acao?page=2", "method": "GET", "rel": "next" }] ``` The possible rel values are: **next** Shows the URL of the immediate next page of results. **last** Shows the URL of the last page of results. **first** Shows the URL of the first page of results. **prev** Shows the URL of the immediate previous page of results. ### Handling Errors[¶](#handling-errors) The Brainiak API returns two levels of error information: > * HTTP error codes and messages in the header > * A JSON object in the response body with additional details that can help you determine how to handle the error. The rest of this page provides a reference of Brainiak errors, with some guidance on how to handle them in your app. #### Client-side Errors[¶](#client-side-errors) There are some possible types of client errors on API calls that receive request bodies, the most common are: Sending and unknown parameters in the request, the response is a 400 with a JSON informing the wrong parameters and the accepted ones. ``` HTTP/1.1 400 Bad Request ``` ``` { "errors": [ "HTTP error: 400\nArgument invalid_param is not supported. The supported querystring arguments are: do_item_count, expand_uri, graph_uri, lang, page, per_page, sort_by, sort_include_empty, sort_order." ] } ``` If the instance does not exist, the response is a 404 with a JSON informing the error ``` HTTP/1.1 404 Not Found Content-Length → 73 ``` ``` { "errors": "HTTP error: 404\nClass class_example in context person does not exist" } ``` When there is a conflict, i.e. the instance is refered by another, there is a dependency between them and therefore, the instance cannot be deleted, for consistency. To delete an instance you should first delete instances that depend on it. ``` HTTP/1.1 409 Not Conflict Content-Length → 30 ``` ``` { "errors": ["Cannot exclude instance because of the dependencies: http://semantica.globo.com/esportes/MateriaEsporte/239172, http://semantica.globo.com/esportes/MateriaEsporte/233213"] } ``` All error objects have resource and field properties so that your client can tell what the problem is. There’s also an error code to let you know what is wrong with the field. These are the possible validation error codes: #### Server-side Errors[¶](#server-side-errors) Server side errors will show a 500 status code with a stack trace to better debugging the error cause. ### Caching[¶](#caching) #### Enabling cache[¶](#enabling-cache) Cache is enabled or disabled at the settings.py of the application, through the variable ENABLE_CACHE. When this global cache configuration is enabled, cache is set (or not) for each resource of the API. To check if cache is enabled for some resource, run: ``` $ curl -i -X OPTIONS http://brainiak.semantica.dev.globoi.com/ HTTP/1.1 204 No Content Server: nginx Date: Thu, 03 Jul 2014 21:00:33 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 0 Connection: keep-alive Access-Control-Allow-Methods: GET, OPTIONS, PURGE Access-Control-Max-Age: 86400 Access-Control-Allow-Origin: * Access-Control-Allow-Headers: Content-Type, Authorization, Backstage-Client-Id ``` If cache is enabled, PURGE will be shown on the response header Access-Control-Allow-Methods. #### Resource cache status[¶](#resource-cache-status) It is possible to check the cache status of a certain resource by the following headers: > * **X-Cache**: tells if there was a HIT (cached data) or MISS (fresh data) at Brainiak API > * **Last-Modified**: date and time when the response was computed. This is specially useful when X-Cache returns HIT. #### Example[¶](#example) The first time a URL is accessed, there will be no cache - so X-Cache will return MISS: ``` $ curl -i -X GET http://brainiak.semantica.dev.globoi.com/ HTTP/1.1 200 OK Server: nginx Date: Thu, 03 Jul 2014 21:00:35 GMT Content-Type: application/json; profile=http://brainiak.semantica.dev.globoi.com/_schema_list Content-Length: 1008 Connection: keep-alive X-Cache: MISS from brainiak.semantica.dev.globoi.com Last-Modified: Thu, 03 Jul 2014 18:00:35 -0300 Etag: "4d53e4145ce64273c7604ad86c4cc81d5dddbb05" Access-Control-Allow-Origin: * ``` From the second time on, X-Cache will contain HIT and Last-Modified will be the same: ``` $ curl -i -X GET http://brainiak.semantica.dev.globoi.com/ HTTP/1.1 200 OK Server: nginx Date: Thu, 03 Jul 2014 21:00:36 GMT Content-Type: application/json; profile=http://brainiak.semantica.dev.globoi.com/_schema_list Content-Length: 1008 Connection: keep-alive X-Cache: HIT from brainiak.semantica.dev.globoi.com Last-Modified: Thu, 03 Jul 2014 18:00:35 -0300 Etag: "f288c34015f52392c33fd6bffd95e7bfb25c4a0a" Access-Control-Allow-Origin: * ``` #### Purge[¶](#purge) To cleanup cache, the PURGE method should be used. Note that for purging purposes, query string parameters are ignored. That means that the same instance could have been cached with different parameters, but when purging the instance all versions should be removed from the cache disregarding the parameters that they were cached with. For the time being, we support purging: just the root, a particular instance, the whole cache. #### Purge Root[¶](#purge-root) Example: ``` $ curl -i -X PURGE http://brainiak.semantica.dev.globoi.com/ HTTP/1.1 200 OK Server: nginx Date: Thu, 03 Jul 2014 21:00:36 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 0 Connection: keep-alive Access-Control-Allow-Origin: * ``` #### Purge Instance[¶](#purge-instance) There is support to PURGE a specific instance given its full path. ``` $ curl -i -X PURGE http://brainiak.semantica.dev.globoi.com/person/Person/IsaacNewton ``` #### Purge all (Recursive purge)[¶](#purge-all-recursive-purge) It is also possible to cleanup recursively, calling PURGE with the header X-Cache-Recursive set to 1: ``` $ curl -i -X PURGE --header "X-Cache-Recursive: 1" http://brainiak.semantica.dev.globoi.com/ ``` At this time, we only accept purging all cache. In the near future, it will be accepted more granular purging, such as purge everything cached from this context, collection, and so on. ### Internationalization[¶](#internationalization) Brainiak supports the internationalization of: > 1. Error messages, and > 2. Ontology & instances string literals It is possible to define the default language of both by editing settings.py‘s DEFAULT_LANG variable. Despite this, it is also possible to customize the language of (2) in most of Brainiak services, by adding lang=pt to the request querystring. #### Developers’ notes[¶](#developers-notes) Brainiak error messages are translated using GETTEXT. The following steps must be followed in order to internationlize a phrase inside Brainiak source code: > i. Wrap the string to be translated using _(). > E.g. if “some expression” must be translated, replace it by _(“some expression”) > ii. Create or update Brainiak translation template: > make translate_template > iii. Update Brainiak Portuguese dictionary based on translation template > make portuguese_dictionary > iv. Compile Portuguese dictionary, so the machine can understand the translations > make compile_portuguese ### Convention for URL Resources[¶](#convention-for-url-resources) We use the following convention for resources: | <http:/>/<domain>/<context_id> | Some context | | <http:/>/<domain>/<context_id>/<class_id> | A collection of instances having the same class in the same context | | <http:/>/<domain>/<context_id>/<class_id>/_schema | The definition of a class given by class_id in the context given by context_id | | <http:/>/<domain>/<context_id>/<class_id>/<instance_id> | A instance identified by instance_id having the schema given by class_id and belonging to the context given by context_id | For each resource there is an URI associated with it, by default we adopt the following rules: | Resources | URI | | --- | --- | | context | <URI_PREFIX><context_id>/ | | class | <URI_PREFIX><context_id>/<class_id> | | instance | <URI_PREFIX><context_id>/<class_id>/<instance_id> | URI_PREFIX is a global Brainiak configuration option, and inside Globo.com we define it with http://semantica.globo.com/. These conventions can be overriden by optional parameters described in [*Overriding URIs*](index.html#parametrization). ### Service Examples[¶](#service-examples) **List all contexts** ``` GET 'http://brainiak.semantica.dev.globoi.com' ``` **List all collections of a context** ``` GET 'http://brainiak.semantica.dev.globoi.com/place' ``` **List all instances of a collection** ``` GET 'http://brainiak.semantica.dev.globoi.com/place/Country' ``` **Get a class associated with a collection** ``` GET 'http://brainiak.semantica.dev.globoi.com/place/Country/_schema' ``` Try it yourself: [Class for Country](forCountry:http://brainiak.semantica.dev.globoi.com/place/Country/_schema) **Get a instance of a collection** ``` GET 'http://brainiak.semantica.dev.globoi.com/place/Country/Brazil' ``` Try it yourself: [Brazil (Country Instance)](http://brainiak.semantica.dev.globoi.com/place/Country/Brazil) Troubleshooting[¶](#troubleshooting) --- When Brainiak is not working as expected this is the first place to look! ### I receive error 404 with message ‘X-Brainiak-Client-Id’ is not known[¶](#i-receive-error-404-with-message-x-brainiak-client-id-is-not-known) The Brainiak uses the triplestore.ini to multiplex access to different backend triplestore databases. The value passed in the header X-Brainiak-Client-Id is the key used to indentify which triplestore is the target endpoint. If no header X-Brainiak-Client-Id is given, the default entry is used as target. The message “{“errors”: [“HTTP error: 404nClient-Id provided at ‘X-Brainiak-Client-Id’ (My client_id) is not known”]}” is returned with error 404, when the key (in the example ‘My client_id’) is not present in the configuration file triplestore.ini. ### How to check if Brainiak is connected with the backend triplestore?[¶](#how-to-check-if-brainiak-is-connected-with-the-backend-triplestore) Any access to /status/virtuoso will yield the connectivity status with the triple store. > * Virtuoso connection not-authenticated | FAILED | <http://localhost:8890/sparql-auth> | Unauthorized > * Virtuoso connection authenticated [api-semantica:[Nu��o�˨e’��Ǟ] | SUCCEED | <http://localhost:8890/sparql-auth> There are two independent attempts to connect to Virtuoso. The first line above represents the status of unauthenticated access, and the second line the status of authenticated access. You both lines have status FAILED then Brainiak is disconnected with the triplestore. In the example above, the second line shows that Brainiak can access the database with the configured user “api-semantica”. ### How to check if Brainiak is connected with the ActiveMQ?[¶](#how-to-check-if-brainiak-is-connected-with-the-activemq) Any access to /status/activemq will yield the connectivity status with ActiveMQ. > ActiveMQ connection not-authenticated | SUCCEED | localhost:61613 The line above shows a successful connection with ActiveMQ. In case of failure, the user should receive a message like: > ActiveMQ connection not-authenticated | FAILED | localhost:61613 | ‘stomp.exception.NotConnectedException’ ### Any service gives me the message: “Access to backend service failed”?[¶](#any-service-gives-me-the-message-access-to-backend-service-failed) If you are getting the error message below, it means that the triplestore is not accessible by Brainiak. error response: ``` { error: HTTP error: 500 Access to backend service failed. HTTP 599: Failed connect to localhost:8890; Connection refused. Check Virtuoso } ``` In this case, check: * are the user and password defined by Brainiak in the environment (or in settings.py) correct ? * is Virtuoso up and running ? * does the machine (in which Brainiak is installed) has access to the Virtuoso database ? ### When filtering instances using p and o I only get “HTTP error: 404”. But when I only use p, it lists items containing the o I defined. What am I doing wrong?[¶](#when-filtering-instances-using-p-and-o-i-only-get-http-error-404-but-when-i-only-use-p-it-lists-items-containing-the-o-i-defined-what-am-i-doing-wrong) Brainiak is internationalized. It is possible that the value mapped by o is in some specific language, eg. “London”@en or “Londres”@pt. Try adding to the query string: > * lang=en, for English > * lang=pt, for Portuguese > * or lang=undefined, if the word is not internationalized E.g, the request below returns 404: ``` GET 'http://brainiak.semantica.dev.globoi.com/G1/Materia/?p1=base:status_de_publicacao&o1=P&p2=G1:cita_a_entidade&o2=http://semantica.globo.com/base/UF_MA' ``` While this second request is successful: ``` GET 'http://brainiak.semantica.dev.globoi.com/G1/Materia/?p1=base:status_de_publicacao&o1=P&p2=G1:cita_a_entidade&o2=http://semantica.globo.com/base/UF_MA&lang=undefined' ``` Releases[¶](#releases) --- ### Version 2.7.4 - 2014/08/14[¶](#version-2-7-4-2014-08-14) #### Fixes, Improvements[¶](#fixes-improvements) * Changes when patching an instance (see [*Patch an Instance*](index.html#document-services/instance/patch_instance)) + Operation delete is now safe in PATCH (i.e. if key does not exist, there is no error) + Patching an unexistent instance will now create it using add/replace patches. It works like PUT, Brainiak will not create the URI. + There is now a validation for expected parameters in op values, only add, replace, and remove are accepted * handling of https respecting X-Forwarded-For header * Fixes several hyperlinks when passing _uri arguments and omitting slugs with ‘_’ ### Version 2.7.3 - 2014/08/05[¶](#version-2-7-3-2014-08-05) #### Fixes, Improvements[¶](#id1) * _suggest service has expand_uri=1 as the default * Fixed broken expand_uri for suggest ### Version 2.7.2 - 2014/08/01[¶](#version-2-7-2-2014-08-01) #### Fixes, Improvements[¶](#id2) * When using filters, the additional predicates listed did not obey the expand_uri parameter * There was an inconsistency with any schema definition that was cached due to an instance being fetched by /_/_/_?instance_uri * Suggest now supports expand_uri to compress results if necessary ### Version 2.7.1 - 2014/07/30[¶](#version-2-7-1-2014-07-30) #### Fixes, Improvements[¶](#id3) * Corrections in the documentation * SchemaNotFound returning 404 instead of 500 HTTP error ### Version 2.7.0 - 2014/07/29[¶](#version-2-7-0-2014-07-29) #### New Features[¶](#new-features) * Querystring parameter expand_uri=1 is the default now instead of expand_uri=0 (default in versions < 2.7.0) #### Fixes, Improvements[¶](#id4) * Suggest was broken when no graphs were specified. * Disable external caches ### Version 2.6.0 - 2014/07/07[¶](#version-2-6-0-2014-07-07) #### New Features[¶](#id5) * Patch instance (see [*Patch an Instance*](index.html#document-services/instance/patch_instance)). #### Fixes, Improvements[¶](#id6) * When filtering a collection of instances, property values are now being casted. #### Refactor[¶](#refactor) * Remove dependency of SPARQLWrapper. ### Version 2.5.1 - 2014/06/06[¶](#version-2-5-1-2014-06-06) #### Fixes, improvements[¶](#id7) * PUT instance raised exception when trying to add property mapping list of values, if the property was obligatory. * Workaround in get_instance turning off inference while retrieving properties of an object. There is a bug in Virtuoso that when property X is a subProperty of property Y, and X has several values associated with some instance, then inference attributes only the first value to X and Y, the remaining are only attributed to Y. ### Version 2.5.0 - 2014/05/19[¶](#version-2-5-0-2014-05-19) #### New Features[¶](#id8) * Stored queries. More on this here (see [*Stored Queries*](index.html#document-services/stored_query/stored_query)). #### Fixes, Improvements[¶](#id9) * Location URI was incorrectly generated after a POST that had URL query params (eg.:?class_uri=) * Validating existence of rdfs:label and/or subproperties when creating/modifying instances. In some methods, e.g. listing a collection, rdfs:label existence for an instance was a premise but it was possible to insert instances without any label properties. * Fixed broken multi-line string insertion. ### Version 2.4.4 - 2014/02/04[¶](#version-2-4-4-2014-02-04) #### Fixes[¶](#fixes) * Fixed caching mechanism to not include invalid instances (e.g. {body: None}) in cache. * Fixed type mapping to include rdfs:Literal to string. ### Version 2.4.3 - 2014/01/17[¶](#version-2-4-3-2014-01-17) #### New Features[¶](#id10) > * Using cached schema in PUT/POST operations on instances. #### Fixes[¶](#id11) > * Fixed missing querystring parameters when building schema (/_schema_list) URL for a collection of instances. > * Fixing hit ratio calculation in Redis usage statistics _status/cache ### Version 2.4.2 - 2014/01/15[¶](#version-2-4-2-2014-01-15) #### New Features[¶](#id12) > * More detailed information for /_status/cache, showing Redis usage statistics #### Fixes[¶](#id13) > * Root resource was not cached including URL parameters, as a side effect pagination would not work for the root resource. > Now the root is cached with all the URL parameters that were given. > * Test suite was cleaned up from tests shadowed by homonymous tests. ### Version 2.4.1 - 2014/01/10[¶](#version-2-4-1-2014-01-10) #### New Features[¶](#id14) > * Support for caching instances. > * Any recursive purge will expire all instances in the cache for the time being. > * Support for purging a specific instance (see [*Caching*](index.html#document-services/cache)). #### Fixes[¶](#id15) > * Removing unused param purge. > * Fixed purging schemas (different GET params cached in different keys). > * The cache key for any instance follows the pattern _@@_/_@@<instance_uri>##instance > * When updating an instance via PUT, the cached version was updated although it lacked the meta_properties. > Now, when updating the cache, the full properties are updated in the cached instance. > * Fixed problem in /_search JSON Schema (see [*Search*](index.html#document-services/search/search)). #### Developers notes[¶](#developers-notes) > * Acceptance test to validate CMA using splinter. ### Version 2.4.0 - 2013/11/28[¶](#version-2-4-0-2013-11-28) #### New Features[¶](#id16) > * Add service for full text search of instances (see [*Search*](index.html#document-services/search/search)). > * Add X-Brainiak-Resource-Uri to response header when creating instances (URI of instance created) > * Internationalization of error messages > * Portuguese version of error messages, despite English (default) > * Validate value uniqueness when property has the annotation property specified in settings.ANNOTATION_PROPERTY_HAS_UNIQUE_VALUE > * Validate data when adding or editing instances (uniqueness, type, required). If the data isn’t compatible to the schema, the response status code is 400 and the payload contains a list with all the inconsistencies. #### Fix[¶](#fix) > * Bugfix for absent Access-Control-Allow-Origin: * in error responses > * When retrieving instances, blank nodes are ignored in the response > * class_prefix was being rendered with an incorrect trailing :. This char : is not part of the URL. #### Enhancements[¶](#enhancements) > * Use relative URLS in class schema (it was absulte before this release) > * Add rel='create' to class schema > * Add rel='suggest' to class schema > * Add rel='create' to class schema > * Add rel='search' to instances’ collection > * Add *temporary* duplicate title to collection JSON schema, for compliance with CMAaaS > * Add _type_title to each item in Suggest response > * Add X-Brainiak-Resource-Uri to header, in order to refer to the URI when a instance is created > * Rename rel='instance' to rel='relatedInstance' and change variable template, for compliance with CMAaaS > * Rename titles in JSON-Schemas for root, context and collection > * Remove header X-Brainiak-Cache-All (functionality is available using X-Brainiak-Cache-Recursive) #### Developers notes[¶](#id17) > * Caching keys refactoring > * When brainiak is initialized, all cache is flushed > * customize.py script allows uploading customizations to CMAaaS > * Only expanded URIs will be used internally from now on > * Nginx-related: comment out X-Scheme so that X-Forwarded-Proto works correctly to https ### Version 2.3.8 - 2013/10/04[¶](#version-2-3-8-2013-10-04) #### Fix[¶](#id18) > * Suggest query using custom fields (before it wasn’t working properly) > * The CORS header Access-Control-Allow-Origin: * was absent in error responses > * Fix in error messages when context_name, class_name, instance_id received ‘_’, > now error messages render the contents of class_uri. graph_uri and instance_uri. ### Version 2.3.7 - 2013/10/31[¶](#version-2-3-7-2013-10-31) #### Enhacements[¶](#enhacements) > * General improvements on Suggest query (support unicode and partial queries) ### Version 2.3.6 - 2013/10/28[¶](#version-2-3-6-2013-10-28) #### Enhacements[¶](#id19) > * Remove xsd:string from instances when adding new instance ### Version 2.3.3-2.3.5 - 2013/10/28[¶](#version-2-3-3-2-3-5-2013-10-28) #### Enhacements[¶](#id20) > * General log improvements ### Version 2.3.2 - 2013/10/28[¶](#version-2-3-2-2013-10-28) #### Enhacements[¶](#id21) > * General improvements on Suggest query ### Version 2.3.1 - 2013/10/23[¶](#version-2-3-1-2013-10-23) #### Enhacements[¶](#id22) > * Suggest works both with ElasticSearch 0.19.x and 0.90.x #### Fixes[¶](#id23) > * Suggest supports queries ending and not ending in s (e.g. James) > * During GET instances, if datatype is not defined in schema, return value as string and not as object (as before) ### Version 2.3.0 - 2013/10/22[¶](#version-2-3-0-2013-10-22) #### New features[¶](#id24) > * Retrieve (GET) and update (PUT) instances only by instance URI (see [*Managing Instances*](index.html#document-services/instance/instance)) #### Refactorings[¶](#refactorings) > * Default to all resources is to use compressed URIs (expand_uri=0) in the response > * Return 200 and empty items in listing resources (before it was 404) #### Enhacements[¶](#id25) > * Enable caching to schema > * Improved performace of suggest in 30x (subproperties are now cached at Redis) > * Validate instance data during POST/PUT using its schema > * Validate instance data during GET using its schema, to return values of properties as their types and cardinalities #### Fixes[¶](#id26) > * Suggest query returns first exact match > * Suggest query supports searches in values which include / ### Version 2.2.5 - 2013/10/15[¶](#version-2-2-5-2013-10-15) #### New features[¶](#id27) > * Any class definition (returned by _schema) now includes a new attribute for each predicate dictionary. > The new attribute is class and it identifies the class uri in which this predicate was defined in the ontology. > This serves to identify predicates that were inherited or direct declared in the class. #### Refactor[¶](#id28) > * #10645 Adding datatype property to the schema (class description), documenting > precisely the semantic type of the range of a datatype predicate. > The format field was used to convey that information, it is no longer used for this purpose. > * #10694 Removing parameters for optional URI expansion in responses: expand_uri_keys and expand_uri_values. > We still support expand_uri to control expansion in the response, but it always impacts keys and values. #### Fixes[¶](#id29) > * Adding unicode conversion to queries, that would break with special unicode chars. > * graph property on any class definition was not expanded when parameter expand_uri was set to 1 > * Some predicates dictionaries in a class definition had inconsitencies when there was a clash between conflicting > homonimous predicates defined in the same inheritance hierarchy. ### Version 2.2.3 + 2.2.4 - 2013/09/25[¶](#version-2-2-3-2-2-4-2013-09-25) #### New features[¶](#id30) > * Evolution of the _suggest service, now supporting retrieval of instances referred by a given target predicate where a textual pattern occurs. > * New expand_object_properties parameter used in instance retrieval. > * New direct_instances_only parameter used in instance lists (collection retrieval). #### Refactor[¶](#id31) > * New endpoint was created for the isolated Braniak deploy. api.semantica -> brainiak.semantica > * Json-schema descriptions are now compliant with Draft-04, and no longer compliant with Draft-03 > * Removed the rdf:type property from the retrieved instance definition #### Fixes[¶](#id32) > * During insertion of instance, property values now receive type cast. > The mapping of json types to semantic types is still simplified. A precise mapping will be implemented in the future. > * Removed the disk cache from Nginx. > * Remove escaping of URL parameters for the profile directive (specifies the json-schema URL) in the Content-Type header. > * Response body of backend erros appear in log files even if the log level is not set to DEBUG > * Removal of restricted attributes (@ and _ prefixes) from the notification sent to the backstage bus ### Version 2.2.0 + 2.2.2 - 2013/08/29[¶](#version-2-2-0-2-2-2-2013-08-29) #### New features[¶](#id33) > * Suggest resource (see [*Suggest*](index.html#document-services/suggest/suggest)) with pagination (uses ElasticSearch) > * Support to multiple triplestore endpoints (see [*Troubleshooting*](index.html#document-troubleshoot) and X-Brainiak-Client-Id entry) #### Refactor[¶](#id34) > * Add @id to context and collection > * Rename hosts barramento.baas -> barramento.backstage > * Refactor error messages to adhere to CPM2 > * PUT and POST <instance> response do not have body anymore > * Removed transactional behavior of POST <instance> regarding ActiveMQ > * Fix inconsistent resource_id in <instance> JSON Schema > * Refactor rel=self to always represent base_url for other relative links > * Root/json_schema is now cached #### Fixes[¶](#id35) > * Fix at GET <instance>: instance_prefix == null > * Fix at PUT <instance> expansion URI not being applied to string literals > * Fix double unicode escaping, so we can use JSON Browser > * Fix collection pagination JSON Schema rels, so they work when filters “p” and “o” are used. For this purpose, collections now have “previous_args”, “next_args”, “first_args” and “last_args”. #### Developers’ notes[¶](#id36) > * Add automate tests to check compliance to JSON-Schema Version 3 > * query_sparql interface was refactored > * The versions 2.2.1 and 2.2.2 were mere adjustments in the deploy procedure with no new features ### Version 2.1.0 - 2013/08/01[¶](#version-2-1-0-2013-08-01) #### New features[¶](#id37) > * New parameters for optional URI expansion in responses: expand_uri, expand_uri_keys and expand_uri_values (see [*Get an Instance*](index.html#document-services/instance/get_instance)). > * Root schema now have direct hyperlinks to collection and instance (see [*Hypermap of Resources*](index.html#document-services/links)). > * DOCs are now being deployed by default #### Fixes[¶](#id38) > * Instances filter with PO ignores literals’ type ### Version 2.0.0 - 2013/07/18[¶](#version-2-0-0-2013-07-18) #### New features[¶](#id39) > * Instances list (filtering) resource supports multiple predicates and objects > * Root resource (/) is currently cached > * New “purge” HTTP method (both recursive and non-recursive), > available on cached resources > * Improve compliance towards json-schema > (“links” section was moved from the instances to their json-schemas) #### Refactor[¶](#id40) > * Instances list (filtering) resource now applies lang to objects (?o) when > literals are provided > * Resources URLs renamed > + <resource>/_schema -> <resource>/_schema_list, when related to a list resource > + /prefixes -> /_prefixes > + /version -> /_version > + /status/<dependency> -> /_status/<dependency> > * Hypermedia links renamed > + instances -> list > + create -> add > * Properties on resources’ responses > + list resources > - “item_count” property was removed by default > (do_item_count querystring param should be used to show “item_count”) > + schema resource > - “format” field, related to “type” field, now uses the same format of the property on the triplestore > - “comment” -> “description” to better comply with json-schema specification > - “required” now maps boolean values, instead of an array of strings > - “_class_prefix” was added to fix navigation of legacy instances > - content-type “profile” variable scapes querystrings’ urls, to please JsonBrowser #### Documentation[¶](#documentation) > * New hypermedia map #### Developers’ notes[¶](#id41) > * SPARQL queries logging is now compatible to Globo.com DBA team’s expectations > * Syslog handler now uses LOG_LOCAL3 (before: LOG_SYSLOG) > * Redis is an optional dependency for running Brainiak locally (tests, however, require it) > * Cache implementation uses Redis and is optional to run Brainiak > * Improved test coverage analysis method > * Updated to Tornado 3.1 ### Version 1.1.0 - 2013/05/28[¶](#version-1-1-0-2013-05-28) > * notification of instance creation, removal and update to external event bus through stomp protocol. Using package DAD for notifications to MOM bus. > * class_prefix argument was added to hypernavigational links. > * more rigorous argument handling in services, invalid parameters make the service fail. On failure, the valid parameters are informed in the error message. > * The Content-Type header in HTTP responses now includes the URL for the class given in the response payload. > * BUGFIX: fixed rdfs:label and rdfs:comment in place/Country/Brazil, now using upper:name and upper:description. > * BUGFIX: the field rdf:type of any instance only contains the direct class of the instance, blank nodes and other intermediate ancestor classes were removed. ### Version 1.0.0 - 2013/04/24[¶](#version-1-0-0-2013-04-24) > * first release in production > * features supported: > > > > + listing of prefixes, contexts, collections and instances > > + retrieval of schemas and instances > > + creation of instances > > + removal of instances > > + update of instances > > >
aws-sdk-grafana
rust
Rust
Crate aws_sdk_grafana === **Please Note: The SDK is currently in Developer Preview and is intended strictly for feedback purposes only. Do not use this SDK for production workloads.** Amazon Managed Grafana is a fully managed and secure data visualization service that you can use to instantly query, correlate, and visualize operational metrics, logs, and traces from multiple sources. Amazon Managed Grafana makes it easy to deploy, operate, and scale Grafana, a widely deployed data visualization tool that is popular for its extensible data support. With Amazon Managed Grafana, you create logically isolated Grafana servers called *workspaces*. In a workspace, you can create Grafana dashboards and visualizations to analyze your metrics, logs, and traces without having to build, package, or deploy any hardware to run Grafana servers. ### Getting Started > Examples are available for many services and operations, check out the > examples folder in GitHub. The SDK provides one crate per AWS service. You must add Tokio as a dependency within your Rust project to execute asynchronous code. To add `aws-sdk-grafana` to your project, add the following to your **Cargo.toml** file: ``` [dependencies] aws-config = "0.56.1" aws-sdk-grafana = "0.33.0" tokio = { version = "1", features = ["full"] } ``` Then in code, a client can be created with the following: ``` use aws_sdk_grafana as grafana; #[::tokio::main] async fn main() -> Result<(), grafana::Error> { let config = aws_config::load_from_env().await; let client = aws_sdk_grafana::Client::new(&config); // ... make some calls with the client Ok(()) } ``` See the client documentation for information on what calls can be made, and the inputs and outputs for each of those calls. ### Using the SDK Until the SDK is released, we will be adding information about using the SDK to the Developer Guide. Feel free to suggest additional sections for the guide by opening an issue and describing what you are trying to do. ### Getting Help * GitHub discussions - For ideas, RFCs & general questions * GitHub issues - For bug reports & feature requests * Generated Docs (latest version) * Usage examples Crate Organization --- The entry point for most customers will be `Client`, which exposes one method for each API offered by Amazon Managed Grafana. The return value of each of these methods is a “fluent builder”, where the different inputs for that API are added by builder-style function call chaining, followed by calling `send()` to get a `Future` that will result in either a successful output or a `SdkError`. Some of these API inputs may be structs or enums to provide more complex structured information. These structs and enums live in `types`. There are some simpler types for representing data such as date times or binary blobs that live in `primitives`. All types required to configure a client via the `Config` struct live in `config`. The `operation` module has a submodule for every API, and in each submodule is the input, output, and error type for that API, as well as builders to construct each of those. There is a top-level `Error` type that encompasses all the errors that the client can return. Any other error type can be converted to this `Error` type via the `From` trait. The other modules within this crate are not required for normal usage. Modules --- * clientClient for calling Amazon Managed Grafana. * configConfiguration for Amazon Managed Grafana. * errorCommon errors and error handling utilities. * metaInformation about this crate. * operationAll operations that this crate can perform. * primitivesPrimitives such as `Blob` or `DateTime` used by other types. * typesData structures used by operation inputs/outputs. Structs --- * ClientClient for Amazon Managed Grafana * ConfigConfiguration for a aws_sdk_grafana service client. Enums --- * ErrorAll possible error types for this service. Crate aws_sdk_grafana === **Please Note: The SDK is currently in Developer Preview and is intended strictly for feedback purposes only. Do not use this SDK for production workloads.** Amazon Managed Grafana is a fully managed and secure data visualization service that you can use to instantly query, correlate, and visualize operational metrics, logs, and traces from multiple sources. Amazon Managed Grafana makes it easy to deploy, operate, and scale Grafana, a widely deployed data visualization tool that is popular for its extensible data support. With Amazon Managed Grafana, you create logically isolated Grafana servers called *workspaces*. In a workspace, you can create Grafana dashboards and visualizations to analyze your metrics, logs, and traces without having to build, package, or deploy any hardware to run Grafana servers. ### Getting Started > Examples are available for many services and operations, check out the > examples folder in GitHub. The SDK provides one crate per AWS service. You must add Tokio as a dependency within your Rust project to execute asynchronous code. To add `aws-sdk-grafana` to your project, add the following to your **Cargo.toml** file: ``` [dependencies] aws-config = "0.56.1" aws-sdk-grafana = "0.33.0" tokio = { version = "1", features = ["full"] } ``` Then in code, a client can be created with the following: ``` use aws_sdk_grafana as grafana; #[::tokio::main] async fn main() -> Result<(), grafana::Error> { let config = aws_config::load_from_env().await; let client = aws_sdk_grafana::Client::new(&config); // ... make some calls with the client Ok(()) } ``` See the client documentation for information on what calls can be made, and the inputs and outputs for each of those calls. ### Using the SDK Until the SDK is released, we will be adding information about using the SDK to the Developer Guide. Feel free to suggest additional sections for the guide by opening an issue and describing what you are trying to do. ### Getting Help * GitHub discussions - For ideas, RFCs & general questions * GitHub issues - For bug reports & feature requests * Generated Docs (latest version) * Usage examples Crate Organization --- The entry point for most customers will be `Client`, which exposes one method for each API offered by Amazon Managed Grafana. The return value of each of these methods is a “fluent builder”, where the different inputs for that API are added by builder-style function call chaining, followed by calling `send()` to get a `Future` that will result in either a successful output or a `SdkError`. Some of these API inputs may be structs or enums to provide more complex structured information. These structs and enums live in `types`. There are some simpler types for representing data such as date times or binary blobs that live in `primitives`. All types required to configure a client via the `Config` struct live in `config`. The `operation` module has a submodule for every API, and in each submodule is the input, output, and error type for that API, as well as builders to construct each of those. There is a top-level `Error` type that encompasses all the errors that the client can return. Any other error type can be converted to this `Error` type via the `From` trait. The other modules within this crate are not required for normal usage. Modules --- * clientClient for calling Amazon Managed Grafana. * configConfiguration for Amazon Managed Grafana. * errorCommon errors and error handling utilities. * metaInformation about this crate. * operationAll operations that this crate can perform. * primitivesPrimitives such as `Blob` or `DateTime` used by other types. * typesData structures used by operation inputs/outputs. Structs --- * ClientClient for Amazon Managed Grafana * ConfigConfiguration for a aws_sdk_grafana service client. Enums --- * ErrorAll possible error types for this service. Struct aws_sdk_grafana::client::Client === ``` pub struct Client { /* private fields */ } ``` Client for Amazon Managed Grafana Client for invoking operations on Amazon Managed Grafana. Each operation on Amazon Managed Grafana is a method on this this struct. `.send()` MUST be invoked on the generated operations to dispatch the request to the service. ### Constructing a `Client` A `Config` is required to construct a client. For most use cases, the `aws-config` crate should be used to automatically resolve this config using `aws_config::load_from_env()`, since this will resolve an `SdkConfig` which can be shared across multiple different AWS SDK clients. This config resolution process can be customized by calling `aws_config::from_env()` instead, which returns a `ConfigLoader` that uses the builder pattern to customize the default config. In the simplest case, creating a client looks as follows: ``` let config = aws_config::load_from_env().await; let client = aws_sdk_grafana::Client::new(&config); ``` Occasionally, SDKs may have additional service-specific that can be set on the `Config` that is absent from `SdkConfig`, or slightly different settings for a specific client may be desired. The `Config` struct implements `From<&SdkConfig>`, so setting these specific settings can be done as follows: ``` let sdk_config = ::aws_config::load_from_env().await; let config = aws_sdk_grafana::config::Builder::from(&sdk_config) .some_service_specific_setting("value") .build(); ``` See the `aws-config` docs and `Config` for more information on customizing configuration. *Note:* Client construction is expensive due to connection thread pool initialization, and should be done once at application start-up. Using the `Client` --- A client has a function for every operation that can be performed by the service. For example, the `ListTagsForResource` operation has a `Client::list_tags_for_resource`, function which returns a builder for that operation. The fluent builder ultimately has a `send()` function that returns an async future that returns a result, as illustrated below: ``` let result = client.list_tags_for_resource() .resource_arn("example") .send() .await; ``` The underlying HTTP requests that get made by this can be modified with the `customize_operation` function on the fluent builder. See the `customize` module for more information. Implementations --- ### impl Client #### pub fn associate_license(&self) -> AssociateLicenseFluentBuilder Constructs a fluent builder for the `AssociateLicense` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to associate the license with. + `license_type(LicenseType)` / `set_license_type(Option<LicenseType>)`: The type of license to associate with the workspace. * On success, responds with `AssociateLicenseOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing data about the workspace. * On failure, responds with `SdkError<AssociateLicenseError>` ### impl Client #### pub fn create_workspace(&self) -> CreateWorkspaceFluentBuilder Constructs a fluent builder for the `CreateWorkspace` operation. * The fluent builder is configurable: + `account_access_type(AccountAccessType)` / `set_account_access_type(Option<AccountAccessType>)`: Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify `ORGANIZATION`, you must specify which organizational units the workspace can access in the `workspaceOrganizationalUnits` parameter. + `client_token(impl Into<String>)` / `set_client_token(Option<String>)`: A unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. + `organization_role_name(impl Into<String>)` / `set_organization_role_name(Option<String>)`: The name of an IAM role that already exists to use with Organizations to access Amazon Web Services data sources and notification channels in other accounts in an organization. + `permission_type(PermissionType)` / `set_permission_type(Option<PermissionType>)`: When creating a workspace through the Amazon Web Services API, CLI or Amazon Web Services CloudFormation, you must manage IAM roles and provision the permissions that the workspace needs to use Amazon Web Services data sources and notification channels. You must also specify a `workspaceRoleArn` for a role that you will manage for the workspace to use when accessing those datasources and notification channels. The ability for Amazon Managed Grafana to create and update IAM roles on behalf of the user is supported only in the Amazon Managed Grafana console, where this value may be set to `SERVICE_MANAGED`. Use only the `CUSTOMER_MANAGED` permission type when creating a workspace with the API, CLI or Amazon Web Services CloudFormation. For more information, see Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels. + `stack_set_name(impl Into<String>)` / `set_stack_set_name(Option<String>)`: The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace. + `workspace_data_sources(DataSourceType)` / `set_workspace_data_sources(Option<Vec<DataSourceType>>)`: This parameter is for internal use only, and should not be used. + `workspace_description(impl Into<String>)` / `set_workspace_description(Option<String>)`: A description for the workspace. This is used only to help you identify this workspace. Pattern: `^[\p{L}\p{Z}\p{N}\p{P}]{0,2048}$` + `workspace_name(impl Into<String>)` / `set_workspace_name(Option<String>)`: The name for the workspace. It does not have to be unique. + `workspace_notification_destinations(NotificationDestinationType)` / `set_workspace_notification_destinations(Option<Vec<NotificationDestinationType>>)`: Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels. + `workspace_organizational_units(impl Into<String>)` / `set_workspace_organizational_units(Option<Vec<String>>)`: Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization. + `workspace_role_arn(impl Into<String>)` / `set_workspace_role_arn(Option<String>)`: Specified the IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from, including both data sources and notification channels. You are responsible for managing the permissions for this role as new data sources or notification channels are added. + `authentication_providers(AuthenticationProviderTypes)` / `set_authentication_providers(Option<Vec<AuthenticationProviderTypes>>)`: Specifies whether this workspace uses SAML 2.0, IAM Identity Center (successor to Single Sign-On), or both to authenticate users for using the Grafana console within a workspace. For more information, see User authentication in Amazon Managed Grafana. + `tags(impl Into<String>, impl Into<String>)` / `set_tags(Option<HashMap<String, String>>)`: The list of tags associated with the workspace. + `vpc_configuration(VpcConfiguration)` / `set_vpc_configuration(Option<VpcConfiguration>)`: The configuration settings for an Amazon VPC that contains data sources for your Grafana workspace to connect to. Connecting to a private VPC is not yet available in the Asia Pacific (Seoul) Region (ap-northeast-2). + `configuration(impl Into<String>)` / `set_configuration(Option<String>)`: The configuration string for the workspace that you create. For more information about the format and configuration options available, see Working in your Grafana workspace. + `network_access_control(NetworkAccessConfiguration)` / `set_network_access_control(Option<NetworkAccessConfiguration>)`: Configuration for network access to your workspace. When this is configured, only listed IP addresses and VPC endpoints will be able to access your workspace. Standard Grafana authentication and authorization will still be required. If this is not configured, or is removed, then all IP addresses and VPC endpoints will be allowed. Standard Grafana authentication and authorization will still be required. + `grafana_version(impl Into<String>)` / `set_grafana_version(Option<String>)`: Specifies the version of Grafana to support in the new workspace. To get a list of supported version, use the `ListVersions` operation. * On success, responds with `CreateWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing data about the workspace that was created. * On failure, responds with `SdkError<CreateWorkspaceError>` ### impl Client #### pub fn create_workspace_api_key(&self) -> CreateWorkspaceApiKeyFluentBuilder Constructs a fluent builder for the `CreateWorkspaceApiKey` operation. * The fluent builder is configurable: + `key_name(impl Into<String>)` / `set_key_name(Option<String>)`: Specifies the name of the key. Keynames must be unique to the workspace. + `key_role(impl Into<String>)` / `set_key_role(Option<String>)`: Specifies the permission level of the key. Valid values: `VIEWER`|`EDITOR`|`ADMIN` + `seconds_to_live(i32)` / `set_seconds_to_live(Option<i32>)`: Specifies the time in seconds until the key expires. Keys can be valid for up to 30 days. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to create an API key. * On success, responds with `CreateWorkspaceApiKeyOutput` with field(s): + `key_name(Option<String>)`: The name of the key that was created. + `key(Option<String>)`: The key token. Use this value as a bearer token to authenticate HTTP requests to the workspace. + `workspace_id(Option<String>)`: The ID of the workspace that the key is valid for. * On failure, responds with `SdkError<CreateWorkspaceApiKeyError>` ### impl Client #### pub fn delete_workspace(&self) -> DeleteWorkspaceFluentBuilder Constructs a fluent builder for the `DeleteWorkspace` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to delete. * On success, responds with `DeleteWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing information about the workspace that was deleted. * On failure, responds with `SdkError<DeleteWorkspaceError>` ### impl Client #### pub fn delete_workspace_api_key(&self) -> DeleteWorkspaceApiKeyFluentBuilder Constructs a fluent builder for the `DeleteWorkspaceApiKey` operation. * The fluent builder is configurable: + `key_name(impl Into<String>)` / `set_key_name(Option<String>)`: The name of the API key to delete. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to delete. * On success, responds with `DeleteWorkspaceApiKeyOutput` with field(s): + `key_name(Option<String>)`: The name of the key that was deleted. + `workspace_id(Option<String>)`: The ID of the workspace where the key was deleted. * On failure, responds with `SdkError<DeleteWorkspaceApiKeyError>` ### impl Client #### pub fn describe_workspace(&self) -> DescribeWorkspaceFluentBuilder Constructs a fluent builder for the `DescribeWorkspace` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to display information about. * On success, responds with `DescribeWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing information about the workspace. * On failure, responds with `SdkError<DescribeWorkspaceError>` ### impl Client #### pub fn describe_workspace_authentication( &self ) -> DescribeWorkspaceAuthenticationFluentBuilder Constructs a fluent builder for the `DescribeWorkspaceAuthentication` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to return authentication information about. * On success, responds with `DescribeWorkspaceAuthenticationOutput` with field(s): + `authentication(Option<AuthenticationDescription>)`: A structure containing information about the authentication methods used in the workspace. * On failure, responds with `SdkError<DescribeWorkspaceAuthenticationError>` ### impl Client #### pub fn describe_workspace_configuration( &self ) -> DescribeWorkspaceConfigurationFluentBuilder Constructs a fluent builder for the `DescribeWorkspaceConfiguration` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to get configuration information for. * On success, responds with `DescribeWorkspaceConfigurationOutput` with field(s): + `configuration(Option<String>)`: The configuration string for the workspace that you requested. For more information about the format and configuration options available, see Working in your Grafana workspace. + `grafana_version(Option<String>)`: The supported Grafana version for the workspace. * On failure, responds with `SdkError<DescribeWorkspaceConfigurationError>` ### impl Client #### pub fn disassociate_license(&self) -> DisassociateLicenseFluentBuilder Constructs a fluent builder for the `DisassociateLicense` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to remove the Grafana Enterprise license from. + `license_type(LicenseType)` / `set_license_type(Option<LicenseType>)`: The type of license to remove from the workspace. * On success, responds with `DisassociateLicenseOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing information about the workspace. * On failure, responds with `SdkError<DisassociateLicenseError>` ### impl Client #### pub fn list_permissions(&self) -> ListPermissionsFluentBuilder Constructs a fluent builder for the `ListPermissions` operation. This operation supports pagination; See `into_paginator()`. * The fluent builder is configurable: + `max_results(i32)` / `set_max_results(Option<i32>)`: The maximum number of results to include in the response. + `next_token(impl Into<String>)` / `set_next_token(Option<String>)`: The token to use when requesting the next set of results. You received this token from a previous `ListPermissions` operation. + `user_type(UserType)` / `set_user_type(Option<UserType>)`: (Optional) If you specify `SSO_USER`, then only the permissions of IAM Identity Center users are returned. If you specify `SSO_GROUP`, only the permissions of IAM Identity Center groups are returned. + `user_id(impl Into<String>)` / `set_user_id(Option<String>)`: (Optional) Limits the results to only the user that matches this ID. + `group_id(impl Into<String>)` / `set_group_id(Option<String>)`: (Optional) Limits the results to only the group that matches this ID. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to list permissions for. This parameter is required. * On success, responds with `ListPermissionsOutput` with field(s): + `next_token(Option<String>)`: The token to use in a subsequent `ListPermissions` operation to return the next set of results. + `permissions(Option<Vec<PermissionEntry>>)`: The permissions returned by the operation. * On failure, responds with `SdkError<ListPermissionsError>` ### impl Client #### pub fn list_tags_for_resource(&self) -> ListTagsForResourceFluentBuilder Constructs a fluent builder for the `ListTagsForResource` operation. * The fluent builder is configurable: + `resource_arn(impl Into<String>)` / `set_resource_arn(Option<String>)`: The ARN of the resource the list of tags are associated with. * On success, responds with `ListTagsForResourceOutput` with field(s): + `tags(Option<HashMap<String, String>>)`: The list of tags that are associated with the resource. * On failure, responds with `SdkError<ListTagsForResourceError>` ### impl Client #### pub fn list_versions(&self) -> ListVersionsFluentBuilder Constructs a fluent builder for the `ListVersions` operation. This operation supports pagination; See `into_paginator()`. * The fluent builder is configurable: + `max_results(i32)` / `set_max_results(Option<i32>)`: The maximum number of results to include in the response. + `next_token(impl Into<String>)` / `set_next_token(Option<String>)`: The token to use when requesting the next set of results. You receive this token from a previous `ListVersions` operation. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to list the available upgrade versions. If not included, lists all versions of Grafana that are supported for `CreateWorkspace`. * On success, responds with `ListVersionsOutput` with field(s): + `next_token(Option<String>)`: The token to use in a subsequent `ListVersions` operation to return the next set of results. + `grafana_versions(Option<Vec<String>>)`: The Grafana versions available to create. If a workspace ID is included in the request, the Grafana versions to which this workspace can be upgraded. * On failure, responds with `SdkError<ListVersionsError>` ### impl Client #### pub fn list_workspaces(&self) -> ListWorkspacesFluentBuilder Constructs a fluent builder for the `ListWorkspaces` operation. This operation supports pagination; See `into_paginator()`. * The fluent builder is configurable: + `max_results(i32)` / `set_max_results(Option<i32>)`: The maximum number of workspaces to include in the results. + `next_token(impl Into<String>)` / `set_next_token(Option<String>)`: The token for the next set of workspaces to return. (You receive this token from a previous `ListWorkspaces` operation.) * On success, responds with `ListWorkspacesOutput` with field(s): + `workspaces(Option<Vec<WorkspaceSummary>>)`: An array of structures that contain some information about the workspaces in the account. + `next_token(Option<String>)`: The token to use when requesting the next set of workspaces. * On failure, responds with `SdkError<ListWorkspacesError>` ### impl Client #### pub fn tag_resource(&self) -> TagResourceFluentBuilder Constructs a fluent builder for the `TagResource` operation. * The fluent builder is configurable: + `resource_arn(impl Into<String>)` / `set_resource_arn(Option<String>)`: The ARN of the resource the tag is associated with. + `tags(impl Into<String>, impl Into<String>)` / `set_tags(Option<HashMap<String, String>>)`: The list of tag keys and values to associate with the resource. You can associate tag keys only, tags (key and values) only or a combination of tag keys and tags. * On success, responds with `TagResourceOutput` * On failure, responds with `SdkError<TagResourceError>` ### impl Client #### pub fn untag_resource(&self) -> UntagResourceFluentBuilder Constructs a fluent builder for the `UntagResource` operation. * The fluent builder is configurable: + `resource_arn(impl Into<String>)` / `set_resource_arn(Option<String>)`: The ARN of the resource the tag association is removed from. + `tag_keys(impl Into<String>)` / `set_tag_keys(Option<Vec<String>>)`: The key values of the tag to be removed from the resource. * On success, responds with `UntagResourceOutput` * On failure, responds with `SdkError<UntagResourceError>` ### impl Client #### pub fn update_permissions(&self) -> UpdatePermissionsFluentBuilder Constructs a fluent builder for the `UpdatePermissions` operation. * The fluent builder is configurable: + `update_instruction_batch(UpdateInstruction)` / `set_update_instruction_batch(Option<Vec<UpdateInstruction>>)`: An array of structures that contain the permission updates to make. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update. * On success, responds with `UpdatePermissionsOutput` with field(s): + `errors(Option<Vec<UpdateError>>)`: An array of structures that contain the errors from the operation, if any. * On failure, responds with `SdkError<UpdatePermissionsError>` ### impl Client #### pub fn update_workspace(&self) -> UpdateWorkspaceFluentBuilder Constructs a fluent builder for the `UpdateWorkspace` operation. * The fluent builder is configurable: + `account_access_type(AccountAccessType)` / `set_account_access_type(Option<AccountAccessType>)`: Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify `ORGANIZATION`, you must specify which organizational units the workspace can access in the `workspaceOrganizationalUnits` parameter. + `organization_role_name(impl Into<String>)` / `set_organization_role_name(Option<String>)`: The name of an IAM role that already exists to use to access resources through Organizations. This can only be used with a workspace that has the `permissionType` set to `CUSTOMER_MANAGED`. + `permission_type(PermissionType)` / `set_permission_type(Option<PermissionType>)`: Use this parameter if you want to change a workspace from `SERVICE_MANAGED` to `CUSTOMER_MANAGED`. This allows you to manage the permissions that the workspace uses to access datasources and notification channels. If the workspace is in a member Amazon Web Services account of an organization, and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose `CUSTOMER_MANAGED`. If you specify this as `CUSTOMER_MANAGED`, you must also specify a `workspaceRoleArn` that the workspace will use for accessing Amazon Web Services resources. For more information on the role and permissions needed, see Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels Do not use this to convert a `CUSTOMER_MANAGED` workspace to `SERVICE_MANAGED`. Do not include this parameter if you want to leave the workspace as `SERVICE_MANAGED`. You can convert a `CUSTOMER_MANAGED` workspace to `SERVICE_MANAGED` using the Amazon Managed Grafana console. For more information, see Managing permissions for data sources and notification channels. + `stack_set_name(impl Into<String>)` / `set_stack_set_name(Option<String>)`: The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace. + `workspace_data_sources(DataSourceType)` / `set_workspace_data_sources(Option<Vec<DataSourceType>>)`: This parameter is for internal use only, and should not be used. + `workspace_description(impl Into<String>)` / `set_workspace_description(Option<String>)`: A description for the workspace. This is used only to help you identify this workspace. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update. + `workspace_name(impl Into<String>)` / `set_workspace_name(Option<String>)`: A new name for the workspace to update. + `workspace_notification_destinations(NotificationDestinationType)` / `set_workspace_notification_destinations(Option<Vec<NotificationDestinationType>>)`: Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels. + `workspace_organizational_units(impl Into<String>)` / `set_workspace_organizational_units(Option<Vec<String>>)`: Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization. + `workspace_role_arn(impl Into<String>)` / `set_workspace_role_arn(Option<String>)`: Specifies an IAM role that grants permissions to Amazon Web Services resources that the workspace accesses, such as data sources and notification channels. If this workspace has `permissionType` `CUSTOMER_MANAGED`, then this role is required. + `vpc_configuration(VpcConfiguration)` / `set_vpc_configuration(Option<VpcConfiguration>)`: The configuration settings for an Amazon VPC that contains data sources for your Grafana workspace to connect to. + `remove_vpc_configuration(bool)` / `set_remove_vpc_configuration(Option<bool>)`: Whether to remove the VPC configuration from the workspace. Setting this to `true` and providing a `vpcConfiguration` to set will return an error. + `network_access_control(NetworkAccessConfiguration)` / `set_network_access_control(Option<NetworkAccessConfiguration>)`: The configuration settings for network access to your workspace. When this is configured, only listed IP addresses and VPC endpoints will be able to access your workspace. Standard Grafana authentication and authorization will still be required. If this is not configured, or is removed, then all IP addresses and VPC endpoints will be allowed. Standard Grafana authentication and authorization will still be required. + `remove_network_access_configuration(bool)` / `set_remove_network_access_configuration(Option<bool>)`: Whether to remove the network access configuration from the workspace. Setting this to `true` and providing a `networkAccessControl` to set will return an error. If you remove this configuration by setting this to `true`, then all IP addresses and VPC endpoints will be allowed. Standard Grafana authentication and authorization will still be required. * On success, responds with `UpdateWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing data about the workspace that was created. * On failure, responds with `SdkError<UpdateWorkspaceError>` ### impl Client #### pub fn update_workspace_authentication( &self ) -> UpdateWorkspaceAuthenticationFluentBuilder Constructs a fluent builder for the `UpdateWorkspaceAuthentication` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update the authentication for. + `authentication_providers(AuthenticationProviderTypes)` / `set_authentication_providers(Option<Vec<AuthenticationProviderTypes>>)`: Specifies whether this workspace uses SAML 2.0, IAM Identity Center (successor to Single Sign-On), or both to authenticate users for using the Grafana console within a workspace. For more information, see User authentication in Amazon Managed Grafana. + `saml_configuration(SamlConfiguration)` / `set_saml_configuration(Option<SamlConfiguration>)`: If the workspace uses SAML, use this structure to map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the `Admin` and `Editor` roles in the workspace. * On success, responds with `UpdateWorkspaceAuthenticationOutput` with field(s): + `authentication(Option<AuthenticationDescription>)`: A structure that describes the user authentication for this workspace after the update is made. * On failure, responds with `SdkError<UpdateWorkspaceAuthenticationError>` ### impl Client #### pub fn update_workspace_configuration( &self ) -> UpdateWorkspaceConfigurationFluentBuilder Constructs a fluent builder for the `UpdateWorkspaceConfiguration` operation. * The fluent builder is configurable: + `configuration(impl Into<String>)` / `set_configuration(Option<String>)`: The new configuration string for the workspace. For more information about the format and configuration options available, see Working in your Grafana workspace. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update. + `grafana_version(impl Into<String>)` / `set_grafana_version(Option<String>)`: Specifies the version of Grafana to support in the new workspace. Can only be used to upgrade (for example, from 8.4 to 9.4), not downgrade (for example, from 9.4 to 8.4). To know what versions are available to upgrade to for a specific workspace, see the `ListVersions` operation. * On success, responds with `UpdateWorkspaceConfigurationOutput` * On failure, responds with `SdkError<UpdateWorkspaceConfigurationError>` ### impl Client #### pub fn from_conf(conf: Config) -> Self Creates a new client from the service `Config`. ##### Panics This method will panic if the `conf` has retry or timeouts enabled without a `sleep_impl`. If you experience this panic, it can be fixed by setting the `sleep_impl`, or by disabling retries and timeouts. #### pub fn config(&self) -> &Config Returns the client’s configuration. ### impl Client #### pub fn new(sdk_config: &SdkConfig) -> Self Creates a new client from an SDK Config. ##### Panics * This method will panic if the `sdk_config` is missing an async sleep implementation. If you experience this panic, set the `sleep_impl` on the Config passed into this function to fix it. * This method will panic if the `sdk_config` is missing an HTTP connector. If you experience this panic, set the `http_connector` on the Config passed into this function to fix it. Trait Implementations --- ### impl Clone for Client #### fn clone(&self) -> Client Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl !RefUnwindSafe for Client ### impl Send for Client ### impl Sync for Client ### impl Unpin for Client ### impl !UnwindSafe for Client Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Same<T> for T #### type Output = T Should always be `Self`### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct aws_sdk_grafana::Client === ``` pub struct Client { /* private fields */ } ``` Client for Amazon Managed Grafana Client for invoking operations on Amazon Managed Grafana. Each operation on Amazon Managed Grafana is a method on this this struct. `.send()` MUST be invoked on the generated operations to dispatch the request to the service. ### Constructing a `Client` A `Config` is required to construct a client. For most use cases, the `aws-config` crate should be used to automatically resolve this config using `aws_config::load_from_env()`, since this will resolve an `SdkConfig` which can be shared across multiple different AWS SDK clients. This config resolution process can be customized by calling `aws_config::from_env()` instead, which returns a `ConfigLoader` that uses the builder pattern to customize the default config. In the simplest case, creating a client looks as follows: ``` let config = aws_config::load_from_env().await; let client = aws_sdk_grafana::Client::new(&config); ``` Occasionally, SDKs may have additional service-specific that can be set on the `Config` that is absent from `SdkConfig`, or slightly different settings for a specific client may be desired. The `Config` struct implements `From<&SdkConfig>`, so setting these specific settings can be done as follows: ``` let sdk_config = ::aws_config::load_from_env().await; let config = aws_sdk_grafana::config::Builder::from(&sdk_config) .some_service_specific_setting("value") .build(); ``` See the `aws-config` docs and `Config` for more information on customizing configuration. *Note:* Client construction is expensive due to connection thread pool initialization, and should be done once at application start-up. Using the `Client` --- A client has a function for every operation that can be performed by the service. For example, the `ListTagsForResource` operation has a `Client::list_tags_for_resource`, function which returns a builder for that operation. The fluent builder ultimately has a `send()` function that returns an async future that returns a result, as illustrated below: ``` let result = client.list_tags_for_resource() .resource_arn("example") .send() .await; ``` The underlying HTTP requests that get made by this can be modified with the `customize_operation` function on the fluent builder. See the `customize` module for more information. Implementations --- ### impl Client #### pub fn associate_license(&self) -> AssociateLicenseFluentBuilder Constructs a fluent builder for the `AssociateLicense` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to associate the license with. + `license_type(LicenseType)` / `set_license_type(Option<LicenseType>)`: The type of license to associate with the workspace. * On success, responds with `AssociateLicenseOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing data about the workspace. * On failure, responds with `SdkError<AssociateLicenseError>` ### impl Client #### pub fn create_workspace(&self) -> CreateWorkspaceFluentBuilder Constructs a fluent builder for the `CreateWorkspace` operation. * The fluent builder is configurable: + `account_access_type(AccountAccessType)` / `set_account_access_type(Option<AccountAccessType>)`: Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify `ORGANIZATION`, you must specify which organizational units the workspace can access in the `workspaceOrganizationalUnits` parameter. + `client_token(impl Into<String>)` / `set_client_token(Option<String>)`: A unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. + `organization_role_name(impl Into<String>)` / `set_organization_role_name(Option<String>)`: The name of an IAM role that already exists to use with Organizations to access Amazon Web Services data sources and notification channels in other accounts in an organization. + `permission_type(PermissionType)` / `set_permission_type(Option<PermissionType>)`: When creating a workspace through the Amazon Web Services API, CLI or Amazon Web Services CloudFormation, you must manage IAM roles and provision the permissions that the workspace needs to use Amazon Web Services data sources and notification channels. You must also specify a `workspaceRoleArn` for a role that you will manage for the workspace to use when accessing those datasources and notification channels. The ability for Amazon Managed Grafana to create and update IAM roles on behalf of the user is supported only in the Amazon Managed Grafana console, where this value may be set to `SERVICE_MANAGED`. Use only the `CUSTOMER_MANAGED` permission type when creating a workspace with the API, CLI or Amazon Web Services CloudFormation. For more information, see Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels. + `stack_set_name(impl Into<String>)` / `set_stack_set_name(Option<String>)`: The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace. + `workspace_data_sources(DataSourceType)` / `set_workspace_data_sources(Option<Vec<DataSourceType>>)`: This parameter is for internal use only, and should not be used. + `workspace_description(impl Into<String>)` / `set_workspace_description(Option<String>)`: A description for the workspace. This is used only to help you identify this workspace. Pattern: `^[\p{L}\p{Z}\p{N}\p{P}]{0,2048}$` + `workspace_name(impl Into<String>)` / `set_workspace_name(Option<String>)`: The name for the workspace. It does not have to be unique. + `workspace_notification_destinations(NotificationDestinationType)` / `set_workspace_notification_destinations(Option<Vec<NotificationDestinationType>>)`: Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels. + `workspace_organizational_units(impl Into<String>)` / `set_workspace_organizational_units(Option<Vec<String>>)`: Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization. + `workspace_role_arn(impl Into<String>)` / `set_workspace_role_arn(Option<String>)`: Specified the IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from, including both data sources and notification channels. You are responsible for managing the permissions for this role as new data sources or notification channels are added. + `authentication_providers(AuthenticationProviderTypes)` / `set_authentication_providers(Option<Vec<AuthenticationProviderTypes>>)`: Specifies whether this workspace uses SAML 2.0, IAM Identity Center (successor to Single Sign-On), or both to authenticate users for using the Grafana console within a workspace. For more information, see User authentication in Amazon Managed Grafana. + `tags(impl Into<String>, impl Into<String>)` / `set_tags(Option<HashMap<String, String>>)`: The list of tags associated with the workspace. + `vpc_configuration(VpcConfiguration)` / `set_vpc_configuration(Option<VpcConfiguration>)`: The configuration settings for an Amazon VPC that contains data sources for your Grafana workspace to connect to. Connecting to a private VPC is not yet available in the Asia Pacific (Seoul) Region (ap-northeast-2). + `configuration(impl Into<String>)` / `set_configuration(Option<String>)`: The configuration string for the workspace that you create. For more information about the format and configuration options available, see Working in your Grafana workspace. + `network_access_control(NetworkAccessConfiguration)` / `set_network_access_control(Option<NetworkAccessConfiguration>)`: Configuration for network access to your workspace. When this is configured, only listed IP addresses and VPC endpoints will be able to access your workspace. Standard Grafana authentication and authorization will still be required. If this is not configured, or is removed, then all IP addresses and VPC endpoints will be allowed. Standard Grafana authentication and authorization will still be required. + `grafana_version(impl Into<String>)` / `set_grafana_version(Option<String>)`: Specifies the version of Grafana to support in the new workspace. To get a list of supported version, use the `ListVersions` operation. * On success, responds with `CreateWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing data about the workspace that was created. * On failure, responds with `SdkError<CreateWorkspaceError>` ### impl Client #### pub fn create_workspace_api_key(&self) -> CreateWorkspaceApiKeyFluentBuilder Constructs a fluent builder for the `CreateWorkspaceApiKey` operation. * The fluent builder is configurable: + `key_name(impl Into<String>)` / `set_key_name(Option<String>)`: Specifies the name of the key. Keynames must be unique to the workspace. + `key_role(impl Into<String>)` / `set_key_role(Option<String>)`: Specifies the permission level of the key. Valid values: `VIEWER`|`EDITOR`|`ADMIN` + `seconds_to_live(i32)` / `set_seconds_to_live(Option<i32>)`: Specifies the time in seconds until the key expires. Keys can be valid for up to 30 days. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to create an API key. * On success, responds with `CreateWorkspaceApiKeyOutput` with field(s): + `key_name(Option<String>)`: The name of the key that was created. + `key(Option<String>)`: The key token. Use this value as a bearer token to authenticate HTTP requests to the workspace. + `workspace_id(Option<String>)`: The ID of the workspace that the key is valid for. * On failure, responds with `SdkError<CreateWorkspaceApiKeyError>` ### impl Client #### pub fn delete_workspace(&self) -> DeleteWorkspaceFluentBuilder Constructs a fluent builder for the `DeleteWorkspace` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to delete. * On success, responds with `DeleteWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing information about the workspace that was deleted. * On failure, responds with `SdkError<DeleteWorkspaceError>` ### impl Client #### pub fn delete_workspace_api_key(&self) -> DeleteWorkspaceApiKeyFluentBuilder Constructs a fluent builder for the `DeleteWorkspaceApiKey` operation. * The fluent builder is configurable: + `key_name(impl Into<String>)` / `set_key_name(Option<String>)`: The name of the API key to delete. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to delete. * On success, responds with `DeleteWorkspaceApiKeyOutput` with field(s): + `key_name(Option<String>)`: The name of the key that was deleted. + `workspace_id(Option<String>)`: The ID of the workspace where the key was deleted. * On failure, responds with `SdkError<DeleteWorkspaceApiKeyError>` ### impl Client #### pub fn describe_workspace(&self) -> DescribeWorkspaceFluentBuilder Constructs a fluent builder for the `DescribeWorkspace` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to display information about. * On success, responds with `DescribeWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing information about the workspace. * On failure, responds with `SdkError<DescribeWorkspaceError>` ### impl Client #### pub fn describe_workspace_authentication( &self ) -> DescribeWorkspaceAuthenticationFluentBuilder Constructs a fluent builder for the `DescribeWorkspaceAuthentication` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to return authentication information about. * On success, responds with `DescribeWorkspaceAuthenticationOutput` with field(s): + `authentication(Option<AuthenticationDescription>)`: A structure containing information about the authentication methods used in the workspace. * On failure, responds with `SdkError<DescribeWorkspaceAuthenticationError>` ### impl Client #### pub fn describe_workspace_configuration( &self ) -> DescribeWorkspaceConfigurationFluentBuilder Constructs a fluent builder for the `DescribeWorkspaceConfiguration` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to get configuration information for. * On success, responds with `DescribeWorkspaceConfigurationOutput` with field(s): + `configuration(Option<String>)`: The configuration string for the workspace that you requested. For more information about the format and configuration options available, see Working in your Grafana workspace. + `grafana_version(Option<String>)`: The supported Grafana version for the workspace. * On failure, responds with `SdkError<DescribeWorkspaceConfigurationError>` ### impl Client #### pub fn disassociate_license(&self) -> DisassociateLicenseFluentBuilder Constructs a fluent builder for the `DisassociateLicense` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to remove the Grafana Enterprise license from. + `license_type(LicenseType)` / `set_license_type(Option<LicenseType>)`: The type of license to remove from the workspace. * On success, responds with `DisassociateLicenseOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing information about the workspace. * On failure, responds with `SdkError<DisassociateLicenseError>` ### impl Client #### pub fn list_permissions(&self) -> ListPermissionsFluentBuilder Constructs a fluent builder for the `ListPermissions` operation. This operation supports pagination; See `into_paginator()`. * The fluent builder is configurable: + `max_results(i32)` / `set_max_results(Option<i32>)`: The maximum number of results to include in the response. + `next_token(impl Into<String>)` / `set_next_token(Option<String>)`: The token to use when requesting the next set of results. You received this token from a previous `ListPermissions` operation. + `user_type(UserType)` / `set_user_type(Option<UserType>)`: (Optional) If you specify `SSO_USER`, then only the permissions of IAM Identity Center users are returned. If you specify `SSO_GROUP`, only the permissions of IAM Identity Center groups are returned. + `user_id(impl Into<String>)` / `set_user_id(Option<String>)`: (Optional) Limits the results to only the user that matches this ID. + `group_id(impl Into<String>)` / `set_group_id(Option<String>)`: (Optional) Limits the results to only the group that matches this ID. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to list permissions for. This parameter is required. * On success, responds with `ListPermissionsOutput` with field(s): + `next_token(Option<String>)`: The token to use in a subsequent `ListPermissions` operation to return the next set of results. + `permissions(Option<Vec<PermissionEntry>>)`: The permissions returned by the operation. * On failure, responds with `SdkError<ListPermissionsError>` ### impl Client #### pub fn list_tags_for_resource(&self) -> ListTagsForResourceFluentBuilder Constructs a fluent builder for the `ListTagsForResource` operation. * The fluent builder is configurable: + `resource_arn(impl Into<String>)` / `set_resource_arn(Option<String>)`: The ARN of the resource the list of tags are associated with. * On success, responds with `ListTagsForResourceOutput` with field(s): + `tags(Option<HashMap<String, String>>)`: The list of tags that are associated with the resource. * On failure, responds with `SdkError<ListTagsForResourceError>` ### impl Client #### pub fn list_versions(&self) -> ListVersionsFluentBuilder Constructs a fluent builder for the `ListVersions` operation. This operation supports pagination; See `into_paginator()`. * The fluent builder is configurable: + `max_results(i32)` / `set_max_results(Option<i32>)`: The maximum number of results to include in the response. + `next_token(impl Into<String>)` / `set_next_token(Option<String>)`: The token to use when requesting the next set of results. You receive this token from a previous `ListVersions` operation. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to list the available upgrade versions. If not included, lists all versions of Grafana that are supported for `CreateWorkspace`. * On success, responds with `ListVersionsOutput` with field(s): + `next_token(Option<String>)`: The token to use in a subsequent `ListVersions` operation to return the next set of results. + `grafana_versions(Option<Vec<String>>)`: The Grafana versions available to create. If a workspace ID is included in the request, the Grafana versions to which this workspace can be upgraded. * On failure, responds with `SdkError<ListVersionsError>` ### impl Client #### pub fn list_workspaces(&self) -> ListWorkspacesFluentBuilder Constructs a fluent builder for the `ListWorkspaces` operation. This operation supports pagination; See `into_paginator()`. * The fluent builder is configurable: + `max_results(i32)` / `set_max_results(Option<i32>)`: The maximum number of workspaces to include in the results. + `next_token(impl Into<String>)` / `set_next_token(Option<String>)`: The token for the next set of workspaces to return. (You receive this token from a previous `ListWorkspaces` operation.) * On success, responds with `ListWorkspacesOutput` with field(s): + `workspaces(Option<Vec<WorkspaceSummary>>)`: An array of structures that contain some information about the workspaces in the account. + `next_token(Option<String>)`: The token to use when requesting the next set of workspaces. * On failure, responds with `SdkError<ListWorkspacesError>` ### impl Client #### pub fn tag_resource(&self) -> TagResourceFluentBuilder Constructs a fluent builder for the `TagResource` operation. * The fluent builder is configurable: + `resource_arn(impl Into<String>)` / `set_resource_arn(Option<String>)`: The ARN of the resource the tag is associated with. + `tags(impl Into<String>, impl Into<String>)` / `set_tags(Option<HashMap<String, String>>)`: The list of tag keys and values to associate with the resource. You can associate tag keys only, tags (key and values) only or a combination of tag keys and tags. * On success, responds with `TagResourceOutput` * On failure, responds with `SdkError<TagResourceError>` ### impl Client #### pub fn untag_resource(&self) -> UntagResourceFluentBuilder Constructs a fluent builder for the `UntagResource` operation. * The fluent builder is configurable: + `resource_arn(impl Into<String>)` / `set_resource_arn(Option<String>)`: The ARN of the resource the tag association is removed from. + `tag_keys(impl Into<String>)` / `set_tag_keys(Option<Vec<String>>)`: The key values of the tag to be removed from the resource. * On success, responds with `UntagResourceOutput` * On failure, responds with `SdkError<UntagResourceError>` ### impl Client #### pub fn update_permissions(&self) -> UpdatePermissionsFluentBuilder Constructs a fluent builder for the `UpdatePermissions` operation. * The fluent builder is configurable: + `update_instruction_batch(UpdateInstruction)` / `set_update_instruction_batch(Option<Vec<UpdateInstruction>>)`: An array of structures that contain the permission updates to make. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update. * On success, responds with `UpdatePermissionsOutput` with field(s): + `errors(Option<Vec<UpdateError>>)`: An array of structures that contain the errors from the operation, if any. * On failure, responds with `SdkError<UpdatePermissionsError>` ### impl Client #### pub fn update_workspace(&self) -> UpdateWorkspaceFluentBuilder Constructs a fluent builder for the `UpdateWorkspace` operation. * The fluent builder is configurable: + `account_access_type(AccountAccessType)` / `set_account_access_type(Option<AccountAccessType>)`: Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify `ORGANIZATION`, you must specify which organizational units the workspace can access in the `workspaceOrganizationalUnits` parameter. + `organization_role_name(impl Into<String>)` / `set_organization_role_name(Option<String>)`: The name of an IAM role that already exists to use to access resources through Organizations. This can only be used with a workspace that has the `permissionType` set to `CUSTOMER_MANAGED`. + `permission_type(PermissionType)` / `set_permission_type(Option<PermissionType>)`: Use this parameter if you want to change a workspace from `SERVICE_MANAGED` to `CUSTOMER_MANAGED`. This allows you to manage the permissions that the workspace uses to access datasources and notification channels. If the workspace is in a member Amazon Web Services account of an organization, and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose `CUSTOMER_MANAGED`. If you specify this as `CUSTOMER_MANAGED`, you must also specify a `workspaceRoleArn` that the workspace will use for accessing Amazon Web Services resources. For more information on the role and permissions needed, see Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels Do not use this to convert a `CUSTOMER_MANAGED` workspace to `SERVICE_MANAGED`. Do not include this parameter if you want to leave the workspace as `SERVICE_MANAGED`. You can convert a `CUSTOMER_MANAGED` workspace to `SERVICE_MANAGED` using the Amazon Managed Grafana console. For more information, see Managing permissions for data sources and notification channels. + `stack_set_name(impl Into<String>)` / `set_stack_set_name(Option<String>)`: The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace. + `workspace_data_sources(DataSourceType)` / `set_workspace_data_sources(Option<Vec<DataSourceType>>)`: This parameter is for internal use only, and should not be used. + `workspace_description(impl Into<String>)` / `set_workspace_description(Option<String>)`: A description for the workspace. This is used only to help you identify this workspace. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update. + `workspace_name(impl Into<String>)` / `set_workspace_name(Option<String>)`: A new name for the workspace to update. + `workspace_notification_destinations(NotificationDestinationType)` / `set_workspace_notification_destinations(Option<Vec<NotificationDestinationType>>)`: Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels. + `workspace_organizational_units(impl Into<String>)` / `set_workspace_organizational_units(Option<Vec<String>>)`: Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization. + `workspace_role_arn(impl Into<String>)` / `set_workspace_role_arn(Option<String>)`: Specifies an IAM role that grants permissions to Amazon Web Services resources that the workspace accesses, such as data sources and notification channels. If this workspace has `permissionType` `CUSTOMER_MANAGED`, then this role is required. + `vpc_configuration(VpcConfiguration)` / `set_vpc_configuration(Option<VpcConfiguration>)`: The configuration settings for an Amazon VPC that contains data sources for your Grafana workspace to connect to. + `remove_vpc_configuration(bool)` / `set_remove_vpc_configuration(Option<bool>)`: Whether to remove the VPC configuration from the workspace. Setting this to `true` and providing a `vpcConfiguration` to set will return an error. + `network_access_control(NetworkAccessConfiguration)` / `set_network_access_control(Option<NetworkAccessConfiguration>)`: The configuration settings for network access to your workspace. When this is configured, only listed IP addresses and VPC endpoints will be able to access your workspace. Standard Grafana authentication and authorization will still be required. If this is not configured, or is removed, then all IP addresses and VPC endpoints will be allowed. Standard Grafana authentication and authorization will still be required. + `remove_network_access_configuration(bool)` / `set_remove_network_access_configuration(Option<bool>)`: Whether to remove the network access configuration from the workspace. Setting this to `true` and providing a `networkAccessControl` to set will return an error. If you remove this configuration by setting this to `true`, then all IP addresses and VPC endpoints will be allowed. Standard Grafana authentication and authorization will still be required. * On success, responds with `UpdateWorkspaceOutput` with field(s): + `workspace(Option<WorkspaceDescription>)`: A structure containing data about the workspace that was created. * On failure, responds with `SdkError<UpdateWorkspaceError>` ### impl Client #### pub fn update_workspace_authentication( &self ) -> UpdateWorkspaceAuthenticationFluentBuilder Constructs a fluent builder for the `UpdateWorkspaceAuthentication` operation. * The fluent builder is configurable: + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update the authentication for. + `authentication_providers(AuthenticationProviderTypes)` / `set_authentication_providers(Option<Vec<AuthenticationProviderTypes>>)`: Specifies whether this workspace uses SAML 2.0, IAM Identity Center (successor to Single Sign-On), or both to authenticate users for using the Grafana console within a workspace. For more information, see User authentication in Amazon Managed Grafana. + `saml_configuration(SamlConfiguration)` / `set_saml_configuration(Option<SamlConfiguration>)`: If the workspace uses SAML, use this structure to map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the `Admin` and `Editor` roles in the workspace. * On success, responds with `UpdateWorkspaceAuthenticationOutput` with field(s): + `authentication(Option<AuthenticationDescription>)`: A structure that describes the user authentication for this workspace after the update is made. * On failure, responds with `SdkError<UpdateWorkspaceAuthenticationError>` ### impl Client #### pub fn update_workspace_configuration( &self ) -> UpdateWorkspaceConfigurationFluentBuilder Constructs a fluent builder for the `UpdateWorkspaceConfiguration` operation. * The fluent builder is configurable: + `configuration(impl Into<String>)` / `set_configuration(Option<String>)`: The new configuration string for the workspace. For more information about the format and configuration options available, see Working in your Grafana workspace. + `workspace_id(impl Into<String>)` / `set_workspace_id(Option<String>)`: The ID of the workspace to update. + `grafana_version(impl Into<String>)` / `set_grafana_version(Option<String>)`: Specifies the version of Grafana to support in the new workspace. Can only be used to upgrade (for example, from 8.4 to 9.4), not downgrade (for example, from 9.4 to 8.4). To know what versions are available to upgrade to for a specific workspace, see the `ListVersions` operation. * On success, responds with `UpdateWorkspaceConfigurationOutput` * On failure, responds with `SdkError<UpdateWorkspaceConfigurationError>` ### impl Client #### pub fn from_conf(conf: Config) -> Self Creates a new client from the service `Config`. ##### Panics This method will panic if the `conf` has retry or timeouts enabled without a `sleep_impl`. If you experience this panic, it can be fixed by setting the `sleep_impl`, or by disabling retries and timeouts. #### pub fn config(&self) -> &Config Returns the client’s configuration. ### impl Client #### pub fn new(sdk_config: &SdkConfig) -> Self Creates a new client from an SDK Config. ##### Panics * This method will panic if the `sdk_config` is missing an async sleep implementation. If you experience this panic, set the `sleep_impl` on the Config passed into this function to fix it. * This method will panic if the `sdk_config` is missing an HTTP connector. If you experience this panic, set the `http_connector` on the Config passed into this function to fix it. Trait Implementations --- ### impl Clone for Client #### fn clone(&self) -> Client Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl !RefUnwindSafe for Client ### impl Send for Client ### impl Sync for Client ### impl Unpin for Client ### impl !UnwindSafe for Client Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Same<T> for T #### type Output = T Should always be `Self`### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Type Alias aws_sdk_grafana::error::SdkError === ``` pub type SdkError<E, R = HttpResponse> = SdkError<E, R>; ``` Error type returned by the client. Aliased Type --- ``` enum SdkError<E, R = HttpResponse> { ConstructionFailure(ConstructionFailure), TimeoutError(TimeoutError), DispatchFailure(DispatchFailure), ResponseError(ResponseError<R>), ServiceError(ServiceError<E, R>), } ``` Variants --- ### ConstructionFailure(ConstructionFailure) The request failed during construction. It was not dispatched over the network. ### TimeoutError(TimeoutError) The request failed due to a timeout. The request MAY have been sent and received. ### DispatchFailure(DispatchFailure) The request failed during dispatch. An HTTP response was not received. The request MAY have been sent. ### ResponseError(ResponseError<R>) A response was received but it was not parseable according the the protocol (for example the server hung up without sending a complete response) ### ServiceError(ServiceError<E, R>) An error response was received from the service Trait Implementations --- ### impl<E, R> ProvideErrorMetadata for SdkError<E, R>where E: ProvideErrorMetadata, #### fn meta(&self) -> &ErrorMetadata Returns error metadata, which includes the error code, message, request ID, and potentially additional information.#### fn code(&self) -> Option<&strReturns the error code if it’s available.#### fn message(&self) -> Option<&strReturns the error message, if there is one.### impl<E, R> RequestId for SdkError<E, R>where R: HttpHeaders, #### fn request_id(&self) -> Option<&strReturns the request ID, or `None` if the service could not be reached. Module aws_sdk_grafana::types === Data structures used by operation inputs/outputs. Modules --- * buildersBuilders * errorError types that Amazon Managed Grafana can respond with. Structs --- * AssertionAttributesA structure that defines which attributes in the IdP assertion are to be used to define information about the users authenticated by the IdP to use the workspace. * AuthenticationDescriptionA structure containing information about the user authentication methods used by the workspace. * AuthenticationSummaryA structure that describes whether the workspace uses SAML, IAM Identity Center, or both methods for user authentication, and whether that authentication is fully configured. * AwsSsoAuthenticationA structure containing information about how this workspace works with IAM Identity Center. * NetworkAccessConfigurationThe configuration settings for in-bound network access to your workspace. * PermissionEntryA structure containing the identity of one user or group and the `Admin`, `Editor`, or `Viewer` role that they have. * RoleValuesThis structure defines which groups defined in the SAML assertion attribute are to be mapped to the Grafana `Admin` and `Editor` roles in the workspace. SAML authenticated users not part of `Admin` or `Editor` role groups have `Viewer` permission over the workspace. * SamlAuthenticationA structure containing information about how this workspace works with SAML. * SamlConfigurationA structure containing information about how this workspace works with SAML. * UpdateErrorA structure containing information about one error encountered while performing an UpdatePermissions operation. * UpdateInstructionContains the instructions for one Grafana role permission update in a UpdatePermissions operation. * UserA structure that specifies one user or group in the workspace. * ValidationExceptionFieldA structure that contains information about a request parameter that caused an error. * VpcConfigurationThe configuration settings for an Amazon VPC that contains data sources for your Grafana workspace to connect to. * WorkspaceDescriptionA structure containing information about an Amazon Managed Grafana workspace in your account. * WorkspaceSummaryA structure that contains some information about one workspace in the account. Enums --- * AccountAccessTypeWhen writing a match expression against `AccountAccessType`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * AuthenticationProviderTypesWhen writing a match expression against `AuthenticationProviderTypes`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * DataSourceTypeWhen writing a match expression against `DataSourceType`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * IdpMetadataA structure containing the identity provider (IdP) metadata used to integrate the identity provider with this workspace. You can specify the metadata either by providing a URL to its location in the `url` parameter, or by specifying the full metadata in XML format in the `xml` parameter. Specifying both will cause an error. * LicenseTypeWhen writing a match expression against `LicenseType`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * NotificationDestinationTypeWhen writing a match expression against `NotificationDestinationType`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * PermissionTypeWhen writing a match expression against `PermissionType`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * RoleWhen writing a match expression against `Role`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * SamlConfigurationStatusWhen writing a match expression against `SamlConfigurationStatus`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * UpdateActionWhen writing a match expression against `UpdateAction`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * UserTypeWhen writing a match expression against `UserType`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * ValidationExceptionReasonWhen writing a match expression against `ValidationExceptionReason`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. * WorkspaceStatusWhen writing a match expression against `WorkspaceStatus`, it is important to ensure your code is forward-compatible. That is, if a match arm handles a case for a feature that is supported by the service but has not been represented as an enum variant in a current version of SDK, your code should continue to work when you upgrade SDK to a future version in which the enum does include a variant for that feature. Module aws_sdk_grafana::primitives === Primitives such as `Blob` or `DateTime` used by other types. Structs --- * DateTimeDateTime in time. * UnknownVariantValueOpaque struct used as inner data for the `Unknown` variant defined in enums in the crate Enums --- * DateTimeFormatFormats for representing a `DateTime` in the Smithy protocols. Struct aws_sdk_grafana::Config === ``` pub struct Config { /* private fields */ } ``` Configuration for a aws_sdk_grafana service client. Service configuration allows for customization of endpoints, region, credentials providers, and retry configuration. Generally, it is constructed automatically for you from a shared configuration loaded by the `aws-config` crate. For example: ``` // Load a shared config from the environment let shared_config = aws_config::from_env().load().await; // The client constructor automatically converts the shared config into the service config let client = Client::new(&shared_config); ``` The service config can also be constructed manually using its builder. Implementations --- ### impl Config #### pub fn builder() -> Builder Constructs a config builder. #### pub fn to_builder(&self) -> Builder Converts this config back into a builder so that it can be tweaked. #### pub fn idempotency_token_provider(&self) -> IdempotencyTokenProvider Returns a copy of the idempotency token provider. If a random token provider was configured, a newly-randomized token provider will be returned. #### pub fn http_connector(&self) -> Option<SharedHttpConnectorReturn the `SharedHttpConnector` to use when making requests, if any. #### pub fn endpoint_resolver(&self) -> SharedEndpointResolver Returns the endpoint resolver. #### pub fn retry_config(&self) -> Option<&RetryConfigReturn a reference to the retry configuration contained in this config, if any. #### pub fn sleep_impl(&self) -> Option<SharedAsyncSleepReturn a cloned shared async sleep implementation from this config, if any. #### pub fn timeout_config(&self) -> Option<&TimeoutConfigReturn a reference to the timeout configuration contained in this config, if any. #### pub fn interceptors(&self) -> impl Iterator<Item = SharedInterceptor> + '_ Returns interceptors currently registered by the user. #### pub fn time_source(&self) -> Option<SharedTimeSourceReturn time source used for this service. #### pub fn app_name(&self) -> Option<&AppNameReturns the name of the app that is using the client, if it was provided. This *optional* name is used to identify the application in the user agent that gets sent along with requests. #### pub fn invocation_id_generator(&self) -> Option<SharedInvocationIdGeneratorReturns the invocation ID generator if one was given in config. The invocation ID generator generates ID values for the `amz-sdk-invocation-id` header. By default, this will be a random UUID. Overriding it may be useful in tests that examine the HTTP request and need to be deterministic. #### pub fn new(config: &SdkConfig) -> Self Creates a new service config from a shared `config`. #### pub fn signing_service(&self) -> &'static str The signature version 4 service signing name to use in the credential scope when signing requests. The signing service may be overridden by the `Endpoint`, or by specifying a custom `SigningService` during operation construction #### pub fn region(&self) -> Option<&RegionReturns the AWS region, if it was provided. #### pub fn credentials_cache(&self) -> Option<SharedCredentialsCacheReturns the credentials cache. Trait Implementations --- ### impl Clone for Config #### fn clone(&self) -> Config Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(sdk_config: &SdkConfig) -> Self Converts to this type from the input type.Auto Trait Implementations --- ### impl !RefUnwindSafe for Config ### impl Send for Config ### impl Sync for Config ### impl Unpin for Config ### impl !UnwindSafe for Config Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Same<T> for T #### type Output = T Should always be `Self`### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Module aws_sdk_grafana::config === Configuration for Amazon Managed Grafana. Modules --- * endpointTypes needed to configure endpoint resolution. * interceptorsTypes needed to implement `Interceptor`. * retryRetry configuration. * timeoutTimeout configuration. Structs --- * AppNameApp name that can be configured with an AWS SDK client to become part of the user agent string. * BuilderBuilder for creating a `Config`. * ConfigConfiguration for a aws_sdk_grafana service client. * ConfigBagLayered configuration structure * CredentialsAWS SDK Credentials * RegionThe region to send requests to. * RuntimeComponentsComponents that can only be set in runtime plugins that the orchestrator uses directly to call an operation. * SharedAsyncSleepWrapper type for sharable `AsyncSleep` * SharedInterceptorInterceptor wrapper that may be shared * SleepFuture returned by `AsyncSleep`. Traits --- * AsyncSleepAsync trait with a `sleep` function. * InterceptorAn interceptor allows injecting code into the SDK ’s request execution pipeline. Module aws_sdk_grafana::operation === All operations that this crate can perform. Modules --- * associate_licenseTypes for the `AssociateLicense` operation. * create_workspaceTypes for the `CreateWorkspace` operation. * create_workspace_api_keyTypes for the `CreateWorkspaceApiKey` operation. * delete_workspaceTypes for the `DeleteWorkspace` operation. * delete_workspace_api_keyTypes for the `DeleteWorkspaceApiKey` operation. * describe_workspaceTypes for the `DescribeWorkspace` operation. * describe_workspace_authenticationTypes for the `DescribeWorkspaceAuthentication` operation. * describe_workspace_configurationTypes for the `DescribeWorkspaceConfiguration` operation. * disassociate_licenseTypes for the `DisassociateLicense` operation. * list_permissionsTypes for the `ListPermissions` operation. * list_tags_for_resourceTypes for the `ListTagsForResource` operation. * list_versionsTypes for the `ListVersions` operation. * list_workspacesTypes for the `ListWorkspaces` operation. * tag_resourceTypes for the `TagResource` operation. * untag_resourceTypes for the `UntagResource` operation. * update_permissionsTypes for the `UpdatePermissions` operation. * update_workspaceTypes for the `UpdateWorkspace` operation. * update_workspace_authenticationTypes for the `UpdateWorkspaceAuthentication` operation. * update_workspace_configurationTypes for the `UpdateWorkspaceConfiguration` operation. Traits --- * RequestIdImplementers add a function to return an AWS request ID Enum aws_sdk_grafana::Error === ``` #[non_exhaustive]pub enum Error { AccessDeniedException(AccessDeniedException), ConflictException(ConflictException), InternalServerException(InternalServerException), ResourceNotFoundException(ResourceNotFoundException), ServiceQuotaExceededException(ServiceQuotaExceededException), ThrottlingException(ThrottlingException), ValidationException(ValidationException), Unhandled(Unhandled), } ``` All possible error types for this service. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### AccessDeniedException(AccessDeniedException) You do not have sufficient permissions to perform this action. ### ConflictException(ConflictException) A resource was in an inconsistent state during an update or a deletion. ### InternalServerException(InternalServerException) Unexpected error while processing the request. Retry the request. ### ResourceNotFoundException(ResourceNotFoundException) The request references a resource that does not exist. ### ServiceQuotaExceededException(ServiceQuotaExceededException) The request would cause a service quota to be exceeded. ### ThrottlingException(ThrottlingException) The request was denied because of request throttling. Retry the request. ### ValidationException(ValidationException) The value of a parameter in the request caused an error. ### Unhandled(Unhandled) An unexpected error occurred (e.g., invalid JSON returned by the service or an unknown error code). Trait Implementations --- ### impl Debug for Error #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(err: AssociateLicenseError) -> Self Converts to this type from the input type.### impl From<CreateWorkspaceApiKeyError> for Error #### fn from(err: CreateWorkspaceApiKeyError) -> Self Converts to this type from the input type.### impl From<CreateWorkspaceError> for Error #### fn from(err: CreateWorkspaceError) -> Self Converts to this type from the input type.### impl From<DeleteWorkspaceApiKeyError> for Error #### fn from(err: DeleteWorkspaceApiKeyError) -> Self Converts to this type from the input type.### impl From<DeleteWorkspaceError> for Error #### fn from(err: DeleteWorkspaceError) -> Self Converts to this type from the input type.### impl From<DescribeWorkspaceAuthenticationError> for Error #### fn from(err: DescribeWorkspaceAuthenticationError) -> Self Converts to this type from the input type.### impl From<DescribeWorkspaceConfigurationError> for Error #### fn from(err: DescribeWorkspaceConfigurationError) -> Self Converts to this type from the input type.### impl From<DescribeWorkspaceError> for Error #### fn from(err: DescribeWorkspaceError) -> Self Converts to this type from the input type.### impl From<DisassociateLicenseError> for Error #### fn from(err: DisassociateLicenseError) -> Self Converts to this type from the input type.### impl From<ListPermissionsError> for Error #### fn from(err: ListPermissionsError) -> Self Converts to this type from the input type.### impl From<ListTagsForResourceError> for Error #### fn from(err: ListTagsForResourceError) -> Self Converts to this type from the input type.### impl From<ListVersionsError> for Error #### fn from(err: ListVersionsError) -> Self Converts to this type from the input type.### impl From<ListWorkspacesError> for Error #### fn from(err: ListWorkspacesError) -> Self Converts to this type from the input type.### impl<R> From<SdkError<AssociateLicenseError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<AssociateLicenseError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<CreateWorkspaceApiKeyError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<CreateWorkspaceApiKeyError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<CreateWorkspaceError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<CreateWorkspaceError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<DeleteWorkspaceApiKeyError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<DeleteWorkspaceApiKeyError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<DeleteWorkspaceError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<DeleteWorkspaceError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<DescribeWorkspaceAuthenticationError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<DescribeWorkspaceAuthenticationError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<DescribeWorkspaceConfigurationError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<DescribeWorkspaceConfigurationError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<DescribeWorkspaceError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<DescribeWorkspaceError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<DisassociateLicenseError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<DisassociateLicenseError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<ListPermissionsError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<ListPermissionsError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<ListTagsForResourceError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<ListTagsForResourceError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<ListVersionsError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<ListVersionsError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<ListWorkspacesError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<ListWorkspacesError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<TagResourceError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<TagResourceError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<UntagResourceError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<UntagResourceError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<UpdatePermissionsError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<UpdatePermissionsError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<UpdateWorkspaceAuthenticationError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<UpdateWorkspaceAuthenticationError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<UpdateWorkspaceConfigurationError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<UpdateWorkspaceConfigurationError, R>) -> Self Converts to this type from the input type.### impl<R> From<SdkError<UpdateWorkspaceError, R>> for Errorwhere R: Send + Sync + Debug + 'static, #### fn from(err: SdkError<UpdateWorkspaceError, R>) -> Self Converts to this type from the input type.### impl From<TagResourceError> for Error #### fn from(err: TagResourceError) -> Self Converts to this type from the input type.### impl From<UntagResourceError> for Error #### fn from(err: UntagResourceError) -> Self Converts to this type from the input type.### impl From<UpdatePermissionsError> for Error #### fn from(err: UpdatePermissionsError) -> Self Converts to this type from the input type.### impl From<UpdateWorkspaceAuthenticationError> for Error #### fn from(err: UpdateWorkspaceAuthenticationError) -> Self Converts to this type from the input type.### impl From<UpdateWorkspaceConfigurationError> for Error #### fn from(err: UpdateWorkspaceConfigurationError) -> Self Converts to this type from the input type.### impl From<UpdateWorkspaceError> for Error #### fn from(err: UpdateWorkspaceError) -> Self Converts to this type from the input type.### impl RequestId for Error #### fn request_id(&self) -> Option<&strReturns the request ID, or `None` if the service could not be reached.Auto Trait Implementations --- ### impl !RefUnwindSafe for Error ### impl Send for Error ### impl Sync for Error ### impl Unpin for Error ### impl !UnwindSafe for Error Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Same<T> for T #### type Output = T Should always be `Self`### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Module aws_sdk_grafana::client === Client for calling Amazon Managed Grafana. ### Constructing a `Client` A `Config` is required to construct a client. For most use cases, the `aws-config` crate should be used to automatically resolve this config using `aws_config::load_from_env()`, since this will resolve an `SdkConfig` which can be shared across multiple different AWS SDK clients. This config resolution process can be customized by calling `aws_config::from_env()` instead, which returns a `ConfigLoader` that uses the builder pattern to customize the default config. In the simplest case, creating a client looks as follows: ``` let config = aws_config::load_from_env().await; let client = aws_sdk_grafana::Client::new(&config); ``` Occasionally, SDKs may have additional service-specific that can be set on the `Config` that is absent from `SdkConfig`, or slightly different settings for a specific client may be desired. The `Config` struct implements `From<&SdkConfig>`, so setting these specific settings can be done as follows: ``` let sdk_config = ::aws_config::load_from_env().await; let config = aws_sdk_grafana::config::Builder::from(&sdk_config) .some_service_specific_setting("value") .build(); ``` See the `aws-config` docs and `Config` for more information on customizing configuration. *Note:* Client construction is expensive due to connection thread pool initialization, and should be done once at application start-up. Using the `Client` --- A client has a function for every operation that can be performed by the service. For example, the `ListTagsForResource` operation has a `Client::list_tags_for_resource`, function which returns a builder for that operation. The fluent builder ultimately has a `send()` function that returns an async future that returns a result, as illustrated below: ``` let result = client.list_tags_for_resource() .resource_arn("example") .send() .await; ``` The underlying HTTP requests that get made by this can be modified with the `customize_operation` function on the fluent builder. See the `customize` module for more information. Modules --- * customizeOperation customization and supporting types. Structs --- * ClientClient for Amazon Managed Grafana Module aws_sdk_grafana::error === Common errors and error handling utilities. Structs --- * DisplayErrorContextProvides a `Display` impl for an `Error` that outputs the full error context Traits --- * ProvideErrorMetadataTrait to retrieve error metadata from a result Type Aliases --- * BoxErrorA boxed error that is `Send` and `Sync`. * SdkErrorError type returned by the client. Module aws_sdk_grafana::meta === Information about this crate. Statics --- * PKG_VERSIONCrate version number.
@pythonit/apollo-server-lambda-with-cors-regex
npm
JavaScript
This is the AWS Lambda integration of GraphQL Server. Apollo Server is a community-maintained open-source GraphQL server that works with many Node.js HTTP server frameworks. [Read the docs](https://www.apollographql.com/docs/apollo-server/v2). [Read the CHANGELOG](https://github.com/apollographql/apollo-server/blob/main/CHANGELOG.md). ``` npm install apollo-server-lambda graphql ``` Deploying with AWS Serverless Application Model (SAM) --- To deploy the AWS Lambda function we must create a Cloudformation Template and a S3 bucket to store the artifact (zip of source code) and template. We will use the [AWS Command Line Interface](https://aws.amazon.com/cli/). #### 1. Write the API handlers In a file named `graphql.js`, place the following code: ``` const { ApolloServer, gql } = require('apollo-server-lambda'); // Construct a schema, using GraphQL schema language const typeDefs = gql` type Query { hello: String } `; // Provide resolver functions for your schema fields const resolvers = { Query: { hello: () => 'Hello world!', }, }; const server = new ApolloServer({ typeDefs, resolvers, // By default, the GraphQL Playground interface and GraphQL introspection // is disabled in "production" (i.e. when `process.env.NODE_ENV` is `production`). // // If you'd like to have GraphQL Playground and introspection enabled in production, // the `playground` and `introspection` options must be set explicitly to `true`. playground: true, introspection: true, }); exports.handler = server.createHandler(); ``` #### 2. Create an S3 bucket The bucket name must be universally unique. ``` aws s3 mb s3://<bucket name> ``` #### 3. Create the Template This will look for a file called graphql.js with the export `graphqlHandler`. It creates one API endpoints: * `/graphql` (GET and POST) In a file called `template.yaml`: ``` AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: GraphQL: Type: AWS::Serverless::Function Properties: Handler: graphql.handler Runtime: nodejs12.x Events: AnyRequest: Type: Api Properties: Path: /graphql Method: ANY ``` #### 4. Package source code and dependencies This will read and transform the template, created in previous step. Package and upload the artifact to the S3 bucket and generate another template for the deployment. ``` aws cloudformation package \ --template-file template.yaml \ --output-template-file serverless-output.yaml \ --s3-bucket <bucket-name> ``` #### 5. Deploy the API This will create the Lambda Function and API Gateway for GraphQL. We use the stack-name `prod` to mean production but any stack name can be used. ``` aws cloudformation deploy \ --template-file serverless-output.yaml \ --stack-name prod \ --capabilities CAPABILITY_IAM ``` Getting request info --- To read information about the current request from the API Gateway event (HTTP headers, HTTP method, body, path, ...) or the current Lambda Context (Function Name, Function Version, awsRequestId, time remaining, ...) use the options function. This way they can be passed to your schema resolvers using the context option. ``` const { ApolloServer, gql } = require('apollo-server-lambda'); // Construct a schema, using GraphQL schema language const typeDefs = gql` type Query { hello: String } `; // Provide resolver functions for your schema fields const resolvers = { Query: { hello: () => 'Hello world!', }, }; const server = new ApolloServer({ typeDefs, resolvers, context: ({ event, context }) => ({ headers: event.headers, functionName: context.functionName, event, context, }), }); exports.handler = server.createHandler(); ``` Modifying the Lambda Response (Enable CORS) --- To enable CORS the response HTTP headers need to be modified. To accomplish this use the `cors` option. ``` const { ApolloServer, gql } = require('apollo-server-lambda'); // Construct a schema, using GraphQL schema language const typeDefs = gql` type Query { hello: String } `; // Provide resolver functions for your schema fields const resolvers = { Query: { hello: () => 'Hello world!', }, }; const server = new ApolloServer({ typeDefs, resolvers, }); exports.handler = server.createHandler({ cors: { origin: '*', credentials: true, }, }); ``` To enable CORS response for requests with credentials (cookies, http authentication) the allow origin header must equal the request origin and the allow credential header must be set to true. ``` const { ApolloServer, gql } = require('apollo-server-lambda'); // Construct a schema, using GraphQL schema language const typeDefs = gql` type Query { hello: String } `; // Provide resolver functions for your schema fields const resolvers = { Query: { hello: () => 'Hello world!', }, }; const server = new ApolloServer({ typeDefs, resolvers, }); exports.handler = server.createHandler({ cors: { origin: true, credentials: true, }, }); ``` ### Cors Options The options correspond to the [express cors configuration](https://github.com/expressjs/cors#configuration-options) with the following fields(all are optional): * `origin`: boolean | string | string[] * `methods`: string | string[] * `allowedHeaders`: string | string[] * `exposedHeaders`: string | string[] * `credentials`: boolean * `maxAge`: number Principles --- GraphQL Server is built with the following principles in mind: * **By the community, for the community**: GraphQL Server's development is driven by the needs of developers * **Simplicity**: by keeping things simple, GraphQL Server is easier to use, easier to contribute to, and more secure * **Performance**: GraphQL Server is well-tested and production-ready - no modifications needed Anyone is welcome to contribute to GraphQL Server, just read [CONTRIBUTING.md](https://github.com/apollographql/apollo-server/blob/main/CONTRIBUTING.md), take a look at the [roadmap](https://github.com/apollographql/apollo-server/blob/main/ROADMAP.md) and make your first PR! Readme --- ### Keywords * GraphQL * Apollo * Server * Lambda * Javascript
rpmodel
cran
R
Package ‘rpmodel’ October 14, 2022 Type Package Title P-Model Description Implements the P-model (Stocker et al., 2020 <doi:10.5194/gmd-13-1545-2020>), predicting acclimated parameters of the enzyme kinetics of C3 photosynthesis, assimilation, and dark respiration rates as a function of the environment (temperature, CO2, vapour pressure deficit, light, atmospheric pressure). Version 1.2.0 License GPL-3 Encoding UTF-8 RoxygenNote 7.1.1 Depends R (>= 3.6) Suggests ggplot2, dplyr, purrr, tidyr, knitr, testthat, covr, markdown VignetteBuilder knitr URL https://github.com/stineb/rpmodel BugReports https://github.com/stineb/rpmodel/issues NeedsCompilation no Author <NAME> [aut, cre] (<https://orcid.org/0000-0002-5070-8109>), <NAME> [ctb] (<https://orcid.org/0000-0002-5070-8109>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2021-06-09 10:00:02 UTC R topics documented: co2_to_c... 2 dampen_ve... 2 density_h2... 3 ftemp_arr... 4 ftemp_inst_jma... 5 ftemp_inst_r... 6 ftemp_inst_vcma... 7 ftemp_kphi... 8 gammasta... 9 km... 10 pat... 11 rpmode... 12 soilmstres... 17 viscosity_h2... 18 co2_to_ca CO2 partial pressure Description Calculates CO2 partial pressure from concentration in ppm. Usage co2_to_ca(co2, patm) Arguments co2 Atmospheric CO2 concentration (ppm) patm Atmospheric pressure (Pa). Value CO2 partial pressure in Pa. dampen_vec Dampen inputs of rpmodel Description Applies an exponential dampening input time series with specified time scale. Usage dampen_vec(vec, tau) Arguments vec A numeric vector for the time series of a daily meteorological variable used as input for rpmodel (temperature, vapour pressure deficit, CO2, or atmospheric pressure). The length of x must be at least 365, i.e., corresponding to one year. tau The time scale of dampening (e-folding time scale of a perturbation). Must be smaller or equal to 365 d. Value A numeric vector of equal length as x with damped variation. The dampening is calculated as: S(t + 1) − S(t) = (X(t + 1) − S(t))/τ Where X is the daily varying time series given by argument x, S is the dampened time returned by this function, and τ is the decay time scale of a perturbation, given by argument tau. Examples ## Not run: dampen_vec( vec = 20 * (sin(doy*pi/(365)))^2 + rnorm(365, mean = 0, sd = 5), tau = 40 ) ## End(Not run) density_h2o Density of water Description Calculates the density of water as a function of temperature and atmospheric pressure, using the Tumlirz Equation. Usage density_h2o(tc, p) Arguments tc numeric, air temperature (tc), degrees C p numeric, atmospheric pressure (p), Pa Value numeric, density of water, kg/m^3 References <NAME> and <NAME>, Jr. (1975) Equation of state of pure water and sea water, Tech. Rept., Marine Physical Laboratory, San Diego, CA. Examples # Density of water at 20 degrees C and standard atmospheric pressure print(density_h2o(20, 101325)) ftemp_arrh Calculates the Arrhenius-type temperature response Description Given a kinetic rate at a reference temperature (argument tkref) this function calculates its temperature- scaling factor following Arrhenius kinetics. Usage ftemp_arrh(tk, dha, tkref = 298.15) Arguments tk Temperature (Kelvin) dha Activation energy (J mol-1) tkref Reference temperature (Kelvin) Details To correct for effects by temperature following Arrhenius kinetics, and given a reference temper- ature T0 , f calculates the temperature scaling. Arrhenius kinetics are described by an equation of form x(T ) = exp(c − ∆Ha /(T R)). The temperature-correction function f (T, ∆Ha ) is thus given by f = x(T )/x(T0 ) which is: f = exp(∆Ha (T − T0 )/(T0 RTK )) ∆Ha is given by argument dha. T is given by argument tk and has to be provided in Kelvin. R is the universal gas constant and is 8.3145 J mol-1 K-1. Note that this is equivalent to f = exp((∆Ha /R)(1/T0 − 1/T )) Value A numeric value for f Examples # Relative rate change from 25 to 10 degrees Celsius (percent change) print( (1.0-ftemp_arrh( 283.15, 100000, tkref = 298.15))*100 ) ftemp_inst_jmax Calculates the instantaneous temperature response of Jmax Description Given Jmax at a reference temperature (argument tcref) this function calculates its temperature- scaling factor following modified Arrhenius kinetics based on Kattge & Knorr (2007). Calculates f for the conversion V = f V ref Usage ftemp_inst_jmax(tcleaf, tcgrowth = tcleaf, tcref = 25) Arguments tcleaf Leaf temperature, or in general the temperature relevant for photosynthesis (de- grees Celsius) tcgrowth (Optional) Growth temperature, in the P-model, taken to be equal to tcleaf (in degrees Celsius). Defaults to tcgrowth = tcleaf. tcref Reference temperature (in degrees Celsius) Details The function is given by Kattge & Knorr (2007) as f v = f (T, ∆Hv)A/B where f (T, ∆Hv) is a regular Arrhenius-type temperature response function (see ftemp_arrh) with Hv = 49884 J mol-1, A = 1 + exp((T 0∆S − Hd)/(T 0R)) and B = 1 + exp((T ∆S − Hd)/(T KR)) Here, T is in Kelvin, T 0 = 293.15 K, Hd = 200000 J mol-1 is the deactivation energy and R is the universal gas constant and is 8.3145 J mol-1 K-1, and ∆S = aS − bST with aS = 659.70 J mol-1 K-1, and bS = 0.75 J mol-1 K-2, and T given in degrees Celsius (!) Value A numeric value for f v References <NAME>. and <NAME>.: Temperature acclimation in a biochemical model of photosynthesis: a reanalysis of data from 36 species, Plant, Cell and Environment, 30,1176–1190, 2007. Examples # Relative change in Jmax going (instantaneously, i.e. # not acclimatedly) from 10 to 25 degrees (percent change): print((ftemp_inst_jmax(25)/ftemp_inst_jmax(10)-1)*100 ) ftemp_inst_rd Calculates the temperature response of dark respiration Description Given the dark respiration at the reference temperature 25 degress Celsius, this function calculates its temperature-scaling factor following Heskel et al. 2016. Usage ftemp_inst_rd(tc) Arguments tc Temperature (degrees Celsius) Details To correct for effects by temperature Heskel et al. 2016, and given the reference temperature T 0 = 25 deg C, this calculates the temperature scaling factor to calculate dark respiration at temperature T (argument tc) as: f r = exp(0.1012(T 0 − T ) − 0.0005(T 02 − T 2 )) where T is given in degrees Celsius. Value A numeric value for f r References <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,and <NAME>.: Convergence in the temperature response of leaf respiration across biomes and plant functional types, Proceedings of the National Academy of Sciences, 113, 3832–3837, doi:10.1073/pnas.1520282113,2016. Examples ## Relative change in Rd going (instantaneously, i.e. not ## acclimatedly) from 10 to 25 degrees (percent change): print( (ftemp_inst_rd(25)/ftemp_inst_rd(10)-1)*100 ) ftemp_inst_vcmax Calculates the instantaneous temperature response of Vcmax Description Given Vcmax at a reference temperature (argument tcref) this function calculates its temperature- scaling factor following modified Arrhenius kinetics based on Kattge & Knorr (2007). Calculates f for the conversion V = f V ref Usage ftemp_inst_vcmax(tcleaf, tcgrowth = tcleaf, tcref = 25) Arguments tcleaf Leaf temperature, or in general the temperature relevant for photosynthesis (de- grees Celsius) tcgrowth (Optional) Growth temperature, in the P-model, taken to be equal to tcleaf (in degrees Celsius). Defaults to tcgrowth = tcleaf. tcref Reference temperature (in degrees Celsius) Details The function is given by Kattge & Knorr (2007) as f v = f (T, ∆Hv)A/B where f (T, ∆Hv) is a regular Arrhenius-type temperature response function (see ftemp_arrh) with Hv = 71513 J mol-1, A = 1 + exp((T 0∆S − Hd)/(T 0R)) and B = 1 + exp((T ∆S − Hd)/(T KR)) Here, T is in Kelvin, T 0 = 293.15 K, Hd = 200000 J mol-1 is the deactivation energy and R is the universal gas constant and is 8.3145 J mol-1 K-1, and ∆S = aS − bST with aS = 668.39 J mol-1 K-1, and bS = 1.07 J mol-1 K-2, and T given in degrees Celsius (!) Value A numeric value for f v References <NAME>. and <NAME>.: Temperature acclimation in a biochemical model of photosynthesis: a reanalysis of data from 36 species, Plant, Cell and Environment, 30,1176–1190, 2007. Examples ## Relative change in Vcmax going (instantaneously, i.e. ## not acclimatedly) from 10 to 25 degrees (percent change): print((ftemp_inst_vcmax(25)/ftemp_inst_vcmax(10)-1)*100 ) ftemp_kphio Calculates the temperature dependence of the quantum yield efficiency Description Calculates the temperature dependence of the quantum yield efficiency following the temperature dependence of the maximum quantum yield of photosystem II in light-adapted tobacco leaves, determined by Bernacchi et al. (2003) Usage ftemp_kphio(tc, c4 = FALSE) Arguments tc Temperature, relevant for photosynthesis (degrees Celsius) c4 Boolean specifying whether fitted temperature response for C4 plants is used. Defaults to FALSE (C3 photoynthesis temperature resposne following Bernacchi et al., 2003 is used). Details The temperature factor for C3 photosynthesis (argument c4 = FALSE) is calculated based on Bernac- chi et al. (2003) as φ(T ) = 0.352 + 0.022T − 0.00034T 2 The temperature factor for C4 (argument c4 = TRUE) photosynthesis is calculated based on unpub- lished work as φ(T ) = −0.008 + 0.00375T − 0.58e − 4T 2 The factor φ(T ) is to be multiplied with leaf absorptance and the fraction of absorbed light that reaches photosystem II. In the P-model these additional factors are lumped into a single apparent quantum yield efficiency parameter (argument kphio to function rpmodel). Value A numeric value for φ(T ) References <NAME>., <NAME>., and <NAME>.: In vivo temperature response func-tions of parame- ters required to model RuBP-limited photosynthesis, Plant Cell Environ., 26, 1419–1430, 2003 Examples ## Relative change in the quantum yield efficiency ## between 5 and 25 degrees celsius (percent change): print(paste((ftemp_kphio(25.0)/ftemp_kphio(5.0)-1)*100 )) gammastar Calculates the CO2 compensation point Description Calculates the photorespiratory CO2 compensation point in absence of dark respiration, Γ∗ (Far- quhar, 1980). Usage gammastar(tc, patm) Arguments tc Temperature, relevant for photosynthesis (degrees Celsius) patm Atmospheric pressure (Pa) Details The temperature and pressure-dependent photorespiratory compensation point in absence of dark respiration Γ ∗ (T, p) is calculated from its value at standard temperature (T 0 = 25deg C) and atmospheric pressure (p0 = 101325 Pa), referred to as Γ ∗ 0, quantified by Bernacchi et al. (2001) to 4.332 Pa (their value in molar concentration units is multiplied here with 101325 Pa to yield 4.332 Pa). Γ ∗ 0 is modified by temperature following an Arrhenius-type temperature response function f (T, ∆Ha) (implemented by ftemp_arrh) with activation energy ∆Ha = 37830 J mol-1 and is corrected for atmospheric pressure p(z) (see patm) at elevation z. Γ∗ = Γ ∗ 0f (T, ∆Ha)p(z)/p0 p(z) is given by argument patm. Value A numeric value for Γ∗ (in Pa) References <NAME>., <NAME>., and <NAME>.: A biochemical model of photosynthetic CO2 assimilation in leaves of C 3 species, Planta, 149, 78–90, 1980. <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>.:Improved temper- ature response functions for models of Rubisco-limited photosyn-thesis, Plant, Cell and Environ- ment, 24, 253–259, 2001 Examples print("CO2 compensation point at 20 degrees Celsius and standard atmosphere (in Pa):") print(gammastar(20, 101325)) kmm Calculates the Michaelis Menten coefficient for Rubisco-limited pho- tosynthesis Description Calculates the Michaelis Menten coefficient of Rubisco-limited assimilation as a function of tem- perature and atmospheric pressure. Usage kmm(tc, patm) Arguments tc Temperature, relevant for photosynthesis (deg C) patm Atmospheric pressure (Pa) Details The Michaelis-Menten coefficient K of Rubisco-limited photosynthesis is determined by the Michalis- Menten constants for O2 and CO2 (Farquhar, 1980) according to: K = Kc(1 + pO2/Ko) where Kc is the Michaelis-Menten constant for CO2 (Pa), Ko is the Michaelis-Menten constant for O2 (Pa), and pO2 is the partial pressure of oxygen (Pa), calculated as 0.209476p, where p is given by argument patm. Kc and Ko follow a temperature dependence, given by the Arrhenius Equation f (implemented by ftemp_arrh): Kc = Kc25f (T, ∆Hkc) Ko = Ko25f (T, ∆Hko) Values ∆Hkc (79430 J mol-1), ∆Hko (36380 J mol-1), Kc25 (39.97 Pa), and Ko25 (27480 Pa) are taken from Bernacchi et al. (2001) and have been converted from values given therein to units of Pa by multiplication with the standard atmosphere (101325 Pa). T is given by the argument tc. Value A numeric value for K (in Pa) References <NAME>., <NAME>., and <NAME>.: A biochemical model of photosynthetic CO2 assimilation in leaves of C 3 species, Planta, 149, 78–90, 1980. <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>.:Improved temper- ature response functions for models of Rubisco-limited photosyn-thesis, Plant, Cell and Environ- ment, 24, 253–259, 2001 Examples print("Michaelis-Menten coefficient at 20 degrees Celsius and standard atmosphere (in Pa):") print(kmm(20, 101325)) patm Calculates atmospheric pressure Description Calculates atmospheric pressure as a function of elevation, by default assuming standard atmo- sphere (101325 Pa at sea level) Usage patm(elv, patm0 = 101325) Arguments elv Elevation above sea-level (m.a.s.l.) patm0 (Optional) Atmospheric pressure at sea level (Pa), defaults to 101325 Pa. Details The elevation-dependence of atmospheric pressure is computed by assuming a linear decrease in temperature with elevation and a mean adiabatic lapse rate (Berberan-Santos et al., 1997): p(z) = p0(1 − Lz/T K0)( gM/(RL)) where z is the elevation above mean sea level (m, argument elv), g is the gravity constant (9.80665 m s-2), p0 is the atmospheric pressure at 0 m a.s.l. (argument patm0, defaults to 101325 Pa), L is the mean adiabatic lapse rate (0.0065 K m-2), M is the molecular weight for dry air (0.028963 kg mol-1), R is the universal gas constant (8.3145 J mol-1 K-1), and T K0 is the standard temperature (298.15 K, corresponds to 25 deg C). Value A numeric value for p References <NAME>., <NAME>., <NAME>., <NAME>.: FAO Irrigation and Drainage Paper No. 56, Food and Agriculture Organization of the United Nations, 1998 Examples print("Standard atmospheric pressure, in Pa, corrected for 1000 m.a.s.l.:") print(patm(1000)) rpmodel Invokes a P-model function call Description R implementation of the P-model and its corollary predictions (Prentice et al., 2014; Han et al., 2017). Usage rpmodel( tc, vpd, co2, fapar, ppfd, patm = NA, elv = NA, kphio = ifelse(do_ftemp_kphio, ifelse(do_soilmstress, 0.087182, 0.081785), 0.049977), beta = 146, soilm = stopifnot(!do_soilmstress), meanalpha = 1, apar_soilm = 0, bpar_soilm = 0.733, c4 = FALSE, method_optci = "prentice14", method_jmaxlim = "wang17", do_ftemp_kphio = TRUE, do_soilmstress = FALSE, returnvar = NULL, verbose = FALSE ) Arguments tc Temperature, relevant for photosynthesis (deg C) vpd Vapour pressure deficit (Pa) co2 Atmospheric CO2 concentration (ppm) fapar (Optional) Fraction of absorbed photosynthetically active radiation (unitless, de- faults to NA) ppfd Incident photosynthetic photon flux density (mol m-2 d-1, defaults to NA). Note that the units of ppfd (per area and per time) determine the units of outputs lue, gpp, vcmax, and rd. For example, if ppfd is provided in units of mol m-2 month-1, then respective output variables are returned as per unit months. patm Atmospheric pressure (Pa). When provided, overrides elv, otherwise patm is calculated using standard atmosphere (101325 Pa), corrected for elevation (ar- gument elv), using the function patm. elv Elevation above sea-level (m.a.s.l.). Is used only for calculating atmospheric pressure (using standard atmosphere (101325 Pa), corrected for elevation (ar- gument elv), using the function patm), if argument patm is not provided. If argument patm is provided, elv is overridden. kphio Apparent quantum yield efficiency (unitless). Defaults to 0.081785 for method_jmaxlim="wang17", do_ftemp_kphio=TRUE,do_soilmstress=FALSE, 0.087182 for method_jmaxlim="wang17",do_ftemp do_soilmstress=TRUE, and 0.049977 for method_jmaxlim="wang17", do_ftemp_kphio=FALSE, do_soilmstress=FALSE, corresponding to the empirically fitted value as pre- sented in Stocker et al. (2019) Geosci. Model Dev. for model setup ’BRC’, ’FULL’, and ’ORG’ respectively. beta Unit cost ratio. Defaults to 146.0 (see Stocker et al., 2019). soilm (Optional, used only if do_soilmstress==TRUE) Relative soil moisture as a fraction of field capacity (unitless). Defaults to 1.0 (no soil moisture stress). This information is used to calculate an empirical soil moisture stress factor (soilmstress) whereby the sensitivity is determined by average aridity, defined by the local annual mean ratio of actual over potential evapotranspiration, sup- plied by argument meanalpha. meanalpha (Optional, used only if do_soilmstress==TRUE) Local annual mean ratio of actual over potential evapotranspiration, measure for average aridity. Defaults to 1.0. apar_soilm (Optional, used only if do_soilmstress==TRUE) Parameter determining the sensitivity of the empirical soil moisture stress function. Defaults to 0.0, the em- pirically fitted value as presented in Stocker et al. (2019) Geosci. Model Dev. for model setup ’FULL’ (corresponding to a setup with method_jmaxlim="wang17",do_ftemp_kphio=TRUE do_soilmstress=TRUE). bpar_soilm (Optional, used only if do_soilmstress==TRUE) Parameter determining the sensitivity of the empirical soil moisture stress function. Defaults to 0.7330, the empirically fitted value as presented in Stocker et al. (2019) Geosci. Model Dev. for model setup ’FULL’ (corresponding to a setup with method_jmaxlim="wang17",do_ftemp_kphio=T do_soilmstress=TRUE). c4 (Optional) A logical value specifying whether the C3 or C4 photosynthetic path- way is followed.Defaults to FALSE. If TRUE, the leaf-internal CO2 concentration is assumed to be very large and m (returned variable mj) tends to 1, and m0 tends to 0.669 (with c = 0.41). method_optci (Optional) A character string specifying which method is to be used for calculat- ing optimal ci:ca. Defaults to "prentice14". Available also "prentice14_num" for a numerical solution to the same optimization criterium as used for "prentice14". method_jmaxlim (Optional) A character string specifying which method is to be used for factoring in Jmax limitation. Defaults to "wang17", based on Wang Han et al. 2017 Nature Plants and (Smith 1937). Available is also "smith19", following the method by Smith et al., 2019 Ecology Letters, and "none" for ignoring effects of Jmax limitation. do_ftemp_kphio (Optional) A logical specifying whether temperature-dependence of quantum yield efficiency after Bernacchi et al., 2003 is to be accounted for. Defaults to TRUE. do_soilmstress (Optional) A logical specifying whether an empirical soil moisture stress factor is to be applied to down-scale light use efficiency (and only light use efficiency). Defaults to FALSE. returnvar (Optional) A character string of vector of character strings specifying which variables are to be returned (see return below). verbose Logical, defines whether verbose messages are printed. Defaults to FALSE. Value A named list of numeric values (including temperature and pressure dependent parameters of the photosynthesis model, P-model predictions, including all its corollary). This includes : • ca: Ambient CO2 expressed as partial pressure (Pa) • gammastar: Photorespiratory compensation point Γ∗, (Pa), see gammastar. • kmm: Michaelis-Menten coefficient K for photosynthesis (Pa), see kmm. • ns_star: Change in the viscosity of water, relative to its value at 25 deg C (unitless). η∗ = η(T )/η(25degC) This is used to scale the unit cost of transpiration. Calculated following Huber et al. (2009). • chi: Optimal ratio of leaf internal to ambient CO2 (unitless). Derived following Prentice et χ = Γ ∗ /ca + (1 − Γ ∗ /ca)ξ/(ξ + D) with p ξ= (β(K + Γ∗)/(1.6η∗)) β is given by argument beta, K is kmm (see kmm), Γ∗ is gammastar (see gammastar). η∗ is ns_star. D is the vapour pressure deficit (argument vpd), ca is the ambient CO2 partial pressure in Pa (ca). • ci: Leaf-internal CO2 partial pressure (Pa), calculated as (χca). • lue: Light use efficiency (g C / mol photons), calculated as LU E = φ(T )φ0m0 M c where φ(T ) is the temperature-dependent quantum yield efficiency modifier (ftemp_kphio) if do_ftemp_kphio==TRUE, and 1 otherwise. φ0 is given by argument kphio. m0 = m if method_jmaxlim=="none", otherwise p m0 = m (1 − (c/m)( 2/3)) with c = 0.41 (Wang et al., 2017) if method_jmaxlim=="wang17". M c is the molecular mass of C (12.0107 g mol-1). m is given returned variable mj. If do_soilmstress==TRUE, LU E is multiplied with a soil moisture stress factor, calculated with soilmstress. • mj: Factor in the light-limited assimilation rate function, given by m = (ci − Γ∗)/(ci + 2Γ∗) where Γ∗ is given by gammastar. • mc: Factor in the Rubisco-limited assimilation rate function, given by mc = (ci − Γ∗)/(ci + K) where K is given by kmm. • gpp: Gross primary production (g C m-2), calculated as GP P = IabsLU E where Iabs is given by fapar*ppfd (arguments), and is NA if fapar==NA or ppfd==NA. Note that gpp scales with absorbed light. Thus, its units depend on the units in which ppfd is given. • iwue: Intrinsic water use efficiency (iWUE, Pa), calculated as iW U E = ca(1 − χ)/(1.6) • gs: Stomatal conductance (gs, in mol C m-2 Pa-1), calculated as gs = A/(ca(1 − χ)) where A is gpp/M c. • vcmax: Maximum carboxylation capacity V cmax (mol C m-2) at growth temperature (argu- ment tc), calculated as V cmax = φ(T )φ0Iabsn where n is given by n = m0 /mc. • vcmax25: Maximum carboxylation capacity V cmax (mol C m-2) normalised to 25 deg C following a modified Arrhenius equation, calculated as V cmax25 = V cmax/f v, where f v is the instantaneous temperature response by Vcmax and is implemented by function ftemp_inst_vcmax. • jmax: The maximum rate of RuBP regeneration () at growth temperature (argument tc), cal- culated using AJ = AC • rd: Dark respiration Rd (mol C m-2), calculated as Rd = b0V cmax(f r/f v) where b0 is a constant and set to 0.015 (Atkin et al., 2015), f v is the instantaneous temper- ature response by Vcmax and is implemented by function ftemp_inst_vcmax, and f r is the instantaneous temperature response of dark respiration following Heskel et al. (2016) and is implemented by function ftemp_inst_rd. Additional variables are contained in the returned list if argument method_jmaxlim=="smith19" • omega: Term corresponding to ω, defined by Eq. 16 in Smith et al. (2019), and Eq. E19 in Stocker et al. (2019). • omega_star: Term corresponding to ω ∗ , defined by Eq. 18 in Smith et al. (2019), and Eq. E21 in Stocker et al. (2019). References <NAME>., <NAME>., and <NAME>.: In vivo temperature response func-tions of parame- ters required to model RuBP-limited photosynthesis, Plant Cell Environ., 26, 1419–1430, 2003 <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,and <NAME>.: Convergence in the temperature response of leaf respiration across biomes and plant functional types, Proceedings of the National Academy of Sciences, 113, 3832–3837, doi:10.1073/pnas.1520282113,2016. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., Metaxa, <NAME>., <NAME>., <NAME>., and <NAME>.: New international formulation for the viscosity of H2O, Journal of Physical and Chemical ReferenceData, 38, 101–125, 2009 Prentice, <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>.: Balancing the costs of carbon gain and water transport: testing a new theoretical frameworkfor plant functional ecology, Ecology Letters, 17, 82–91, 10.1111/ele.12211,http://dx.doi.org/10.1111/ele.12211, 2014. <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,<NAME>. J., and <NAME>.: Towards a universal model for carbon dioxide uptake by plants, Nat Plants, 3, 734–741, 2017. <NAME>., et al.: Global variability in leaf respiration in relation to climate, plant func-tional types and leaf traits, New Phytologist, 206, 614–636, doi:10.1111/nph.13253, https://nph.onlinelibrary.wiley.com/doi/abs/10.1111/nph.13253. <NAME>., <NAME>., <NAME>. , <NAME>. , <NAME>., <NAME>. , <NAME>. Y., <NAME>., <NAME>. , <NAME>. , <NAME>. , <NAME>., <NAME>. , Rogers, A. , <NAME>., <NAME>. , <NAME>., <NAME>., <NAME>. , <NAME>. and <NAME>. (2019), Global photosynthetic capacity is optimized to the environment. Ecol Lett, 22: 506-517. doi:10.1111/ele.13210 Stocker, B. et al. Geoscientific Model Development Discussions (in prep.) Examples ## Not run: rpmodel( tc = 20, vpd = 1000, co2 = 400, ppfd = 30, elv = 0) ## End(Not run) soilmstress Calculates an empirical soil moisture stress factor Description Calculates an empirical soil moisture stress factor as a function of relative soil moisture (fraction of field capacity). Usage soilmstress(soilm, meanalpha = 1, apar_soilm = 0, bpar_soilm = 0.685) Arguments soilm Relative soil moisture as a fraction of field capacity (unitless). Defaults to 1.0 (no soil moisture stress). meanalpha Local annual mean ratio of actual over potential evapotranspiration, measure for average aridity. Defaults to 1.0. apar_soilm (Optional, used only if do_soilmstress==TRUE) Parameter determining the sensitivity of the empirical soil moisture stress function. Defaults to 0.0, the em- pirically fitted value as presented in Stocker et al. (2019) Geosci. Model Dev. for model setup ’FULL’ (corresponding to a setup with method_jmaxlim="wang17", do_ftemp_kphio=TRUE, do_soilmstress=TRUE). bpar_soilm (Optional, used only if do_soilmstress==TRUE) Parameter determining the sensitivity of the empirical soil moisture stress function. Defaults to ~0.6, the empirically fitted value as presented in Stocker et al. (2019) Geosci. Model Dev. for model setup ’FULL’ (corresponding to a setup with method_jmaxlim="wang17",do_ftemp_kphio=T do_soilmstress=TRUE). Details The soil moisture stress factor is calculated using a quadratic function that is 1 above soilm = 0.6 and has a sensitivity, given by the y-axis cutoff, (zero soil moisture), determined by average aridity (argument meanalpha) as: β = q(θ − θ∗)2 + 1 for θ < θ∗ and β = 1.0 otherwise. θ∗ is fixed at 0.6. q is the sensitivity parameter and is calculated as a linear function of average aridity, quantified by the local annual mean ratio of actual over potential evapotranspiration, termed α: q = (β0 − 1)/(θ ∗ −θ0)2 θ0 is 0.0, and β0 = a + bα a is given by argument apar, b is given by argument bpar. Value A numeric value for β References Stocker, B. et al. Geoscientific Model Development Discussions (in prep.) Examples ## Relative reduction (%) in GPP due to soil moisture stress at ## relative soil water content ('soilm') of 0.2: print((soilmstress(0.2)-1)*100 ) viscosity_h2o Viscosity of water Description Calculates the viscosity of water as a function of temperature and atmospheric pressure. Usage viscosity_h2o(tc, p) Arguments tc numeric, air temperature (tc), degrees C p numeric, atmospheric pressure (p), Pa Value numeric, viscosity of water (mu), Pa s References <NAME>., <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, ..., <NAME> (2009) New international formulation for the viscosity of H2O, J. Phys. Chem. Ref. Data, Vol. 38(2), pp. 101-125. Examples print("Density of water at 20 degrees C and standard atmospheric pressure:") print(density_h2o(20, 101325))
github.com/coreos/etcd/proxy/grpcproxy/cache
go
Go
None Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package cache exports functionality for efficiently caching and mapping `RangeRequest`s to corresponding `RangeResponse`s. ### Index [¶](#pkg-index) * [Variables](#pkg-variables) * [type Cache](#Cache) * + [func NewCache(maxCacheEntries int) Cache](#NewCache) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) ``` var ( DefaultMaxEntries = 2048 ErrCompacted = [rpctypes](/github.com/coreos/[email protected]+incompatible/etcdserver/api/v3rpc/rpctypes).[ErrGRPCCompacted](/github.com/coreos/[email protected]+incompatible/etcdserver/api/v3rpc/rpctypes#ErrGRPCCompacted) ) ``` ### Functions [¶](#pkg-functions) This section is empty. ### Types [¶](#pkg-types) #### type [Cache](https://github.com/coreos/etcd/blob/v3.3.27/proxy/grpcproxy/cache/store.go#L34) [¶](#Cache) ``` type Cache interface { Add(req *[pb](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb).[RangeRequest](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb#RangeRequest), resp *[pb](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb).[RangeResponse](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb#RangeResponse)) Get(req *[pb](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb).[RangeRequest](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb#RangeRequest)) (*[pb](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb).[RangeResponse](/github.com/coreos/[email protected]+incompatible/etcdserver/etcdserverpb#RangeResponse), [error](/builtin#error)) Compact(revision [int64](/builtin#int64)) Invalidate(key [][byte](/builtin#byte), endkey [][byte](/builtin#byte)) Size() [int](/builtin#int) Close() } ``` #### func [NewCache](https://github.com/coreos/etcd/blob/v3.3.27/proxy/grpcproxy/cache/store.go#L53) [¶](#NewCache) ``` func NewCache(maxCacheEntries [int](/builtin#int)) [Cache](#Cache) ```
learningtower
cran
R
Package ‘learningtower’ February 18, 2023 Title OECD PISA Datasets from 2000-2018 in an Easy-to-Use Format Version 1.0.1 Description The Programme for International Student Assessment (PISA) is a global study con- ducted by the Organization for Economic Cooperation and Development (OECD) in mem- ber and non-member countries to assess educational systems by assessing 15-year- old school students academic performance in mathematics, science, and read- ing. This datasets contains information on their scores and other socioeconomic characteris- tics, information about their school and its infrastructure, as well as the countries that are tak- ing part in the program. Depends R (>= 3.5.0) Encoding UTF-8 RoxygenNote 7.2.3 VignetteBuilder knitr License MIT + file LICENSE URL https://kevinwang09.github.io/learningtower/, https://github.com/kevinwang09/learningtower BugReports https://github.com/kevinwang09/learningtower/issues Imports tibble, dplyr Suggests testthat (>= 3.0.0), knitr, rmarkdown, ggplot2, forcats, scales Config/testthat/edition 3 NeedsCompilation no Author <NAME> [aut, cre], <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-02-18 09:50:02 UTC R topics documented: countrycod... 2 load_studen... 2 schoo... 3 student_subset_200... 4 countrycode Country iso3c and name mapping for PISA OECD countries partici- pants. Description A dataset containing mapping of the country ISO code to the country names. More information on participating countries can be found at https://www.oecd.org/pisa/aboutpisa/pisa-participants. htm. Format A tibble of the following variables • country: Country 3 character code. Note that some regions/territories are coded as country for ease of input. Character. • country_name: Country name. Note that some regions/territories are coded as country for ease of input. Character. load_student load_student() function allows the user to extract the PISA student scores for any desired year from 2000-2018 Description load_student() function was created to extract the data of student’s scores in any years from 2000- 2018, the function requires any of the year as it argument or a string "all" that will return all the PISA scores of the students from the years 2000-2018. Usage load_student(year = "2000") Arguments year is the required parameter for the function to display the dataset the user wants to view the PISA scores for the selected year else the entire student data will be available to the user Value A dataset of PISA scores of students that took the test in the selected year as per user from the years 2000-2018 Examples ## Not run: library(learningtower) student_all <- load_student("all") student_2000 <- load_student("2000") ## End(Not run) school School data available for the years 2000-2018 from the PISA OECD database Description A dataset containing school weight and other information from the triennial testing of 15 year olds around the globe. Original data available from https://www.oecd.org/pisa/data/. Format A tibble of the following variables • year: Year of the PISA data. Factor. • country_iso3c: Country 3 character code. Note that some regions/territories are coded as country for ease of input. Factor. • school_id: The school identification number, unique for each country and year combination. Factor. • fund_gov: Percentage of total funding for school year from government. Numeric. • fund_fees: Percentage of total funding for school year from student fees or school charges paid by parents. Numeric. • fund_donation: Percentage of total funding for school year from benefactors, donations, bequests, sponsorship, parent fundraising. Numeric. • enrol_boys: Number of boys in the school. Numeric. • enrol_girls: Number of girls in the school. Numeric. • stratio: Student-Teacher ratio. Numeric. • public_private: Is the school a public or private school. Factor. • staff_shortage: Shortage of staff. Numeric. • sch_wgt: The final survey weight score for the schools. Numeric. • school_size: The school size. Numeric. student_subset_2000 Sample student data available for the years 2000-2018 from the PISA OECD database Description A sample student subset dataset containing scores and other information from the triennial testing of 15 year olds around the globe. Original data available from https://www.oecd.org/pisa/data/. Format A tibble of the following variables • year: Year of the PISA data. Factor. • country: Country 3 character code. Note that some regions/territories are coded as country for ease of input. Factor. • school_id: The school identification number, unique for each country and year combination. Factor. • student_id: The student identification number, unique for each school, country and year combination. Factor. • mother_educ: Highest level of mother’s education. Ranges from "less than ISCED1" to "ISCED 3A". Factor. Note that in 2000, all entries are missing. • father_educ: Highest level of father’s education. Ranges from "less than ISCED1" to "ISCED 3A". Factor. Note that in 2000, all entries are missing. • gender: Gender of the student. Only "male" and "female" are recorded. Factor. Note that we call this variable gender and not sex as this term was used in the OECD PISA database. • computer: Possession of computer. Only "yes" and "no" are recorded. Factor. • internet: Access to internet. Only "yes" and "no" are recorded. Factor. • math: Simulated score in mathematics. Numeric. • read: Simulated score in reading. Numeric. • science: Simulated score in science. Numeric. • stu_wgt: The final survey weight score for the student score. Numeric. • desk: Possession of desk to study at. Only "yes" and "no" are recorded. Factor. • room: Possession of a room of your own. Only "yes" and "no" are recorded. Factor. • dishwasher: Possession of a dishwasher. Only "yes" and "no" are recorded. Factor. Note that in 2015 and 2018, all entries are missing. • television: Number of televisions. "0", "1", "2" are code for no, one and two TVs in the house. "3+" codes for three or more TVs. Factor. Note that in 2003, all entries are missing. • computer_n: Number of computers. "0", "1", "2" are code for no, one and two computers in the house. "3+" codes for three or more computers. Factor. Note that in 2003, all entries are missing. • car: Number of cars. "0", "1", "2" are code for no, one and two cars in the house. "3+" codes for three or more cars Factor. Note that in 2003, all entries are missing. • book: Number of books. Factor. Note that encoding is different in the years 2000 and 2003 compared to all other years. Factor. Evaluate table(student$book, student$year) for a demo. • wealth: Family wealth. Numeric. Note that in 2003, all entries are missing. • escs: Index of economic, social and cultural status. Numeric. Examples library(dplyr) data(student_subset_2000) data(student_subset_2003) dplyr::bind_rows( student_subset_2000, student_subset_2003 )
matlab
cran
R
Package ‘matlab’ June 1, 2022 Version 1.0.4 Date 2022-05-31 Title 'MATLAB' Emulation Package Author <NAME> Maintainer <NAME> <<EMAIL>> Description Emulate 'MATLAB' code using 'R'. Depends R (>= 2.15) Imports methods URL https://cran.r-project.org/package=matlab License Artistic-2.0 Copyright file COPYRIGHTS LazyLoad true NeedsCompilation no Repository R-Forge Date/Publication 2022-05-31 23:32:38 Repository/R-Forge/Project estimate Repository/R-Forge/Revision 43 Repository/R-Forge/DateTimeStamp 2022-05-31 23:32:38 R topics documented: matlab-packag... 2 cei... 3 cel... 4 colorba... 4 ey... 6 factor... 7 filepart... 8 filese... 9 fin... 9 fi... 10 flipl... 11 fullfil... 11 hil... 12 images... 13 isempt... 14 isprim... 15 jet.color... 15 linspac... 16 logspac... 17 magi... 18 meshgri... 19 mo... 20 multiline.plot.color... 20 ndim... 21 nextpow... 22 nume... 23 one... 23 padarra... 24 pasca... 25 pathse... 26 pow... 26 prime... 27 repma... 28 reshap... 29 rosse... 30 rot9... 30 siz... 31 size_t-clas... 32 st... 33 strcm... 33 su... 34 ticto... 35 vande... 35 matlab-package MATLAB Emulation Functions Description Wrapper functions and variables used to replicate MATLAB function calls as best possible to sim- plify porting. Details Package: matlab Type: Package Version: 1.0.4 Date: 2022-05-31 License: Artistic-2.0 They are no more complete than absolutely necessary and are quite possibly broken for fringe cases. For a complete list of functions, use library(help="matlab"). For a high-level summary of the changes for each revision, use file.show(system.file("NEWS", package="matlab")). Note In certain cases, these may not correspond exactly with MATLAB API as sometimes it just wasn’t possible. Author(s) <NAME> <<EMAIL>> ceil MATLAB ceil function Description Rounds to the nearest integer. Usage ceil(x) Arguments x numeric to be rounded Details Simply invokes ceiling for those more used to C library API name. Value Returns numeric vector containing smallest integers not less than the corresponding elements of argument x. Author(s) <NAME> <<EMAIL>> See Also fix, Round Examples ceil(c(0.9, 1.3, 2.4)) cell MATLAB cell function Description Create cell array. Usage cell(...) Arguments ... numeric dimensions for the result Value Returns list consisting of empty matrices. Defaults to square if dimension argument resolves to a single value. Author(s) <NAME> <<EMAIL>> See Also ones, zeros Examples cell(3) cell(c(3, 3)) # same thing cell(3, 3) # same thing cell(size(matrix(NA, 3, 3))) # same thing colorbar MATLAB colorbar function Description Displays colorbar showing the color scale. Usage colorbar(C, location=c("EastOutside", "WestOutside", "NorthOutside", "SouthOutside"), ...) Arguments C numeric vector or matrix representing data values location character scalar indicating desired orientation with respect to the axes ... graphical parameters for image may also be passed as arguments to this method Details The values of the elements of C are indices into the current palette that determine the color of each patch. This implementation differs a bit from its MATLAB counterpart in that the values must be passed explicitly. Author(s) <NAME> <<EMAIL>> See Also imagesc, jet.colors, layout, par Examples doPlot <- function(C, cb.loc=c("EastOutside", "WestOutside", "NorthOutside", "SouthOutside"), ...) { saved.par <- par(no.readonly=TRUE) on.exit(par(saved.par)) layout.EO <- function() { ## divide the device into one row and nine columns ## allocate figure 1 the first eight columns ## allocate figure 2 the last column layout(matrix(c(1, 1, 1, 1, 1, 1, 1, 1, 2), ncol=9)) } layout.WO <- function() { ## divide the device into one row and nine columns ## allocate figure 1 the last eight columns ## allocate figure 2 the first column layout(matrix(c(2, 1, 1, 1, 1, 1, 1, 1, 1), ncol=9)) } layout.NO <- function() { ## divide the device into six rows and one column ## allocate figure 1 the last five rows ## allocate figure 2 the first row layout(matrix(c(2, 1, 1, 1, 1, 1), nrow=6)) } layout.SO <- function() { ## divide the device into six rows and one column ## allocate figure 1 the first five rows ## allocate figure 2 the last row layout(matrix(c(1, 1, 1, 1, 1, 2), nrow=6)) } location <- match.arg(cb.loc) switch(EXPR=location, EastOutside = layout.EO(), WestOutside = layout.WO(), NorthOutside = layout.NO(), SouthOutside = layout.SO()) imagesc(C, ...) colorbar(C, location, ...) } values <- matrix(c(seq(1, 5, by=1), seq(2, 10, by=2), seq(3, 15, by=3)), nrow=3, byrow=TRUE) dev.new(width=8, height=7) doPlot(values, "EastOutside", col=jet.colors(16)) eye MATLAB eye function Description Create an identity matrix. Usage eye(m, n) Arguments m, n numeric scalar specifying dimensions for the result Value Returns matrix of order 1. Defaults to square if second dimension argument n not provided. Author(s) <NAME> <<EMAIL>> See Also ones, zeros Examples eye(3) factors MATLAB factor function Description Performs prime factorization. Usage factors(n) Arguments n numeric scalar specifying composite number to be factored Details Computes the prime factors of n in ascending order, each one as often as its multiplicity requires, such that n == prod(factors(n)). Value Returns vector containing the prime factors of n. Note The corresponding MATLAB function is called ’factor’, but was renamed here to avoid conflict with R’s compound object class. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also isprime, primes Examples factors(1002001) # 7 7 11 11 13 13 factors(65537) # is prime ## Euler's calculation factors(2^32 + 1) # 641 6700417 fileparts MATLAB fileparts function Description Return filename parts. Usage fileparts(pathname) Arguments pathname character string representing pathname to be parsed Details Determines the path, filename, extension, and version for the specified file. The returned ext con- tains a dot (.) before the file extension. The returned versn is always an empty string as the field is provided for compatibility with its namesake’s results. Value Returns a list with components: pathstr character string representing directory path name character string representing base of file name ext character string representing file extension versn character string representing version. Unused Note Returns same insane results as does its namesake when handling relative directories, UNIX hidden files, and tilde expansion. Hidden files are returned with name containing a zero length vector and ext containing the actual name. For best results, use this routine to process files, not directories. Author(s) <NAME> <<EMAIL>> See Also fullfile Examples ## Rename dot-txt file as dot-csv ans <- fileparts("/home/luser/foo.txt") fullfile(ans$pathstr, paste(ans$name, "csv", sep=".")) # /home/luser/foo.csv filesep MATLAB filesep function Description Returns the character that separates directory names in filenames. Usage filesep Details Variable that contains the value of .Platform$file.sep. Value Returns character representing this platform’s file separator. Note Implemented as an R variable rather than a function such that it more closely resembles normal MATLAB usage. Author(s) <NAME> <<EMAIL>> See Also fileparts, fullfile, pathsep find MATLAB find function Description Finds indices of elements. Usage find(x) Arguments x expression to evaluate Details If expression is not logical, finds indices of nonzero elements of argument x. Value Returns indices of corresponding elements matching the expression x. Author(s) <NAME> <<EMAIL>> Examples find(-3:3 >= 0) find(c(0, 1, 0, 2, 3)) fix MATLAB fix function Description Rounds toward zero. Usage fix(A) Arguments A numeric to be rounded Details Simply invokes trunc. Value Returns vector containing integers by truncating the corresponding values of argument A toward zero. Author(s) <NAME> <<EMAIL>> See Also ceil, Round Examples fix(c(1.3, 2.5, 3.7)) fliplr MATLAB matrix flip functions Description Flips matrices either left-right or up-down. Usage fliplr(object) flipud(object) Arguments object vector or matrix to be flipped Details These are S4 generic functions. Value Return value is the same type as argument object. Author(s) <NAME> <<EMAIL>> See Also rot90 Examples fliplr(1:9) flipud(1:9) # same as previous since vectors have no orientation in R fliplr(matrix(1:9, 3, 3, byrow=TRUE)) flipud(matrix(1:9, 3, 3, byrow=TRUE)) fullfile MATLAB fullfile function Description Contructs path to a file from components in platform-independent manner Usage fullfile(...) Arguments ... character strings representing path components Details Builds a full filename from the directories and filename specified. This is conceptually equivalent to paste(dir1, dir2, dir3, filename, sep=filesep) with care taken to handle cases when directories begin or end with a separator. Value Returns character vector of arguments concatenated term-by-term and separated by file separator if all arguments have a positive length; otherwise, an empty character vector. Author(s) <NAME> <<EMAIL>> See Also fileparts, filesep Examples fullfile("", "etc", "profile") # /etc/profile hilb MATLAB hilb function Description Create a Hilbert matrix. Usage hilb(n) Arguments n numeric scalar specifying dimensions for the result Details The Hilbert matrix is a notable example of a poorly conditioned matrix. Its elements are H[i, j] = 1 / (i + j - 1) . Value Returns an n-by-n matrix constructed as described above. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> Examples hilb(3) imagesc MATLAB imagesc function Description Scales image data to the full range of the current palette and displays the image. Usage imagesc(x=seq(ncol(C)), y=seq(nrow(C)), C, col=jet.colors(12), ...) Arguments x,y locations of grid lines at which the values in C are measured. These must be finite, non-missing and in (strictly) ascending order. By default, the dimensions of C are used. C numeric matrix representing data to be plotted. Note that x can be used instead of C for convenience. col vector of colors used to display image data ... graphical parameters for image may also be passed as arguments to this method Details Each element of C corresponds to a rectangular area in the image. The values of the elements of C are indices into the current palette that determine the color of each patch. The method interprets the matrix data as a table of f(x[i], y[j]) values, so that the x axis corre- sponds to column number and the y axis to row number, with row 1 at the top, i.e., the same as the conventional printed layout of a matrix. Author(s) <NAME> <<EMAIL>> See Also image, jet.colors, par Examples values <- matrix(c(seq(1, 5, by=1), seq(2, 10, by=2), seq(3, 15, by=3)), nrow=3, byrow=TRUE) imagesc(values, xlab="cols", ylab="rows", col=jet.colors(16)) isempty MATLAB isempty function Description Determine if object is empty. Usage isempty(A) Arguments A object to evaluate Details An empty object has at least one dimension of size zero. Value Returns TRUE if x is an empty object; otherwise, FALSE. Author(s) <NAME> <<EMAIL>> Examples isempty(1:3) # FALSE isempty(array(NA, c(2, 0, 2))) # TRUE isprime MATLAB isprime function Description Array elements that are prime numbers. Usage isprime(x) Arguments x numeric vector or matrix containing nonnegative integer values Value Returns an array (or vector) the same size as x containing logical 1 (true) for the elements of x which are prime, and logical 0 (false) otherwise. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also factors, primes Examples x <- c(2, 3, 0, 6, 10) ans <- isprime(x) ## 1, 1, 0, 0, 0 as.logical(ans) ## true, true, false, false, false jet.colors MATLAB jet function Description Creates a vector of n colors beginning with dark blue, ranging through shades of blue, cyan, green, yellow and red, and ending with dark red. Usage jet.colors(n) Arguments n numeric scalar specifying number of colors to be in the palette Value Returns vector of n color names. This can be used either to create a user-defined color palette for subsequent graphics, a col= specification in graphics functions, or in par. Author(s) <NAME> <<EMAIL>> See Also palette, par, rgb Examples require(graphics) x <- 1:16 pie(x, col=jet.colors(length(x))) linspace MATLAB linspace function Description Generate linearly spaced vectors. Usage linspace(a, b, n=100) Arguments a numeric scalar specifying starting point b numeric scalar specifying ending point n numeric scalar specifying number of points to be generated Details Similar to colon operator but gives direct control over the number of points. Note also that although MATLAB doesn’t specifically document this, the number of points generated is actually floor(n). Value Returns vector containing containing n points linearly spaced between a and b inclusive. If n < 2, the result will be the ending point b. Author(s) <NAME> <<EMAIL>> See Also logspace Examples linspace(1, 10, 4) logspace MATLAB logspace function Description Generate logarithmically spaced vectors. Usage logspace(a, b, n=50) Arguments a numeric scalar specifying exponent for starting point b numeric scalar specifying exponent for ending point n numeric scalar specifying number of points to be generated Details Useful for creating frequency vectors, it is a logarithmic equivalent of linspace. Value Returns vector containing containing n points logarithmically spaced between decades 10a and 10b . For n < 2, b is returned. Author(s) <NAME> <<EMAIL>> See Also linspace Examples logspace(1, pi, 36) magic MATLAB magic function Description Create a magic square. Usage magic(n) Arguments n numeric scalar specifying dimensions for the result Details The value of the characteristic sum for a magic square of order n is sum(1 : n2 )/n. The order n must be a scalar greater than or equal to 3; otherwise, the result will be either a nonmagic square, or else the degenerate magic squares 1 and []. Value Returns an n-by-n matrix constructed from the integers 1 through N 2 with equal row and column sums. Note A magic square, scaled by its magic sum, is doubly stochastic. Author(s) <NAME> <<EMAIL>> See Also ones, zeros Examples magic(3) meshgrid MATLAB meshgrid functions Description Generate X and Y matrices for three-dimensional plots. Usage meshgrid(x, y, z, nargout=2) Arguments x, y, z numeric vectors of values nargout numeric scalar that determines number of dimensions to return Details In the first example below, the domain specified by vectors x and y are transformed into two arrays which can be used to evaluate functions of two variables and three-dimensional surface plots. The rows of the output array x are copies of the vector x; columns of the output array y are copies of the vector y. The second example below is syntactic sugar for specifying meshgrid(x, x). The third example below produces three-dimensional arrays used to evaluate functions of three variables and three-dimensional volumetric plots. Value Returns list containing eiher two or three matrices depending on the value of nargout. x, y, z output matrices Note Limited to two- or three-dimensional Cartesian space. Author(s) <NAME> <<EMAIL>> Examples meshgrid(1:3, 10:14) # example 1 meshgrid(1:3) # example 2 meshgrid(5:8, 10:14, 2:3, 3) # example 3 mod MATLAB mod/rem functions Description Provides modulus and remainder after division. Usage mod(x, y) rem(x, y) Arguments x, y numeric vectors or objects Value Returns vector containing result of the element by element operations. Author(s) <NAME> <<EMAIL>> Examples ## same results with x, y having the same sign mod(5, 3) rem(5, 3) ## same results with x, y having different signs mod(-5, 3) rem(-5, 3) multiline.plot.colors MATLAB multiline plot colors Description Creates a vector of colors equivalent to MATLAB’s default colors to use for multiline plots. Usage multiline.plot.colors() Details This is equivalent to the MATLAB command get(gca, 'ColorOrder') Value Returns vector of color names. This can be used either to create a user-defined color palette for subsequent graphics, a col= specification in graphics functions, or in par. Note Method should be considered experimental and will most likely be removed and replaced with similar functionality in the near future. Author(s) <NAME> <<EMAIL>> See Also palette, par, rgb Examples require(graphics) x <- matrix(1:16, nrow=2, byrow=TRUE) matplot(x, type="l", col=multiline.plot.colors()) ndims MATLAB ndims function Description Provides number of array dimensions. Usage ndims(A) Arguments A object of which to determine the number of dimensions Details Simply invokes length(size(A)). Value Returns the number of dimensions in the array A. Note The number of dimensions is always greater than or equal to 2. Initial implementation returned length. Author(s) <NAME> <<EMAIL>> See Also size Examples ndims(2:9) # 2 ndims(magic(4)) # 2 ndims(array(1:8, c(2,2,2))) # 3 nextpow2 MATLAB nextpow2 function Description Smallest power of 2 greater than or equal to its argument. Usage nextpow2(x) Arguments x numeric or complex value(s). Details Computes the smallest power of two that is greater than or equal to the absolute value of x. (That is, p that satisfies 2p ≥ abs(x)). For negative or complex values, the absolute value will be taken. Value Returns numeric result containing integer p as described above. Nonscalar input returns an element- by-element result (of same size/dimensions as its input). Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also pow2 Examples nextpow2(10) # 4 nextpow2(1:10) # 0 1 2 2 3 3 3 3 4 4 nextpow2(-2^10) # 10 nextpow2(.Machine$double.eps) # -52 nextpow2(c(0.5, 0.25, 0.125)) # -1 -2 -3 numel MATLAB numel function Description Provides number of elements in array A or subscripted array expression. Usage numel(A, varargin) Arguments A object of which to determine the number of elements varargin unimplemented Value Returns prod(size(A)). Author(s) <NAME> <<EMAIL>> See Also prod, size Examples numel(2:9) # 8 numel(magic(4)) # 16 ones MATLAB ones/zeros functions Description Create a matrix consisting of all ones or zeros. Usage ones(...) zeros(...) Arguments ... numeric dimensions for the result Value Returns matrix consisting only of ones (or zeros). Defaults to square if dimension argument resolves to a single value. Author(s) <NAME> <<EMAIL>> See Also eye Examples ones(3) ones(c(3, 3)) # same thing ones(3, 3) # same thing ones(size(matrix(NA, 3, 3))) # same thing zeros(3) padarray MATLAB padarray function Description Pad array. Usage padarray(A, padsize, padval=0, direction=c("both", "pre", "post")) Arguments A vector, matrix, or array to be padded padsize integer vector specifying both amount of padding and the dimension along which to add it padval scalar value specifying pad value, which defaults to 0. Instead, it may specify the method used to determine pad values. Valid values for the method are: "circular" pad with circular repetition of elements within the dimension "replicate" pad by repeating border elements of array "symmetric" pad array with mirror reflections of itself direction character string specifying direction to apply padding. Valid values are: "both" pad before first element and after last array element along each dimension "pre" pad after last array element along each dimension "post" pad before first array element along each dimension Details This is an S4 generic function. Value Return value is the same type as argument A with requested padding. Author(s) <NAME> <<EMAIL>> Examples padarray(1:4, c(0, 2)) # 0 0 [1 2 3 4] 0 0 padarray(1:4, c(0, 2), -1) # -1 -1 [1 2 3 4] -1 -1 padarray(1:4, c(0, 2), -1, "post") # [1 2 3 4] -1 -1 padarray(1:4, c(0, 3), "symmetric", "pre") # 3 2 1 [1 2 3 4] padarray(letters[1:5], c(0, 3), "replicate") # a a a [a b c d e] e e e padarray(letters[1:5], c(0, 3), "circular", "post") # [a b c d e] a b c pascal MATLAB pascal function Description Generate Pascal matrix. Usage pascal(n, k=0) Arguments n numeric scalar specifying order k numeric scalar specifying desired option. Valid values are 0, 1, or 2 Details Specifying k = 0 returns symmetric positive definite matrix with integer entries taken from Pascal’s triangle. Specifying k = 1 returns the lower triangular Cholesky factor (up to the signs of the columns) of the Pascal matrix. Specifying k = 2 returns a cube root of the identity matrix. Value Returns matrix of order n according to specified option k. Author(s) <NAME> <<EMAIL>> Examples pascal(4) pascal(3, 2) pathsep MATLAB pathsep function Description Returns the character that separates directory names in a list such as the PATH environment variable. Usage pathsep Details Variable that contains the value of .Platform$path.sep. Value Returns character representing this platform’s path separator. Note Implemented as an R variable rather than a function such that it more closely resembles normal MATLAB usage. Author(s) <NAME> <<EMAIL>> See Also filesep pow2 MATLAB pow2 function Description Power with base 2. Usage pow2(f, e) Arguments f numeric vector of factors e numeric vector of exponents for base 2 Details Computes the expression f * 2^e for corresponding elements of f and e. If e is missing, it sets e to f and f to 1. Imaginary parts of complex values are ignored unless e is missing. Value Returns numeric vector constructed as described above. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also nextpow2 Examples pow2(c(0, 1, 2, 3)) # 1 2 4 8 pow2(c(0, -1, 2, 3), c(0,1,-2,3)) # 0.0 -2.0 0.5 24.0 pow2(1i) # 0.7692389+0.6389613i # For IEEE arithmetic... pow2(1/2, 1) # 1 pow2(pi/4, 2) # pi pow2(-3/4, 2) # -3 pow2(1/2, -51) # .Machine$double.eps pow2(1/2, -1021) # .Machine$double.xmin primes MATLAB primes function Description Generate a list of prime numbers. Usage primes(n) Arguments n scalar numeric specifying largest prime number desired. Details Generates the list of prime numbers less than or equal to n using a variant of the basic "Sieve of Eratosthenes" algorithm. This approach is reasonably fast, but requires a copious amount of memory when n is large. A prime number is one that has no other factors other than 1 and itself. Value Returns numeric vector containing prime numbers less than or equal to argument n. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> See Also isprime, factors Examples primes(1000) length(primes(1e6)) # 78498 prime numbers less than one million ## Not run: length(primes(1e7)) # 664579 prime numbers less than ten million length(primes(1e8)) # 5761455 prime numbers less than one hundred million ## End(Not run) repmat MATLAB repmat function Description Replicate and tile a matrix. Usage repmat(A, ...) Arguments A vector or matrix to be tiled. Must be numeric, logical, complex or character. ... numeric dimensions for the result Value Returns matrix with value A tiled to the number of dimensions specified. Defaults to square if dimension argument resolves to a single value. Author(s) <NAME> <<EMAIL>> See Also ones, zeros Examples repmat(1, 3) # same as ones(3) repmat(1, c(3, 3)) # same thing repmat(1, 3, 3) # same thing repmat(1, size(matrix(NA, 3, 3))) # same thing repmat(matrix(1:4, 2, 2), 3) reshape MATLAB reshape function Description Reshape matrix or array. Usage reshape(A, ...) Arguments A matrix or array containing the original data ... numeric dimensions for the result Details In the first example below, an m-by-n matrix is created whose elements are taken column-wise from A. An error occurs if A does not have m ∗ n elements. In the second example below, an n-dimensional array with the same elements as A but reshaped to have the size m-by-n-by-p. The product of the specified dimensions must be the same as prod(size(A)). In the third example below, an n-dimensional array with the same elements as A but reshaped to siz, a vector representing the dimensions of the reshaped array. The quantity prod(siz) must be the same as prod(size(A)). Value Returns matrix (or array) of requested dimensions containing the elements of A. Author(s) <NAME> <<EMAIL>> Examples Xmat.2d <- matrix(1:12, nrow=4, ncol=3) reshape(Xmat.2d, 6, 2) # example 1 reshape(Xmat.2d, c(6, 2)) # same thing Xarr.3d <- reshape(Xmat.2d, c(6, 2, 1)) # example 2 reshape(Xmat.2d, size(Xarr.3d)) # example 3 rosser MATLAB rosser function Description Create the Rosser matrix, a classic symmetric eigenvalue test problem. Usage rosser() Details The returned matrix has the following features: • a double eigenvalue • three nearly equal eigenvalues • dominant eigenvalues of opposite sign • a zero eigenvalue • a small, nonzero eigenvalue Value Returns an 8-by-8 matrix with integer elements. Author(s) <NAME> <<EMAIL>> Examples rosser() rot90 MATLAB rot90 function Description Rotates matrix counterclockwise k*90 degrees. Usage rot90(A, k=1) Arguments A matrix to be rotated k numeric scalar specifying the number of times to rotate (1..4) Details Rotating 4 times (360 degrees) returns the original matrix unchanged. Value Returns matrix corresponding to argument A having been rotated argument k number of times. Author(s) <NAME> <<EMAIL>> See Also fliplr, flipud Examples rot90(matrix(1:4, 2, 2)) size MATLAB size function Description Provides dimensions of X. Usage size(X, dimen) Arguments X vector, matrix, or array object dimen numeric scalar specifies particular dimension Details This is an S4 generic function. Vector will be treated as a single row matrix. Stored value is equivalent to dim. Value Returns object of class size_t containing the dimensions of input argument X if invoked with a single argument. Returns integer value of specified dimension if invoked with two arguments. If dimen specifies a higher dimension than exists, returns 1 representing the singleton dimension. Note Handling of vectors is different than in initial implementation. Initial implementation returned length. Author(s) <NAME> <<EMAIL>> Examples size(2:9) # 1 8 size(matrix(1:8, 2, 4)) # 2 4 size(matrix(1:8, 2, 4), 2) # 4 size(matrix(1:8, 2, 4), 3) # 1 size_t-class Class "size\_t" Description This class represents the dimensions of another R object Objects from the Class Objects can be created by calls of the form new("size_t", ...). Use of generator method is preferred. Slots .Data: object of class "integer" containing size values Extends Class "integer", from data part. Class "vector", by class "integer". Class "numeric", by class "integer". Note Internal class supporting size. Author(s) <NAME> <<EMAIL>> std MATLAB std function Description Computes the standard deviation of the values of x. Usage std(x, flag=0) Arguments x numeric vector or matrix flag numeric scalar. If 0, selects unbiased algorithm. If 1, selects biased algorithm (currently unsupported). Details Simply invokes sd. Value Return value depends on argument x. If vector, returns the standard deviation. If matrix, returns vector containing the standard deviation of each column. Author(s) <NAME> <<EMAIL>> Examples std(1:2) ^ 2 strcmp MATLAB strcmp function Description Compare strings. Usage strcmp(S, T) Arguments S, T character vectors to evaluate Details Comparisons are case-sensitive and any leading and trailing blanks in either of the strings are ex- plicitly included in the comparison. Value Returns TRUE if S is identical to T; otherwise, FALSE. Note Value returned is the opposite of the C language convention. Author(s) <NAME> <<EMAIL>> Examples strcmp("foo", "bar") # FALSE strcmp(c("yes", "no"), c("yes", "no")) # TRUE sum MATLAB sum function Description Provides sum of elements. Usage sum(x, na.rm=FALSE) Arguments x numeric or logical to be summed na.rm logical scalar. If TRUE, remove missing values Details This is an S4 generic function. Value Return value depends on argument x. If vector, returns the same as sum. If matrix, returns vector containing the sum of each column. Author(s) <NAME> <<EMAIL>> Examples sum(1:9) sum(matrix(1:9, 3, 3)) tictoc MATLAB timer functions Description Provides stopwatch timer. Function tic starts the timer and toc updates the elapsed time since the timer was started. Usage tic(gcFirst=FALSE) toc(echo=TRUE) Arguments gcFirst logical scalar. If TRUE, perform garbage collection prior to starting stopwatch echo logical scalar. If TRUE, print elapsed time to screen Details Provides analog to system.time. Function toc can be invoked multiple times in a row. Author(s) <NAME> <<EMAIL>> Examples tic() for(i in 1:100) mad(runif(1000)) # kill time toc() vander MATLAB vander function Description Generate Vandermonde matrix from a vector of numbers. Usage vander(v) Arguments v numeric or complex vector of values Details Generates the Vandermonde matrix whose columns are powers of the vector v (of length n) using the formula A[i, j] = v[i]^(n-j) Used when fitting a polynomial to given points. Value Returns an n-by-n matrix constructed as described above. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>> Examples vander(1:5)
@trivikr-test/client-application-discovery-service-esm
npm
JavaScript
@aws-sdk/client-application-discovery-service === Description --- AWS SDK for JavaScript ApplicationDiscoveryService Client for Node.js, Browser and React Native. AWS Application Discovery Service AWS Application Discovery Service helps you plan application migration projects. It automatically identifies servers, virtual machines (VMs), and network dependencies in your on-premises data centers. For more information, see the [AWS Application Discovery Service FAQ](http://aws.amazon.com/application-discovery/faqs/). Application Discovery Service offers three ways of performing discovery and collecting data about your on-premises servers: * **Agentless discovery** is recommended for environments that use VMware vCenter Server. This mode doesn't require you to install an agent on each host. It does not work in non-VMware environments. + Agentless discovery gathers server information regardless of the operating systems, which minimizes the time required for initial on-premises infrastructure assessment. + Agentless discovery doesn't collect information about network dependencies, only agent-based discovery collects that information. * **Agent-based discovery** collects a richer set of data than agentless discovery by using the AWS Application Discovery Agent, which you install on one or more hosts in your data center. + The agent captures infrastructure and application information, including an inventory of running processes, system performance information, resource utilization, and network dependencies. + The information collected by agents is secured at rest and in transit to the Application Discovery Service database in the cloud. * **AWS Partner Network (APN) solutions** integrate with Application Discovery Service, enabling you to import details of your on-premises environment directly into Migration Hub without using the discovery connector or discovery agent. + Third-party application discovery tools can query AWS Application Discovery Service, and they can write to the Application Discovery Service database using the public API. + In this way, you can import data into Migration Hub and view it, so that you can associate applications with servers and track migrations. **Recommendations** We recommend that you use agent-based discovery for non-VMware environments, and whenever you want to collect information about network dependencies. You can run agent-based and agentless discovery simultaneously. Use agentless discovery to complete the initial infrastructure assessment quickly, and then install agents on select hosts to collect additional information. **Working With This Guide** This API reference provides descriptions, syntax, and usage examples for each of the actions and data types for Application Discovery Service. The topic for each action shows the API request parameters and the response. Alternatively, you can use one of the AWS SDKs to access an API that is tailored to the programming language or platform that you're using. For more information, see [AWS SDKs](http://aws.amazon.com/tools/#SDKs). * Remember that you must set your Migration Hub home region before you call any of these APIs. * You must make API calls for write actions (create, notify, associate, disassociate, import, or put) while in your home region, or a `HomeRegionNotSetException` error is returned. * API calls for read actions (list, describe, stop, and delete) are permitted outside of your home region. * Although it is unlikely, the Migration Hub home region could change. If you call APIs outside the home region, an `InvalidInputException` is returned. * You must call `GetHomeRegion` to obtain the latest Migration Hub home region. This guide is intended for use with the [AWS Application Discovery Service User Guide](http://docs.aws.amazon.com/application-discovery/latest/userguide/). All data is handled according to the [AWS Privacy Policy](http://aws.amazon.com/privacy/). You can operate Application Discovery Service offline to inspect collected data before it is shared with the service. Installing --- To install the this package, simply type add or install @aws-sdk/client-application-discovery-service using your favorite package manager: * `npm install @aws-sdk/client-application-discovery-service` * `yarn add @aws-sdk/client-application-discovery-service` * `pnpm add @aws-sdk/client-application-discovery-service` Getting Started --- ### Import The AWS SDK is modulized by clients and commands. To send a request, you only need to import the `ApplicationDiscoveryServiceClient` and the commands you need, for example `AssociateConfigurationItemsToApplicationCommand`: ``` // ES5 example const { ApplicationDiscoveryServiceClient, AssociateConfigurationItemsToApplicationCommand, } = require("@aws-sdk/client-application-discovery-service"); ``` ``` // ES6+ example import { ApplicationDiscoveryServiceClient, AssociateConfigurationItemsToApplicationCommand, } from "@aws-sdk/client-application-discovery-service"; ``` ### Usage To send a request, you: * Initiate client with configuration (e.g. credentials, region). * Initiate command with input parameters. * Call `send` operation on client with command object as input. * If you are using a custom http handler, you may call `destroy()` to close open connections. ``` // a client can be shared by different commands. const client = new ApplicationDiscoveryServiceClient({ region: "REGION" }); const params = { /** input parameters */ }; const command = new AssociateConfigurationItemsToApplicationCommand(params); ``` #### Async/await We recommend using [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) operator to wait for the promise returned by send operation as follows: ``` // async/await. try { const data = await client.send(command); // process data. } catch (error) { // error handling. } finally { // finally. } ``` Async-await is clean, concise, intuitive, easy to debug and has better error handling as compared to using Promise chains or callbacks. #### Promises You can also use [Promise chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) to execute send operation. ``` client.send(command).then( (data) => { // process data. }, (error) => { // error handling. } ); ``` Promises can also be called using `.catch()` and `.finally()` as follows: ``` client .send(command) .then((data) => { // process data. }) .catch((error) => { // error handling. }) .finally(() => { // finally. }); ``` #### Callbacks We do not recommend using callbacks because of [callback hell](http://callbackhell.com/), but they are supported by the send operation. ``` // callbacks. client.send(command, (err, data) => { // process err and data. }); ``` #### v2 compatible style The client can also send requests using v2 compatible style. However, it results in a bigger bundle size and may be dropped in next major version. More details in the blog post on [modular packages in AWS SDK for JavaScript](https://aws.amazon.com/blogs/developer/modular-packages-in-aws-sdk-for-javascript/) ``` import * as AWS from "@aws-sdk/client-application-discovery-service"; const client = new AWS.ApplicationDiscoveryService({ region: "REGION" }); // async/await. try { const data = await client.associateConfigurationItemsToApplication(params); // process data. } catch (error) { // error handling. } // Promises. client .associateConfigurationItemsToApplication(params) .then((data) => { // process data. }) .catch((error) => { // error handling. }); // callbacks. client.associateConfigurationItemsToApplication(params, (err, data) => { // process err and data. }); ``` ### Troubleshooting When the service returns an exception, the error will include the exception information, as well as response metadata (e.g. request id). ``` try { const data = await client.send(command); // process data. } catch (error) { const { requestId, cfId, extendedRequestId } = error.$metadata; console.log({ requestId, cfId, extendedRequestId }); /** * The keys within exceptions are also parsed. * You can access them by specifying exception names: * if (error.name === 'SomeServiceException') { * const value = error.specialKeyInException; * } */ } ``` Getting Help --- Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests, but have limited bandwidth to address them. * Visit [Developer Guide](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html) or [API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html). * Check out the blog posts tagged with [`aws-sdk-js`](https://aws.amazon.com/blogs/developer/tag/aws-sdk-js/) on AWS Developer Blog. * Ask a question on [StackOverflow](https://stackoverflow.com/questions/tagged/aws-sdk-js) and tag it with `aws-sdk-js`. * Join the AWS JavaScript community on [gitter](https://gitter.im/aws/aws-sdk-js-v3). * If it turns out that you may have found a bug, please [open an issue](https://github.com/aws/aws-sdk-js-v3/issues/new/choose). To test your universal JavaScript code in Node.js, browser and react-native environments, visit our [code samples repo](https://github.com/aws-samples/aws-sdk-js-tests). Contributing --- This client code is generated automatically. Any modifications will be overwritten the next time the `@aws-sdk/client-application-discovery-service` package is updated. To contribute to client you can check our [generate clients scripts](https://github.com/aws/aws-sdk-js-v3/tree/main/scripts/generate-clients). License --- This SDK is distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), see LICENSE for more information. Readme --- ### Keywords none
works_jinbuguo_com_lfs_lfs62_index_html
free_programming_book
Unknown
# Linux From Scratch Date: 1999-01-01 Categories: Tags: Copyright 1999–2006 <NAME> 谨以本书献给 LinuxSir.org 以及所有热爱 Linux 的人们。译者: 金步国(0-5章) ipconfigme(6-7章) bobkey(8-9章) 发布日期:2008年3月1日 [最终正式版] [致谢]感谢之前的 LFS 5.0 和 6.0 翻译小组,没有他们之前辛勤工作积累的资料单靠我们3个人是不可能完成这项工作的。同样也要感谢所有指出预览版中错误的朋友以及对中译本提出建议与期望的朋友(随机顺序):fisow Robot5 tonytop cnhnln youbest leiv d00m3d asdmusic crandyworld juwen_zhong 晨想 alexlee1216 sonic_yq kikiwarm shooter x_crdjn ilptt linlin911911 ,是你们让中文版更加完美。 [版权声明]本手册译者皆是开源理念的坚定支持者,所以本手册虽然不是软件,但是遵照开源的精神发布。 [题外话]大部分 LFSer 都认为学习 LFS 需要有熟练使用 Linux 的基础,并且大部分听说过 LFS 的人都有一个印象:那是高手的玩具,不是我等菜鸟玩得了的……我不完全赞同,我认为基础如何并非关键,契而不舍的精神和强烈的求知欲才更加重要。想想自己接触 Linux 一个月左右的时候就有了和 Gerard 一样的想法,因为在学习 RedHat / Fedora / Debian 甚至是 Gentoo 的时候,我感觉到自己并不是在学习 Linux 而是在学习这些发行版各自的专有特性,他们把 Linux 本来的面貌层层包裹起来,让我不能深入理解背后的机制。并且这些版本各自有自己的优点和缺点,不能完全满足我的要求。其实那时候我的 Linux 水平仅仅限于会在控制台上敲几个 ls 之类的命令,从未编译过软件,连 make 都没听说过呢。但是我迫切想知道如何定制一个完全适合自己的 Linux 系统,问了好多 Linuxer ,把 Google 搜了个底朝天,也未能得到完整性的答案,唯一让我印象深刻的就是能够容纳在一张软盘上的 babyLinux ,但是它显然太简单,不能满足我的要求。一直郁闷了很久,好不容易机缘巧合,Qoo 兄弟叫我来 LinuxSir.Org 论坛的 LFS 版看看,当时论坛上只有一份不完整的 LFS 6.0 中文版,看完序言后,我激动的跳了起来,欢呼不已!这就是我梦寐以求的东西啊!于是在尚未安装过 LFS 的情况下,静下心来花了十多天时间先完整的翻译了 LFS 6.1 ,又花了5-6天时间,一行命令一行命令地完成了 LFS 的全过程。在学习 LFS 的20天里,我对 Linux 的理解发生了质的飞跃。大约没有人赞同学习 Linux 可以从 LFS 开始,这确实有一定的道理,但是 LFS 教给你的都是真正的 Linux "基础知识",并且这些知识可以为将来的进一步学习打下绝对扎实的基础。所以我要用自己的亲身经历鼓励那些刚刚接触 Linux 的新生牛犊勇敢的从 LFS 开始:没有基础不要紧,缺什么补什么!当你把 LFS 做完了,也就脱离"菜鸟"的行列了,用 LFS 给你的强大翅膀,勇敢地继续飞翔吧! 译者十分愿意与他人共享劳动成果,如果你对我的其他翻译作品或者技术文章有兴趣,可以在如下位置查看现有作品的集:
TSeriesMMA
cran
R
Package ‘TSeriesMMA’ October 12, 2022 Title Multiscale Multifractal Analysis of Time Series Data Version 0.1.1 Description Multiscale multifractal analysis (MMA) (Gierałtowski et al., 2012)<DOI:10.1103/PhysRevE.85.021915> is a time series analysis method, designed to describe scaling properties of fluctuations within the signal analyzed. The main result of this procedure is the so called Hurst surface h(q,s) , which is a dependence of the local Hurst exponent h (fluctuation scaling exponent) on the multifractal parameter q and the scale of observation s (data window width). Depends R (>= 3.0.2) License GPL (>= 2) Encoding UTF-8 LazyData true Author <NAME> [aut, cre], <NAME> [aut], <NAME> [aut], <NAME> [aut] Maintainer <NAME> <<EMAIL>> NeedsCompilation no Repository CRAN Date/Publication 2017-01-04 10:56:05 R topics documented: mm... 2 mma Multiscale Multifractal Analysis of Time Series Data Description Multiscale Multifractal Analysis of Time Series Data Usage mma(smin = 10, smax = 600, qmin = -5, qmax = 5, data, col = "V1", theta = -45, phi = 25) Arguments smin Minimal s scale used, when calculating Fq(s) functions family (default 10) smax Maximal s scale used, when calculating Fq(s) functions family, has to be multi- ple of 5 (default 600; in general should be near to N/50, where N is a time series length) qmin Minimal multifractal parameter q used (default -5) qmax Maximal cmultifractal parameter q used (deafault 5) data Time series data col The color variation of the plot theta Angle of view phi Second angle of view Examples ## Not run: mma(smax=30, data=timeSeriesData) ## End(Not run)
@storybook/addon-events
npm
JavaScript
Storybook Addon Events === This [storybook](https://storybooks.js.org) ([source](https://github.com/storybookjs/storybook)) addon allows you to add events for your stories. [Framework Support](https://github.com/storybookjs/storybook/blob/master/ADDONS_SUPPORT.md) [Storybook Addon Events Live Demo](https://z4o4z.github.io/storybook-addon-events/index.html) ### Getting Started ``` npm i --save-dev @storybook/addon-events event-emitter ``` within `.storybook/main.js`: ``` module.exports = { addons: ['@storybook/addon-events'] } ``` Then write your stories like this: ``` import withEvents from '@storybook/addon-events'; import EventEmitter from 'event-emitter'; import Logger from './Logger'; import * as EVENTS from './events'; const emitter = new EventEmitter(); const emit = emitter.emit.bind(emitter); export default { title: 'withEvents', decorators: [ withEvents({ emit, events: [ { name: EVENTS.TEST_EVENT_1, title: 'Test event 1', payload: 0, }, { name: EVENTS.TEST_EVENT_2, title: 'Test event 2', payload: 'asdasdad asdasdasd', }, { name: EVENTS.TEST_EVENT_3, title: 'Test event 3', payload: { string: 'value', number: 123, array: [1, 2, 3], object: { string: 'value', number: 123, array: [1, 2, 3], }, }, }, { name: EVENTS.TEST_EVENT_4, title: 'Test event 4', payload: [ { string: 'value', number: 123, array: [1, 2, 3], }, { string: 'value', number: 123, array: [1, 2, 3], }, { string: 'value', number: 123, array: [1, 2, 3], }, ], }, ] }), ], } export const defaultView = () => ( <Logger emitter={emitter} /> ); ``` Readme --- ### Keywords * addon * events * react * storybook * data-state
phonfieldwork
cran
R
Package ‘phonfieldwork’ October 14, 2022 Type Package Title Linguistic Phonetic Fieldwork Tools Version 0.0.11 Depends R (>= 3.5.0) Imports tuneR, phonTools, grDevices, utils, graphics, rmarkdown, xml2, uchardet, tools Description There are a lot of different typical tasks that have to be solved during phonetic re- search and experiments. This includes creating a presentation that will contain all stimuli, renam- ing and concatenating multiple sound files recorded during a session, automatic annota- tion in 'Praat' TextGrids (this is one of the sound annotation standards provided by 'Praat' soft- ware, see Boersma & Weenink 2020 <https://www.fon.hum.uva.nl/praat/>), creat- ing an html table with annotations and spectrograms, and converting multiple for- mats ('Praat' TextGrid, 'ELAN', 'EXMARaLDA', 'Audacity', subtitles '.srt', and 'FLEx' flex- text). All of these tasks can be solved by a mixture of different tools (any programming lan- guage has programs for automatic renaming, and Praat contains scripts for concatenating and re- naming files, etc.). 'phonfieldwork' provides a functionality that will make it eas- ier to solve those tasks independently of any additional tools. You can also compare the function- ality with other pack- ages: 'rPraat' <https://CRAN.R-project.org/package=rPraat>, 'textgRid' <https: //CRAN.R-project.org/package=textgRid>. License GPL (>= 2) SystemRequirements pandoc (>= 1.14) - http://pandoc.org URL https://CRAN.R-project.org/package=phonfieldwork, https://docs.ropensci.org/phonfieldwork/ BugReports https://github.com/ropensci/phonfieldwork/issues Encoding UTF-8 LazyData true RoxygenNote 7.1.1 VignetteBuilder knitr Suggests knitr, tidyverse, tidyr, dplyr, DT, lingtypology, testthat, readxl Language en-US NeedsCompilation no Author <NAME> [aut, cre] (<https://orcid.org/0000-0003-1990-6083>), <NAME> [rev] (<https://orcid.org/0000-0001-7087-9776>), <NAME> [rev] (<https://orcid.org/0000-0001-8584-3880>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2021-03-02 13:20:05 UTC R topics documented: add_leading_symbol... 3 annotate_textgri... 3 audacity_to_d... 4 concatenate_soundfile... 5 concatenate_textgrid... 6 create_empty_textgri... 7 create_glossed_documen... 8 create_image_look_u... 9 create_presentatio... 10 create_sound_pla... 11 create_subannotatio... 12 create_viewe... 13 df_to_tie... 14 draw_soun... 15 draw_spectrogra... 18 eaf_to_d... 20 exb_to_d... 21 extract_interval... 21 flextext_to_d... 22 formant_to_d... 23 get_sound_duratio... 24 get_textgrid_name... 24 intensity_to_d... 25 pitch_to_d... 25 read_from_folde... 26 remove_textgrid_tie... 27 rename_soundfile... 27 set_textgrid_name... 28 srt_to_d... 29 textgrid_to_d... 30 tier_to_d... 30 add_leading_symbols Create indices padded with zeros Description Create indices padded with zeros. This is important for creating appropriate for sorting names. Usage add_leading_symbols(file_names) Arguments file_names vector of any values. Value A string with numbers padded with leadinng zero. Author(s) <NAME> <<EMAIL>> annotate_textgrid Annotate textgrid Description Annotates textgrids. It is possible to define step in the argument "each", so each second element of the tier will be annotated. Usage annotate_textgrid( annotation, textgrid, tier = 1, each = 1, backup = TRUE, write = TRUE ) Arguments annotation vector of stimuli textgrid character with a filename or path to the TextGrid tier value that could be either ordinal number of the tier either name of the tier each non-negative integer. Each element of x is repeated each times backup logical. If TRUE (by default) it creates a backup tier. write logical. If TRUE (by dafault) it overwrites an existing tier. Value a string that contain TextGrid. If argument write is TRUE, then no output. Author(s) <NAME> <<EMAIL>> Examples annotate_textgrid( annotation = c("", "t", "e", "s", "t"), textgrid = system.file("extdata", "test.TextGrid", package = "phonfieldwork" ), tier = 2, write = FALSE ) audacity_to_df Audacity’s labels to dataframe Description Audacity make it possible to annotate sound files with labels that can be exported as a .tsv file with .txt extension. This function convert result to dataframe. Usage audacity_to_df(file_name) Arguments file_name file_name string with a filename or path to the .txt file produced by Audacity Value a dataframe with columns: content, time_start, time_end, source. Author(s) <NAME> <<EMAIL>> Examples audacity_to_df(system.file("extdata", "test_audacity.txt", package = "phonfieldwork" )) concatenate_soundfiles Concatenate sounds Description Creates a merged sound file from old sound files in a folder. If the annotation argument is not equal to NULL, it creates an annotation file (Praat .TextGrid, ELAN .eaf or EXMARaLDA .exb) with original sound names annotation. Usage concatenate_soundfiles( path, result_file_name = "concatenated", annotation = "textgrid" ) Arguments path path to the directory with soundfiles. result_file_name name of the result and annotation files. annotation character. There are several variants: "textgrid" for Praat TextGrid, "eaf" for ELAN’s .eaf file, or "exb" for EXMARaLDA’s .exb file. It is also possible to use NULL in order to prevent the creation of the annotation file. Value no output Author(s) <NAME> <<EMAIL>> Examples # create two files in a temprary folder "test_folder" s1 <- system.file("extdata", "test.wav", package = "phonfieldwork") s2 <- system.file("extdata", "post.wav", package = "phonfieldwork") tdir <- tempdir() file.copy(c(s1, s2), tdir) # here are two .wav files in a folder list.files(tdir) # [1] "post.wav" "test.wav" ... # Concatenate all files from the folder into concatenated.wav and create # corresponding TextGrid concatenate_soundfiles(path = tdir, result_file_name = "concatenated") list.files(tdir) # [1] "concatenated.TextGrid" "concatenated.wav" "post.wav" "test.wav" ... concatenate_textgrids Concatenate sounds Description Creates a merged sound file from old sound files in a folder. If the annotation argument is not equal to NULL, it creates an annotation file (Praat .TextGrid, ELAN .eaf or EXMARaLDA .exb) with original sound names annotation. Usage concatenate_textgrids(path, result_file_name = "concatenated") Arguments path path to the directory with soundfiles. result_file_name name of the result and annotation files. Value no output Author(s) <NAME> <<EMAIL>> Examples # create two files in a temprary folder "test_folder" t1 <- system.file("extdata", "test.TextGrid", package = "phonfieldwork") t2 <- system.file("extdata", "post.TextGrid", package = "phonfieldwork") tdir <- tempdir() file.copy(c(t1, t2), tdir) # here are two .wav files in a folder list.files(tdir) # [1] "post.TextGrid" "test.TextGrid" ... # Concatenate all TextGrids from the folder into concatenated.TextGrid concatenate_textgrids(path = tdir, result_file_name = "concatenated") list.files(tdir) # [1] "concatenated.TextGrid" "post.TextGrid" "test.TextGrid" ... create_empty_textgrid Create an empty TextGrid Description Creates an empty Praat TextGrid in the same folder as a reference sound file. It is possible to manage with predefined number of tiers, their names and their types. Usage create_empty_textgrid( duration, tier_name = NULL, point_tier = NULL, path, result_file_name = "new_textgrid" ) Arguments duration integer. Duration of the textgrid. If you do not know the duration of your audio file use the get_sound_duration() function. tier_name a vector that contain tier names. point_tier a vector that defines which tiers should be made point tiers. This argument excepts numeric values (e. g. c(2, 4) means second and forth tiers) or character (e. g. c("a", "b") means tiers with names "a" and "b") path path to the directory with soundfiles. result_file_name name of the result and annotation files. Value The function returns no output, just creates a Praat TextGrid in the same folder as a reference sound file. Author(s) <NAME> <<EMAIL>> Examples tmp <- tempfile(fileext = ".TextGrid") create_empty_textgrid(1, path = dirname(tmp), result_file_name = basename(tmp)) create_glossed_document Create a glossed document Description Creates a file with glossed example (export from .flextext or other formats) Usage create_glossed_document( flextext = NULL, rows = c("gls"), output_dir, output_file = "glossed_document", output_format = "html", example_pkg = NULL ) Arguments flextext path to a .flextext file or a dataframe with the following columns: p_id, s_id, w_id, txt, cf, hn, gls, msa, morph, word, phrase, paragraph, free_trans, text, text_title rows vector of row names from the flextext that should appear in the final document. Possible values are: "cf", "hn", "gls", "msa". "gls" is default. output_dir the output directory for the rendered file output_file the name of the result .html file (by default glossed_document). output_format The option can be "html" or "docx" example_pkg vector with name of the LaTeX package for glossing (possible values: "gb4e", "langsci", "expex", "philex") Value If render is FALSE, the function returns a path to the temporary file with .csv file. If render is TRUE, there is no output in a function. Author(s) <NAME> <<EMAIL>> create_image_look_up Create image look_up objects for html viewer Description Create image look_up objects for html viewer Usage create_image_look_up(img_src, img_caption = NULL, text = "&#x1f441;") Arguments img_src string or vector of strings with a image(s) path(s). img_caption string or vector of strings that will be displayed when image is clicked. text string o vector of strings that will be displayed as view link. By default it is eye emoji (&#x1f441;). Value a string or vector of strings Author(s) <NAME> <<EMAIL>> create_presentation Creates a presentation Description Creates an html or powerpoint presentation in a working directory from list of words and transla- tions. Here is an example of such presentation. Usage create_presentation( stimuli, translations = "", external = NULL, font_size = 50, output_dir, output_format = "html", output_file = "stimuli_presentation", render = TRUE ) Arguments stimuli the vector of stimuli (obligatory). Can be a path to an image. translations the vector of translations (optional) external the vector with the indices of external images font_size font size in px (50, by default) output_dir the output directory for the rendered file output_format the string that difine the R Markdown output format: "html" (by default) or "pptx" output_file the name of the result presentation file (by default stimuli_presentation) render the logical argument, if TRUE render the created R Markdown presentation to the output_dir folder, otherwise returns the path to the temporary file with a Rmd file. Value If render is FALSE, the function returns a path to the temporary file. If render is TRUE, there is no output in a function. Author(s) <NAME> <<EMAIL>> Examples create_presentation( stimuli = c("rzeka", "drzewo"), translations = c("river", "tree"), render = FALSE ) # with image create_presentation( stimuli = c( "rzeka", "drzewo", system.file("extdata", "r-logo.png", package = "phonfieldwork" ) ), translations = c("river", "tree", ""), external = 3, render = FALSE ) create_sound_play Create audio play objects for html viewer Description Create audio play objects for html viewer Usage create_sound_play(snd_src, text = "&#x1f442;") Arguments snd_src string or vector of strings with a image(s) path(s). text string o vector of strings that will be displayed as view link. By default it is ear emoji (&#x1f442;). Value a string or vector of strings Author(s) <NAME> <<EMAIL>> create_subannotation Create boundaries in a texgrid tier Description Create boundaries in a texgrid tier Usage create_subannotation( textgrid, tier = 1, new_tier_name = "", n_of_annotations = 4, each = 1, omit_blank = TRUE, overwrite = TRUE ) Arguments textgrid character with a filename or path to the TextGrid tier value that could be either ordinal number of the tier either name of the tier new_tier_name a name of a new created tier n_of_annotations number of new annotations per annotation to create each non-negative integer. Each new blank annotation is repeated every first, second or ... times omit_blank logical. If TRUE (by dafault) it doesn’t create subannotation for empy annota- tions. overwrite logical. If TRUE (by dafault) it overwrites an existing tier. Value a string that contain TextGrid. If argument write is TRUE, then no output. Author(s) <NAME> <<EMAIL>> Examples create_subannotation(system.file("extdata", "test.TextGrid", package = "phonfieldwork" ), tier = 1, overwrite = FALSE ) create_viewer Create an annotation viewer Description Creates an html file with table and sound preview and player Usage create_viewer( audio_dir, picture_dir, table, captions = NULL, sorting_columns = NULL, about = "Created with the `phonfieldworks` package (Moroz 2020).", map = FALSE, output_dir, output_file = "stimuli_viewer", render = TRUE ) Arguments audio_dir path to the directory with sounds picture_dir path to the directory with pictures table data frame with data ordered according to files in the audio folder captions vector of strings that will be used for captions for a picture. sorting_columns vector of strings for sorting the result column about it is either .Rmd file or string with the text for about information: author, project, place of gahtered information and other metadata, version of the viewer and so on map the logical argument, if TRUE and there is a glottocode column in table output_dir the output directory for the rendered file output_file the name of the result .html file (by default stimuli_viewer) render the logical argument, if TRUE renders the created R Markdown viewer to the output_dir folder, otherwise returns the path to the temporary file with a .csv file. Value If render is FALSE, the function returns a path to the temporary file with .csv file. If render is TRUE, there is no output in a function. Author(s) <NAME> <<EMAIL>> df_to_tier Dataframe to TextGrid’s tier Description Convert a dataframe to a Praat TextGrid. Usage df_to_tier(df, textgrid, tier_name = "", overwrite = TRUE) Arguments df an R dataframe object that contains columns named "content", "time_start" and "time_end" textgrid a character with a filename or path to the TextGrid tier_name a vector that contain a name for a created tier overwrite a logic argument, if TRUE overwrites the existing TextGrid file Value If overwrite is FALSE, then the function returns a vector of strings with a TextGrid. If overwrite is TRUE, then no output. Author(s) <NAME> <<EMAIL>> Examples time_start <- c(0.00000000, 0.01246583, 0.24781914, 0.39552363, 0.51157715) time_end <- c(0.01246583, 0.24781914, 0.39552363, 0.51157715, 0.65267574) content <- c("", "T", "E", "S", "T") df_to_tier(my_df <- data.frame(id = 1:5, time_start, time_end, content), system.file("extdata", "test.TextGrid", package = "phonfieldwork" ), overwrite = FALSE ) draw_sound Draw Oscilogram, Spectrogram and annotation Description Create oscilogram and spectrogram plot. Usage draw_sound( file_name, annotation = NULL, from = NULL, to = NULL, zoom = NULL, text_size = 1, output_file = NULL, title = NULL, freq_scale = "kHz", frequency_range = c(0, 5), dynamic_range = 50, window_length = 5, window = "kaiser", windowparameter = -1, preemphasisf = 50, spectrum_info = TRUE, raven_annotation = NULL, formant_df = NULL, pitch = NULL, pitch_range = c(75, 350), intensity = NULL, output_width = 750, output_height = 500, output_units = "px", sounds_from_folder = NULL, textgrids_from_folder = NULL, pic_folder_name = "pics", title_as_filename = TRUE, prefix = NULL, suffix = NULL, autonumber = FALSE ) Arguments file_name a sound file annotation a source for annotation files (path to TextGrid file or dataframe created from other linguistic types, e. g. via textgrid_to_df(), eaf_to_df() or other functions) from Time in seconds at which to start extraction. to Time in seconds at which to stop extraction. zoom numeric vector of zoom window time (in seconds). It will draw the whole os- cilogram and part of the spectrogram. text_size numeric, text size (default = 1). output_file the name of the output file title the title for the plot freq_scale a string indicating the type of frequency scale. Supported types are: "Hz" and "kHz". frequency_range vector with the range of frequencies to be displayed for the spectrogram up to a maximum of fs/2. By default this is set to 0-5 kHz. dynamic_range values greater than this many dB below the maximum will be displayed in the same color window_length the desired analysis window length in milliseconds. window A string indicating the type of window desired. Supported types are: "rectangu- lar", "hann", "hamming", "cosine", "bartlett", "gaussian", and "kaiser". windowparameter The parameter necessary to generate the window, if appropriate. At the moment, the only windows that require parameters are the Kaiser and Gaussian windows. By default, these are set to 2 for kaiser and 0.4 for gaussian windows. preemphasisf Preemphasis of 6 dB per octave is added to frequencies above the specified fre- quency. For no preemphasis, set to a frequency higher than the sampling fre- quency. spectrum_info logical. If TRUE then add information about window method and params. raven_annotation Raven (Center for Conservation Bioacoustics) style annotations (boxes over spectrogram). The dataframe that contains time_start, time_end, freq_low and freq_high columns. Optional columns are colors and content. formant_df dataframe with formants from formant_to_df() function pitch path to the Praat ‘.Pitch‘ file or result of pitch_to_df() function. This variable provide data for visualisation of a pitch contour exported from Praat. pitch_range vector with the range of frequencies to be displayed. By default this is set to 75-350 Hz. intensity path to the Praat ‘.Intensity‘ file or result of intensity_to_df() function. This variable provide data for visualisation of an intensity contour exported from Praat. output_width the width of the device output_height the height of the device output_units the units in which height and width are given. Can be "px" (pixels, the default), "in" (inches), "cm" or "mm". sounds_from_folder path to a folder with multiple sound files. If this argument is not NULL, then the function goes through all files and creates picture for all of them. textgrids_from_folder path to a folder with multiple .TextGrid files. If this argument is not NULL, then the function goes through all files and create picture for all of them. pic_folder_name name for a folder, where all pictures will be stored in case sounds_from_folder argument is not NULL title_as_filename logical. If true adds filename title to each picture prefix prefix for all file names for created pictures in case sounds_from_folder argu- ment is not NULL suffix suffix for all file names for created pictures in case sounds_from_folder argu- ment is not NULL autonumber if TRUE automatically add number of extracted sound to the file_name. Prevents from creating a duplicated files and wrong sorting. Value Oscilogram and spectrogram plot (and possibly TextGrid annotation). Author(s) <NAME> <<EMAIL>> Examples ## Not run: draw_sound(system.file("extdata", "test.wav", package = "phonfieldwork")) draw_sound( system.file("extdata", "test.wav", package = "phonfieldwork"), system.file("extdata", "test.TextGrid", package = "phonfieldwork" ) ) draw_sound(system.file("extdata", "test.wav", package = "phonfieldwork"), system.file("extdata", "test.TextGrid", package = "phonfieldwork"), pitch = system.file("extdata", "test.Pitch", package = "phonfieldwork" ), pitch_range = c(50, 200) ) draw_sound(system.file("extdata", "test.wav", package = "phonfieldwork"), system.file("extdata", "test.TextGrid", package = "phonfieldwork"), pitch = system.file("extdata", "test.Pitch", package = "phonfieldwork" ), pitch_range = c(50, 200), intensity = intensity_to_df(system.file("extdata", "test.Intensity", package = "phonfieldwork" )) ) draw_sound(system.file("extdata", "test.wav", package = "phonfieldwork"), formant_df = formant_to_df(system.file("extdata", "e.Formant", package = "phonfieldwork" )) ) ## End(Not run) draw_spectrogram Draw spectrograms Description This function was slightly changed from phonTools::spectrogram(). Argument description is copied from phonTools::spectrogram(). Usage draw_spectrogram( sound, fs = 22050, text_size = 1, window_length = 5, dynamic_range = 50, window = "kaiser", windowparameter = -1, freq_scale = "kHz", spectrum_info = TRUE, timestep = -1000, padding = 10, preemphasisf = 50, frequency_range = c(0, 5), nlevels = dynamic_range, x_axis = TRUE, title = NULL, raven_annotation = NULL, formant_df = NULL ) Arguments sound Either a numeric vector representing a sequence of samples taken from a sound wave or a sound object created with the loadsound() or makesound() functions. fs The sampling frequency in Hz. If a sound object is passed this does not need to be specified. text_size numeric, text size (default = 1). window_length The desired analysis window length in milliseconds. dynamic_range Values greater than this many dB below the maximum will be displayed in the same color. window A string indicating the type of window desired. Supported types are: rectangu- lar, hann, hamming, cosine, bartlett, gaussian, and kaiser. windowparameter The parameter necessary to generate the window, if appropriate. At the moment, the only windows that require parameters are the Kaiser and Gaussian windows. By default, these are set to 2 for kaiser and 0.4 for gaussian windows. freq_scale a string indicating the type of frequency scale. Supported types are: "Hz" and "kHz". spectrum_info logical. If TRUE then add information about window method and params. timestep If a negative value is given, -N, then N equally-spaced time steps are calculated. If a positive number is given, this is the spacing between adjacent analyses, in milliseconds. padding The amount of zero padding for each window, measured in units of window length. For example, if the window is 50 points, and padding = 10, 500 zeros will be appended to each window. preemphasisf Preemphasis of 6 dB per octave is added to frequencies above the specified fre- quency. For no preemphasis, set to a frequency higher than the sampling fre- quency. frequency_range vector with the range of frequencies to be displayed for the spectrogram up to a maximum of fs/2. This is set to 0-5 kHz by default. nlevels The number of divisions to be used for the z-axis of the spectrogram. By default it is set equal to the dynamic range, meaning that a single color represents 1 dB on the z-axis. x_axis If TRUE then draw x axis. title Character with the title. raven_annotation Raven (Center for Conservation Bioacoustics) style annotations (boxes over spectrogram). The dataframe that contains time_start, time_end, freq_low and freq_high columns. Optional columns are colors and content. formant_df dataframe with formants from formant_to_df() function Author(s) <NAME> <<EMAIL>> Examples ## Not run: draw_spectrogram(system.file("extdata", "test.wav", package = "phonfieldwork" )) ## End(Not run) eaf_to_df ELAN’s .eaf file to dataframe Description Convert .eaf file from ELAN to a dataframe. Usage eaf_to_df(file_name) Arguments file_name string with a filename or path to the .eaf file Value a dataframe with columns: tier, id, content, tier_name, tier_type, time_start, time_end, source). Author(s) <NAME> <<EMAIL>> Examples eaf_to_df(system.file("extdata", "test.eaf", package = "phonfieldwork")) exb_to_df EXMARaLDA’s .exb file to dataframe Description Convert .exb file from EXMARaLDA to a dataframe. Usage exb_to_df(file_name) Arguments file_name string with a filename or path to the .exb file Value a dataframe with columns: tier, id, content, tier_name, tier_type, tier_category, tier_speaker, time_start, time_end, source. Author(s) <NAME> <<EMAIL>> Examples exb_to_df(system.file("extdata", "test.exb", package = "phonfieldwork")) extract_intervals Extract intervals Description Extract sound according to non-empty annotated intervals from TextGrid and create soundfiles with correspondent names. Usage extract_intervals( file_name, textgrid, tier = 1, prefix = NULL, suffix = NULL, autonumber = TRUE, path ) Arguments file_name path to the soundfile textgrid path to the TextGrid tier tier number or name that should be used as base for extraction and names prefix character vector containing prefix(es) for file names suffix character vector containing suffix(es) for file names autonumber if TRUE automatically add number of extracted sound to the file_name. Prevents from creating a duplicated files and wrong sorting. path path to the directory where create extracted soundfiles. Value no output Author(s) <NAME> <<EMAIL>> Examples # create two files in a temprary folder "test_folder" s <- system.file("extdata", "test.wav", package = "phonfieldwork") tdir <- tempdir() file.copy(s, tdir) # Extract intervals according the TextGrid into the path extract_intervals( file_name = paste0(tdir, "/test.wav"), textgrid = system.file("extdata", "test.TextGrid", package = "phonfieldwork" ), path = tdir ) list.files(tdir) # [1] "e-2.wav" "s-3.wav" "t-1.wav" "t-4.wav" "test.wav" flextext_to_df FLEX’s .flextext file to dataframe Description Convert .flextext file from FLEX to a dataframe. Usage flextext_to_df(file_name) Arguments file_name string with a filename or path to the .flextext file Value a dataframe with columns: p_id, s_id, w_id, txt, cf, hn, gls, msa, morph, word, phrase, paragraph, free_trans, text, text_title Author(s) <NAME> <<EMAIL>> formant_to_df Praat Formant object to dataframe Description Convert a Praat Formant object to a dataframe. Usage formant_to_df(file_name) Arguments file_name string with a filename or path to the Formant file Value a dataframe with columns: time_start, time_end, frequency, bandwidth and formant Author(s) <NAME> <<EMAIL>> Examples formant_to_df(system.file("extdata", "e.Formant", package = "phonfieldwork")) get_sound_duration Get file(s) duration Description Calculate sound(s) duration. Usage get_sound_duration(file_name) Arguments file_name a sound file Author(s) <NAME> <<EMAIL>> Examples get_sound_duration( system.file("extdata", "test.wav", package = "phonfieldwork") ) get_textgrid_names Extract TextGrid names Description Extract TextGrid names. Usage get_textgrid_names(textgrid) Arguments textgrid path to the TextGrid Value return a vector of tier names from given TextGrid Author(s) <NAME> <<EMAIL>> Examples get_textgrid_names(system.file("extdata", "test.TextGrid", package = "phonfieldwork" )) intensity_to_df Praat Intensity tier to dataframe Description Convert a Praat Intensity tier to a dataframe. Usage intensity_to_df(file_name) Arguments file_name string with a filename or path to the Intensity tier Value a dataframe with columns: time_start, time_end, Intensity Author(s) <NAME> <<EMAIL>> Examples intensity_to_df(system.file("extdata", "test.Intensity", package = "phonfieldwork")) pitch_to_df Praat Pitch tier to dataframe Description Convert a Praat Pitch tier to a dataframe. Usage pitch_to_df(file_name, candidates = "") Arguments file_name string with a filename or path to the Pitch tier candidates Praat Pitch tier contains multiple candidates for each time slice, use the value "all" if you want to get them all Value a dataframe with columns: time_start, time_end, frequency and, if candidates = "all", candidate_id and strength Author(s) <NAME> <<EMAIL>> Examples pitch_to_df(system.file("extdata", "test.Pitch", package = "phonfieldwork")) read_from_folder Read multiple files from the folder Description This function reads multiple files from the folder. The first argument is the path, the second argu- ment is the type of files to read. Usage read_from_folder(path, type) Arguments path to a folder with multiple sound files. type should be one of the following: "duration", "audacity", "eaf", "exb", "flextext", "formant", "intensity", "picth", "srt", "textgrid" Author(s) <NAME> <<EMAIL>> Examples read_from_folder(system.file("extdata", package = "phonfieldwork"), "eaf") remove_textgrid_tier Remove tier from texgrid Description Remove tier from texgrid Usage remove_textgrid_tier(textgrid, tier, overwrite = TRUE) Arguments textgrid character with a filename or path to the TextGrid tier value that could be either ordinal number of the tier either name of the tier overwrite logical. If TRUE (by dafault) it overwrites an existing tier. Value a string that contain TextGrid. If argument write is TRUE, then no output. rename_soundfiles Rename soundfiles Description Rename soundfiles using the template from user. Usage rename_soundfiles( stimuli, translations = NULL, prefix = NULL, suffix = NULL, order = NULL, missing = NULL, path, autonumbering = TRUE, backup = TRUE, logging = TRUE ) Arguments stimuli character vector of stimuli translations character vector of translations (optonal). This values are added after stimuli to the new files’ names so the result will be ...stimulus_translation.... prefix character vector of length one containing prefix for file names suffix character vector of length one containing suffix for file names order numeric vector that define the order of stimuli. By default the order of the stimuli is taken. missing numeric vector that define missing stimuli in case when some stimuli are not recorded. path path to the directory with soundfiles. autonumbering logical. If TRUE, function creates an automatic numbering of files. backup logical. If TRUE, function creates backup folder with all files. By default is TRUE. logging logical. If TRUE creates a .csv file with the correspondences of old names and new names. This could be useful for restoring in case something goes wrong. Value no output Author(s) <NAME> <<EMAIL>> set_textgrid_names Rewrite TextGrid names Description Rewrite TextGrid names. Usage set_textgrid_names(textgrid, tiers, names, write = TRUE) Arguments textgrid path to the TextGrid tiers integer vector with the number of tiers that should be named names vector of strings with new names for TextGrid tiers write logical. If TRUE (by dafault) it overwrites an existing tier Value a string that contain TextGrid. If argument write is TRUE, then no output. Author(s) <NAME> <<EMAIL>> Examples set_textgrid_names(system.file("extdata", "test.TextGrid", package = "phonfieldwork" ), tiers = 3, names = "new_name", write = FALSE ) srt_to_df Subtitles .srt file to dataframe Description Convert subtitles .srt file to a dataframe. Usage srt_to_df(file_name) Arguments file_name string with a filename or path to the .srt file Value a dataframe with columns: id, content, time_start, time_end, source. Author(s) <NAME> <<EMAIL>> Examples srt_to_df(system.file("extdata", "test.srt", package = "phonfieldwork")) textgrid_to_df TextGrid to dataframe Description Convert Praat TextGrid to a dataframe. Usage textgrid_to_df(file_name) Arguments file_name string with a filename or path to the TextGrid Value a dataframe with columns: id, time_start, time_end (if it is an interval tier – the same as the start value), content, tier, tier_name and source Author(s) <NAME> <<EMAIL>> Examples textgrid_to_df(system.file("extdata", "test.TextGrid", package = "phonfieldwork" )) # this is and example of reading a short .TextGrid format textgrid_to_df(system.file("extdata", "test_short.TextGrid", package = "phonfieldwork" )) tier_to_df TextGrid’s tier to dataframe Description Convert selected tier from a Praat TextGrid to a dataframe. Usage tier_to_df(file_name, tier = 1) Arguments file_name string with a filename or path to the TextGrid tier value that could be either ordinal number of the tier either name of the tier. By default is ’1’. Value a dataframe with columns: id, time_start, time_end, content, , tier_name Author(s) <NAME> <<EMAIL>> Examples tier_to_df(system.file("extdata", "test.TextGrid", package = "phonfieldwork" )) tier_to_df( system.file("extdata", "test.TextGrid", package = "phonfieldwork" ), "intervals" )
endorse
cran
R
Package ‘endorse’ October 13, 2022 Version 1.6.2 Date 2022-5-2 Title Bayesian Measurement Models for Analyzing Endorsement Experiments Author <NAME> [aut, cre], <NAME> [aut], <NAME> [ctb] Maintainer <NAME> <<EMAIL>> Depends coda, utils Description Fit the hierarchical and non-hierarchical Bayesian measurement models proposed by Bul- lock, Imai, and Shapiro (2011) <DOI:10.1093/pan/mpr031> to analyze endorsement experi- ments. Endorsement experiments are a survey methodology for eliciting truthful responses to sen- sitive questions. This methodology is helpful when measuring support for socially sensitive po- litical actors such as militant groups. The model is fitted with a Markov chain Monte Carlo algo- rithm and produces the output containing draws from the posterior distribution. LazyLoad yes LazyData yes License GPL (>= 2) URL https://github.com/SensitiveQuestions/endorse/ NeedsCompilation yes Repository CRAN Date/Publication 2022-05-02 07:00:12 UTC R topics documented: endors... 2 endorse.plo... 11 GeoCoun... 13 GeoI... 13 pakista... 14 predict.endors... 15 endorse Fitting the Measurement Model of Political Support via Markov Chain Monte Carlo Description This function generates a sample from the posterior distribution of the measurement model of po- litical support. Individual-level covariates may be included in the model. The details of the model are given under ‘Details’. See also Bullock et al. (2011). Usage endorse(Y, data, data.village = NA, village = NA, treat = NA, na.strings = 99, identical.lambda = TRUE, covariates = FALSE, formula.indiv = NA, hierarchical = FALSE, formula.village = NA, h = NULL, group = NULL, x.start = 0, s.start = 0, beta.start = 1, tau.start = NA, lambda.start = 0, omega2.start = .1, theta.start = 0, phi2.start = .1, kappa.start = 0, psi2.start = 1, delta.start = 0, zeta.start = 0, rho2.start = 1, mu.beta = 0, mu.x = 0, mu.theta = 0, mu.kappa = 0, mu.delta = 0, mu.zeta = 0, precision.beta = 0.04, precision.x = 1, precision.theta = 0.04, precision.kappa = 0.04, precision.delta = 0.04, precision.zeta = 0.04, s0.omega2= 1, nu0.omega2 = 10, s0.phi2 = 1, nu0.phi2 = 10, s0.psi2 = 1, nu0.psi2 = 10, s0.sig2 = 1, nu0.sig2 = 400, s0.rho2 = 1, nu0.rho2 = 10, MCMC = 20000, burn = 1000, thin = 1, mh = TRUE, prop = 0.001, x.sd = TRUE, tau.out = FALSE, s.out = FALSE, omega2.out = TRUE, phi2.out = TRUE, psi2.out = TRUE, verbose = TRUE, seed.store = FALSE, update = FALSE, update.start = NULL) Arguments Y a list of the variable names for the responses. It should take the following form: list(Q1 = c("varnameQ1.1", "varnameQ1.2", ...),...). If treat is NA, the first variable for each question should be the responses of the control observations while each of the other variables should correspond to each endorser. treat should be supplied if only one variable name is provided for a question in this argument. If auxiliary information is included, it is assumed that Y is coded such that higher values indicate more of the sensitive trait. data data frame containing the individual-level variables. The cases must be com- plete, i.e., no NA’s are allowed. data.village data frame containing the village-level variables. The cases must be complete, i.e., no NA’s are allowed. If auxiliary information is included, the data frame should include only the unique group identifier and the unique identifier for the units at which prediction is desired. The package does not currently support the inclusion of covariates in models with auxiliary information. village character. The variable name of the village indicator in the individual-level data. If auxiliary information is included, this should correspond to the variable name of the units at which prediction is desired. treat An optional matrix of non negative integers indicating the treatment status of each observation and each question. Rows are observations and columns are questions. 0 represents the control status while positive integers indicate treat- ment statuses. If treat is set to NA, the function generates the treatment matrix using Y. The default is NA. na.strings a scalar or a vector indicating the values of the response variable that are to be interpreted as “Don’t Know” or “Refused to Answer.” The value should not be NA unless treat is provided, because NA’s are interpreted as the response to the question with another endorsement. Default is 99. identical.lambda logical. If TRUE, the model with a common lambda across questions will be fitted. The default is TRUE. covariates logical. If TRUE, the model includes individual-level covariates. The default is FALSE. formula.indiv a symbolic description specifying the individual level covariates for the support parameter and the ideal points. The formula should be one-sided, e.g. ~ Z1 + Z2. hierarchical logical. IF TRUE, the hierarchical model with village level predictors will be fitted. The default is FALSE. formula.village a symbolic description specifying the village level covariates for the support parameter and the ideal points. The formula should be one-sided. h Auxiliary data functionality. Optional named numeric vector with length equal to number of groups. Names correspond to group labels and values correspond to auxiliary moments (i.e. to the known share of the sensitive trait at the group level). group Auxiliary data functionality. Optional character string. The variable name of the group indicator in the individual-level data (e.g. group = "county"). x.start starting values for the ideal points vector x. If x.start is set to a scalar, the starting values for the ideal points of all respondents will be set to the scalar. If x.start is a vector of the same length as the number of observations, then this vector will be used as the starting values. The default is 0. s.start starting values for the support parameter, si jk. If s.start is set to a scalar, the starting values for the support parameter of all respondents and all questions will be the scalar. If s.start is set to a matrix, it should have the same number of rows as the number of observations and the same number of columns as the number of questions. Also, the value should be zero for the control condition. The default is 0. beta.start starting values for the question related parameters, αj and βj . If beta.start is set to a scalar, the starting values for the support parameter of all respondents and all questions will be the scalar. If beta.start is set to a matrix, the number of rows should be the number of questions and the number of columns should be 2. The first column will be the starting values for αj and the second column will be the starting values for βj . Since the parameter values are constrained to be positive, the starting values should be also positive. The default is 1. tau.start starting values for the cut points in the response model. If NA, the function generates the starting values so that each interval between the cut points is 0.5. If tau.start is set to a matrix, the number of rows should be the same as the number of questions and the number of columns should be the maximum value of the number of categories in the responses. The first cut point for each question should be set to 0 while the last one set to the previous cut point plus 1000. The default is NA. lambda.start starting values for the coefficients in the support parameter model, λj k. If lambda.start is set to a scalar, the starting values for all coefficients will be the scalar. If lambda.start is set to a matrix, the number of rows should be the number of the individual level covariates (plus the number of villages, if the model is hierarchical), and the number of columns should be the number of en- dorsers (times the number of questions, if the model is with varying lambdas). The default is 0. omega2.start starting values for the variance of the support parameters, ωjk2 . If set to a scalar, 2 the starting values for omegajk will be the diagonal matrix with the diagonal elements set to the scalar. If omega2.start is set to a matrix, the number of rows should be the number of questions, while the number of columns should be the same as the number of endorsers. The default is .1. theta.start starting values for the means of the λjk for each endorser. If theta.start is set to a scalar, the starting values for all parameters will be the scalar. If theta.start is set to a matrix, the number of rows should be the number of endorsers and the number of columns should be the dimension of covariates. The default is 0. phi2.start starting values for the covariance matrices of the coefficients of the support pa- rameters, Φk . Φk is assumed to be a diagonal matrix. If phi2.start is set to a scalar, the starting values for all covariance matrices will be the same diago- nal matrix with the diagonal elements set to the scalar. If phi2.start is set to a vector, the length should be the number of endorsers times the dimension of covariates. The default is .1. kappa.start starting values for the coefficients on village level covariates in the support pa- rameter model, κk . If kappa.start is set to a scalar, the starting values for all coefficients will be the scalar. If kappa.start is set to a matrix, the number of rows should be the number of the village level covariates, and the number of columns should be the number of endorsers (times the number of questions, if the varying-lambda model is fitted). The default is 0. psi2.start starting values for the variance of the village random intercepts in the support parameter model, ψk2 . If psi2.start is set to a scalar, the starting values for ψk2 will be the diagonal matrix with the diagonal elements set to the scalar. If psi2.start is set to a vector, its length should be the number of endorsers (times the number of questions, if the varying-lambda model is fitted). The default is .1. delta.start starting values for the coefficients on individual level covariates in the ideal point model. Will be used only if covariates = TRUE. If delta.start is set to a scalar, the starting values for all coefficients will be the scalar. If delta.start is set to a vector, the length should be the dimension of covariates. The default is 0. zeta.start starting values for the coefficients on village level covariates in the ideal point model. Will be used only if covariates = TRUE. If zeta.start is set to a scalar, the starting values for all coefficients will be the scalar. If zeta.start is set to a vector, the length should be the dimension of covariates. The default is 0. rho2.start numeric. starting values for the variance of the village random intercepts in the ideal point model, ρ2 . The default is 1. mu.beta the mean of the independent Normal prior on the question related parameters. Can be either a scalar or a matrix of dimension the number of questions times 2. The default is 0. mu.x the mean of the independent Normal prior on the question related parameters. Can be either a scalar or a vector of the same length as the number of observa- tions. The default is 0. mu.theta the mean of the independent Normal prior on the mean of the coefficients in the support parameter model. Can be either a scalar or a vector of the same length as the dimension of covariates. The default is 0. mu.kappa the mean of the independent Normal prior on the coefficients of village level covariates. Can be either a scalar or a matrix of dimension the number of co- variates times the number of endorsers. If auxiliary information is included, the value of mu.kappa will be computed for each group such that the prior probabil- ity of the support parameter taking a positive value is equal to the known value of h. The default is 0. mu.delta the mean of the independent Normal prior on the the coefficients in the ideal point model. Can be either a scalar or a vector of the same length as the dimen- sion of covariates. The default is 0. mu.zeta the mean of the independent Normal prior on the the coefficients of village level covariates in the ideal point model. Can be either a scalar or a vector of the same length as the dimension of covariates. The default is 0. precision.beta the precisions (inverse variances) of the independent Normal prior on the ques- tion related parameters. Can be either a scalar or a 2 × 2 diagonal matrix. The default is 0.04. precision.x scalar. The known precision of the independent Normal distribution on the ideal points. The default is 1. precision.theta the precisions of the independent Normal prior on the means of the coefficients in the support parameter model. Can be either a scalar or a vector of the same length as the dimension of covariates. The default is 0.04. precision.kappa the precisions of the independent Normal prior on the coefficients of village level covariates in the support parameter model. Can be either a scalar or a vector of the same length as the dimension of covariates. If auxiliary information is included, the value of precision.kappa will be fixed to 100000. The default is 0.04. precision.delta the precisions of the independent Normal prior on the the coefficients in the ideal point model. Can be either a scalar or a square matrix of the same dimension as the dimension of covariates. The default is 0.04. precision.zeta the precisions of the independent Normal prior on the the coefficients of village level covariates in the ideal point model. Can be either a scalar or a square matrix of the same dimension as the dimension of covariates. The default is 0.04. s0.omega2 scalar. The scale of the independent scaled inverse- chi-squared prior for the variance parameter in the support parameter model. If auxiliary information is included, the value of s0.omega2 will be fixed to the default. The default is 1. nu0.omega2 scalar. The degrees of freedom of the independent scaled inverse-chi-squared prior for the variance parameter in the support parameter model. If auxiliary information is included, the value of nu0.omega2 will be fixed to the default. The default is 10. s0.phi2 scalar. The scale of the independent scaled inverse-chi-squared prior for the variances of the coefficients in the support parameter model. The default is 1. nu0.phi2 scalar. The degrees of freedom of the independent scaled inverse-chi-squared prior for the variances of the coefficients in the support parameter model. The default is 10. s0.psi2 scalar. The scale of the independent scaled inverse-chi-squared prior for the variances of the village random intercepts in the support parameter model. The default is 1. nu0.psi2 scalar. The degrees of freedom of the independent scaled inverse-chi-squared prior for the variances of the village random intercepts in the support parameter model. The default is 10. s0.sig2 scalar. The scale of the independent scaled inverse-chi-squared prior for the variance parameter in the ideal point model. The default is 1. nu0.sig2 scalar. The degrees of freedom of the independent scaled inverse-chi-squared prior for the variance parameter in the ideal point model. The default is 400. s0.rho2 scalar. The scale of the independent scaled inverse-chi-squared prior for the variances of the village random intercepts in the ideal point model. The default is 1. nu0.rho2 scalar. The degrees of freedom of the independent scaled inverse-chi-squared prior for the variances of the village random intercepts in the ideal point model. The default is 10. MCMC the number of iterations for the sampler. The default is 20000. burn the number of burn-in iterations for the sampler. The default is 1000. thin the thinning interval used in the simulation. The default is 1. mh logical. If TRUE, the Metropolis-Hastings algorithm is used to sample the cut points in the response model. The default is TRUE. prop a positive number or a vector consisting of positive numbers. The length of the vector should be the same as the number of questions. This argument sets proposal variance for the Metropolis-Hastings algorithm in sampling the cut points of the response model. The default is 0.001. x.sd logical. If TRUE, the standard deviation of the ideal points in each draw will be stored. If FALSE, a sample of the ideal points will be stored. NOTE: Because storing a sample takes an enormous amount of memory, this option should be selected only if the chain is thinned heavily or the data have a small number of observations. tau.out logical. A switch that determines whether or not to store the cut points in the response model. The default is FALSE. s.out logical. If TRUE, the support parameter for each respondent and each question will be stored. The default is FALSE. NOTE: Because storing a sample takes an enormous amount of memory, this option should be selected only if the chain is thinned heavily or the data have a small number of observations. omega2.out logical. If TRUE, the variannce parameter of the support parameter model will be stored. The default is TRUE. phi2.out logical. If TRUE, the variannce parameter of the model for the coefficients in the support parameter model will be stored. The default is TRUE. psi2.out logical. If TRUE, the variance of the village random intercepts in the support parameter model will be stored. The default is TRUE. verbose logical. A switch that determines whether or not to print the progress of the chain and Metropolis acceptance ratios for the cut points of the response model. The default is TRUE. seed.store logical. If TRUE, the seed will be stored in order to update the chain later. The default is FALSE. update logical. If TURE, the function is run to update a chain. The default is FALSE. update.start list. If the function is run to update a chain, the output object of the previous run should be supplied. The default is NULL. Details The model takes the following form: Consider an endorsement experiment where we wish to measure the level of support for K political actors. In the survey, respondents are asked whether or not they support each of J policies chosen by researchers. Let Yij represent respondent i’s answer to the survey question regarding policy j. Suppose that the response variable Yij is the ordered factor variable taking one of Lj levels, i.e., Yij ∈ {0, 1, . . . , Lj − 1} where Lj > 1. We assume that a greater value of Yij indicates a greater level of support for policy j. We denote an M dimensional vector of the observed characteristics of respondent i by Zi . In the experiment, we randomly assign one of K political actors as an endorser to respondent i’s question regarding policy j and denote this treatment variable by Tij ∈ {0, 1, . . . , K}. We use Tij = 0 to represent the control observations where no political endorsement is attached to the question. Alternatively, one may use the endorsement by a neutral actor as the control group. The model for the response variable, Yij , is given by, Yij = l if τl < Yij∗ ≤ τl+1 , Yij∗ | Tij = k ∼ N (−αj + βj (xi + sijk ), I) where l ∈ {0, 1, . . . , Lj }, τ0 = −∞ < τ1 = 0 < τ2 < . . . < τLj = ∞. βj ’s are assumed to be positive. The model for the support parameter, sijk , is given by if Tij 6= 0, sijk ∼ N (ZiT λjk , ωjk 2 ) with covariates, and sijk ∼ N (λjk , ωjk ), without covariates, for j = 1, . . . , J, k = 1, . . . , K, and if Tij = 0, sijk = 0. The λ’s in the support parameter model are modeled in the following hierarchical manner, λjk ∼ N (θk , Φk ) for k = 1, . . . , K. If you set identical.lambda = FALSE and hierarchical = TRUE, the model for sijk is if Tij 6= 0, sijk ∼ N (λ0jk,village[i] + ZiT λjk , ωjk 2 ) and λ0jk,village[i] ∼ N (Vvillage[i] κjk , ψjk ) for k = 1, . . . , K and j = 1, . . . , J. In addition, λ and κ are modeled in the following hierarchical manner, λ∗jk ∼ N (θk , Φk ) for k = 1, . . . , K, where λ∗jk = (λTjk , κTjk )T . If you set identical.lambda = TRUE and hierarchical = TRUE, the model for sijk is if Tij 6= 0, sijk ∼ N (λ0k,village[i] + ZiT λk , ωk2 ) and λ0k,village[i] ∼ N (Vvillage[i] T for k = 1, . . . , K. If the covariates are included in the model, the model for the ideal points is given by xi ∼ N (ZiT δ, σx2 ) for i = 1, . . . , N where σx2 is a known prior variance. If you set hierarchical = TRUE, the model is xi ∼ N (δvillage[i] + ZiT δ, σ 2 ) and 0 T δvillage[i] ∼ N (Vvillage[i] ζ, ρ2 ) for k = 1, . . . , K. Finally, the following independent prior distributions are placed on unknown parameters, for j = 1, . . . , J, βj ∼ T N βj >0 (µβ , σβ2 ) for j = 1, . . . , J, δ ∼ N (µδ , Σδ ), θk ∼ N (µθ , Σθ ) for k = 1, . . . , K, ωjk ∼ Inv−χ2 (νω0 , s0ω ) for j = 1, . . . , J and k = 1, . . . , K, and diag(Φk ) ∼ Inv−χ2 (νΦ 0 for k = 1, . . . , K, where Φk is assumed to be a diagonal matrix. Value An object of class "endorse", which is a list containing the following elements: beta an "mcmc" object. A sample from the posterior distribution of α and β. x If x.sd = TRUE, a vector of the standard deviation of the ideal points in each draw. If x.sd = FALSE, an mcmc object that contains a sample from the posterior distribution of the ideal points. s If s.out = TRUE, an mcmc object that contains a sample from the posterior dis- tribution of sijk . Variable names are: s(observation id)(question id). delta If covariates = TRUE, an mcmc object that contains a sample from the posterior distribution of δ. tau If tau.out = TRUE, an mcmc object that contains a sample from the posterior distribution of τ . lambda an mcmc object. A sample from the posterior distribution of λ. Variable names are: lambda(question id)(group id).(covariate id). theta an mcmc object. A sample from the posterior distribution of θ. kappa an mcmc object. zeta an mcmc object. Note that the posterior sample of all parameters are NOT standardized. In making posterior infer- ence, each parameter should be divided by the standard deviation of x (in the default setting, it is given as "x") or by σ 2 (in the default setting, it is given as "sigma2"). Also note that α and the intercept in δ (or, if the model is hierarchical, the intercept in ζ) are not identified. Instead, or, if the model is hierarchical, is identified after either of the above standardization, where δ0 and ζ0 denote the intercepts. When using the auxiliary data functionality, the following objects are included: aux logical value indicating whether estimation incorporates auxiliary moments nh integer count of the number of auxiliary moments Author(s) <NAME>, Department of Political Science, University of Michigan <<EMAIL>> <NAME>, Department of Government and Statistics, Harvard University <<EMAIL>>, https://imai.fas.harvard.edu References Bullock, Will, <NAME>, and <NAME>. (2011) “Statistical Analysis of Endorsement Experiments: Measuring Support for Militant Groups in Pakistan,” Political Analysis, Vol. 19, No. 4 (Autumn), pp.363-384. Examples ## Not run: data(pakistan) Y <- list(Q1 = c("Polio.a", "Polio.b", "Polio.c", "Polio.d", "Polio.e"), Q2 = c("FCR.a", "FCR.b", "FCR.c", "FCR.d", "FCR.e"), Q3 = c("Durand.a", "Durand.b", "Durand.c", "Durand.d", "Durand.e"), Q4 = c("Curriculum.a", "Curriculum.b", "Curriculum.c", "Curriculum.d", "Curriculum.e")) ## Varying-lambda non-hierarchical model without covariates endorse.out <- endorse(Y = Y, data = pakistan, identical.lambda = FALSE, covariates = FALSE, hierarchical = FALSE) ## Varying-lambda non-hierarchical model with covariates indiv.covariates <- formula( ~ female + rural) endorse.out <- endorse(Y = Y, data = pakistan, identical.lambda = FALSE, covariates = TRUE, formula.indiv = indiv.covariates, hierarchical = FALSE) ## Common-lambda non-hierarchical model with covariates indiv.covariates <- formula( ~ female + rural) endorse.out <- endorse(Y = Y, data = pakistan, identical.lambda = TRUE, covariates = TRUE, formula.indiv = indiv.covariates, hierarchical = FALSE) ## Varying-lambda hierarchical model without covariates div.data <- data.frame(division = sort(unique(pakistan$division))) div.formula <- formula(~ 1) endorse.out <- endorse(Y = Y, data = pakistan, data.village = div.data, village = "division", identical.lambda = FALSE, covariates = FALSE, hierarchical = TRUE, formula.village = div.formula) ## Varying-lambda hierarchical model with covariates endorse.out <- endorse(Y = Y, data = pakistan, data.village = div.data, village = "division", identical.lambda = FALSE, covariates = TRUE, formula.indiv = indiv.covariates, hierarchical = TRUE, formula.village = div.formula) ## Common-lambda hierarchical model without covariates endorse.out <- endorse(Y = Y, data = pakistan, data.village = div.data, village = "division", identical.lambda = TRUE, covariates = FALSE, hierarchical = TRUE, formula.village = div.formula) ## Common-lambda hierarchical model with covariates endorse.out <- endorse(Y = Y, data = pakistan, data.village = div.data, village = "division", identical.lambda = TRUE, covariates = TRUE, formula.indiv = indiv.covariates, hierarchical = TRUE, formula.village = div.formula) ## End(Not run) endorse.plot Descriptive Plot of Endorsement Experiment Data Description This function creates a descriptive plot for a question in an endorsement experiment. Usage endorse.plot(Y, data, scale, dk = 98, ra = 99, yaxis = NULL, col.seq = NA) Arguments Y a character vector. List of the variable names for the responses to a question. Each variable name corresponds to each treatment status. data data frame containing the variables. scale an integer. The scale of the responses. The function assumes that the responses are coded so that 1 indicates the lowest support while the integer specified in this argument represents the highest support. dk an integer indicating the value of the response variable that is to be interpreted as “Don’t Know.” Default is 98. ra an integer indicating the value of the response variable that is to be interpreted as “Refused.” Default is 99. yaxis a character vector of the same length as Y. The argument will be used for the label of the horizontal axis. The order should be the same as Y. col.seq a vector of colors for the bars or bar components. By default, a gradation of gray where the darkest indicates the highest support level. Value A descriptive plot for the responses to a question. Author(s) <NAME>, Department of Political Science, University of Michigan <<EMAIL>>. <NAME>, Department of Government and Statistics, Harvard University <<EMAIL>>, https://imai.fas.harvard.edu/ Examples data(pakistan) Y <- c("Polio.a", "Polio.b", "Polio.c", "Polio.d", "Polio.e") yaxis <- c("Control", "Kashmir", "Afghan", "Al-Qaida", "Tanzeems") endorse.plot(Y = Y, data = pakistan, scale = 5) GeoCount Counting Incidents around Points Description This function calculates the number of incidents (e.g., violent events) within a specified distance around specified points (e.g., villages). Usage GeoCount(x, y, distance, x.latitude = "latitude", x.longitude = "longitude", y.latitude = "latitude", y.longitude = "longitude") Arguments x data frame containing the longitude and the latitude of points. y data frame containing the longitude and the latitude of incidents. distance numeric. The distance from points in kilometers. x.latitude character. The variable name for the latitude in x. x.longitude character. The variable name for the longitude in x. y.latitude character. The variable name for the latitude in y. y.longitude character. The variable name for the longitude in y. Author(s) <NAME>, Department of Political Science, University of Michigan <<EMAIL>>. GeoId Getting Indices of Incidents around a specified point Description This function obtains the indices of incidents within a specified distance around a specified point. Usage GeoId(x, y, distance, x.latitude = "latitude", x.longitude = "longitude", y.latitude = "latitude", y.longitude = "longitude") Arguments x data frame containing the longitude and the latitude of a point. y data frame containing the longitude and the latitude of incidents. distance numeric. The distance from villages in kilometers. x.latitude character. The variable name for the latitude in x. x.longitude character. The variable name for the longitude in x. y.latitude character. The variable name for the latitude in y. y.longitude character. The variable name for the longitude in y. Value A vector containing the indices of y that are within distance kilometers around the point specified by x. If there are multiple observations in x, the first row is used as the point. Author(s) <NAME>, Department of Political Science, University of Michigan <<EMAIL>>. pakistan Pakistan Survey Experiment on Support for Militant Groups Description This data set is a subset of the data from the endorsement experiment conducted in Pakistan to study support for militant groups. The survey was implemented by Fair et al. (2009). It is also used by Bullock et al. (2011). Usage data(pakistan) Format A data frame containing 5212 observations. The variables are: • division: division number. • edu: education. 1 if “illiterate”; 2 if “primary”; 3 if “middle”; 4 if “matric”; 5 if “intermediate (f.a/f.sc),” “graduate (b.a/b.sc.),” or “professionals (m.a /or other professional degree).” • inc: approximate monthly income. 1 if less than 3000 rupees; 2 if 3000 to 10,000 rupees; 3 if 10,001 to 15,000 rupees; 4 if more than 15,000 rupees. • female: 0 if male; 1 if female • rural: 0 if rural; 1 if urban • Polio.a-e: support for World Health Organization’s plan of universal polio vaccinations in Pakistan. 5 indicates the highest support while 1 indicates the lowest support. • FCR.a-e: support for the reform of the Frontier Crimes Regulation (FCR) governing the tribal areas. 5 indicates the highest support while 1 indicates the lowest support. • Durand.a-e: support for using peace jirgas to resolve disputes over the Afghan border, the Durand Line. 5 indicates the highest support while 1 indicates the lowest support. • Curriculum.a-e: support for the Government of Pakistan’s plan of curriculum reforms in religious schools or madaris. 5 indicates the highest support while 1 indicates the lowest support. For the response variables, endorsers are: • varname.a: control (no endorsement). • varname.b: Pakistani militant groups in Kashmir. • varname.c: Militants fighting in Afghanistan. • varname.d: Al-Qaida. • varname.e: <NAME>. Source Bullock, Will, <NAME>, and <NAME>. 2011. Replication data for: Statistical analysis of endorsement experiments: Measuring support for militant groups in Pakistan. hdl:1902.1/14840. The Dataverse Network. References Bullock, Will, <NAME>, and <NAME>. (2011) “Statistical Analysis of Endorsement Experiments: Measuring Support for Militant Groups in Pakistan,” Political Analysis, Vol. 19, No. 4 (Autumn), pp.363-384. Fair, <NAME>., <NAME>, and <NAME>. (2009) “The Roots of Militancy: Explaining Support for Political Violence in Pakistan,” Working Paper, Princeton University. predict.endorse Predict Method for the Measurement Model of Political Support Description Function to calculate predictions from a measurement model fitted to an endorsement experiment data. Usage ## S3 method for class 'endorse' predict(object, newdata, type = c("prob.support", "linear.s"), standardize = TRUE, ...) Arguments object a fitted object of class inheriting from "endorse" newdata an optional data frame containing data that will be used to make predictions from. If omitted, the data used to fit the regression are used. type the type of prediction required. The default is on the scale of the predicted probability of positive support; the alternative "linear.s" is on the scale of sijk . standardize logical switch indicating if the predicted values on the scale of sijk are standard- ized so that its variance is one. ... further arguments to be passed to or from other methods. Details predict.endorse produces predicted support for political actors from a fitted "endorse" object. If newdata is omitted the predictions are based on the date used for the fit. Setting type specifies the type of predictions. The default is "prob.support", in which case the function computes the average predicted probability of positive support:  T  Zi λ j P (sijk > 0 | Zi , λj , ωj ) = Φ ωj for each political group k. If type is set to be "linear.s", the output is the predicted mean of support parameters: E(sijk | Zi , λj ) = ZiT λj . If the logical standardize is TRUE, the predicted mean of support is standardized by dividing by ωj . Value A "mcmc" object for predicted values. Author(s) <NAME>, Department of Political Science, University of Michigan <<EMAIL>>. See Also endorse for model fitting
transliterate
readthedoc
Python
transliterate 1.10.2 documentation [transliterate](index.html#document-index) --- transliterate[¶](#transliterate) === Bi-directional transliterator for Python. Transliterates (unicode) strings according to the rules specified in the language packs (source script <-> target script). Comes with language packs for the following languages (listed in alphabetical order): * Armenian * Bulgarian (beta) * Georgian * Greek * Macedonian (alpha) * Mongolian (alpha) * Russian * Serbian (alpha) * Ukrainian (beta) There are also a number of useful tools included, such as: * Simple lorem ipsum generator, which allows lorem ipsum generation in the language chosen. * Language detection for the text (if appropriate language pack is available). * Slugify function for non-latin texts. Prerequisites[¶](#prerequisites) --- * Python >=2.7, >=3.4, PyPy Installation[¶](#installation) --- Install with latest stable version from PyPI. ``` pip install transliterate ``` or install the latest stable version from BitBucket: ``` pip install https://bitbucket.org/barseghyanartur/transliterate/get/stable.tar.gz ``` or install the latest stable version from GitHub: ``` pip install https://github.com/barseghyanartur/transliterate/archive/stable.tar.gz ``` That’s all. See the [Usage and examples](#usage-and-examples) section for more. Usage and examples[¶](#usage-and-examples) --- ### Simple usage[¶](#simple-usage) Required imports ``` from transliterate import translit, get_available_language_codes ``` Original text ``` text = "Lorem ipsum dolor sit amet" ``` Transliteration to Armenian ``` print(translit(text, 'hy')) # Լօրեմ իպսում դօլօր սիտ ամետ ``` Transliteration to Georgian ``` print(translit(text, 'ka')) # ლორემ იპსუმ დოლორ სით ამეთ ``` Transliteration to Greek ``` print(translit(text, 'el')) # Λορεμ ιψθμ δολορ σιτ αμετ ``` Transliteration to Russian ``` print(translit(text, 'ru')) # Лорем ипсум долор сит амет ``` List of available (registered) languages ``` print(get_available_language_codes()) # ['el', 'hy', 'ka', 'ru'] ``` Reversed transliterations are transliterations made from target language to source language (in terms they are defined in language packs). In case of reversed transliterations, you may leave out the `language_code` attribute, although if you know it on beforehand, specify it since it works faster that way. Reversed transliteration from Armenian ``` print(translit(u"Լօրեմ իպսում դօլօր սիտ ամետ", 'hy', reversed=True)) # Lorem ipsum dolor sit amet ``` Reversed transliteration from Armenian with `language_code` argument left out ``` print(translit(u"Լօրեմ իպսում դօլօր սիտ ամետ", reversed=True)) # Lorem ipsum dolor sit amet ``` Reversed transliteration from Georgian ``` print(translit(u"ლორემ იპსუმ დოლორ სით ამეთ", 'ka', reversed=True)) # Lorem ipsum dolor sit amet ``` Reversed transliteration from Georgian with `language_code` argument left out ``` print(translit(u"ლორემ იპსუმ დოლორ სით ამეთ", reversed=True)) # Lorem ipsum dolor sit amet ``` Reversed transliteration from Greek ``` print(translit(u"Λορεμ ιψθμ δολορ σιτ αμετ", 'el', reversed=True)) # Lorem ipsum dolor sit amet ``` Reversed transliteration from Greek with `language_code` argument left out ``` print(translit(u"Λορεμ ιψθμ δολορ σιτ αμετ", reversed=True)) # Lorem ipsum dolor sit amet ``` Reversed transliteration from Russian (Cyrillic) ``` print(translit(u"Лорем ипсум долор сит амет", 'ru', reversed=True)) # Lorеm ipsum dolor sit amеt ``` Reversed transliteration from Russian (Cyrillic) with `language_code` argument left out ``` print(translit(u"Лорем ипсум долор сит амет", reversed=True)) # Lorem ipsum dolor sit amet ``` Testing the decorator ``` from transliterate.decorators import transliterate_function @transliterate_function(language_code='hy') def decorator_test(text): return text print(decorator_test(u"Lorem ipsum dolor sit amet")) # Լօրեմ իպսում դօլօր սիտ ամետ ``` ### Working with large amounts of data[¶](#working-with-large-amounts-of-data) If you know which language pack shall be used for transliteration, especially when working with large amounts of data, it makes sense to get the transliteration function in the following way: ``` from transliterate import get_translit_function translit_hy = get_translit_function('hy') print(translit_hy(u"Լօրեմ իպսում դօլօր սիտ ամետ", reversed=True)) # Lorem ipsum dolor sit amet print(translit_hy(u"Lorem ipsum dolor sit amet")) # Լօրեմ իպսում դօլօր սիտ ամետ ``` ### Registering a custom language pack[¶](#registering-a-custom-language-pack) #### Basics[¶](#basics) Make sure to call the `autodiscover` function before registering your own language packs if you want to use the bundled language packs along with your own custom ones. ``` from transliterate.discover import autodiscover autodiscover() ``` Then the custom language pack part comes. ``` from transliterate.base import TranslitLanguagePack, registry class ExampleLanguagePack(TranslitLanguagePack): language_code = "example" language_name = "Example" mapping = ( u"abcdefghij", u"1234567890", ) registry.register(ExampleLanguagePack) print(get_available_language_codes()) # ['el', 'hy', 'ka', 'ru', 'example'] print(translit(text, 'example')) # Lor5m 9psum 4olor s9t 1m5t ``` It’s possible to replace existing language packs with your own ones. By default, existing language packs are not force-installed. To force install a language pack, set the `force` argument to True when registering a language pack. In that case, if a language pack with same language code has already been registered, it will be replaced; otherwise, if language pack didn’t exist in the registry, it will be just registered. ``` registry.register(ExampleLanguagePack, force=True) ``` Forced language packs can’t be replaced or unregistered. #### API in depth[¶](#api-in-depth) There are 7 class properties that you could/should be using in your language pack, of which 4 are various sorts of mappings. ##### Mappings[¶](#mappings) * `mapping` (tuple): A tuple of two strings, that simply represent the mapping of characters from the source language to the target language. For example, if your source language is Latin and you want to convert “a”, “b”, “c”, “d” and “e” characters to appropriate characters in Russian Cyrillic, your mapping would look as follows: ``` mapping = (u"abcde", u"абцде") ``` Example (taken from the Greek language pack). ``` mapping = ( u"abgdezhiklmnxoprstyfwuABGDEZHIKLMNXOPRSTYFWU", u"αβγδεζηικλμνξοπρστυφωθΑΒΓΔΕΖΗΙΚΛΜΝΞΟΠΡΣΤΥΦΩΘ", ) ``` * `reversed_specific_mapping` (tuple): When making reversed translations, the `mapping` property is still used, but in some cases you need to provide additional rules. This property (`reversed_specific_mapping`) is meant for such cases. Further, is alike the `mapping`. Example (taken from the Greek language pack). ``` reversed_specific_mapping = ( u"θΘ", u"uU" ) ``` * `pre_processor_mapping` (dict): A dictionary of mapping from source language to target language. Use this only in cases if a single character in source language shall be represented by more than one character in the target language. Example (taken from the Greek language pack). ``` pre_processor_mapping = { u"th": u"θ", u"ch": u"χ", u"ps": u"ψ", u"TH": u"Θ", u"CH": u"Χ", u"PS": u"Ψ", } ``` * `reversed_specific_pre_processor_mapping`: Same as `pre_processor_mapping`, but used in reversed translations. Example (taken from the Armenian language pack) ``` reversed_specific_pre_processor_mapping = { u"ու": u"u", u"Ու": u"U" } ``` ##### Additional[¶](#additional) * `character_ranges` (tuple): A tuple of character ranges (unicode table). Used in language detection. Works only if `detectable` property is set to True. Be aware, that language (or shall I better be saying - script) detection is very basic and is based on characters only. * `detectable` (bool): If set to True, language pack would be used for automatic language detection. ### Using the lorem ipsum generator[¶](#using-the-lorem-ipsum-generator) Note, that due to incompatibility of the original lorem-ipsum-generator package with Python 3, when used with Python 3 transliterate uses its’ own simplified fallback lorem ipsum generator (which still does the job). Required imports ``` from transliterate.contrib.apps.translipsum import TranslipsumGenerator ``` Generating paragraphs in Armenian ``` g_am = TranslipsumGenerator(language_code='hy') print(g_am.generate_paragraph()) # Մագնա տրիստիքուե ֆաուցիբուս ֆամես նետուս նետուս օրցի մաուրիս, # սուսցիպիտ. Դապիբուս րիսուս սեդ ադիպիսցինգ դիցտում. Ֆերմենտում ուրնա # նատօքուե ատ. Uլտրիցես եգետ, տացիտի. Լիտօրա ցլասս ցօնուբիա պօսուերե # մալեսուադա ին իպսում իդ պեր վե. ``` Generating sentense in Georgian ``` g_ka = TranslipsumGenerator(language_code='ka') print(g_ka.generate_sentence()) # გგეთ ყუამ არსუ ვულფუთათე რუთრუმ აუთორ. ``` Generating sentense in Greek ``` g_el = TranslipsumGenerator(language_code='el') print(g_el.generate_sentence()) # Νεc cρασ αμετ, ελιτ vεστιβθλθμ εθ, αενεαν ναμ, τελλθσ vαριθσ. ``` Generating sentense in Russian (Cyrillic) ``` g_ru = TranslipsumGenerator(language_code='ru') print(g_ru.generate_sentence()) # Рисус cонсеcтетуер, фусcе qуис лаореет ат ерос пэдэ фелис магна. ``` ### Language detection[¶](#language-detection) Required imports ``` from transliterate import detect_language ``` Detect Armenian text ``` detect_language(u'Լօրեմ իպսում դօլօր սիտ ամետ') # hy ``` Detect Georgian text ``` detect_language(u'ლორემ იპსუმ დოლორ სით ამეთ') # ka ``` Detect Greek text ``` detect_language(u'Λορεμ ιψθμ δολορ σιτ αμετ') # el ``` Detect Russian (Cyrillic) text ``` detect_language(u'Лорем ипсум долор сит амет') # ru ``` ### Slugify[¶](#slugify) Required imports ``` from transliterate import slugify ``` Slugify Armenian text ``` slugify(u'Լօրեմ իպսում դօլօր սիտ ամետ') # lorem-ipsum-dolor-sit-amet ``` Slugify Georgian text ``` slugify(u'ლორემ იპსუმ დოლორ სით ამეთ') # lorem-ipsum-dolor-sit-amet ``` Slugify Greek text ``` slugify(u'Λορεμ ιψθμ δολορ σιτ αμετ') # lorem-ipsum-dolor-sit-amet ``` Slugify Russian (Cyrillic) text ``` slugify(u'Лорем ипсум долор сит амет') # lorem-ipsum-dolor-sit-amet ``` Missing a language pack?[¶](#missing-a-language-pack) --- Missing a language pack for your own language? Contribute to the project by making one and it will appear in a new version (which will be released very quickly). Writing documentation[¶](#writing-documentation) --- Keep the following hierarchy. ``` === title === header === sub-header --- sub-sub-header ~~~~~~~~~~~~~~ sub-sub-sub-header ^^^^^^^^^^^^^^^^^^ sub-sub-sub-sub-header ++++++++++++++++++++++ sub-sub-sub-sub-sub-header ************************** ``` License[¶](#license) --- GPL-2.0-only OR LGPL-2.1-or-later Support[¶](#support) --- For any issues contact me at the e-mail given in the [Author](#author) section. Author[¶](#author) --- <NAME> <[<EMAIL>](mailto:<EMAIL>%4<EMAIL>)Documentation[¶](#documentation) --- Contents: ### transliterate package[¶](#transliterate-package) #### Subpackages[¶](#subpackages) ##### transliterate.contrib package[¶](#transliterate-contrib-package) ###### Subpackages[¶](#subpackages) ####### transliterate.contrib.apps package[¶](#transliterate-contrib-apps-package) ######## Subpackages[¶](#subpackages) ######### transliterate.contrib.apps.translipsum package[¶](#transliterate-contrib-apps-translipsum-package) ########## Submodules[¶](#submodules) ########## transliterate.contrib.apps.translipsum.utils module[¶](#module-transliterate.contrib.apps.translipsum.utils) *class* `transliterate.contrib.apps.translipsum.utils.``Generator`(**args*, ***kwargs*)[[source]](_modules/transliterate/contrib/apps/translipsum/utils.html#Generator)[¶](#transliterate.contrib.apps.translipsum.utils.Generator) Bases: `object` Fallback lorem ipsum generator for Python 3. `generate_paragraph`(*num_sentences=4*)[[source]](_modules/transliterate/contrib/apps/translipsum/utils.html#Generator.generate_paragraph)[¶](#transliterate.contrib.apps.translipsum.utils.Generator.generate_paragraph) Generate paragraph. `generate_sentence`()[[source]](_modules/transliterate/contrib/apps/translipsum/utils.html#Generator.generate_sentence)[¶](#transliterate.contrib.apps.translipsum.utils.Generator.generate_sentence) Generate sentence. `generate_word`()[[source]](_modules/transliterate/contrib/apps/translipsum/utils.html#Generator.generate_word)[¶](#transliterate.contrib.apps.translipsum.utils.Generator.generate_word) Generate word. ########## Module contents[¶](#module-transliterate.contrib.apps.translipsum) *class* `transliterate.contrib.apps.translipsum.``TranslipsumGenerator`(*language_code*, *reversed=False*, **args*, ***kwargs*)[[source]](_modules/transliterate/contrib/apps/translipsum.html#TranslipsumGenerator)[¶](#transliterate.contrib.apps.translipsum.TranslipsumGenerator) Bases: `lipsum.Generator` Lorem ipsum generator. `generate_paragraph`(**args*, ***kwargs*)[[source]](_modules/transliterate/contrib/apps/translipsum.html#TranslipsumGenerator.generate_paragraph)[¶](#transliterate.contrib.apps.translipsum.TranslipsumGenerator.generate_paragraph) Generate paragraph. `generate_sentence`(**args*, ***kwargs*)[[source]](_modules/transliterate/contrib/apps/translipsum.html#TranslipsumGenerator.generate_sentence)[¶](#transliterate.contrib.apps.translipsum.TranslipsumGenerator.generate_sentence) Generate sentence. ######## Module contents[¶](#module-transliterate.contrib.apps) ####### transliterate.contrib.languages package[¶](#transliterate-contrib-languages-package) ######## Subpackages[¶](#subpackages) ######### transliterate.contrib.languages.bg package[¶](#transliterate-contrib-languages-bg-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.bg.data package[¶](#transliterate-contrib-languages-bg-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.bg.data.default module[¶](#module-transliterate.contrib.languages.bg.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.bg.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.bg.translit_language_pack module[¶](#module-transliterate.contrib.languages.bg.translit_language_pack) *class* `transliterate.contrib.languages.bg.translit_language_pack.``BulgarianLanguagePack`[[source]](_modules/transliterate/contrib/languages/bg/translit_language_pack.html#BulgarianLanguagePack)[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Bulgarian language. See <http://en.wikipedia.org/wiki/Romanization_of_Bulgarian> for details. `character_ranges` *= ((1024, 1279), (1280, 1327))*[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack.character_ranges) `detectable` *= False*[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack.detectable) `language_code` *= 'bg'*[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack.language_code) `language_name` *= 'Bulgarian'*[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack.language_name) `mapping` *= (u'abvgdeziyklmnoprstufhABVGDEZIYKLMNOPRSTUFH', u'\u0430\u0431\u0432\u0433\u0434\u0435\u0437\u0438\u0439\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u0445\u0410\u0411\u0412\u0413\u0414\u0415\u0417\u0418\u0419\u041a\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u0423\u0424\u0425')*[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack.mapping) `pre_processor_mapping` *= {u'Ch': u'\u0427', u'Q': u'\u042f', u'Sh': u'\u0428', u'Sht': u'\u0429', u'Ts': u'\u0426', u'Ya': u'\u042f', u'Yu': u'\u042e', u'Zh': u'\u0416', u'ch': u'\u0447', u'q': u'\u042f', u'sh': u'\u0448', u'sht': u'\u0449', u'ts': u'\u0446', u'ya': u'\u044f', u'yu': u'\u044e', u'zh': u'\u0436'}*[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'\u044c\u044a\u042a', u'yaA')*[¶](#transliterate.contrib.languages.bg.translit_language_pack.BulgarianLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.bg) ######### transliterate.contrib.languages.el package[¶](#transliterate-contrib-languages-el-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.el.data package[¶](#transliterate-contrib-languages-el-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.el.data.default module[¶](#module-transliterate.contrib.languages.el.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.el.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.el.translit_language_pack module[¶](#module-transliterate.contrib.languages.el.translit_language_pack) *class* `transliterate.contrib.languages.el.translit_language_pack.``GreekLanguagePack`[[source]](_modules/transliterate/contrib/languages/el/translit_language_pack.html#GreekLanguagePack)[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Greek language. See http://en.wikipedia.org/wiki/Greek_alphabet and https://en.wikipedia.org/wiki/Romanization_of_Greek#Modern_Greek for details. `character_ranges` *= ((880, 1023), (7936, 8191))*[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack.character_ranges) `detectable` *= True*[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack.detectable) `language_code` *= 'el'*[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack.language_code) `language_name` *= 'Greek'*[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack.language_name) `mapping` *= (u'avgdeziklmnxoprstyfAVGDEZIKLMNXOPRSTYF', u'\u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b9\u03ba\u03bb\u03bc\u03bd\u03be\u03bf\u03c0\u03c1\u03c3\u03c4\u03c5\u03c6\u0391\u0392\u0393\u0394\u0395\u0396\u0399\u039a\u039b\u039c\u039d\u039e\u039f\u03a0\u03a1\u03a3\u03a4\u03a5\u03a6')*[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack.mapping) `pre_processor_mapping` *= {u'Au': u'\u0391\u03c5', u'B': u'\u039c\u03c0', u'Ch': u'\u03a7', u'Ef': u'\u0395\u03c5', u'Eu': u'\u0395\u03c5', u'Ev': u'\u0395\u03c5', u'Ey': u'\u0395\u03c5', u'Gk': u'\u0393\u03ba', u'If': u'\u0397\u03c5', u'Iv': u'\u0397\u03c5', u'Iy': u'\u0397\u03c5', u'Oi': u'\u039f\u03b9', u'Ou': u'\u039f\u03c5', u'Oy': u'\u039f\u03c5', u'Ps': u'\u03a8', u'Th': u'\u0398', u'U': u'\u03a5', u'Yi': u'\u03a5\u03b9', u'au': u'\u03b1\u03c5', u'b': u'\u03bc\u03c0', u'ch': u'\u03c7', u'ef': u'\u03b5\u03c5', u'eu': u'\u03b5\u03c5', u'ev': u'\u03b5\u03c5', u'ey': u'\u03b5\u03c5', u'gch': u'\u03b3\u03be', u'gk': u'\u03b3\u03ba', u'gx': u'\u03b3\u03be', u'if': u'\u03b7\u03c5', u'iv': u'\u03b7\u03c5', u'iy': u'\u03b7\u03c5', u'nch': u'\u03b3\u03be', u'ng': u'\u03b3\u03b3', u'nx': u'\u03b3\u03be', u'oi': u'\u03bf\u03b9', u'ou': u'\u03bf\u03c5', u'oy': u'\u03bf\u03c5', u'ps': u'\u03c8', u'th': u'\u03b8', u'u': u'\u03c5', u'yi': u'\u03c5\u03b9'}*[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'\u03c2\u03ac\u03ad\u03ae\u03af\u03cd\u03cc\u03ce\u03ca\u03cb\u0390\u03b0\u03c9\u03a9\u03b7\u0397\u03f5\u03f1', u'saeiiyooiyiyooiier')*[¶](#transliterate.contrib.languages.el.translit_language_pack.GreekLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.el) ######### transliterate.contrib.languages.he package[¶](#transliterate-contrib-languages-he-package) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.he.translit_language_pack module[¶](#module-transliterate.contrib.languages.he.translit_language_pack) *class* `transliterate.contrib.languages.he.translit_language_pack.``HebrewLanguagePack`[[source]](_modules/transliterate/contrib/languages/he/translit_language_pack.html#HebrewLanguagePack)[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Hebrew language. See <http://en.wikipedia.org/wiki/Hebrew_alphabet> for details. See the <http://en.wikipedia.org/wiki/Romanization_of_Hebrew#When_to_transliterate> for transliteration details. Note, that this language pack implements the new standards (2006) of Hebrew Academy. Confirmed a אּ v ב b בּּּ ּg ג gg ג ּd ד dd דּ h ה h הּ v ו vv וּ z ז zz זּ `character_ranges` *= ((1328, 1423), (64272, 64287))*[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack.character_ranges) `detectable` *= True*[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack.detectable) `language_code` *= 'he'*[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack.language_code) `language_name` *= 'Hebrew'*[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack.language_name) `mapping` *= (u'abgdvzhilmnsfckrt', u'\u05d0\u05d1\u05d2\u05d3\u05d5\u05d6\u05d7\u05d9\u05dc\u05de\u05e0\u05e1\u05e4\u05e6\u05e7\u05e8\u05ea')*[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack.mapping) `pre_processor_mapping` *= {u'aa': u'\u05e2', u'cs': u'\u05e5', u'fs': u'\u05e3', u"ha'": u'\u05d4', u'ka': u'\u05db', u'ks': u'\u05da', u'ms': u'\u05dd', u'ns': u'\u05df', u'sh': u'\u05e9', u'tt': u'\u05d8'}*[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'\u05e4', u'p')*[¶](#transliterate.contrib.languages.he.translit_language_pack.HebrewLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.he) ######### transliterate.contrib.languages.hi package[¶](#transliterate-contrib-languages-hi-package) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.hi.translit_language_pack module[¶](#module-transliterate.contrib.languages.hi.translit_language_pack) *class* `transliterate.contrib.languages.hi.translit_language_pack.``HindiLanguagePack`[[source]](_modules/transliterate/contrib/languages/hi/translit_language_pack.html#HindiLanguagePack)[¶](#transliterate.contrib.languages.hi.translit_language_pack.HindiLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Hindi language. See http://en.wikipedia.org/wiki/Hindi for details. `character_ranges` *= ((2304, 2431),)*[¶](#transliterate.contrib.languages.hi.translit_language_pack.HindiLanguagePack.character_ranges) `detectable` *= True*[¶](#transliterate.contrib.languages.hi.translit_language_pack.HindiLanguagePack.detectable) `language_code` *= 'hi'*[¶](#transliterate.contrib.languages.hi.translit_language_pack.HindiLanguagePack.language_code) `language_name` *= 'Hindi'*[¶](#transliterate.contrib.languages.hi.translit_language_pack.HindiLanguagePack.language_name) `mapping` *= (u'aeof', u'\u0905\u0907\u0913\u092b')*[¶](#transliterate.contrib.languages.hi.translit_language_pack.HindiLanguagePack.mapping) `pre_processor_mapping` *= {u'b': u'\u092c\u0940', u'c': u'\u0938\u0940', u'd': u'\u0921\u0940', u'g': u'\u091c\u0940', u'h': u'\u090f\u091a', u'i': u'\u0906\u0908', u'j': u'\u091c\u0947', u'k': u'\u0915\u0947', u'l': u'\u0905\u0932', u'm': u'\u090d\u092e', u'n': u'\u0905\u0928', u'p': u'\u092a\u0940', u'q': u'\u0915\u094d\u092f\u0942', u'r': u'\u0906\u0930', u's': u'\u090f\u0938', u't': u'\u091f\u0940', u'u': u'\u092f\u0942', u'w': u'\u0921\u092c\u094d\u0932\u0942', u'x': u'\u0905\u0915\u094d\u0938', u'y': u'\u0935\u093e\u092f', u'z': u'\u091c\u095c'}*[¶](#transliterate.contrib.languages.hi.translit_language_pack.HindiLanguagePack.pre_processor_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.hi) ######### transliterate.contrib.languages.hy package[¶](#transliterate-contrib-languages-hy-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.hy.data package[¶](#transliterate-contrib-languages-hy-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.hy.data.default module[¶](#module-transliterate.contrib.languages.hy.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.hy.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.hy.translit_language_pack module[¶](#module-transliterate.contrib.languages.hy.translit_language_pack) *class* `transliterate.contrib.languages.hy.translit_language_pack.``ArmenianLanguagePack`[[source]](_modules/transliterate/contrib/languages/hy/translit_language_pack.html#ArmenianLanguagePack)[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Armenian language. See https://en.wikipedia.org/wiki/Armenian_alphabet for details. `character_ranges` *= ((1328, 1423), (64272, 64287))*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.character_ranges) `detectable` *= True*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.detectable) `language_code` *= 'hy'*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.language_code) `language_name` *= 'Armenian'*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.language_name) `mapping` *= (u'abgdezilxkhmjnpsvtrcq&ofABGDEZILXKHMJNPSVTRCQOF', u'\u0561\u0562\u0563\u0564\u0565\u0566\u056b\u056c\u056d\u056f\u0570\u0574\u0575\u0576\u057a\u057d\u057e\u057f\u0580\u0581\u0584\u0587\u0585\u0586\u0531\u0532\u0533\u0534\u0535\u0536\u053b\u053c\u053d\u053f\u0540\u0544\u0545\u0546\u054a\u054d\u054e\u054f\u0550\u0551\u0554\u0555\u0556')*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.mapping) `pre_processor_mapping` *= {u'Ch': u'\u0549', u'Dj': u'\u054b', u'Dz': u'\u0541', u"E'": u'\u0537', u'Gh': u'\u0542', u'Jh': u'\u053a', u'Ph': u'\u0553', u'Sh': u'\u0547', u'Tch': u'\u0543', u'Th': u'\u0539', u'Ts': u'\u053e', u'U': u'\u0548\u0582', u'Vo': u'\u0548', u'Y': u'\u0538', u'ch': u'\u0579', u'dj': u'\u057b', u'dz': u'\u0571', u"e'": u'\u0567', u'gh': u'\u0572', u'jh': u'\u056a', u'ph': u'\u0583', u'sh': u'\u0577', u'tch': u'\u0573', u'th': u'\u0569', u'ts': u'\u056e', u'u': u'\u0578\u0582', u'vo': u'\u0578', u'y': u'\u0568'}*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'\u057c\u054c', u'rR')*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.reversed_specific_mapping) `reversed_specific_pre_processor_mapping` *= {u'\u0548\u0582': u'U', u'\u0578\u0582': u'u'}*[¶](#transliterate.contrib.languages.hy.translit_language_pack.ArmenianLanguagePack.reversed_specific_pre_processor_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.hy) ######### transliterate.contrib.languages.ka package[¶](#transliterate-contrib-languages-ka-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.ka.data package[¶](#transliterate-contrib-languages-ka-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.ka.data.default module[¶](#module-transliterate.contrib.languages.ka.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.ka.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.ka.translit_language_pack module[¶](#module-transliterate.contrib.languages.ka.translit_language_pack) *class* `transliterate.contrib.languages.ka.translit_language_pack.``GeorgianLanguagePack`[[source]](_modules/transliterate/contrib/languages/ka/translit_language_pack.html#GeorgianLanguagePack)[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Georgian language. See [`](#id1)<http://en.wikipedia.org/wiki/Georgian_alphabet> for details. `character_ranges` *= ((4256, 4293), (4304, 4348), (11520, 11557))*[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack.character_ranges) `detectable` *= True*[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack.detectable) `language_code` *= 'ka'*[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack.language_code) `language_name` *= 'Georgian'*[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack.language_name) `mapping` *= (u'ABGDEVZTIKLMNOPJRSTUFQYCXHabgdevztiklmnoprsufqycxjhw', u'\u10d0\u10d1\u10d2\u10d3\u10d4\u10d5\u10d6\u10d7\u10d8\u10d9\u10da\u10db\u10dc\u10dd\u10de\u10df\u10e0\u10e1\u10e2\u10e3\u10e4\u10e5\u10e7\u10ea\u10ee\u10f0\u10d0\u10d1\u10d2\u10d3\u10d4\u10d5\u10d6\u10d7\u10d8\u10d9\u10da\u10db\u10dc\u10dd\u10de\u10e0\u10e1\u10e3\u10e4\u10e5\u10e7\u10ea\u10ee\u10ef\u10f0\u10ec')*[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack.mapping) `pre_processor_mapping` *= {u'ch': u'\u10e9', u"ch'": u'\u10ed', u'dz': u'\u10eb', u'gh': u'\u10e6', u'kh': u'\u10ee', u'sh': u'\u10e8', u'ts': u'\u10ec', u'zh': u'\u10df'}*[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack.pre_processor_mapping) `translit`(*value*, *reversed=False*, *strict=False*, *fail_silently=True*)[[source]](_modules/transliterate/contrib/languages/ka/translit_language_pack.html#GeorgianLanguagePack.translit)[¶](#transliterate.contrib.languages.ka.translit_language_pack.GeorgianLanguagePack.translit) Transliterate the given value according to the rules. Rules are set in the transliteration pack. | Parameters: | * **value** (*str*) – * **reversed** (*bool*) – * **strict** (*bool*) – * **fail_silently** (*bool*) – | | Return str: | | ########## Module contents[¶](#module-transliterate.contrib.languages.ka) ######### transliterate.contrib.languages.l1 package[¶](#transliterate-contrib-languages-l1-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.l1.data package[¶](#transliterate-contrib-languages-l1-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.l1.data.default module[¶](#module-transliterate.contrib.languages.l1.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.l1.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.l1.translit_language_pack module[¶](#module-transliterate.contrib.languages.l1.translit_language_pack) *class* `transliterate.contrib.languages.l1.translit_language_pack.``Latin1SupplementLanguagePack`[[source]](_modules/transliterate/contrib/languages/l1/translit_language_pack.html#Latin1SupplementLanguagePack)[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Latin1 Supplement. Though not exactly a language, it’s a set of commonly found unicode characters. See http://en.wikipedia.org/wiki/Latin-1_Supplement_%28Unicode_block%29 for details. `character_ranges` *= ((192, 214), (216, 246), (248, 255))*[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack.character_ranges) `detectable` *= True*[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack.detectable) `language_code` *= 'l1'*[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack.language_code) `language_name` *= 'Latin1 Supplement'*[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack.language_name) `mapping` *= (u'abcdefghijklmnopqrstuvwxyzABCDEFGHILJKMNOPQRSTUVWXYZ', u'abcdefghijklmnopqrstuvwxyzABCDEFGHILJKMNOPQRSTUVWXYZ')*[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack.mapping) `reversed_specific_mapping` *= (u'\xe0\xc0\xe1\xc1\xe2\xc2\xe3\xc3\xe8\xc8\xe9\xc9\xea\xca\xeb\xcb\xec\xcc\xed\xcd\xee\xce\xef\xcf\xf0\xd0\xf1\xd1\xf2\xd2\xf3\xd3\xf4\xd4\xf5\xd5\xf9\xd9\xfa\xda\xfb\xdb\xfd\xdd\xff\u0178', u'aAaAaAaAeEeEeEeEiIiIiIiIdDnNoOoOoOaOuUuUuUyYyY')*[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack.reversed_specific_mapping) `reversed_specific_pre_processor_mapping` *= {u'\xc4': u'Ae', u'\xc5': u'Aa', u'\xc6': u'Ae', u'\xc7': u'Ts', u'\xd6': u'Oe', u'\xd8': u'Oe', u'\xdc': u'Ue', u'\xde': u'Th', u'\xdf': u'ss', u'\xe4': u'ae', u'\xe5': u'aa', u'\xe6': u'ae', u'\xe7': u'ts', u'\xf0': u'dh', u'\xf6': u'oe', u'\xf8': u'oe', u'\xfc': u'ue', u'\xfe': u'th'}*[¶](#transliterate.contrib.languages.l1.translit_language_pack.Latin1SupplementLanguagePack.reversed_specific_pre_processor_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.l1) ######### transliterate.contrib.languages.mk package[¶](#transliterate-contrib-languages-mk-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.mk.data package[¶](#transliterate-contrib-languages-mk-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.mk.data.default module[¶](#module-transliterate.contrib.languages.mk.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.mk.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.mk.translit_language_pack module[¶](#module-transliterate.contrib.languages.mk.translit_language_pack) *class* `transliterate.contrib.languages.mk.translit_language_pack.``MacedonianLanguagePack`[[source]](_modules/transliterate/contrib/languages/mk/translit_language_pack.html#MacedonianLanguagePack)[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Macedonian language. See <http://en.wikipedia.org/wiki/Romanization_of_Macedonian> for details. `character_ranges` *= ((1024, 1279), (1280, 1327))*[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack.character_ranges) `detectable` *= False*[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack.detectable) `language_code` *= 'mk'*[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack.language_code) `language_name` *= 'Macedonian'*[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack.language_name) `mapping` *= (u'abvgdezijklmnoprstufhcABVGDEZIJKLMNOPRSTUFHC', u'\u0430\u0431\u0432\u0433\u0434\u0435\u0437\u0438\u0458\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0410\u0411\u0412\u0413\u0414\u0415\u0417\u0418\u0408\u041a\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u0423\u0424\u0425\u0426')*[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack.mapping) `pre_processor_mapping` *= {u'Ch': u'\u0427', u'Dz': u'\u0405', u'Dzh': u'\u040f', u'Gj': u'\u0403', u'Kj': u'\u040c', u'Lj': u'\u0409', u'Nj': u'\u040a', u'Sh': u'\u0428', u'Zh': u'\u0416', u'ch': u'\u0447', u'dz': u'\u0455', u'dzh': u'\u045f', u'gj': u'\u0453', u'lj': u'\u0459', u'nj': u'\u045a', u'sh': u'\u0448', u'zh': u'\u0436', u'\u043a\u0458': u'\u045c'}*[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'', u'')*[¶](#transliterate.contrib.languages.mk.translit_language_pack.MacedonianLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.mk) ######### transliterate.contrib.languages.mn package[¶](#transliterate-contrib-languages-mn-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.mn.data package[¶](#transliterate-contrib-languages-mn-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.mn.data.default module[¶](#module-transliterate.contrib.languages.mn.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.mn.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.mn.translit_language_pack module[¶](#module-transliterate.contrib.languages.mn.translit_language_pack) *class* `transliterate.contrib.languages.mn.translit_language_pack.``MongolianLanguagePack`[[source]](_modules/transliterate/contrib/languages/mn/translit_language_pack.html#MongolianLanguagePack)[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Mongolian language. See https://en.wikipedia.org/wiki/Mongolian_Cyrillic_alphabet for details. `character_ranges` *= ((1024, 1279), (1280, 1327))*[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack.character_ranges) `detectable` *= False*[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack.detectable) `language_code` *= 'mn'*[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack.language_code) `language_name` *= 'Mongolian'*[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack.language_name) `mapping` *= (u'abvgdjziklmnoprstuufhewABVGDJZIKLMNOPRSTUUFHEW', u'\u0430\u0431\u0432\u0433\u0434\u0436\u0437\u0438\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u04af\u0444\u0445\u044d\u0432\u0410\u0411\u0412\u0413\u0414\u0416\u0417\u0418\u041a\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u0423\u04ae\u0424\u0425\u042d\u0412')*[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack.mapping) `pre_processor_mapping` *= {u'AI': u'\u0410\u0419', u'Ai': u'\u0410\u0439', u'CH': u'\u0427', u'EI': u'\u042d\u0419', u'Ei': u'\u042d\u0439', u'II': u'\u0418\u0419', u'Ii': u'\u0418\u0439', u'KH': u'\u0425', u'OI': u'\u041e\u0419', u'Oi': u'\u041e\u0439', u'SH': u'\u0428', u'TS': u'\u0426', u'UI': u'\u0423\u0419', u'Ui': u'\u0423\u0439', u'YA': u'\u042f', u'YE': u'\u0415', u'YO': u'\u0401', u'YU': u'\u042e', u'Yo': u'\u0401', u'Yu': u'\u042e\u0443', u'ai': u'\u0430\u0439', u'ch': u'\u0447', u'ei': u'\u044d\u0439', u'ii': u'\u0438\u0439', u'kh': u'\u0445', u'oi': u'\u043e\u0439', u'sh': u'\u0448', u'ts': u'\u0446', u'ui': u'\u0443\u0439', u'ya': u'\u044f', u'ye': u'\u0435', u'yo': u'\u0451', u'yu': u'\u044e'}*[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'\u044a\u044c\u042a\u042c\u0439\u0419\u04e9\u04e8\u0443\u0423\u04af\u04ae', u'iiIIiIoOuUuU')*[¶](#transliterate.contrib.languages.mn.translit_language_pack.MongolianLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.mn) ######### transliterate.contrib.languages.ru package[¶](#transliterate-contrib-languages-ru-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.ru.data package[¶](#transliterate-contrib-languages-ru-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.ru.data.default module[¶](#module-transliterate.contrib.languages.ru.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.ru.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.ru.translit_language_pack module[¶](#module-transliterate.contrib.languages.ru.translit_language_pack) *class* `transliterate.contrib.languages.ru.translit_language_pack.``RussianLanguagePack`[[source]](_modules/transliterate/contrib/languages/ru/translit_language_pack.html#RussianLanguagePack)[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Russian language. See http://en.wikipedia.org/wiki/Russian_alphabet for details. `character_ranges` *= ((1024, 1279), (1280, 1327))*[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack.character_ranges) `detectable` *= True*[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack.detectable) `language_code` *= 'ru'*[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack.language_code) `language_name` *= 'Russian'*[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack.language_name) `mapping` *= (u"abvgdezijklmnoprstufhcC'y'ABVGDEZIJKLMNOPRSTUFH'Y'", u'\u0430\u0431\u0432\u0433\u0434\u0435\u0437\u0438\u0439\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0426\u044a\u044b\u044c\u0410\u0411\u0412\u0413\u0414\u0415\u0417\u0418\u0419\u041a\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u0423\u0424\u0425\u042a\u042b\u042c')*[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack.mapping) `pre_processor_mapping` *= {u'Ch': u'\u0427', u'Ja': u'\u042f', u'Ju': u'\u042e', u'Sch': u'\u0429', u'Sh': u'\u0428', u'Ts': u'\u0426', u'Zh': u'\u0416', u'ch': u'\u0447', u'ja': u'\u044f', u'ju': u'\u044e', u'sch': u'\u0449', u'sh': u'\u0448', u'ts': u'\u0446', u'zh': u'\u0436'}*[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'\u0451\u044d\u0401\u042d\u044a\u044c\u042a\u042c', u"eeEE''''")*[¶](#transliterate.contrib.languages.ru.translit_language_pack.RussianLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.ru) ######### transliterate.contrib.languages.sr package[¶](#transliterate-contrib-languages-sr-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.sr.data package[¶](#transliterate-contrib-languages-sr-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.sr.data.default module[¶](#module-transliterate.contrib.languages.sr.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.sr.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.sr.translit_language_pack module[¶](#module-transliterate.contrib.languages.sr.translit_language_pack) *class* `transliterate.contrib.languages.sr.translit_language_pack.``SerbianLanguagePack`[[source]](_modules/transliterate/contrib/languages/sr/translit_language_pack.html#SerbianLanguagePack)[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Serbian language. See <https://en.wikipedia.org/wiki/Romanization_of_Serbian> for details. `character_ranges` *= ((1032, 1264), (0, 383))*[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack.character_ranges) `detectable` *= False*[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack.detectable) `language_code` *= 'sr'*[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack.language_code) `language_name` *= 'Serbian'*[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack.language_name) `mapping` *= (u'abvgd\u0111e\u017ezijklmnoprst\u0107ufhc\u010d\u0161ABVGD\u0110E\u017dZIJKLMNOPRST\u0106UFHC\u010c\u0160', u'\u0430\u0431\u0432\u0433\u0434\u0452\u0435\u0436\u0437\u0438\u0458\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u045b\u0443\u0444\u0445\u0446\u0447\u0448\u0410\u0411\u0412\u0413\u0414\u0402\u0415\u0416\u0417\u0418\u0408\u041a\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u040b\u0423\u0424\u0425\u0426\u0427\u0428')*[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack.mapping) `pre_processor_mapping` *= {u'D\u017e': u'\u040f', u'Lj': u'\u0409', u'Nj': u'\u040a', u'd\u017e': u'\u045f', u'lj': u'\u0459', u'nj': u'\u045a'}*[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'',)*[¶](#transliterate.contrib.languages.sr.translit_language_pack.SerbianLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.sr) ######### transliterate.contrib.languages.uk package[¶](#transliterate-contrib-languages-uk-package) ########## Subpackages[¶](#subpackages) ########### transliterate.contrib.languages.uk.data package[¶](#transliterate-contrib-languages-uk-data-package) ############ Submodules[¶](#submodules) ############ transliterate.contrib.languages.uk.data.default module[¶](#module-transliterate.contrib.languages.uk.data.default) ############ Module contents[¶](#module-transliterate.contrib.languages.uk.data) ########## Submodules[¶](#submodules) ########## transliterate.contrib.languages.uk.translit_language_pack module[¶](#module-transliterate.contrib.languages.uk.translit_language_pack) *class* `transliterate.contrib.languages.uk.translit_language_pack.``UkrainianLanguagePack`[[source]](_modules/transliterate/contrib/languages/uk/translit_language_pack.html#UkrainianLanguagePack)[¶](#transliterate.contrib.languages.uk.translit_language_pack.UkrainianLanguagePack) Bases: [`transliterate.base.TranslitLanguagePack`](index.html#transliterate.base.TranslitLanguagePack) Language pack for Ukrainian language. See http://en.wikipedia.org/wiki/Ukrainian_alphabet for details. `character_ranges` *= ((1024, 1279), (1280, 1327))*[¶](#transliterate.contrib.languages.uk.translit_language_pack.UkrainianLanguagePack.character_ranges) `language_code` *= 'uk'*[¶](#transliterate.contrib.languages.uk.translit_language_pack.UkrainianLanguagePack.language_code) `language_name` *= 'Ukrainian'*[¶](#transliterate.contrib.languages.uk.translit_language_pack.UkrainianLanguagePack.language_name) `mapping` *= (u"abvhgdezyijklmnoprstuf'ABVHGDEZYIJKLMNOPRSTUF'", u'\u0430\u0431\u0432\u0433\u0491\u0434\u0435\u0437\u0438\u0456\u0439\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444\u044c\u0410\u0411\u0412\u0413\u0490\u0414\u0415\u0417\u0418\u0406\u0419\u041a\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u0423\u0424\u042c')*[¶](#transliterate.contrib.languages.uk.translit_language_pack.UkrainianLanguagePack.mapping) `pre_processor_mapping` *= {u'Ch': u'\u0427', u'Ja': u'\u042f', u'Ju': u'\u042e', u'Kh': u'\u0425', u'Sh': u'\u0428', u'Shch': u'\u0429', u'Ts': u'\u0426', u'Ye': u'\u0404', u'Yi': u'\u0407', u'Zh': u'\u0416', u'ch': u'\u0447', u'ja': u'\u044f', u'ju': u'\u044e', u'kh': u'\u0445', u'sh': u'\u0448', u'shch': u'\u0449', u'ts': u'\u0446', u'ye': u'\u0454', u'yi': u'\u0457', u'zh': u'\u0436'}*[¶](#transliterate.contrib.languages.uk.translit_language_pack.UkrainianLanguagePack.pre_processor_mapping) `reversed_specific_mapping` *= (u'\u044c\u042c', u"''")*[¶](#transliterate.contrib.languages.uk.translit_language_pack.UkrainianLanguagePack.reversed_specific_mapping) ########## Module contents[¶](#module-transliterate.contrib.languages.uk) ######## Module contents[¶](#module-transliterate.contrib.languages) ###### Module contents[¶](#module-transliterate.contrib) ##### transliterate.tests package[¶](#transliterate-tests-package) ###### Subpackages[¶](#subpackages) ####### transliterate.tests.data package[¶](#transliterate-tests-data-package) ######## Submodules[¶](#submodules) ######## transliterate.tests.data.default module[¶](#module-transliterate.tests.data.default) ######## Module contents[¶](#module-transliterate.tests.data) ###### Submodules[¶](#submodules) ###### transliterate.tests.base module[¶](#module-transliterate.tests.base) ###### transliterate.tests.defaults module[¶](#module-transliterate.tests.defaults) ###### transliterate.tests.helpers module[¶](#module-transliterate.tests.helpers) `transliterate.tests.helpers.``log_info`(*func*)[[source]](_modules/transliterate/tests/helpers.html#log_info)[¶](#transliterate.tests.helpers.log_info) Print some useful info. `transliterate.tests.helpers.``py2only`(*func*)[[source]](_modules/transliterate/tests/helpers.html#py2only)[¶](#transliterate.tests.helpers.py2only) Skip the test on Python 3. ###### transliterate.tests.test_transliterate module[¶](#module-transliterate.tests.test_transliterate) *class* `transliterate.tests.test_transliterate.``TransliterateTest`(*methodName='runTest'*)[[source]](_modules/transliterate/tests/test_transliterate.html#TransliterateTest)[¶](#transliterate.tests.test_transliterate.TransliterateTest) Bases: `unittest.case.TestCase` Test `transliterate.utils.translit`. `setUp`()[[source]](_modules/transliterate/tests/test_transliterate.html#TransliterateTest.setUp)[¶](#transliterate.tests.test_transliterate.TransliterateTest.setUp) Set up. `test_01_get_available_language_codes`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_01_get_available_language_codes) `test_02_translit_latin_to_armenian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_02_translit_latin_to_armenian) `test_03_translit_latin_to_georgian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_03_translit_latin_to_georgian) `test_04_translit_latin_to_greek`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_04_translit_latin_to_greek) `test_06_translit_latin_to_bulgarian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_06_translit_latin_to_bulgarian_cyrillic) `test_06_translit_latin_to_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_06_translit_latin_to_cyrillic) `test_06_translit_latin_to_mongolian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_06_translit_latin_to_mongolian_cyrillic) `test_06_translit_latin_to_serbian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_06_translit_latin_to_serbian_cyrillic) `test_06_translit_latin_to_ukrainian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_06_translit_latin_to_ukrainian_cyrillic) `test_07_translit_armenian_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_07_translit_armenian_to_latin) `test_08_translit_georgian_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_08_translit_georgian_to_latin) `test_09_translit_greek_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_09_translit_greek_to_latin) `test_11_translit_bulgarian_cyrillic_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_11_translit_bulgarian_cyrillic_to_latin) `test_11_translit_cyrillic_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_11_translit_cyrillic_to_latin) `test_11_translit_mongolian_cyrillic_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_11_translit_mongolian_cyrillic_to_latin) `test_11_translit_serbian_cyrillic_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_11_translit_serbian_cyrillic_to_latin) `test_11_translit_ukrainian_cyrillic_to_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_11_translit_ukrainian_cyrillic_to_latin) `test_12_function_decorator`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_12_function_decorator) `test_13_method_decorator`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_13_method_decorator) `test_14_function_decorator`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_14_function_decorator) `test_15_register_custom_language_pack`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_15_register_custom_language_pack) `test_16_translipsum_generator_armenian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_16_translipsum_generator_armenian) `test_17_translipsum_generator_georgian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_17_translipsum_generator_georgian) `test_18_translipsum_generator_greek`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_18_translipsum_generator_greek) `test_20_translipsum_generator_bulgarian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_20_translipsum_generator_bulgarian_cyrillic) `test_20_translipsum_generator_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_20_translipsum_generator_cyrillic) `test_20_translipsum_generator_mongolian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_20_translipsum_generator_mongolian_cyrillic) `test_20_translipsum_generator_serbian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_20_translipsum_generator_serbian_cyrillic) `test_20_translipsum_generator_ukrainian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_20_translipsum_generator_ukrainian_cyrillic) `test_21_language_detection_armenian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_21_language_detection_armenian) `test_22_language_detection_georgian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_22_language_detection_georgian) `test_23_language_detection_greek`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_23_language_detection_greek) `test_25_false_language_detection_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_25_false_language_detection_cyrillic) `test_25_language_detection_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_25_language_detection_cyrillic) `test_26_slugify_armenian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_26_slugify_armenian) `test_27_slugify_georgian`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_27_slugify_georgian) `test_28_slugify_greek`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_28_slugify_greek) `test_30_slugify_bulgarian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_30_slugify_bulgarian_cyrillic) `test_30_slugify_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_30_slugify_cyrillic) `test_30_slugify_mongolian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_30_slugify_mongolian_cyrillic) `test_30_slugify_serbian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_30_slugify_serbian_cyrillic) `test_30_slugify_ukrainian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_30_slugify_ukrainian_cyrillic) `test_31_override_settings`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_31_override_settings) `test_31b_get_translit_function`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_31b_get_translit_function) `test_32_auto_translit_reversed`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_32_auto_translit_reversed) `test_33_register_unregister`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_33_register_unregister) `test_35_translit_serbian_cyrillic_to_serbian_latin`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_35_translit_serbian_cyrillic_to_serbian_latin) `test_35_translit_serbian_latin_to_serbian_cyrillic`(**args*, ***kwargs*)[¶](#transliterate.tests.test_transliterate.TransliterateTest.test_35_translit_serbian_latin_to_serbian_cyrillic) ###### Module contents[¶](#module-transliterate.tests) #### Submodules[¶](#submodules) #### transliterate.base module[¶](#module-transliterate.base) *class* `transliterate.base.``TranslitLanguagePack`[[source]](_modules/transliterate/base.html#TranslitLanguagePack)[¶](#transliterate.base.TranslitLanguagePack) Bases: `object` Base language pack. > The attributes below shall be defined in every language pack. > `language_code`: Language code (obligatory). Example value: ‘hy’, ‘ru’. > `language_name`: Language name (obligatory). Example value: ‘Armenian’, > > > ‘Russian’. > `character_ranges`: Character ranges that are specific to the language. > When making a pack, check [this](http://en.wikipedia.org/wiki/List_of_Unicode_characters) page for > the ranges. > `mapping`: Mapping (obligatory). A tuple, consisting of two strings > (source and target). Example value: (u’abc’, u’աբց’). > `reversed_specific_mapping`: Specific mapping (one direction only) used > when transliterating from target script to source script (reversed > transliteration). > ՝՝pre_processor_mapping՝՝: Pre processor mapping (optional). A dictionary > mapping for letters that can’t be represented by a single latin letter. > ՝՝reversed_specific_pre_processor_mapping՝՝: Pre processor mapping ( > optional). A dictionary mapping for letters that can’t be represented > by a single latin letter (reversed transliteration). > | example: | | ``` >>> class ArmenianLanguagePack(TranslitLanguagePack): >>> language_code = "hy" >>> language_name = "Armenian" >>> character_ranges = ((0x0530, 0x058F), (0xFB10, 0xFB1F)) >>> mapping = ( >>> u"abgdezilxkhmjnpsvtrcq&ofABGDEZILXKHMJNPSVTRCQOF", # Source script >>> u"աբգդեզիլխկհմյնպսվտրցքևօֆԱԲԳԴԵԶԻԼԽԿՀՄՅՆՊՍՎՏՐՑՔՕՖ", # Target script >>> ) >>> reversed_specific_mapping = ( >>> u"ռՌ", >>> u"rR" >>> ) >>> pre_processor_mapping = { >>> # lowercase >>> u"e'": u"է", >>> u"y": u"ը", >>> u"th": u"թ", >>> u"jh": u"ժ", >>> u"ts": u"ծ", >>> u"dz": u"ձ", >>> u"gh": u"ղ", >>> u"tch": u"ճ", >>> u"sh": u"շ", >>> u"vo": u"ո", >>> u"ch": u"չ", >>> u"dj": u"ջ", >>> u"ph": u"փ", >>> u"u": u"ու", >>> >>> # uppercase >>> u"E'": u"Է", >>> u"Y": u"Ը", >>> u"Th": u"Թ", >>> u"Jh": u"Ժ", >>> u"Ts": u"Ծ", >>> u"Dz": u"Ձ", >>> u"Gh": u"Ղ", >>> u"Tch": u"Ճ", >>> u"Sh": u"Շ", >>> u"Vo": u"Ո", >>> u"Ch": u"Չ", >>> u"Dj": u"Ջ", >>> u"Ph": u"Փ", >>> u"U": u"Ու" >>> } >>> reversed_specific_pre_processor_mapping = { >>> u"ու": u"u", >>> u"Ու": u"U" >>> } Note, that in Python 3 you won't be using u prefix before the strings. ``` `character_ranges` *= None*[¶](#transliterate.base.TranslitLanguagePack.character_ranges) `characters` *= None*[¶](#transliterate.base.TranslitLanguagePack.characters) *classmethod* `contains`(*character*)[[source]](_modules/transliterate/base.html#TranslitLanguagePack.contains)[¶](#transliterate.base.TranslitLanguagePack.contains) Check if given character belongs to the language pack. | Return bool: | | *classmethod* `detect`(*num_words=None*)[[source]](_modules/transliterate/base.html#TranslitLanguagePack.detect)[¶](#transliterate.base.TranslitLanguagePack.detect) Detect the language. Heavy language detection, which is activated for languages that are harder detect (like Russian Cyrillic and Ukrainian Cyrillic). | Parameters: | * **value** (*unicode*) – Input string. * **num_words** (*int*) – Number of words to base decision on. | | Return bool: | True if detected and False otherwise. | `detectable` *= False*[¶](#transliterate.base.TranslitLanguagePack.detectable) `language_code` *= None*[¶](#transliterate.base.TranslitLanguagePack.language_code) `language_name` *= None*[¶](#transliterate.base.TranslitLanguagePack.language_name) `make_strict`(*value*, *reversed=False*)[[source]](_modules/transliterate/base.html#TranslitLanguagePack.make_strict)[¶](#transliterate.base.TranslitLanguagePack.make_strict) Strip out unnecessary characters from the string. | Parameters: | * **value** (*string*) – * **reversed** (*bool*) – | | Return string: | | `mapping` *= None*[¶](#transliterate.base.TranslitLanguagePack.mapping) `pre_processor_mapping` *= None*[¶](#transliterate.base.TranslitLanguagePack.pre_processor_mapping) `pre_processor_mapping_keys` *= []*[¶](#transliterate.base.TranslitLanguagePack.pre_processor_mapping_keys) `reversed_characters` *= None*[¶](#transliterate.base.TranslitLanguagePack.reversed_characters) `reversed_pre_processor_mapping` *= None*[¶](#transliterate.base.TranslitLanguagePack.reversed_pre_processor_mapping) `reversed_pre_processor_mapping_keys` *= []*[¶](#transliterate.base.TranslitLanguagePack.reversed_pre_processor_mapping_keys) `reversed_specific_mapping` *= None*[¶](#transliterate.base.TranslitLanguagePack.reversed_specific_mapping) `reversed_specific_pre_processor_mapping` *= None*[¶](#transliterate.base.TranslitLanguagePack.reversed_specific_pre_processor_mapping) `reversed_specific_pre_processor_mapping_keys` *= []*[¶](#transliterate.base.TranslitLanguagePack.reversed_specific_pre_processor_mapping_keys) *classmethod* `suggest`(*reversed=False*, *limit=None*)[[source]](_modules/transliterate/base.html#TranslitLanguagePack.suggest)[¶](#transliterate.base.TranslitLanguagePack.suggest) Suggest possible variants (some sort of auto-complete). | Parameters: | * **value** (*str*) – * **limit** (*int*) – Limit number of suggested variants. | | Return list: | | `translit`(*value*, *reversed=False*, *strict=False*, *fail_silently=True*)[[source]](_modules/transliterate/base.html#TranslitLanguagePack.translit)[¶](#transliterate.base.TranslitLanguagePack.translit) Transliterate the given value according to the rules. Rules are set in the transliteration pack. | Parameters: | * **value** (*str*) – * **reversed** (*bool*) – * **strict** (*bool*) – * **fail_silently** (*bool*) – | | Return str: | | #### transliterate.conf module[¶](#module-transliterate.conf) #### transliterate.decorators module[¶](#module-transliterate.decorators) `transliterate.decorators.``transliterate_function`[¶](#transliterate.decorators.transliterate_function) alias of `transliterate.decorators.TransliterateFunction` `transliterate.decorators.``transliterate_method`[¶](#transliterate.decorators.transliterate_method) alias of `transliterate.decorators.TransliterateMethod` #### transliterate.defaults module[¶](#module-transliterate.defaults) #### transliterate.discover module[¶](#module-transliterate.discover) `transliterate.discover.``autodiscover`()[[source]](_modules/transliterate/discover.html#autodiscover)[¶](#transliterate.discover.autodiscover) Auto-discover the language packs in contrib/apps. #### transliterate.exceptions module[¶](#module-transliterate.exceptions) *exception* `transliterate.exceptions.``ImproperlyConfigured`[[source]](_modules/transliterate/exceptions.html#ImproperlyConfigured)[¶](#transliterate.exceptions.ImproperlyConfigured) Bases: `exceptions.Exception` Exception raised when developer didn’t configure the code properly. *exception* `transliterate.exceptions.``InvalidRegistryItemType`[[source]](_modules/transliterate/exceptions.html#InvalidRegistryItemType)[¶](#transliterate.exceptions.InvalidRegistryItemType) Bases: `exceptions.ValueError` Raised when an attempt is made to register an item in the registry. Raised when an attempt is made to register an item in the registry which does not have a proper type. *exception* `transliterate.exceptions.``LanguageCodeError`[[source]](_modules/transliterate/exceptions.html#LanguageCodeError)[¶](#transliterate.exceptions.LanguageCodeError) Bases: `exceptions.Exception` Exception raised when language code is empty or has incorrect value. *exception* `transliterate.exceptions.``LanguageDetectionError`[[source]](_modules/transliterate/exceptions.html#LanguageDetectionError)[¶](#transliterate.exceptions.LanguageDetectionError) Bases: `exceptions.Exception` Exception raised when language can’t be detected. Exception raised when language can’t be detected for the text given. *exception* `transliterate.exceptions.``LanguagePackNotFound`[[source]](_modules/transliterate/exceptions.html#LanguagePackNotFound)[¶](#transliterate.exceptions.LanguagePackNotFound) Bases: `exceptions.Exception` Exception raised when language pack is not found. Exception raised when language pack is not found for the language code given. #### transliterate.helpers module[¶](#module-transliterate.helpers) `transliterate.helpers.``PROJECT_DIR`(*base*)[¶](#transliterate.helpers.PROJECT_DIR) Project dir. `transliterate.helpers.``project_dir`(*base*)[[source]](_modules/transliterate/helpers.html#project_dir)[¶](#transliterate.helpers.project_dir) Project dir. #### transliterate.utils module[¶](#module-transliterate.utils) `transliterate.utils.``detect_language`(*text*, *num_words=None*, *fail_silently=True*, *heavy_check=False*)[[source]](_modules/transliterate/utils.html#detect_language)[¶](#transliterate.utils.detect_language) Detect the language from the value given. Detect the language from the value given based on ranges defined in active language packs. | Parameters: | * **value** (*unicode*) – Input string. * **num_words** (*int*) – Number of words to base decision on. * **fail_silently** (*bool*) – * **heavy_check** (*bool*) – If given, heavy checks would be applied when simple checks don’t give any results. Heavy checks are language specific and do not apply to a common logic. Heavy language detection is defined in the `detect` method of each language pack. | | Return str: | Language code. | `transliterate.utils.``get_available_language_codes`()[[source]](_modules/transliterate/utils.html#get_available_language_codes)[¶](#transliterate.utils.get_available_language_codes) Get list of language codes for registered language packs. | Return list: | | `transliterate.utils.``get_available_language_packs`()[[source]](_modules/transliterate/utils.html#get_available_language_packs)[¶](#transliterate.utils.get_available_language_packs) Get list of registered language packs. | Return list: | | `transliterate.utils.``get_translit_function`(*language_code*)[[source]](_modules/transliterate/utils.html#get_translit_function)[¶](#transliterate.utils.get_translit_function) Return translit function for the language given. | Parameters: | **language_code** (*str*) – | | Return callable: | | | | `transliterate.utils.``slugify`(*text*, *language_code=None*)[[source]](_modules/transliterate/utils.html#slugify)[¶](#transliterate.utils.slugify) Slugify the given text. If no `language_code` is given, auto-detect the language code from text given. | Parameters: | * **text** (*str*) – * **language_code** (*str*) – | | Return str: | | `transliterate.utils.``suggest`(*value*, *language_code=None*, *reversed=False*, *limit=None*)[[source]](_modules/transliterate/utils.html#suggest)[¶](#transliterate.utils.suggest) Suggest possible variants. | Parameters: | * **value** (*str*) – * **language_code** (*str*) – * **reversed** (*bool*) – If set to True, reversed translation is made. * **limit** (*int*) – Limit number of suggested variants. | | Return list: | | `transliterate.utils.``translit`(*value*, *language_code=None*, *reversed=False*, *strict=False*)[[source]](_modules/transliterate/utils.html#translit)[¶](#transliterate.utils.translit) Transliterate the text for the language given. Language code is optional in case of reversed translations (from some script to latin). | Parameters: | * **value** (*str*) – * **language_code** (*str*) – * **reversed** (*bool*) – If set to True, reversed translation is made. * **strict** (*bool*) – If given, all that are not found in the transliteration pack, are simply stripped out. | | Return str: | | #### Module contents[¶](#module-transliterate) `transliterate.``detect_language`(*text*, *num_words=None*, *fail_silently=True*, *heavy_check=False*)[[source]](_modules/transliterate/utils.html#detect_language)[¶](#transliterate.detect_language) Detect the language from the value given. Detect the language from the value given based on ranges defined in active language packs. | Parameters: | * **value** (*unicode*) – Input string. * **num_words** (*int*) – Number of words to base decision on. * **fail_silently** (*bool*) – * **heavy_check** (*bool*) – If given, heavy checks would be applied when simple checks don’t give any results. Heavy checks are language specific and do not apply to a common logic. Heavy language detection is defined in the `detect` method of each language pack. | | Return str: | Language code. | `transliterate.``get_available_language_codes`()[[source]](_modules/transliterate/utils.html#get_available_language_codes)[¶](#transliterate.get_available_language_codes) Get list of language codes for registered language packs. | Return list: | | `transliterate.``get_available_language_packs`()[[source]](_modules/transliterate/utils.html#get_available_language_packs)[¶](#transliterate.get_available_language_packs) Get list of registered language packs. | Return list: | | `transliterate.``get_translit_function`(*language_code*)[[source]](_modules/transliterate/utils.html#get_translit_function)[¶](#transliterate.get_translit_function) Return translit function for the language given. | Parameters: | **language_code** (*str*) – | | Return callable: | | | | `transliterate.``slugify`(*text*, *language_code=None*)[[source]](_modules/transliterate/utils.html#slugify)[¶](#transliterate.slugify) Slugify the given text. If no `language_code` is given, auto-detect the language code from text given. | Parameters: | * **text** (*str*) – * **language_code** (*str*) – | | Return str: | | `transliterate.``translit`(*value*, *language_code=None*, *reversed=False*, *strict=False*)[[source]](_modules/transliterate/utils.html#translit)[¶](#transliterate.translit) Transliterate the text for the language given. Language code is optional in case of reversed translations (from some script to latin). | Parameters: | * **value** (*str*) – * **language_code** (*str*) – * **reversed** (*bool*) – If set to True, reversed translation is made. * **strict** (*bool*) – If given, all that are not found in the transliteration pack, are simply stripped out. | | Return str: | | ### Release history[¶](#release-history) #### 1.10.2[¶](#id1) 2018-09-17 * Add `get_translit_function` for speed-ups when looping through a large set of strings. #### 1.10.1[¶](#id2) 2018-05-02 * Fixes and improvements in Georgian language pack. Removed historical asomtavruli (an old Georgian script which is no longer used) support. * Improvements in Serbian language pack. #### 1.10[¶](#id3) 2017-07-07 * Added Serbian language pack. * Drop Python 2.6 support. #### 1.9[¶](#id4) 2016-12-27 * Dropping Python 3.2 and Python 3.3 support. * Clean up. * pep8 fixes. * Minor fixes in Greek language pack. * Dedicated shell in example project. * Tested again PyPy. #### 1.8.1[¶](#id5) 2016-07-11 * Fixes in Mongolia language pack. #### 1.8[¶](#id6) 2016-07-09 * Added Macedonian language pack. * Added Mongolian language pack. * Drop support for Python 3.2. #### 1.7.6[¶](#id7) 2016-01-29 * Fixes in language detection. #### 1.7.5[¶](#id8) 2015-11-11 * Fixes in Greek language. #### 1.7.4[¶](#id9) 2015-10-24 * Python wheels support added. #### 1.7.3[¶](#id10) 2014-07-30 * Added Bulgarian language pack. #### 1.7.2[¶](#id11) 2014-06-18 * Refactored Python 3.2 support approach. #### 1.7.1[¶](#id12) 2014-06-17 * Refactored tests. #### 1.7[¶](#id13) 2014-06-17 * Added Python 3.2 support. #### 1.6.1[¶](#id14) 2014-05-21 * Fixes in Russian language pack. #### 1.6[¶](#id15) 2014-03-12 * Ukrainian language pack added. * Each language pack got an extra properly `detectable`, which is set to False by default. Language packs with that properly set to False are excluded from language auto-detection. * Improved tests. #### 1.5[¶](#id16) 2013-10-15 * Lowering `six` package requirement to 1.1.0. * Minor documentation improvements. #### 1.4[¶](#id17) 2013-10-11 * Added a fallback lorem ipsum generator for Python 3. #### 1.3[¶](#id18) 2013-10-01 * Fixed reversed translation of some chars in Russian language pack. * Improved tests. * Minor API improvements. #### 1.2[¶](#id19) 2013-09-08 * Python 3 support added. #### 1.1[¶](#id20) 2013-09-08 * Allow language packs to be unregistered when not forced. * Minor documentation improvements. #### 1.0[¶](#id21) 2013-08-04 * Auto transliterate when reversed added * Better exception handling. #### 0.9[¶](#id22) 2013-08-03 * Greek language pack status changed to beta. * Improvements of slugify and language detection of Greek language. #### 0.8[¶](#id23) 2013-08-03 * Greek language support added. * Minor fixes in Georgian language pack. #### 0.7[¶](#id24) 2013-08-03 * Georgian language support added. #### 0.6[¶](#id25) 2013-08-03 * Minor fixes. #### 0.5[¶](#id26) 2013-07-31 * Configurable settings added. * Minor fixes. * Better debugging. * Minor documentation improvements. #### 0.4[¶](#id27) 2013-07-17 * Python 2.6 support added. * Minor documentation improvements. #### 0.3[¶](#id28) 2013-07-14 * Slugify feature added. * Language auto detection from given text added. * Minor fixes. #### 0.2[¶](#id29) 2013-07-12 * Lorem ipsum generator added. * Minor documentation improvements. #### 0.1[¶](#id30) 2013-07-11 * Initial. Indices and tables[¶](#indices-and-tables) --- * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html)
www_kurshtml_edu_pl
free_programming_book
YAML
absolutne (2), adres (8), agent (1), akapit (4), akronim (1), aktualizacja (1), aktywacja (1), aktywne (1), alfabet (7), alias (1), alternatywne (2), animacja (2), ankieta (4), anulowanie (2), application (1), argument (2), argumenty (3), arkusz (9), artykuł (1), Atom (1), atrybut (15), audio (1), autor (3), banner (3), baza (1), bezwzględne (2), blok (9), blokada (16), błąd (13), BMP (3), bot (7), brat (3), button (2), cache (1), całkowite (4), cecha (4), centrowanie (8), certyfikat (1), CGI (1), chat (3), Chrome (157), ciało (5), ciągłe (4), cień (2), cosinus (2), CSS (22), CSS3 (79), CTR (1), cudzysłów (2), CWIS (1), cyfra (4), cykl (1), cytat (3), czarno-białe (1), czas (49), czat (3), czcionka (18), ćwiczenia (8), daklaracja (2), dalekopis (1), darmowe (5), data (48), definicja (3), dekoracja (2), deskryptor (9), diakrytyczne (5), dodanie (3), dokument (13), dolne (12), domena (1), domyślne (4), dopasowanie (12), dostępność (14), dotyk (1), DPI (1), drukarka (6), drukowanie (7), drzewo (7), DTD (4), duszek (1), dymek (1), dysk (1), dyskusja (2), dział (1), dziecko (6), dziedziczenie (6), dzień (6), dziesiętne (2), dźwięk (3), E (5), e-mail (6), ECMAScript (1), edytor (3), efekt (2), ekran (1), elastyczne (2), elastyczny (1), element (34), elipsa (1), emfaza (1), emoji (11), emotikona (11), Enter (6), etykieta (3), film (4), filtr (4), Firefox (151), font (17), format (2), formatowanie (2), formularz (14), forum (1), forum dyskusyjne (1), fotografia (21), fraza (3), FTP (3), funkcja (8), gadżet (1), galeria (2), gazeta (1), generator (1), GIF (3), globalne (12), główne (1), GMT (1), godzina (4), Google (18), Googlebot (5), Gopher (1), gorący punkt (1), górne (12), gradient (2), grafika (22), gratis (5), grubość (6), grupa (5), grupa dyskusyjna (1), grzbiet (2), hasło (1), HDTV (1), hiperłacze (5), hiperłącze (11), hiperłcze (5), hipertekst (1), hosting (3), HTML (12), HTML5 (28), HTTP (4), HTTPS (1), ICO (1), identyfikator (1), ikona (11), ilustracja (2), image (1), import (2), indeks (9), indeksowanie (8), Infinity (4), inicjalizacja (2), instancja (11), interaktywne (1), Internet Explorer (131), interpretacja (1), interpunkcja (1), ISO (2), JavaScript (5), język (13), JPG (4), JSON (3), justowanie (4), JXR (1), kadr (2), kadrowanie (2), kanał informacyjny (1), kanoniczny (1), kapitaliki (2), kartka (4), kaskadowość (3), kasowanie (1), katalog (1), kąt (6), kierunek (3), klasa (3), klawiatura (1), klawisz (1), klucz (2), kod (7), kodowanie (3), kolejność (6), kolor (16), kolumna (14), kombi (2), komentarz (2), komórka (7), komponent (1), kompozycja (1), kompresja (1), komunikat (1), komunikator (1), koniec (4), konkurs (1), konstruktor (18), kontekst (1), konto (4), konwersja (4), kopiowanie (1), korzeń (1), korzyści (2), kotwica (16), krój (4), krzyżyk (1), księga gości (2), kształt (1), kurs (2), kursor (3), kursywa (3), layout (10), legenda (2), lewe (8), liczba (37), licznik (3), ligatury (2), linia (12), linia bazowa (2), linijka (5), link (22), Linux (1), lista (20), litera (11), logarytm (6), logiczne (9), logowanie (1), lokalizacja (1), lokalne (4), losowe (2), łączenie (7), łącznik (1), Mac OS X (1), maksymalne (4), margines (20), marker (4), matematyka (26), MathML (2), media (7), menu (8), miesiąc (8), mieszane (15), migotanie (2), milisekunda (10), MIME (7), minimalne (4), minuta (4), mobilne (3), modyfikacja (1), MSIE (3), multimedia (5), muzyka (3), mysz (4), myszka (4), nagłówek (10), nakładanie (1), NaN (23), napisy (1), narożniki (1), następujące (1), nawigacja (1), nawis (1), nazwa (4), negacja (1), news (1), newsletter (2), nieparzyste (1), nieskończoność (4), niewidomy (3), niezmienność (6), NNTP (1), nowicjusz (2), numeracja (4), numerowanie (6), obcinanie (3), obiekt (27), oblewanie (3), obramowanie (21), obrazek (29), obrys (5), obszar (1), ochrona (3), odległość (5), odniesienie (1), odnośnik (21), odstęp (15), odsyłacz (19), odświeżanie (1), odtwarzacz (4), odwołanie (4), odzyłacz (2), okno (5), okres (1), opcja (1), Opera (159), opieczętowanie (2), opis (1), optymalizacja (3), organizacja (1), osadzanie (4), osadzenie (2), ostrzeżenie (1), otwierane (3), outline (1), ósemkowe (2), PageRank (1), papier (4), paragraf (4), parametr (2), parametry (3), parzyste (1), pętla (2), PHP (8), pi (1), pierwiastek (3), piktogram (10), pionowe (15), plik (13), płynne (1), pływające (6), PNG (4), pobieranie (1), pochylenie (3), początek (5), początki (2), początkujący (2), poczta (6), podkreślenie (4), podpis (3), podpowiedź (1), podpunkt (1), podrozdział (1), podstawy (2), podstrona (3), podświetlenie (2), pogrubienie (3), pokaz (1), pole (13), polimorfizm (1), polski (10), polskie (2), połączenie (2), położenie (5), pomniejszenie (2), pop-under (2), pop-up (2), poprzedzające (1), porównanie (1), pośrednik (1), potomek (3), powielanie (2), powiększenie (1), powtarzanie (4), powtórka (30), poziome (14), pozycja (20), pozycjonowanie (14), prawa autorskie (4), prawe (8), prezentacja (2), priorytet (2), projektor (2), promień (2), promocja (2), proporcje (2), prototyp (6), przeciąganie (2), przeglądarka (1), przekierowanie (1), przekreślenie (2), przekształcenie (2), przełamanie (7), przełącznik (2), przenośne (2), przepełnienie (3), przeplot (1), przerwa (1), przerywane (3), przesłanianie (1), przestarzałe (3), przesunięcie (5), przewijanie (3), przezroczystość (1), przeźroczystość (1), przodek (2), przycinanie (2), przycisk (6), przykład (3), przykłady (3), przyleganie (1), pseudoelement (2), pseudoklasa (1), publikacja (4), pudełko (2), punkt (8), punktor (4), puste (2), pytania (24), quirks (4), ramka (26), ramki (5), RangeError (5), ranking (1), RDF (1), redakcja (1), redukcja (2), reguła (2), reguły (2), rejestracja (1), reklama (6), relatywne (1), resetowanie (3), RGB (1), robo (1), robot (7), rodzaj (4), rodzic (4), rodzina (4), rok (4), rotacja (1), rotator (1), rowek (2), rozciąganie (2), rozciągnięcie (2), rozdział (1), rozdzielczość (1), rozmiar (13), rozmiary (2), rozmowa (1), rozplanowanie (1), rozstrzelenie (4), rozszerzalność (2), rozszerzanie (1), rozszerzenie (2), rozwijane (2), rozwijanie (1), różnice (1), RSS (1), RWD (4), rzeczywiste (1), SDTV (1), sekcja (5), sekunda (4), selektor (9), semantyczny (4), semantyka (4), SEO (14), separator (2), serwer (4), SGML (2), siatka (2), sierota (1), singleton (1), sinus (2), skalowanie (3), skasowanie (1), skorowidz (1), skórka (2), skrót (2), skrótowiec (1), skrypt (27), slajd (1), słownik (2), słowo (1), słuch (1), smartfon (3), sonda (3), sortowanie (1), spacja (2), spam (2), społeczność (1), sprawdzenie (1), SSH (1), SSI (2), SSL (2), stała (2), stałe (1), standard (4), statyczne (1), statystyka (1), stopka (3), stos (2), strefa (1), strona (4), strona kodowa (3), strona WWW (6), stronicowane (1), strzałka (1), styl (7), style (7), subskrypcja (1), suwak (3), SVG (4), symbol (11), SyntaxError (4), syntezator mowy (3), system (1), szablon (11), szczegółowość (1), szerokość (19), szesnastkowe (2), szkielet (9), szyba (1), ścieżka (1), ściśnięcie (1), tabela (11), tabele (2), tablet (2), tablica (26), tabulator (5), tag (1), tangens (3), tapeta (6), tekst (108), telewizor (2), telnet (1), tematyka (1), teraz (2), termin (2), terminal (1), text (1), tło (14), transformacja (1), treść (8), trygonometria (7), tworzenie (1), tworzenie stron (2), tydzień (2), typ (5), TypeError (76), tytuł (4), układ (3), ukryte (6), ukryty (1), ulubione (1), undefined (3), Unicode (3), uniwersalne (1), URIError (4), URL (16), ustalone (1), ustawienie (8), usunięcie (6), UTC (18), UTF (3), użytkownik (2), video (1), waga (1), WAIS (1), wariant (5), wartość (14), ważność (1), wcięcie (1), wczytanie (1), wczytywanie (1), wdowa (1), webmaster (3), WEBP (1), WEFT (1), wewnętrzne (8), wideo (2), widget (1), widzialność (6), widżet (3), wielkość (3), wielopoziomowe (2), wiersz (11), Windows (3), wizualne (1), własność (2), właściwość (14), wpisywanie (3), wskazówki (1), wskaźnik (3), współpraca (1), wstawianie (1), wstawienie (1), wstawka (1), WWW (2), wybór (1), wycinek (4), wyczyszczenie (4), wydruk (7), wykaz (13), wykładnicze (3), wykonanie (3), wymagania (1), wymiary (1), wypełnienie (1), wypunktowanie (8), wyraz (2), wyrażenia regularne (8), wyrównanie (6), wyróżnienie (1), wyróżnik (4), wysłanie (1), wysokość (14), wysuwane (1), wyszukiwarka (13), wyśrodkowanie (8), wyświetlanie (3), wytłuszczenie (3), wytyczne (3), wywołanie (2), względne (1), wzorzec (8), XHTML (9), XHTML5 (3), XML (3), zabezpieczenie (3), zaczepienie (1), zagnieżdżanie (4), zakładki (2), zakres (1), zalety (2), załamywanie (2), załącznik (1), zamiana (2), zamiennik (1), zamrożenie (2), zaokrąglenie (8), zapytanie (2), zasady (2), zastępowanie (1), zawartość (3), zawijanie (8), zaznaczanie (1), zaznaczenie (1), zdjęcie (21), zewnętrzne (1), zgodność (4), zmiana (1), zmienna (1), znaczenie (1), znacznik (26), znak (21), znak wodny (1), zogniskowanie (1), źródło (1) # IP tester IP tester Twoje dane: IP: 202.81.115.3 host: 202.81.115.3 proxy: 202.81.115.3 (202.81.115.3) Pokaż hosta/IP: Zlokalizuj IP: Sprawdź IP: Europa : Ameryka : Azja, Pacyfik : <NAME>, Karaiby : Afryka : © www.kurshtml.edu.pl | Polityka prywatności absolute (15), action (29), adres (96), adres strony (49), adresy (16), akapit (101), akapity (13), align (53), align self (53), align text (28), arkusz stylów (34), arkusze (34), arkusze stylów (32), array (56), article (13), atrybut (80), atrybut znacznika (32), atrybuty (206), atrybuty znaczników (18), author (14), auto (58), autor (18), autor strony (15), background (56), background color (38), background image (16), background position (16), background repeat (17), bezpośrednio (77), bgcolor (9), biały (15), block (22), blok (38), blok tekstu (20), blokada (24), blue (21), body (68), body background (14), body color (18), body html (52), body style (25), bold (22), border (68), border right (68), border styl (17), bottom (54), button (20), button type (16), call (59), caption (20), center (50), charset (22), checked (13), circle (13), class (99), code (13), color (96), color strony (54), content (38), cytat (11), czas (62), czas data (19), czcionka (21), czcionka tabeli (14), czcionki (54), czerwony (27), dalej (28), dane (32), darmowe (15), data (25), deklaracje (21), display (22), display block (15), doctype (16), doctype html (16), document (34), dodać atrybut (27), dokumentu (146), dostępu (50), drzewa (16), duże (24), dymek (9), dzieci (15), dziedziczenie (133), edytory (13), efekt (49), efekty (14), element (156), email (4), enter (13), favicon (2), fieldset (14), film html (3), first line (20), fixed right (13), flexbox (6), float (19), font (53), font color (21), font face (4), font family (15), font size (30), font style (41), font weight (21), form (43), form action (28), formatowanie (28), formatowanie tekstu (13), formularz (23), formularza (43), formularze (18), fuksja (2), function (61), galeria (4), generator kolorów (4), grafika (21), hasło (16), head (60), height (54), hidden (28), hiperłącze (4), hover (15), href (73), href name (73), html (192), html body (51), html formularze (16), html lang (20), html menu (55), html nagłówek treści (18), html obramowanie (16), html odsyłacze (29), html tabele (15), html tekst (104), html zielonych (12), html5 (24), https (19), identyfikator (108), iframe (19), ikona (3), image (35), image repeat (13), index (35), index html (29), inherit (104), inline (40), input (42), input type (31), isnan (16), italic (9), javascript (40), jednostki (13), język (112), język html (30), język polski (84), język strony (31), justify (23), klasa (90), klasy (96), klawisz (22), kluczowe (15), kolejność (25), kolor (87), kolor czcionki (15), kolor html (41), kolor linii (23), kolor obramowania (14), kolor strony (47), kolor tabeli (27), kolor tekstem (9), kolor tekstu (46), kolor tekstu html (29), kolorów (23), kolory (14), kolumna (18), kolumny (26), komentarze (9), komórka tabeli (58), komórki (21), koniec (27), koniec strony (20), konta (15), kontrolki (22), kropka (13), krój czcionki (3), kurs zielonych (2), label (19), lang (103), left (93), legend (13), lewej (125), lewej strony (43), line height (14), linia (32), linii (137), link (57), link html (38), linki (20), list (33), list style (25), lista (64), lista definicyjna (3), lista liczby rzymskie (3), lista uporządkowana (3), listy (43), listy html (22), lokalizacja (18), mail (28), mapa (7), margin (38), margin bottom (17), margines (17), margines wewnętrzny (10), marginesy (20), marginesy wewnętrzne (6), mark (5), media (122), menu (76), menu html (57), message (15), meta (44), meta charset (15), middle (15), model pudełkowy (6), multimedia (14), multimedia html (14), nagłówek (39), nagłówek treści (24), nagłówek treść (17), nagłówka (19), nakładanie (5), napis przycisku (3), nazwa strony (47), nbsp (6), notatnik (3), nowe okno (14), number (123), numer (32), obiekt (90), object (59), obramowania (52), obramowania tabeli (16), obramowanie (27), obramowanie komórek (8), obramowanie obrazka (7), obramowanie strony (14), obraz (12), obrazek (63), obrazek html (32), obrazek tekstu (29), obrazka (50), obrazki (15), obrazkowe (17), obszar tekstowy (7), odległość (16), odnośnik (20), odnośnik strony (14), odnośniki (17), odstęp (26), odsyłacz (40), odsyłacz pliku (13), odsyłacz strony (22), odsyłacze (39), onclick (82), onmousemove (70), onmouseover (75), opis (165), opis strony (44), option (19), order (4), osadzić (13), otworzyć (17), outline (14), padding (33), padding left (20), padding right (33), paragraf (8), pattern (3), pierwiastek (3), plik (55), pliki (32), pochylenie (14), początek (26), pocztowy (14), podanie (71), podkreślenie (15), podpis (6), podstrony (27), pogrubienie (21), pogrubienie tekstu (14), pola formularzu (16), pole (32), pole tekstowe (15), polski (87), position (32), powtórka (10), pozycja (45), pozycjonowanie obrazka (2), prawej (123), prawo (17), przeglądarka (60), przejście (15), przełamanie (13), przerwa (5), przycisk (24), przycisk strony (14), przyciski (16), przykład (531), przykład html (116), punkt (40), punkty (17), radio (13), ramka (20), ramki (43), ramy (12), ramy dokumentu (11), repeat (20), return (39), rodzaj (31), rozmiar (56), rozmiar czcionki (20), rozmiar tabeli (15), rozmiar tekst (31), rozmiar tekstu (26), rozmiary (37), rozmiary tabeli (13), rozwijane (5), screen width (3), script (48), search (13), section (13), select (29), selektor (164), selektor atrybutem (15), selektor klasy (13), selektorów (21), selektory elementów (8), selektory pseudoklas (5), serce (3), size (55), size text (22), skrypt (41), skrypty (34), small (21), solid (27), sort (3), source (18), space between (19), spacja (12), span (30), spis (16), spis treści (12), stopka (14), string (89), strona (86), strona internetowa (4), strona tekstu (35), stronie (176), strony (255), struktura (7), struktura dokumentu (3), styl (109), styl linii (55), styl lokalny (4), styl obramowania (18), style (230), style background (34), style border (47), style html (69), style obramowania (34), style pogrubienie (14), style text align right (20), stylesheet (21), submit (16), szablon (15), szablon strony (16), szablon strony html (14), szerokość (68), szerokość kolumny (15), szerokość strony (34), ścieżka (22), ścieżka dostępu (19), tabel (18), tabela (15), tabele (21), tabeli (106), table (37), table align (16), tablica (20), tablica tablicy (14), target (24), tbody (14), tekst (314), tekst alternatywny (23), tekst html (108), tekst kolor (47), tekst lewej stronie (22), tekst lewej strony (30), tekst obrazek (36), tekst obrazka (30), tekst prawej (99), tekst rozmiar (31), tekst tabeli (59), temat (45), test (71), text (75), text align (28), text color (24), text decoration (16), text indeed (83), text padding (15), text size (22), text style (45), textarea (20), title (123), treść (99), tworzenie (15), type (69), tytuł (106), tytuł strony (52), tytuł tabeli (49), tytuły (13), układ (16), układ strony (16), ustawić (22), ustawienie (50), ustawienie obrazka (13), ustawienie tekstu (36), ustawienie wysokości (14), valign (10), vertical (13), visited (16), warto (44), wczytywanie (16), wewnętrzny (16), white (20), width (88), widżety (2), wielkość (27), wielkość czcionki (14), wielkość tekstu (15), wiersz (16), wiersze (19), własności (57), właściwości (26), wpisać (130), wskazówki (3), wstaw (22), wstawianie (148), wstawianie linii (18), wstawianie obrazka (22), wstawianie obrazków (12), wstawianie strony (70), wstawianie styl (18), wstawianie stylów (145), wstawianie tabeli (56), wstawianie tekstu (32), wstawianie zdjęcia (5), wstawić (67), wstawić html (58), wstawić obrazek (18), wstawienie (42), wstęp (33), wygląd (79), wygląd strony (47), wykaz (28), wyrównanie (24), wyrównanie lewej (16), wyrównanie prawej (16), wyrównanie tekstu (23), wyrównanie tekstu lewej (15), wysokość (63), wyśrodkowanie (25), wyśrodkowanie tabeli (14), wyśrodkowanie tekstu (22), wyśrodkowanie tekstu prawej (16), wyśrodkowany tekst (3), zamykający (92), zapis (18), zapisać (29), zapisać html (18), zdjecie (6), zdjęcia (19), zdjęcie (16), zewnętrzny (16), zielony (14), zmiana (31), zmienić kolor (22), znacznik (248), znacznik nagłówka (12), znacznik sekcji (13), znacznik zamykający (91), znaczniki (57), znaczniki html (40), znaczy (13), znaki (61), znaki specjalne (16), znaki specjalne html (13), zrobić (66), zrobić html (38) # Lista skórek Dzięki systemowi skórek możesz dopasować wygląd tego serwisu do swoich oczekiwań. Poniżej znajduje się lista dostępnych szablonów, wykonanych przez czytelników Kursu HTML. Jeżeli chcesz, aby wykonana przez Ciebie skórka znalazła się na tej liście, zobacz: Skórki kurshtml.edu.pl. ## Lista skórek ### Czarna # Autor: Agniecha Czarna skórka ożywiona elementami świetlnymi. Pasuje do tipsów: czarnych, fuchsia, #69c. ### GreenSpirit # Autor: <NAME> (jsmp) Prosta i szybka skórka, nie obciążona zbędną grafiką. Założeniem był minimalizm, który będzie ładnie się prezentować. Mam nadzieję że skórka zagości na waszych ekranach... ### KDE # Autor: <NAME> (GPL) Emulacja wyglądu popularnego linuksowego środowiska graficznego - K Desktop Environment. Idealny wybór dla wszystkich fanatyków Linuksa oraz dla tych, którzy chcieliby zobaczyć chociaż w przybliżeniu, jak wygląda Linux, ale nie mają ochoty instalować nowego systemu operacyjnego. ### KDE 4 # Autor: <NAME> (GPL) Emulacja wyglądu popularnego linuksowego środowiska graficznego - K Desktop Environment w wersji 4 i menedżera plików Dolphin. ### Kurs HTML 2.0 # Autor: <NAME> Tak wyglądała strona Kursu HTML przez wiele lat. Jeżeli tęsknisz za poprzednim wyglądem, możesz do niego wrócić w każdej chwili. ### Lightyellow # Autor: <NAME> Skin jest w całości oparty na CSS, nie ma praktycznie żadnej grafiki, co przyspiesza wczytywanie strony. Postawiłem w nim przede wszystkim na czytelność. Skórka posiada czyste, ładne kolory, które umilają czytanie kursu. ### Magicstyle # Autor: <NAME> Skin jest przystosowany dla osób słabowidzących, ponieważ są wyraźne, duże litery. Założeniem była prostota, ale bardzo przyjemna dla oczu. Życzę miłego czytania kursu w mojej szacie graficznej. ### Maxim # Autor: Piotr 'MuKuL' Makal Szczególną cechą tej skórki jest jej czas powstawania, który był bardzo długi - stąd jej naturalne piękno. Mam nadzieję, iż ten skin będzie dla niektórych z was domyślnym kursuhtml. ### Różowa # Autor: Agniecha Skórka dla wszystkich czytających kurs, a będących jednocześnie fanami różu, a także dla romantycznych dusz lubiących kwiatki. Kolorystycznie pasuje również do tipsów. ### Simple theme # Autor: Piotr 'MuKuL' Makal Prosty i lekki styl, bez zbędnej grafiki, potrafi wykorzystać całą powierzchnię okna przeglądarki; przygotowany dla tych co podczas nauki będą zmieniali rozmiary okienek w systemie. ## Wygląd domyślny Aby przywrócić domyślny wygląd wszystkich stron serwisu, kliknij poniższy przycisk: ## Prawa autorskie Wyłącznymi właścicielami wszystkich prezentowanych tutaj szablonów graficznych są ich autorzy. Każdy autor indywidualnie odpowiada za poszanowanie praw autorskich osób trzecich podczas tworzenia swojej pracy. #000000 #111111 #222222 #333333 #444444 #555555 #666666 #777777 #888888 #999999 #AAAAAA #BBBBBB #CCCCCC #DDDDDD #EEEEEE #FFFFFF #000000 #000033 #000066 #000099 #0000CC #0000FF #003300 #003333 #003366 #003399 #0033CC #0033FF #006600 #006633 #006666 #006699 #0066CC #0066FF #009900 #009933 #009966 #009999 #0099CC #0099FF #00CC00 #00CC33 #00CC66 #00CC99 #00CCCC #00CCFF #00FF00 #00FF33 #00FF66 #00FF99 #00FFCC #00FFFF #330000 #330033 #330066 #330099 #3300CC #3300FF #333300 #333333 #333366 #333399 #3333CC #3333FF #336600 #336633 #336666 #336699 #3366CC #3366FF #339900 #339933 #339966 #339999 #3399CC #3399FF #33CC00 #33CC33 #33CC66 #33CC99 #33CCCC #33CCFF #33FF00 #33FF33 #33FF66 #33FF99 #33FFCC #33FFFF #660000 #660033 #660066 #660099 #6600CC #6600FF #663300 #663333 #663366 #663399 #6633CC #6633FF #666600 #666633 #666666 #666699 #6666CC #6666FF #669900 #669933 #669966 #669999 #6699CC #6699FF #66CC00 #66CC33 #66CC66 #66CC99 #66CCCC #66CCFF #66FF00 #66FF33 #66FF66 #66FF99 #66FFCC #66FFFF #990000 #990033 #990066 #990099 #9900CC #9900FF #993300 #993333 #993366 #993399 #9933CC #9933FF #996600 #996633 #996666 #996699 #9966CC #9966FF #999900 #999933 #999966 #999999 #9999CC #9999FF #99CC00 #99CC33 #99CC66 #99CC99 #99CCCC #99CCFF #99FF00 #99FF33 #99FF66 #99FF99 #99FFCC #99FFFF #CC0000 #CC0033 #CC0066 #CC0099 #CC00CC #CC00FF #CC3300 #CC3333 #CC3366 #CC3399 #CC33CC #CC33FF #CC6600 #CC6633 #CC6666 #CC6699 #CC66CC #CC66FF #CC9900 #CC9933 #CC9966 #CC9999 #CC99CC #CC99FF #CCCC00 #CCCC33 #CCCC66 #CCCC99 #CCCCCC #CCCCFF #CCFF00 #CCFF33 #CCFF66 #CCFF99 #CCFFCC #CCFFFF #FF0000 #FF0033 #FF0066 #FF0099 #FF00CC #FF00FF #FF3300 #FF3333 #FF3366 #FF3399 #FF33CC #FF33FF #FF6600 #FF6633 #FF6666 #FF6699 #FF66CC #FF66FF #FF9900 #FF9933 #FF9966 #FF9999 #FF99CC #FF99FF #FFCC00 #FFCC33 #FFCC66 #FFCC99 #FFCCCC #FFCCFF #FFFF00 #FFFF33 #FFFF66 #FFFF99 #FFFFCC #FFFFFF Jeśli jeszcze niezbyt dobrze rozumiesz formularze, specjalnie dla Ciebie napisałem ten przykład. Myślę, że po jego przeczytaniu, wyjaśni się wiele niezrozumiałych dotąd rzeczy. Wyróżnione fragmenty, można (a nawet trzeba) zastąpić innym tekstem. Są to np. pytania, poszczególne odpowiedzi, wartości parametrów i inne. Czcionką pogrubioną (pomiędzy znakami `<!--` a `-->` ) zaznaczono komentarze. Nie są one oczywiście konieczne (możesz je pominąć). Natomiast pozwalają zorientować się, czego dotyczy fragment kodu poniżej nich. > <form action="mailto:<EMAIL>" method="post" enctype="text/plain"><div> <!-- Podstawowe pole tekstowe --> <input name="Imię">Podaj swoje imię<br> <input name="Nazwisko">Podaj swoje nazwisko <!-- Pole typu RADIO --> <p>Podaj swoją płeć:</p> <input type="radio" name="Płeć" value="Kobieta">Kobieta <input type="radio" name="Płeć" value="Mężczyzna">Mężczyzna <!-- Pole typu RADIO --> <p>Ile masz lat?</p> <input type="radio" name="Wiek" value="mniej niż 15">mniej niż 15<br> <input type="radio" name="Wiek" value="15-19">15-19<br> <input type="radio" name="Wiek" value="20-29">20-29<br> <input type="radio" name="Wiek" value="30-39">30-39<br> <input type="radio" name="Wiek" value="40-60">40-60<br> <input type="radio" name="Wiek" value="więcej niż 60">więcej niż 60 <!-- Pole typu CHECKBOX --> <p>Jaką lubisz muzykę (możesz zaznaczyć więcej możliwości)?</p> <input type="checkbox" name="Muzyka" value="Rock">Rock<br> <input type="checkbox" name="Muzyka" value="Heavy Metal">Heavy Metal<br> <input type="checkbox" name="Muzyka" value="Pop">Pop<br> <input type="checkbox" name="Muzyka" value="Techno">Techno<br> <input type="checkbox" name="Muzyka" value="Muzyka poważna">Muzyka poważna<br> <input type="checkbox" name="Muzyka" value="Inna">Inna (podaj jaka): <input name="Muzyka"> <!-- Lista rozwijalna (typ podstawowy) z zaznaczoną opcją domyślną --> <p>Jakiej przeglądarki internetowej używasz?</p> <select name="Przeglądarka"> <option selected>Chrome</option> <option>Opera</option> <option>Firefox</option> <option>Edge</option> <option>Inna</option> </select> <!-- Lista rozwijalna (typ rozszerzony) z zaznaczoną opcją domyślną i zmniejszoną wysokością --> <p>Jakie znasz systemy operacyjne (możesz wybrać kilka opcji trzymając klawisz Ctrl)?</p> <select name="System operacyjny" multiple size="3"> <option selected>Windows</option> <option>DOS</option> <option>Linux</option> <option>Inny</option> </select> <!-- Pole komentarza (o powiększonych rozmiarach oraz z tekstem domyślnym) --> <p>Podaj swój komentarz:</p> <textarea name="Komentarz" cols="50" rows="10">Proszę, wpisz tutaj jakiś komentarz...</textarea> <br><br><br> <!-- Przycisk WYŚLIJ --> <input type="submit" value="Wyślij formularz"> <!-- Przycisk WYCZYŚĆ DANE --> <input type="reset" value="Wyczyść dane"> </div></formotrzymamy: Jeśli chcemy, aby opisy w lewej kolumnie przylegały do pól formularza (wyrównanie do prawej), wystarczy dla komórek tabeli `<td>` (lub pierwszej kolumny) dodać atrybut `align="right"` . > Date.prototype.constructor Tworzenie stron WWW WWW, czyli codzienne życie webmastera. phpBB Popularne forum dyskusyjne rozwijane na zasadach Open Source. © logeen | Polityka prywatności (CSS 3 - interpretuje Firefox 19, Opera 15, Chrome 4) > selektor { cecha: initial } Aby zmienić wygląd jakiegoś elementu na stronie, trzeba go najpierw wskazać. W języku CSS robi się to za pomocą tzw. selektora. W najprostszym przypadku jest to nazwa wybranego znacznika, który wcześniej wstawiliśmy do naszego dokumentu HTML. Wszystko co znajduje się wewnątrz tak wskazanego znacznika - czyli zarówno tekst, jak i inne znaczniki - otrzyma style podane w deklaracji. Przykładowo, aby zmienić kolor tła oraz teksu na całej stronie, możemy się posłużyć selektorem `body` , ponieważ właśnie wewnątrz znacznika `<body>...</body>` znajduje się cała zawartość strony. Zatem w arkuszu stylów wystarczy umieścić następujący kod: > body { background-color: black; color: white; } Zwróć uwagę, że deklaracja stylów, którą ujmuje się w nawiasy klamrowe, składa się tutaj z dwóch linijek. Każda z nich rozpoczyna się od podania tzw. cechy (inaczej własności), po której następuje wartość. Cecha określa, co chcemy zmienić w wyglądzie wybranego elementu, natomiast wartość - w jaki sposób ma się to zmienić. Zatem gdyby przetłumaczyć powyższą regułę stylów na bardziej zrozumiały język, brzmiałaby ona mniej więcej tak: dla całej zawartości znacznika `body` (selektor) zmień kolor tła (cecha `background-color` ) na czarny (wartość `black` ) i kolor tekstu (cecha `color` ) na biały (wartość `white` ). Pamiętaj, aby po wpisaniu cechy (własności) zawsze postawić znak dwukropka, a po każdej wartości - średnik. Zwróć również uwagę, że jeśli cecha (bądź wartość) zawiera znak myślnika (np. `background-color` ), to przed nim ani po nim nie może znajdować się spacja. Aby ustalić inny kolor tła albo tekstu, wystarczy że w miejsce wartości wstawisz wybraną definicję koloru - zobacz: Wykaz kolorów. Poza zwykłym tekstem na stronę możesz wprowadzić znaczniki (tzw. tagi). Znacznik jest to specjalny tekst umieszczony w nawiasach ostrych - np.: `<b>` . Jest on częścią składni języka HTML i pozwala sterować wyglądem strony. Dzięki niemu możesz np. ustalić kolor tła, rodzaj formatowania tekstu, wstawić obrazek czy tabelę itd. Znacznik nie jest widoczny na ekranie. Widoczne są tylko efekty jego działania (np. wstawienie obrazka). Ja sam aby umieszczony powyżej znacznik `<b>` był widoczny, musiałem się posłużyć pewną "sztuczką" (jeśli nie możesz wytrzymać i już teraz chcesz wiedzieć jaką, zajrzyj na stronę: Znaki specjalne). Ponieważ znaki: "<" (znak mniejszości) oraz ">" (znak większości) są zarezerwowane dla znaczników, nie powinny się one pojawić w normalnej treści strony. Jeżeli musimy ich użyć, należy wpisywać zamiast nich odpowiednio: &lt; oraz &gt;. Ponadto znak "&" (ampersand - angielskie "and" - Shift+7) należy zastępować przez: &amp; Istnieją znaczniki otwierające (np.: `<b>` ) oraz zamykające (np.: `</b>` ). Zauważ, że znacznik zamykający rozpoczyna się ukośnikiem (czyli znakiem: "/") i ma taką samą nazwę jak otwierający. Pomiędzy znacznikami otwierającym i zamykającym może znaleźć się jakiś tekst, który chcemy np. poddać formatowaniu (w tym przypadku będzie to wytłuszczenie tekstu), np.: > <b>Ten tekst zostanie wytłuszczony.</b>albo > <b> Ten tekst zostanie wytłuszczony. </b>(oba powyższe sposoby są równoważne). > <br> Powyższy znacznik ( `<br>` ) stosuje się gdy chcemy natychmiastowo zakończyć linię. Zapytasz zapewne: Po co go stosować, nie można po prostu nacisnąć Enter i przenieść kursor tekstowy do następnej linii? Otóż nie można. Przeglądarka internetowa ignoruje wszelkie znaki przejścia do następnej linii za pomocą klawisza Enter (ignoruje również postawienie obok siebie więcej niż jednej spacji - zobacz: Znaki specjalne). Na przykład jeśli wpiszesz w edytorze taki tekst: > To jest pierwsza linia... a to jest druga linia. * ACRONYM - dla oznaczania wszystkich skrótów powinien być używany znacznik ABBR * APPLET - w zamian należy używać znacznika OBJECT * ISINDEX - może zostać zastąpiony przez kontrolki formularzy * DIR - w zamian należy używać znacznika UL * NOSCRIPT - nie może być używany w języku XHTML5 w przypadku serwowania dokumentu z typem MIME "application/xhtml+xml"; element został wycofany w składni XML, ponieważ parser HTML odczytuje go jako czysty tekst (inaczej do dokumentu załadowałyby się np. objęte nim arkusze CSS, nawet jeżeli przeglądarka obsługuje skrypty), co nie jest możliwe w języku XML Czy tworzenie stron internetowych naprawdę jest tak trudne, jak mówią? * Edytory HTML Który edytor HTML wybrać: Pajączek, CoreEditor, Bluefish, Brackets, PSPad, gedit, Kate, Quanta Plus, SCREEM, Smultron? * Ramy dokumentu Jak wygląda typowy dokument HTML? Co to są podstrony? * Wpisywanie tekstu W jaki sposób wpisuje się tekst na stronach WWW? Jakie są zasady poprawnego wpisywania znaków interpunkcyjnych w tekście komputerowym? * Znaczniki Co to są znaczniki HTML? * Koniec linii W jaki sposób pogrubić (wytłuścić) tekst na stronie WWW? * Tekst pochylony W jaki sposób pochylić tekst na stronie WWW (kursywa)? * Tekst podkreślony W jaki sposób podkreślić tekst na stronie WWW? * Wielkość czcionki W jaki sposób zmienić rozmiar czcionki na stronie WWW? * Kolor czcionki W jaki sposób zmienić kolor czcionki na stronie WWW? * Rodzaj czcionki W jaki sposób zmienić rodzaj czcionki na stronie WWW? * Łączenie parametrów W jaki sposób zmienić wygląd tekstu na stronie WWW? * Kolor tła oraz tekstu W jaki sposób zmienić kolor tła oraz kolor tekstu na stronie WWW? * Wstawienie obrazka Do czego służą odsyłacze (hiperłącza, linki, odnośniki hipertekstowe)? * Odsyłacz do adresu internetowego Jak wstawić link (odsyłacz, hiperłącze, odnośnik hipertekstowy) na stronie WWW? * Odsyłacz pocztowy Jak wstawić adres e-mail na stronie WWW? * Odsyłacz obrazkowy W jaki sposób wstawić na stronie WWW odnośnik (link, hiperłącze, odsyłacz hipertekstowy) obrazkowy (graficzny), czyli klikalny przycisk? * Jak zrobić dobrą stronę Czego unikać, aby Twoja strona WWW nie odstraszała internautów? * Gotowiec HTML Potrzebujesz na jutro gotowej, profesjonalnie wyglądającej strony HTML (gotowiec) i to zupełnie za darmo? * Podsumowanie HTML * Powtórka HTML Widzę, że jesteś "zielony/zielona"... ale nic się nie martw. Jeśli koniecznie chcesz "zmienić kolor", przeczytaj umieszczony poniżej tekst. Pozwoli Ci on, stworzyć Twoją pierwszą stronę internetową, nawet w ciągu jednego dnia. Jeśli uważasz, że pisanie stron w języku HTML jest dla Ciebie "czarną magią", a sama strona jest jakimś tajemniczym i bardzo skomplikowanym dokumentem, to się mylisz. Napisanie krótkiej strony internetowej jest prostsze niż Ci się wydaje. Zatem nie trać już czasu na wymówki typu:> Ja się niczego nie nauczę! i tym podobne, bo to nieprawda. Zacznij już lepiej czytać. Mam tylko jedną prośbę: postaraj się przeczytać w miarę uważnie i po kolei całą treść na tej stronie. Jeśli pominiesz jakiś punkt lub przeczytasz go zbyt pobieżnie, może to spowodować, że nie zrozumiesz następnych. * HTML 4.01 Specification * XHTML 1.0 The Extensible HyperText Markup Language * XHTML 1.1 - Module-based XHTML * HTML5 - A vocabulary and associated APIs for HTML and XHTML * Differences from HTML4 * Unicode Character Database Aby dodać zwykły tekst do istniejącej strony internetowej, wystarczy otworzyć wybrany plik *.html w edytorze HTML. Następnie trzeba wyszukać miejsce w dokumencie, gdzie ma zostać dodany nowy tekst - powinno to być gdzieś wewnątrz sekcji `<body>...</body>` . Tekst można w tym miejscu po prostu wpisać z klawiatury albo wkleić ze schowka systemowego np. przy pomocy kombinacji klawiszy Ctrl+V (pod systemem Windows). Na koniec można zapisać zmieniony plik *.html przy pomocy skrótu klawiaturowego: Ctrl+S. Poza zwykłym tekstem na stronę możesz wprowadzić znaczniki (tzw. tagi). Znacznik jest to specjalny tekst umieszczony w nawiasach ostrych - np.: `<b>` . Jest on częścią składni języka HTML i pozwala sterować wyglądem strony. Dzięki niemu możesz np. ustalić kolor tła, rodzaj formatowania tekstu, wstawić obrazek czy tabelę itd. Znacznik nie jest widoczny na ekranie. Widoczne są tylko efekty jego działania (np. wstawienie obrazka). Ja sam aby umieszczony powyżej znacznik `<b>` był widoczny, musiałem się posłużyć pewną "sztuczką" (jeśli nie możesz wytrzymać i już teraz chcesz wiedzieć jaką, zajrzyj na stronę: Znaki specjalne). Ponieważ znaki: "<" (znak mniejszości) oraz ">" (znak większości) są zarezerwowane dla znaczników, nie powinny się one pojawić w normalnej treści strony. Jeżeli musimy ich użyć, należy wpisywać zamiast nich odpowiednio: &lt; oraz &gt;. Ponadto znak "&" (ampersand - angielskie "and" - Shift+7) należy zastępować przez: &amp; Istnieją znaczniki otwierające (np.: `<b>` ) oraz zamykające (np.: `</b>` ). Zauważ, że znacznik zamykający rozpoczyna się ukośnikiem (czyli znakiem: "/") i ma taką samą nazwę jak otwierający. Pomiędzy znacznikami otwierającym i zamykającym może znaleźć się jakiś tekst, który chcemy np. poddać formatowaniu (w tym przypadku będzie to wytłuszczenie tekstu), np.: > <b>Ten tekst zostanie wytłuszczony.</b>albo > <b> Ten tekst zostanie wytłuszczony. </b>(oba powyższe sposoby są równoważne). Ponieważ znaki: "<" (znak mniejszości) oraz ">" (znak większości) są zarezerwowane dla znaczników, nie powinny się one pojawić w normalnej treści strony. Jeżeli musimy ich użyć, należy wpisywać zamiast nich odpowiednio: &lt; oraz &gt;. > <br> Powyższy znacznik ( `<br>` ) stosuje się gdy chcemy natychmiastowo zakończyć linię. Zapytasz zapewne: Po co go stosować, nie można po prostu nacisnąć Enter i przenieść kursor tekstowy do następnej linii? Otóż nie można. Przeglądarka internetowa ignoruje wszelkie znaki przejścia do następnej linii za pomocą klawisza Enter (ignoruje również postawienie obok siebie więcej niż jednej spacji - zobacz: Znaki specjalne). Na przykład jeśli wpiszesz w edytorze taki tekst: > To jest pierwsza linia... a to jest druga linia. Aby ustawić dwie linijki tekstu jedna pod drugą, umieść pomiędzy nimi znacznik `<br>` . > <p>Tu wpisz treść akapitu</p> Akapit (w pewnych warunkach nazywany paragrafem) to pewien ustęp w tekście. Następujące po sobie akapity, są rozdzielone linijką przerwy. Treść akapitu należy wpisać pomiędzy znacznikami `<p>` oraz `</p>` . Przyjęło się, że praktycznie każdy zwykły tekst na stronie WWW umieszcza się w akapitach. Pojedynczy akapit przedstawia ustęp w tekście, który nieco różni się tematycznie od poprzedniego. Zamiast stosować dwa znaczniki końca linii: `<br><br>` , można po prostu objąć wybrany fragment tekstu paragrafem. Efekt będzie identyczny, a dodatkowo przeglądarka lepiej wyświetli taki tekst. Dzięki temu strona będzie wyglądała estetyczniej i łatwiej będzie można odszukać na niej interesujące informacje. Akapit (paragraf) jest bardzo ważny w składni HTML, ponieważ pozwala w określony sposób sformatować tekst na ekranie (ułożyć go w podany sposób). Robi się to podając atrybuty znacznika. Atrybut wpisuje się zawsze wewnątrz znacznika otwierającego - bezpośrednio po jego nazwie (oddzielony od niej spacją), a przed znakiem zamknięcia nawiasu ostrego, czyli przed ">". Każdy znacznik ma ściśle określone atrybuty, które obsługuje. W przypadku akapitu można zastosować m.in. następujące: * Wyrównanie tekstu do lewej strony (domyślnie) > <p style="text-align: left">Treść akapitu</p> lub po prostu > <p>Treść akapitu</p> * Wyrównanie tekstu do prawej > <p style="text-align: right">Treść akapitu</p> * Wyśrodkowanie tekstu > <p style="text-align: center">Treść akapitu</p> * Justowanie tekstu (wyrównanie do obu marginesów jednocześnie) > <p style="text-align: justify">Treść akapitu</p> We wszystkich przypadkach wyróżnione zostały właśnie atrybuty znacznika wraz z ich wartościami (wartość atrybutu podaje się w cudzysłowie po znaku równości).W miejsce tekstu: Treść akapitu, należy wpisać tekst, który ma zostać sformatowany w sposób określony przez parametr. ### Przykład <p {text-align} style="text-align: left",wyrównanie do lewej, wyrównanie do lewej (style="text-align: left"), (style="text-align: left")... style="text-align: right",wyrównanie do prawej, wyrównanie do prawej (style="text-align: right"), (style="text-align: right")... style="text-align: center",wyśrodkowanie, wyśrodkowanie (style="text-align: center"), (style="text-align: center")... justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify"); justowanie, czyli wyrównanie do obu marginesów jednocześnie (style="text-align: justify")... . > <b>Tu wpisz tekst</bZnacznik ten pozwala pogrubić (wytłuścić) część tekstu (ang. "bold"), który się wewnątrz niego znajduje. Podobna funkcja jest zwykle dostępna w zwykłych edytorach (np.: WordPad), podczas tworzenia normalnego dokumentu tekstowego. Ten tekst jest pogrubiony (wytłuszczony) Pozwala napisać tekst pismem pochylonym, czyli kursywą (ang. "italic"). Pozwala podkreślić fragment tekstu (ang. "underline"). Domyślnie tekst na stronie internetowej jest napisany zwykłą czcionką. Aby podkreślić fragment tekstu, wystarczy umieścić go wewnątrz znacznika `<u>...</u>` . W ten sposób często oznacza się nieartykułowany tekst albo błąd ortograficzny. > <span style="font-size: rozmiar">Tu wpisz tekst</span### Przykład {font-size} Czcionka o rozmiarze xx-small Czcionka o rozmiarze x-small Czcionka o rozmiarze small (domyślna) Czcionka o rozmiarze medium Czcionka o rozmiarze large Czcionka o rozmiarze x-large Czcionka o rozmiarze xx-large . > <span style="color: kolor">Tu wpisz tekst</spanblack | (czarny) | | --- | --- | white | (biały) | silver | (srebrny) | gray | (szary) | maroon | (kasztanowy) | red | (czerwony) | purple | (purpurowy) | fuchsia | (fuksja) | green | (zielony) | lime | (limonowy) | olive | (oliwkowy) | yellow | (żółty) | navy | (granatowy) | blue | (niebieski) | teal | (zielonomodry) | aqua | (akwamaryna) | Jeśli za mało Ci tych szesnastu kolorów, zajrzyj na stronę pt.: Kolory. Edytory HTML posiadają często specjalny selektor kolorów, za pomocą którego można w prosty sposób wybrać barwę o dowolnym odcieniu. Po wpisaniu w edytorze HTML następującego kodu: > <span style="color: red">Ten tekst został napisany czcionką koloru czerwonego</spanna ekranie przeglądarki otrzymamy: Ten tekst został napisany czcionką koloru czerwonego zmieni kolor tekstu na czerwony. > <span style="font-family: rodzaj">Tu wpisz tekst</span>lub > <span style="font-family: rodzaj1, rodzaj2, rodzaj3...">Tu wpisz tekst</span. Wszystkie powyższe parametry (atrybuty i znaczniki) dotyczące tekstu można łączyć, np. po wpisaniu w edytorze: > <p style="text-align: center"><span style="font-size: large; color: red"><b><i><u> To jest jakiś tekst </u></i></b></span></pTo jest jakiś tekst Zauważ, że znaczniki zamykamy w kolejności odwrotnej jak je otwieraliśmy. Czyli najpierw zamykamy znacznik, który został otwarty jako ostatni (w naszym przykładzie jest to: `<u>` ), a na końcu zamykamy ten znacznik, który otworzyliśmy jako pierwszy (czyli `<p>` ). Dodatkowo wartości atrybutu `style="..."` odnoszące się do tego samego znacznika (w naszym przypadku jest to znacznik `<span>` ), można połączyć wypisując je po kolei rozdzielone od siebie znakami średnika (w naszym przypadku są to wartości: ``` "font-size: large; color: red" ``` ). Kolejność wpisywania zarówno wartości atrybutu jak i znaczników (otwierających) jest dowolna. Natomiast jako: "ustawienie" należy wpisać: * left * Obrazek będzie ustawiony po lewej stronie względem otaczającego go tekstu * right * Obrazek po prawej stronie względem tekstu Dla zainteresowanychJeśli chcesz dowiedzieć się więcej na temat dodatkowych możliwości przy wstawianiu obrazków na stronach internetowych, zobacz rozdział: Multimedia / Obrazek. ### Przykład <img {float}style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left", style="float: left"... style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right", style="float: right"... Polecenie pozwala wyśrodkować obrazek, czyli ustawić go na środku ekranu. Dla zainteresowanychJeśli chcesz dowiedzieć się więcej na temat dodatkowych możliwości przy wstawianiu obrazków na stronach internetowych, zobacz rozdział: Multimedia / Obrazek. ### Przykład {text-align: center} <img. (w obrębie całego Internetu) . > <a href="mailto:adres poczty e-mail">opis odsyłacza</aTen odsyłacz jest przydatny, gdy pragniesz umieścić na stronie adres swojej skrzynki poczty elektronicznej (e-mail). Dzięki temu będziesz w stałym kontakcie z internautami odwiedzającymi Twoją stronę. Pamiętaj, że podanie swojego adresu na stronie WWW, może spowodować, że zaczną do Ciebie przychodzić niechciane wiadomości - reklamówki (tzw. spam). Dobrym pomysłem może być założenie sobie darmowego konta pocztowego w dowolnym portalu internetowym i podanie adresu takiego konta na swojej stronie - darmowe konto zawsze można zmienić. Zakładając stronę WWW na darmowym serwerze, często dostajemy również konto e-mail. Wtedy można z niego skorzystać. Dla zainteresowanychJeśli chcesz dowiedzieć się więcej na temat dodatkowych możliwości przy wstawianiu odsyłaczy pocztowych na stronach internetowych, zobacz rozdział: Odsyłacze / Odsyłacz pocztowy. ### Przykład <a mailtoJako przykład użycia takiego odsyłacza możesz wysłać list do mnie. Tylko proszę, jeśli nie masz nic konkretnego do napisania, nie przysyłaj mi pustych listów ;-) . Wszystkie odsyłacze przedstawione do tej pory, miały postać tekstową. Jeśli chcesz umieścić w swoim serwisie np. menu z obrazkowymi przyciskami, należy w tym celu użyć następującego polecenia: > <a href="adres"><img src="Tu podaj względną ścieżkę dostępu do obrazka" alt="Tu podaj tekst alternatywny" style="border: 0"></a* względną ścieżkę dostępu do dowolnej podstrony Twojego serwisu (np.: index.html), * adres internetowy poprzedzony przez "http://" lub "https://" (np.: http://www.onet.pl), * adres poczty elektronicznej poprzedzony przez "mailto:" (np.: mailto:<EMAIL>). Jak widać odsyłacza obrazkowego możemy użyć w połączeniu z dowolnym typem odnośników (do podstrony, do adresu internetowego lub pocztowy). Jednak najczęściej w ten sposób tworzy się menu nawigacyjne serwisu (odsyłacze do podstron). Obrazki przycisków najlepiej zapisywać w formacie GIF. Jeśli nie masz zacięcia artystycznego, nie musisz samodzielnie rysować wszystkich grafik. W Internecie na pewno znajdziesz wiele stron, gdzie możesz darmowo pobrać gotowe przyciski. Dla zainteresowanychJeśli chcesz dowiedzieć się więcej na temat dodatkowych możliwości przy wstawianiu odsyłaczy obrazkowych na stronach internetowych, zobacz rozdział: Odsyłacze / Odsyłacz obrazkowy. ### Przykład <a href, imgTo by było na tyle. Poznane tu polecenia powinny pozwolić Ci na napisanie prostej, ale zarazem dość dobrze wyglądającej strony WWW. Jeśli już teraz chcesz jak najszybciej sprawdzić w praktyce poznane wiadomości, to tutaj możesz skorzystać z szybkiego edytora stron próbnych, który pozwoli Ci napisać Twoją pierwszą testową stronę WWW. A więc do dzieła... Jeżeli będziesz mieć więcej czasu, zajrzyj do dalszych rozdziałów tego kursu. Znajdziesz tam o wiele więcej przydatnych znaczników, dzięki którym napiszesz jeszcze lepszą stronę. Aby kontynuować Kurs HTML, kliknij poniższe linki: Dodatkowo w rozdziale: I co dalej możesz przeczytać szczegółowy opis, jak wprowadzić swoją stronę do Internetu (zupełnie za darmo).Zapraszam... Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu HTML. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. > <p>Tu wpisz treść akapitu</p> > <p style="text-align: left">Treść akapitu</p> > <p>Treść akapitu</p> > <p style="text-align: right">Treść akapitu</p> > <p style="text-align: center">Treść akapitu</p> > <p style="text-align: justify">Treść akapitu</p > <b>Tu wpisz tekst</b > <i>Tu wpisz tekst</i > <u>Tu wpisz tekst</u > <span style="font-size: rozmiar">Tu wpisz tekst</span > <span style="color: kolor">Tu wpisz tekst</span > <body style="background-color: kolor tła; color: kolor tekstu"> Tu jest właściwa treść strony </body > <img src="Tu podaj względną ścieżkę dostępu do obrazka" alt="Tu podaj tekst alternatywny" style="float: ustawienie" > <a href="względna ścieżka dostępu do podstrony">opis odsyłacza</a > <a href="adres internetowy">opis odsyłacza</a > <a href="mailto:adres poczty e-mail">opis odsyłacza</a > <a href="adres"><img src="Tu podaj względną ścieżkę dostępu do obrazka" alt="Tu podaj tekst alternatywny" style="border: 0"></aDate: 2002-11-02 Categories: Tags: * Jak wprowadzić stronę do Internetu Jak wprowadzić swoją stronę do Internetu (zupełnie za darmo)? * Darmowe serwery Jaki serwer wybrać na swoją stronę? Jak założyć konto na stronę WWW? * Płatne serwery Co jest ważne przy wyborze domeny (adresu) swojej strony internetowej? Czym się różnią płatne usługi hostingowe od darmowych serwerów WWW? Na co zwrócić uwagę wybierając płatny hosting? * Wysłanie strony Jak za pomocą programu FTP przesyłać na serwer pliki wchodzące w skład strony? Jak zablokować dostęp do swojego konta osobom trzecim? * Modyfikacja W jaki sposób zaktualizować swoją stronę WWW? * Aliasy Gdzie znaleźć łatwiejszy do zapamiętania adres dla Twojej strony? * Rejestracja W jaki sposób wstawić na swojej stronie darmowe komponenty: licznik odwiedzin, statystyki odwiedzin, księga gości, forum dyskusyjne, ankieta, sonda, czat (chat), subskrypcja (newsletter)? * Podsumowanie Date: 2001-05-31 Categories: Tags: * Co to jest XHTML? Co to jest język XHTML? * Jakie korzyści daje przejście z HTML na XHTML? Po co powstał język XHTML? * Czy HTML umarł? Czy przejście z języka HTML do XHTML wymaga przepisania wszystkich stron od nowa? * Wymagania stawiane dokumentom XHTML Jak dostosować dokument HTML do standardu XHTML? * Różnice między HTML 4 a XHTML 1.0 Czym różni się HTML 4 od XHTML 1.0? * Różnice między XHTML 1.0 Strict a XHTML 1.1 Czym różni się XHTML 1.0 Strict od XHTML 1.1? * Typy MIME dokumentów XHTML Co to są typy MIME dokumentów i dlaczego są tak ważne w języku XHTML? W jaki sposób automatycznie dobrać typ MIME, tak aby nie powodować błędów w starszych przeglądarkach? Źródło: XHTML 1.0 The Extensible HyperText Markup Language . * allow-same-origin * Zezwala odczytywać ciasteczka przeglądarki oraz dane użytkownika z innych podobnych mechanizmów. * allow-scripts * Zezwala na uruchamiania skryptów JavaScript. * allow-top-navigation * Pozwala na używanie atrybutu `target="_top"` dla odnośników. * allow-top-navigation-by-user-activation * Pozwala na używanie atrybutu `target="_top"` dla odnośników, ale tylko jeśli użytkownik sam w nie kliknie, a nie zostaną otwarte automatycznie poprzez skrypt w ramce (obsługuje: Opera 45, Chrome 58). * soft * Tekst nie zostanie zawinięty w chwili wysyłania formularza, choć może być w taki sposób wyświetlony na ekranie (domyślnie). * hard * W momencie wysłania formularza, przeglądarka automatycznie zawinie tekst wpisany w polu, tzn. doda do niego znaki nowej linii, tak aby wyglądał jak na ekranie przed wysłaniem. Nadanie atrybutu `decoding="sync"` może spowolnić wyświetlanie całej strony - zwłaszcza w przypadku dużych obrazków. Zastosowanie: IMG. * A * Jeżeli sam nie zawiera się w elemencie wyświetlanym w linii, może obejmować sobą również elementy blokowe z wyjątkiem interaktywnych: A, BUTTON, DETAILS, EMBED, IFRAME, KEYGEN, LABEL, SELECT, TEXTAREA, AUDIO (z atrybutem `controls` ), IMG (z atrybutem `usemap="..."` ), INPUT (z atrybutem `type="..."` innym niż "hidden"), MENU (z atrybutem `type="toolbar"` ), OBJECT (z atrybutem `usemap="..."` ), VIDEO (z atrybutem `controls` ). Szczególnego podkreślenia wymaga, że jest to niezwykle pomocna zmiana. Dzięki niej, mając np. listę artykułów z tytułami, skróconymi wprowadzeniami i zdjęciem, nie trzeba już wstawiać trzy razy tego samego linku przy każdym artykule, aby osobno objąć zawartość każdego z tych elementów. HTML5 pozwala objąć jednym znacznikiem odnośnika wszystkie te elementy jednocześnie - nawet jeśli część z nich jest wyświetlana w bloku. * ADDRESS * Odnosi się do najbliższego elementu ARTICLE lub BODY, w którym został wstawiony. Może zawierać również elementy blokowe z wyjątkiem: nagłówków (H1, H2, H3, H4, H5, H6), sekcji (ARTICLE, ASIDE, NAV, SECTION), HEADER, FOOTER, ADDRESS. * B * Tekst na który należy zwrócić uwagę z powodów czysto użytkowych. Nie nadaje dodatkowej ważności treści ani nie stawia akcentu wypowiedzi. Przydatne przy oznaczaniu słów kluczowych w tekście albo wprowadzenia na początku artykułu. * CAPTION * Może zawierać również elementy blokowe z wyjątkiem TABLE. * CITE * Oznacza wyłącznie tytuły prac (książek, opracowań, wierszy, piosenek, filmów, gier, obrazów itp.), a nie ich autorów. * DL * Lista opisowa (ang. description list). Nie nadaje się teraz do oznaczania dialogów. * FIELDSET * Nie musi zawierać elementu LEGEND. * HR * Oddziela bloki tematyczne sekcji artykułu na poziomie akapitów. * I * Oznacza np. termin techniczny, idiom z innego języka albo fragment wtrąconego tekstu. * LABEL * Kliknięcie na etykietę nie musi już oznaczać automatycznego przeniesienia kursora tekstowego do skojarzonego z nią pola formularza, chyba że takie jest standardowe zachowanie systemu operacyjnego użytkownika. * MENU * Służy do budowy użytecznych pasków narzędzi oraz menu kontekstowych. * NOSCRIPT * Zostanie wyświetlony wyłącznie, jeśli przeglądarka w ogóle nie obsługuje dynamicznych skryptów, a nie kiedy nie potrafi zinterpretować języka skryptowego, określonego w poprzedzającym go znaczniku SCRIPT. * S * Oznacza treść, która nie jest dłużej trafna lub istotna, z punktu widzenia pozostałej zawartości dokumentu. * SCRIPT * Istnieje możliwość określenia dodatkowych wartości atrybutu `type="..."` - np.: "text/plain", "text/xml", "application/octet-stream", "application/xml". W tak oznaczonym elemencie można zapisać surowe dane dla dynamicznych skryptów używanych na stronie. * SMALL * Reprezentuje przypisy (wyjaśnienia, zastrzeżenia, ograniczenia prawne, prawa autorskie). * STRONG * Oznacza wysoką ważność, a nie mocne wyróżnienie tekstu. * TH * Może zawierać również elementy blokowe z wyjątkiem: HEADER, FOOTER, sekcji (ARTICLE, ASIDE, NAV, SECTION), nagłówków (H1, H2, H3, H4, H5, H6). * U * Nieartykułowany tekst albo oznaczenie błędu ortograficznego. * TABLE, THEAD, TBODY, TFOOT, TR, OL, UL, DL * Mogą być puste (nie zawierać żadnych elementów potomnych). * accept * Dla elementów INPUT pozwala użyć ogólnych wartości: "audio/*" (dowolny plik w formacie dźwiękowym), "video/*" (dowolny plik w formacie wideo), "image/*" (dowolny plik graficzny). * accesskey * Możliwość użycia listy klawiszy rozdzielonych spacjami, z których przeglądarka może wybrać najbardziej dla niej odpowiedni. * action * Nie może zawierać pustej wartości. * border * Dla znacznika TABLE może zawierać tylko pustą wartość lub cyfrę "1". * colspan * Dla elementów TD i TH musi zawierać wartość większą od zera. * coords * Dla znacznika AREA nie może zawierać wartości procentowej, gdy `shape="circle"` . * defer * Jasno określono, że wywoła załadowanie pliku skryptu osadzonego przy pomocy SCRIPT, kiedy kod strony zostanie w całości wczytany przez przeglądarkę. * dir * Dodano nową wartość - "auto". * enctype * Dla znacznika FORM dodano obsługę "text/plain". * href * Dla elementu LINK nie może zawierać pustej wartości. Dla elementu BASE musi zawierać adres bezwzględny. Dla elementu A może zawierać IRI (od zwykłego adresu URL różni się tym, że może składać się z liter spoza alfabetu łacińskiego). Wymagane jest jednak przy tym, aby dokument był zapisany przy użyciu strony kodowej UTF-8 lub UTF-16. * http-equiv * Dla elementu META nie oznacza już nagłówków HTTP serwera, ale dyrektywy przeglądarki. * id * Może zawierać dowolnie długą wartość, pod warunkiem że nie powtarza się drugi raz w tym samym dokumencie, nie jest pusta ani nie zawiera spacji. * lang * Może zawierać pustą wartość. * media * Dla znacznika LINK akceptuje zapytania mediów, a domyślnie posiada wartość "all". * onclick... * Atrybuty obsługi zdarzeń interfejsu użytkownika mogą zawierać wyłącznie kod skryptu, napisany w języku JavaScript. * start, type * Dla elementu OL nie są już zdeprecjonowane. * style * Może zawierać wyłącznie kod CSS - jako języka formatowania. * tabindex * Przyjmuje również wartości ujemne, co oznacza, że element może zostać aktywowany, ale nie za pomocą klawisza tabulatora. * target * Dla znaczników A i AREA nie jest już zdeprecjonowany. Może być przydatny w połączeniu z IFRAME. * type * Nie jest już konieczny dla elementów SCRIPT ani STYLE, o ile językiem skryptowym jest JavaScript, a językiem formatowania - odpowiednio CSS. * usemap * Dla znacznika IMG nie może już zawierać adresu URL, ale odniesienie do identyfikatora, rozpoczynające się znakiem krzyżyka ("#"). * value * Dla elementu LI nie jest już zdeprecjonowany. * width, height * Dla znaczników IMG, IFRAME, OBJECT nie mogą zawierać wartości procentowych. Nie mogą również zostać użyte do spłaszczenia ani rozciągnięcia elementów niezgodnie z ich oryginalnymi proporcjami. * border * Jeśli jest podany dla znacznika IMG, musi zawierać wartość "0" (zero). W zamian lepiej używać CSS. * language * Jeśli jest podany dla znacznika SCRIPT, musi zawierać wartość "JavaScript" (wielkość liter w zapisie nie ma znaczenia). Nie może kolidować z wartością `type="..."` . Najlepiej w ogóle pominąć atrybut `language="..."` , ponieważ nie ma on żadnej użytecznej funkcji. * name * Zamiast niego dla elementu A lepiej używać atrybutu `id="..."` . * Podsekcja 1.1 (zawiera akapit: "Akapit podsekcji 1.1") * Podsekcja 1.2 (zawiera akapit: "Akapit podsekcji 1.2") * Podsekcja 1.1 * miesiąc * 2011-11 * data * 2011-11-12 * 11-12 (każdy 12 listopada) * czas * 14:54 * 14:54:39 * 14:54:39.92922 * data i czas lokalny * 2011-11-12T14:54 * 2011-11-12T14:54:39 * 2011-11-12T14:54:39.92922 * 2011-11-12 14:54 * 2011-11-12 14:54:39 * 2011-11-12 14:54:39.92922 * strefa czasowa * Z, +0000, +00:00 (czas UTC) * +0100, +01:00 (czas zimowy w Polsce) * +0200, +02:00 (czas letni w Polsce) * -0800, -08:00 * data i czas ze strefą czasową * 2011-11-12T14:54Z * 2011-11-12T14:54:39Z * 2011-11-12T14:54:39.92922Z * 2011-11-12T14:54+0000 * 2011-11-12T14:54:39+0000 * 2011-11-12T14:54:39.92922+0000 * 2011-11-12T14:54+00:00 * 2011-11-12T14:54:39+00:00 * 2011-11-12T14:54:39.92922+00:00 * 2011-11-12T06:54-0800 * 2011-11-12T06:54:39-0800 * 2011-11-12T06:54:39.92922-0800 * 2011-11-12T06:54-08:00 * 2011-11-12T06:54:39-08:00 * 2011-11-12T06:54:39.92922-08:00 * 2011-11-12 14:54Z * 2011-11-12 14:54:39Z * 2011-11-12 14:54:39.92922Z * 2011-11-12 14:54+0000 * 2011-11-12 14:54:39+0000 * 2011-11-12 14:54:39.92922+0000 * 2011-11-12 14:54+00:00 * 2011-11-12 14:54:39+00:00 * 2011-11-12 14:54:39.92922+00:00 * 2011-11-12 06:54-0800 * 2011-11-12 06:54:39-0800 * 2011-11-12 06:54:39.92922-0800 * 2011-11-12 06:54-08:00 * 2011-11-12 06:54:39-08:00 * 2011-11-12 06:54:39.92922-08:00 * tydzień * 2011-W46 (46-ty tydzień 2011 roku) * rok * 2011 * czas trwania * PT4H18M3S (4 godziny 18 minut 3 sekundy) * 4h 18m 3s * Nieokreślony stopień ukończenia: > <progress>alternatywa</progress> * Pasek postępu: > <progress value="współczynnik">alternatywa</progress> <progress value="wartość" max="maksimum">alternatywa</progress* alternatywa * Alternatywna zawartość, wyświetlana w przeglądarkach, które nie obsługują HTML5. Powinno się tam umieścić np. tekst "Proszę czekać..." albo "Ukończono: 50%". * współczynnik * Wartość z przedziału od 0.0 (stopień postępu 0%) do 1.0 (100%). * wartość * Liczba z przedziału od 0 (zero) do maksimum. * maksimum * Maksymalna wartość, po osiągnięciu której zadanie uważa się za ukończone (100%). * Pasek wyniku: > <meter value="współczynnik">alternatywa</meter> * Minimum i maksimum: > <meter value="wartość" min="minimum" max="maksimum">alternatywa</meter> * Przedziały wartości: > <meter value="współczynnik" low="niski" high="wysoki">alternatywa</meter> <meter value="wartość" min="minimum" max="maksimum" low="niska" high="wysoka">alternatywa</meter> * Wartość optymalna: > <meter value="współczynnik" low="niski" high="wysoki" optimum="optymalny">alternatywa</meter> <meter value="wartość" min="minimum" max="maksimum" low="niska" high="wysoka" optimum="optymalna">alternatywa</meter* alternatywa * Alternatywna zawartość, wyświetlana w przeglądarkach, które nie obsługują HTML5. Powinno się tam umieścić np. zapisaną tekstowo wartość, którą przedstawia pasek wyniku. * współczynnik * Wartość z przedziału od 0.0 (0%) do 1.0 (100%). * wartość * Liczba z przedziału od minimum do maskimum. * minimum, maksimum * Przedział dopuszczalnych wartości jakie może osiągnąć wynik. * niski, wysoki, optymalny * Liczby z przedziału od 0.0 do 1.0 (niski ≤ wysoki), które określają, jaka wartość współczynnika jest uznawana odpowiednio za: niską, wysoką, optymalną. * niska, wysoka, optymalna * Liczby z przedziału od minimum do maksimum (niska ≤ wysoka), które określają, jaka wartość jest uznawana odpowiednio za: niską, wysoką, optymalną. * Panel domyślnie zamknięty: > <details> <summary>nagłówek</summary> ... </details> * Panel domyślnie otwarty: > <details open> <summary>nagłówek</summary> ... </details* lokalizacja pliku w formacie 1, lokalizacja pliku w formacie 2... * Lokalizacja pliku obrazka na dysku lub adres URL do pliku w Internecie zapisanego przy użyciu różnych formatów. Zostanie wyświetlony tylko jeden z podanych plików graficznych - pierwszy w kolejności którego format jest obsługiwany przez przeglądarkę. * format 1, format 2... * Nazwa formatu (typ MIME), w którym został zapisany plik obrazka - np.: "image/webp" (WebP), "image/vnd.ms-photo" (JPEG XR - extended range), "image/svg+xml" (Scalable Vector Graphics). * lokalizacja pliku w formacie podstawowym * Lokalizacja pliku dla przeglądarek, które w ogóle nie obsługują znacznika `PICTURE` albo jeśli nie obsługują żadnego z formatów wymienionych w znacznikach SOURCE. * Tekst alternatywny * Tekst który zostanie wyświetlony, jeżeli przeglądarka nie zdoła wyświetlić żadnego obrazka. * lokalizacja pliku 1, lokalizacja pliku 2... * Lokalizacja pliku obrazka na dysku lub adres URL do pliku w Internecie wykadrowanego w odpowiedni sposób. Zostanie wyświetlony tylko jeden z podanych plików graficznych - pierwszy w kolejności który spełnia zapytanie mediów podane w atrybucie `media="..."` . * zapytanie mediów 1, zapytanie mediów 2... * Na przykład: "(max-width: 500px)" [zobacz: Zapytania mediów]. * lokalizacja pliku podstawowego * Lokalizacja pliku dla przeglądarek, które w ogóle nie obsługują znacznika `PICTURE` albo jeśli nie spełniają żadnego z zapytań mediów wymienionych w znacznikach SOURCE. * Tekst alternatywny * Tekst który zostanie wyświetlony, jeżeli przeglądarka nie zdoła wyświetlić żadnego obrazka. * Większość z nich nie została wcześniej oficjalnie ustandaryzowana, dlatego były interpretowane odmienne lub w ogóle nieobsługiwane w niektórych przeglądarkach. * Nie istniało standardowe API, dzięki któremu można by w prosty sposób wstawić na stronie odtwarzacz z własną skórką, realizować dynamiczne listy odtwarzania itp. * Wymagały do działania zainstalowanych wtyczek (np. Adobe Flash Player), przez co czasem nadmiernie obciążały procesor, a przy tym nie były w ogóle obsługiwane przez wiele urządzeń mobilnych (smartfony, tablety). Dodatkowo wymagały od webmastera znajomości środowiska Adobe Flash (i zakup komercyjnej licencji) albo konieczności korzystania jedynie z ogólnodostępnych odtwarzaczy Flash, bez możliwości dopasowania ich do własnych potrzeb. * Często działały tylko w systemie operacyjnym Microsoft Windows, uniemożliwiając obejrzenie filmów czy posłuchania muzyki użytkownikom Maców i Linuksa. * Zdarzały się poważne trudności z ustawieniem warstw (otwierane menu, okna dialogowe) ponad oknem wyświetlanym przez wtyczkę. Często okno odtwarzania wtyczki po prostu zawsze przebijało przez taką warstwę. * Brakowało możliwości zmiany wyglądu przy pomocy CSS. * Nie było możliwe dołączenie do filmów własnych napisów. * Wymaga zainstalowanej na komputerze wtyczki. Nie każda przeglądarka obsługuje wszystkie rodzaje wtyczek. Nie każda wtyczka jest dostępna dla wszystkich rodzajów systemów operacyjnych. Nie każdy użytkownik wie, jak samodzielnie zainstalować wtyczkę. * Webmaster nadal nie dostaje standardowego API, dzięki któremu mógłby dynamicznie manipulować odtwarzanym materiałem multimedialnym. * Element EMBED nie posiada znacznika zamykającego, a element NOEMBED nadal nie został wprowadzony do specyfikacji. Zatem nie można zastosować żadnej automatycznej alternatywy, jeżeli przeglądarka użytkownika nie obsługuje żądanej wtyczki. * Tylko podstawowe atrybuty znacznika EMBED zostały opisane w specyfikacji. Pozostałe zależą od możliwości użytej wtyczki. * Element ten nie jest w żaden sposób zoptymalizowany do odtwarzania filmów ani muzyki. * Podstawowy odtwarzacz wideo (niezalecane!): > <video src="lokalizacja pliku">Treść alternatywna</video> * Podstawowy odtwarzacz audio (niezalecane!): > <audio src="lokalizacja pliku">Treść alternatywna</audio> * Odtwarzacz wielu formatów wideo: > <video> <source src="lokalizacja pliku w formacie 1" type='format 1'> <source src="lokalizacja pliku w formacie 2" type='format 2'> (...) Treść alternatywna </video> * Odtwarzacz wielu formatów audio: > <audio> <source src="lokalizacja pliku w formacie 1" type='format 1'> <source src="lokalizacja pliku w formacie 2" type='format 2'> (...) Treść alternatywna </audio* lokalizacja pliku * Lokalizacja pliku multimedialnego na dysku lub adres URL do pliku w Internecie. * Treść alternatywna * Zawartość, która zostanie wyświetlona, jeżeli przeglądarka nie obsługuje tego znacznika. Może to być np. bezpośredni link do pobrania pliku multimedialnego na swój dysk lokalny albo zbiór znaczników realizujący uniwersalny sposób odtwarzania plików w HTML 4. Należy zwrócić uwagę, że treść alternatywna nie zostanie wyświetlona, jeżeli przeglądarka obsługuje znacznik AUDIO/VIDEO, a jedynie nie rozpoznaje podanego formatu pliku audio/wideo. * lokalizacja pliku w formacie 1, lokalizacja pliku w formacie 2... * Lokalizacja tego samego filmu bądź muzyki, zapisanych przy użyciu różnych formatów. Zostanie odtworzony tylko jeden z podanych plików - pierwszy w kolejności którego format jest obsługiwany przez przeglądarkę. Sposób ten nie służy do tworzenia list odtwarzania. * format 1, format 2... * Nazwa formatu (typ MIME), w którym został zapisany plik. Szczególnie dla formatów wideo powinno się dodatkowo podać nazwę kodeków, za pomocą których został skonwertowany obraz i dźwięk (zobacz przykłady poniżej: Kodeki MP4, Kodeki OGG/OGV). * none * Żadna część pliku nie zostanie załadowana, zanim nie rozpocznie się jego odtwarzanie. Opcja przydatna, jeżeli odtwarzacz jest na stronie elementem pobocznym i użytkownik może nigdy go nie użyć albo ewentualnie kiedy zależy nam na zminimalizowaniu transferu. * metadata * Pobiera tylko tzw. metadane zapisane w pliku (wymiary, lista ścieżek, czas trwania itp.) oraz możliwe, że kilka pierwszych klatek filmu. * auto * Przeglądarka może dowolnie pobierać plik - w szczególności załadować go w całości do pamięci, nawet jeśli nigdy nie zostanie odtworzony. * H.264 Constrained baseline profile video (main and extended video compatible) level 3 and Low-Complexity AAC audio in MP4 container * * napisy.vtt * Lokalizacja pliku tekstowego z napisami (*.vtt) - na dysku lub adres URL do pliku w Internecie. Dodanie atrybutu `default` jest konieczne. Inaczej napisy mogą nie zostać wyświetlone! * lokalizacja pliku w formacie 1, lokalizacja pliku w formacie 2..., format 1, format 2..., Treść alternatywna * Opisane w rozdziale: VIDEO, AUDIO, SOURCE. * Nazwa pliku musi mieć rozszerzenie *.vtt, a nie *.vtt.txt. Aby to zrobić w Notatniku, w oknie zapisywania pliku wybierz opcję: "Zapisz jako typ: Wszystkie pliki", a następnie wpisz pełną nazwę (np. napisy.vtt). * Plik napisów musi być zapisany przy użyciu kodowania znaków UTF-8 - nieważne przy użyciu jakiej strony kodowej został utworzony dokument HTML, w którym jest wstawiony odtwarzacz wideo z dołączonymi tymi napisami. Aby to zrobić w Notatniku, w oknie zapisywania pliku wybierz opcję: "Kodowanie: UTF-8". Jeżeli używasz innego edytora możesz posiadać dodatkowo opcję zapisu pliku bez tzw. znaku BOM (znacznik kolejności bajtów) - dla plików *.vtt może on zarówno zostać dodany, jak i pominięty. W tym przypadku raczej korzystniej będzie go dodać (Notatnik robi to automatycznie). * subtitles * Typowe napisy, które widzimy np. w kinie na obcojęzycznych filmach. Są po prostu tłumaczeniem na język rodzimy wszystkich kwestii wypowiadanych przez aktorów na ekranie. * captions * Opisuje nie tylko dialogi, ale również wszystkie istotne dźwięki w filmie, które są konieczne do pełnego zrozumienia fabuły. Tego typu napisy często są używane przez osoby niesłyszące. Jednak mogą być przydatne również w sytuacji, kiedy użytkownik sam wyciszy dźwięk. * descriptions * Tego typu napisy zwykle są odczytywane na głos przez syntezator mowy, a nie wyświetlane bezpośrednio na filmie. Zawierają tekstowy opis całego filmu, z którego często korzystają osoby niewidome. Może on być jednak przydatny również w sytuacji, kiedy z jakiegoś powodu wideo nie może być odtworzone - np. kiedy kierujemy samochodem. * align - ustawienie w poziomie * rl - napis przy lewej krawędzi * lr - napis przy prawej krawędzi Date: 2011-11-12 Categories: Tags: Co to jest język HTML5? * Czy XHTML umarł? Jak wygląda typowy dokument (X)HTML5? * Nowe elementy HTML5 Jakie nowe elementy (znaczniki) znajdują się w HTML5? * Nowe atrybuty HTML5 Jakie nowe atrybuty znajdują się w HTML5? * Zmienione elementy i atrybuty HTML5 Jakie elementy (znaczniki) i atrybuty zostały zmienione (zmodyfikowane) w HTML5? * Przestarzałe elementy i atrybuty HTML5 Jakie elementy (znaczniki) i atrybuty wycofano (usunięto) w HTML5? * Sekcja <sectionJak podzielić tematycznie obszerniejsze fragmenty dokumentu HTML5? * Artykuł <articleJak wstawić artykuł do dokumentu HTML5? * Wstawka <asideW jaki sposób poprawnie wstawić do dokumentu podtytuł? * Nagłówek <headerJak powinno się wstawiać wprowadzenie w dokumentach HTML5? * Stopka <footerJak wstawić na stronie WWW sekcję z linkami nawigacyjnymi? * Szablon strony w HTML5 Jak powinien wyglądać szablon (szkielet) strony w języku HTML5? * Załącznik <figure, figcaptionW jaki sposób oznaczyć w HTML5: ilustrację, diagram, zdjęcie, kod źródłowy, rysunek, rycinę, wykres, załącznik? * Główna treść <mainW jaki sposób wskazać główną zawartość strony WWW? * Uwydatnienie <markJak zaznaczyć lub uwydatnić część tekstu? * Data i czas <timeW jaki sposób poprawnie oznaczać datę i czas w dokumentach HTML5? * Możliwy koniec linii <wbrJak umożliwić przeglądarce przełamanie długiej linii do następnego wiersza? * Autouzupełnianie <datalistW jaki sposób dodać autouzupełnianie pola formularza? * Pasek postępu <progressJak wstawić na stronie WWW pasek postępu? * Pasek wyniku <meterJak wstawić na stronie WWW pasek głosowania w ankiecie? * Otwierany panel <details, summaryCo zrobić, aby wstawić na stronę panel, otwierany po kliknięciu myszką? * Responsywny obrazek <picture, sourceW jaki sposób wstawić na stronie internetowej obrazek (grafikę, zdjęcie, fotografię, ilustrację), który automatycznie dopasowuje się do wielkości ekranu? * Filmy i dźwięk <video, audio, sourceW jaki sposób wstawić odtwarzacz filmów wideo lub muzyki audio na stronie internetowej? * Napisy do filmów <trackJak dodać napisy (ścieżkę tekstową) do filmu wideo? * Powtórka Uważny czytelnik w tym momencie może poczuć się nieco zdezorientowany - "Najpierw uczyłem się HTML 4, potem dowiedziałem się, że lepszy od niego może być XHTML, a teraz jeszcze muszę się uczyć HTML5?". W wielu zastosowaniach język HTML jest zupełnie wystarczający. Nie każdy webmaster musi znać język XML, a zatem tym bardziej nie będzie miał potrzeby korzystania z jego narzędzi. Jednak pisanie dokumentów HTML w taki sposób, aby składniowo były zgodne z językiem XHTML 1 (a więc również XML), tak naprawdę raczej niewiele kosztuje. Być może kiedyś zajdzie potrzeba wykorzystania dodatkowych możliwości XHTML, a wtedy dokumenty będą już do tego praktycznie przygotowane. Mimo swojej nieco mylącej nazwy, specyfikacja HTML5 tak naprawdę definiuje dwa języki: HTML5 oraz XHTML5. Ten drugi jest tym samym, czym był XHTML 1 dla HTML 4, czyli korzysta dokładnie z tych samych znaczników i atrybutów, a jedynie określa nieco inny sposób zapisu oraz klika dodatkowych ograniczeń w celu uzyskania zgodności z ogólnym językiem XML. Nie ma zatem obawy - XHTML nie umarł i na dodatek ma się całkiem dobrze :-) Jeżeli jednak czytelnik woli korzystać z uproszczonej składni HTML i nie sądzi, że własności XML kiedykolwiek będą mu potrzebne, nie ma żadnych przeszkód, aby używać zapisu właściwego tylko dla języka HTML. Tworząc specyfikację HTML5 organizacja W3C dała jasno do zrozumienia (pod delikatnym naciskiem producentów przeglądarek), że język HTML nie zostanie porzucony na rzecz XHTML, ale że będą się rozwijać jednocześnie. . * allow-same-origin * Zezwala odczytywać ciasteczka przeglądarki oraz dane użytkownika z innych podobnych mechanizmów. * allow-scripts * Zezwala na uruchamiania skryptów JavaScript. * allow-top-navigation * Pozwala na używanie atrybutu `target="_top"` dla odnośników. * allow-top-navigation-by-user-activation * Pozwala na używanie atrybutu `target="_top"` dla odnośników, ale tylko jeśli użytkownik sam w nie kliknie, a nie zostaną otwarte automatycznie poprzez skrypt w ramce (obsługuje: Opera 45, Chrome 58). * soft * Tekst nie zostanie zawinięty w chwili wysyłania formularza, choć może być w taki sposób wyświetlony na ekranie (domyślnie). * hard * W momencie wysłania formularza, przeglądarka automatycznie zawinie tekst wpisany w polu, tzn. doda do niego znaki nowej linii, tak aby wyglądał jak na ekranie przed wysłaniem. * A * Jeżeli sam nie zawiera się w elemencie wyświetlanym w linii, może obejmować sobą również elementy blokowe z wyjątkiem interaktywnych: A, BUTTON, DETAILS, EMBED, IFRAME, KEYGEN, LABEL, SELECT, TEXTAREA, AUDIO (z atrybutem `controls` ), IMG (z atrybutem `usemap="..."` ), INPUT (z atrybutem `type="..."` innym niż "hidden"), MENU (z atrybutem `type="toolbar"` ), OBJECT (z atrybutem `usemap="..."` ), VIDEO (z atrybutem `controls` ). Szczególnego podkreślenia wymaga, że jest to niezwykle pomocna zmiana. Dzięki niej, mając np. listę artykułów z tytułami, skróconymi wprowadzeniami i zdjęciem, nie trzeba już wstawiać trzy razy tego samego linku przy każdym artykule, aby osobno objąć zawartość każdego z tych elementów. HTML5 pozwala objąć jednym znacznikiem odnośnika wszystkie te elementy jednocześnie - nawet jeśli część z nich jest wyświetlana w bloku. * ADDRESS * Odnosi się do najbliższego elementu ARTICLE lub BODY, w którym został wstawiony. Może zawierać również elementy blokowe z wyjątkiem: nagłówków (H1, H2, H3, H4, H5, H6), sekcji (ARTICLE, ASIDE, NAV, SECTION), HEADER, FOOTER, ADDRESS. * B * Tekst na który należy zwrócić uwagę z powodów czysto użytkowych. Nie nadaje dodatkowej ważności treści ani nie stawia akcentu wypowiedzi. Przydatne przy oznaczaniu słów kluczowych w tekście albo wprowadzenia na początku artykułu. * CAPTION * Może zawierać również elementy blokowe z wyjątkiem TABLE. * CITE * Oznacza wyłącznie tytuły prac (książek, opracowań, wierszy, piosenek, filmów, gier, obrazów itp.), a nie ich autorów. * DL * Lista opisowa (ang. description list). Nie nadaje się teraz do oznaczania dialogów. * FIELDSET * Nie musi zawierać elementu LEGEND. * HR * Oddziela bloki tematyczne sekcji artykułu na poziomie akapitów. * I * Oznacza np. termin techniczny, idiom z innego języka albo fragment wtrąconego tekstu. * LABEL * Kliknięcie na etykietę nie musi już oznaczać automatycznego przeniesienia kursora tekstowego do skojarzonego z nią pola formularza, chyba że takie jest standardowe zachowanie systemu operacyjnego użytkownika. * MENU * Służy do budowy użytecznych pasków narzędzi oraz menu kontekstowych. * NOSCRIPT * Zostanie wyświetlony wyłącznie, jeśli przeglądarka w ogóle nie obsługuje dynamicznych skryptów, a nie kiedy nie potrafi zinterpretować języka skryptowego, określonego w poprzedzającym go znaczniku SCRIPT. * S * Oznacza treść, która nie jest dłużej trafna lub istotna, z punktu widzenia pozostałej zawartości dokumentu. * SCRIPT * Istnieje możliwość określenia dodatkowych wartości atrybutu `type="..."` - np.: "text/plain", "text/xml", "application/octet-stream", "application/xml". W tak oznaczonym elemencie można zapisać surowe dane dla dynamicznych skryptów używanych na stronie. * SMALL * Reprezentuje przypisy (wyjaśnienia, zastrzeżenia, ograniczenia prawne, prawa autorskie). * STRONG * Oznacza wysoką ważność, a nie mocne wyróżnienie tekstu. * TH * Może zawierać również elementy blokowe z wyjątkiem: HEADER, FOOTER, sekcji (ARTICLE, ASIDE, NAV, SECTION), nagłówków (H1, H2, H3, H4, H5, H6). * U * Nieartykułowany tekst albo oznaczenie błędu ortograficznego. * TABLE, THEAD, TBODY, TFOOT, TR, OL, UL, DL * Mogą być puste (nie zawierać żadnych elementów potomnych). * accept * Dla elementów INPUT pozwala użyć ogólnych wartości: "audio/*" (dowolny plik w formacie dźwiękowym), "video/*" (dowolny plik w formacie wideo), "image/*" (dowolny plik graficzny). * accesskey * Możliwość użycia listy klawiszy rozdzielonych spacjami, z których przeglądarka może wybrać najbardziej dla niej odpowiedni. * action * Nie może zawierać pustej wartości. * border * Dla znacznika TABLE może zawierać tylko pustą wartość lub cyfrę "1". * colspan * Dla elementów TD i TH musi zawierać wartość większą od zera. * coords * Dla znacznika AREA nie może zawierać wartości procentowej, gdy `shape="circle"` . * defer * Jasno określono, że wywoła załadowanie pliku skryptu osadzonego przy pomocy SCRIPT, kiedy kod strony zostanie w całości wczytany przez przeglądarkę. * dir * Dodano nową wartość - "auto". * enctype * Dla znacznika FORM dodano obsługę "text/plain". * href * Dla elementu LINK nie może zawierać pustej wartości. Dla elementu BASE musi zawierać adres bezwzględny. Dla elementu A może zawierać IRI (od zwykłego adresu URL różni się tym, że może składać się z liter spoza alfabetu łacińskiego). Wymagane jest jednak przy tym, aby dokument był zapisany przy użyciu strony kodowej UTF-8 lub UTF-16. * http-equiv * Dla elementu META nie oznacza już nagłówków HTTP serwera, ale dyrektywy przeglądarki. * id * Może zawierać dowolnie długą wartość, pod warunkiem że nie powtarza się drugi raz w tym samym dokumencie, nie jest pusta ani nie zawiera spacji. * lang * Może zawierać pustą wartość. * media * Dla znacznika LINK akceptuje zapytania mediów, a domyślnie posiada wartość "all". * onclick... * Atrybuty obsługi zdarzeń interfejsu użytkownika mogą zawierać wyłącznie kod skryptu, napisany w języku JavaScript. * start, type * Dla elementu OL nie są już zdeprecjonowane. * style * Może zawierać wyłącznie kod CSS - jako języka formatowania. * tabindex * Przyjmuje również wartości ujemne, co oznacza, że element może zostać aktywowany, ale nie za pomocą klawisza tabulatora. * target * Dla znaczników A i AREA nie jest już zdeprecjonowany. Może być przydatny w połączeniu z IFRAME. * type * Nie jest już konieczny dla elementów SCRIPT ani STYLE, o ile językiem skryptowym jest JavaScript, a językiem formatowania - odpowiednio CSS. * usemap * Dla znacznika IMG nie może już zawierać adresu URL, ale odniesienie do identyfikatora, rozpoczynające się znakiem krzyżyka ("#"). * value * Dla elementu LI nie jest już zdeprecjonowany. * width, height * Dla znaczników IMG, IFRAME, OBJECT nie mogą zawierać wartości procentowych. Nie mogą również zostać użyte do spłaszczenia ani rozciągnięcia elementów niezgodnie z ich oryginalnymi proporcjami. * border * Jeśli jest podany dla znacznika IMG, musi zawierać wartość "0" (zero). W zamian lepiej używać CSS. * language * Jeśli jest podany dla znacznika SCRIPT, musi zawierać wartość "JavaScript" (wielkość liter w zapisie nie ma znaczenia). Nie może kolidować z wartością `type="..."` . Najlepiej w ogóle pominąć atrybut `language="..."` , ponieważ nie ma on żadnej użytecznej funkcji. * name * Zamiast niego dla elementu A lepiej używać atrybutu `id="..."` . * ACRONYM - dla oznaczania wszystkich skrótów powinien być używany znacznik ABBR * APPLET - w zamian należy używać znacznika OBJECT * ISINDEX - może zostać zastąpiony przez kontrolki formularzy * DIR - w zamian należy używać znacznika UL * NOSCRIPT - nie może być używany w języku XHTML5 w przypadku serwowania dokumentu z typem MIME "application/xhtml+xml"; element został wycofany w składni XML, ponieważ parser HTML odczytuje go jako czysty tekst (inaczej do dokumentu załadowałyby się np. objęte nim arkusze CSS, nawet jeżeli przeglądarka obsługuje skrypty), co nie jest możliwe w języku XML * Sekcja 1 (zawiera akapit "Akapit sekcji 1") * Podsekcja 1.1 (zawiera akapit: "Akapit podsekcji 1.1") * Podsekcja 1.2 (zawiera akapit: "Akapit podsekcji 1.2") * Podsekcja 1.1 * miesiąc * 2011-11 * data * 2011-11-12 * 11-12 (każdy 12 listopada) * czas * 14:54 * 14:54:39 * 14:54:39.92922 * data i czas lokalny * 2011-11-12T14:54 * 2011-11-12T14:54:39 * 2011-11-12T14:54:39.92922 * 2011-11-12 14:54 * 2011-11-12 14:54:39 * 2011-11-12 14:54:39.92922 * strefa czasowa * Z, +0000, +00:00 (czas UTC) * +0100, +01:00 (czas zimowy w Polsce) * +0200, +02:00 (czas letni w Polsce) * -0800, -08:00 * data i czas ze strefą czasową * 2011-11-12T14:54Z * 2011-11-12T14:54:39Z * 2011-11-12T14:54:39.92922Z * 2011-11-12T14:54+0000 * 2011-11-12T14:54:39+0000 * 2011-11-12T14:54:39.92922+0000 * 2011-11-12T14:54+00:00 * 2011-11-12T14:54:39+00:00 * 2011-11-12T14:54:39.92922+00:00 * 2011-11-12T06:54-0800 * 2011-11-12T06:54:39-0800 * 2011-11-12T06:54:39.92922-0800 * 2011-11-12T06:54-08:00 * 2011-11-12T06:54:39-08:00 * 2011-11-12T06:54:39.92922-08:00 * 2011-11-12 14:54Z * 2011-11-12 14:54:39Z * 2011-11-12 14:54:39.92922Z * 2011-11-12 14:54+0000 * 2011-11-12 14:54:39+0000 * 2011-11-12 14:54:39.92922+0000 * 2011-11-12 14:54+00:00 * 2011-11-12 14:54:39+00:00 * 2011-11-12 14:54:39.92922+00:00 * 2011-11-12 06:54-0800 * 2011-11-12 06:54:39-0800 * 2011-11-12 06:54:39.92922-0800 * 2011-11-12 06:54-08:00 * 2011-11-12 06:54:39-08:00 * 2011-11-12 06:54:39.92922-08:00 * tydzień * 2011-W46 (46-ty tydzień 2011 roku) * rok * 2011 * czas trwania * PT4H18M3S (4 godziny 18 minut 3 sekundy) * 4h 18m 3s * Nieokreślony stopień ukończenia: > <progress>alternatywa</progress> * Pasek postępu: > <progress value="współczynnik">alternatywa</progress> <progress value="wartość" max="maksimum">alternatywa</progress> * alternatywa * Alternatywna zawartość, wyświetlana w przeglądarkach, które nie obsługują HTML5. Powinno się tam umieścić np. tekst "Proszę czekać..." albo "Ukończono: 50%". * współczynnik * Wartość z przedziału od 0.0 (stopień postępu 0%) do 1.0 (100%). * wartość * Liczba z przedziału od 0 (zero) do maksimum. * maksimum * Maksymalna wartość, po osiągnięciu której zadanie uważa się za ukończone (100%). * Pasek wyniku: > <meter value="współczynnik">alternatywa</meter> * Minimum i maksimum: > <meter value="wartość" min="minimum" max="maksimum">alternatywa</meter> * Przedziały wartości: > <meter value="współczynnik" low="niski" high="wysoki">alternatywa</meter> <meter value="wartość" min="minimum" max="maksimum" low="niska" high="wysoka">alternatywa</meter> * Wartość optymalna: > <meter value="współczynnik" low="niski" high="wysoki" optimum="optymalny">alternatywa</meter> <meter value="wartość" min="minimum" max="maksimum" low="niska" high="wysoka" optimum="optymalna">alternatywa</meter> * alternatywa * Alternatywna zawartość, wyświetlana w przeglądarkach, które nie obsługują HTML5. Powinno się tam umieścić np. zapisaną tekstowo wartość, którą przedstawia pasek wyniku. * współczynnik * Wartość z przedziału od 0.0 (0%) do 1.0 (100%). * wartość * Liczba z przedziału od minimum do maskimum. * minimum, maksimum * Przedział dopuszczalnych wartości jakie może osiągnąć wynik. * niski, wysoki, optymalny * Liczby z przedziału od 0.0 do 1.0 (niski ≤ wysoki), które określają, jaka wartość współczynnika jest uznawana odpowiednio za: niską, wysoką, optymalną. * niska, wysoka, optymalna * Liczby z przedziału od minimum do maksimum (niska ≤ wysoka), które określają, jaka wartość jest uznawana odpowiednio za: niską, wysoką, optymalną. * Panel domyślnie zamknięty: > <details> <summary>nagłówek</summary> ... </details> * Panel domyślnie otwarty: > <details open> <summary>nagłówek</summary> ... </details> * lokalizacja pliku w formacie 1, lokalizacja pliku w formacie 2... * Lokalizacja pliku obrazka na dysku lub adres URL do pliku w Internecie zapisanego przy użyciu różnych formatów. Zostanie wyświetlony tylko jeden z podanych plików graficznych - pierwszy w kolejności którego format jest obsługiwany przez przeglądarkę. * format 1, format 2... * Nazwa formatu (typ MIME), w którym został zapisany plik obrazka - np.: "image/webp" (WebP), "image/vnd.ms-photo" (JPEG XR - extended range), "image/svg+xml" (Scalable Vector Graphics). * lokalizacja pliku w formacie podstawowym * Lokalizacja pliku dla przeglądarek, które w ogóle nie obsługują znacznika `PICTURE` albo jeśli nie obsługują żadnego z formatów wymienionych w znacznikach SOURCE. * Tekst alternatywny * Tekst który zostanie wyświetlony, jeżeli przeglądarka nie zdoła wyświetlić żadnego obrazka. * lokalizacja pliku 1, lokalizacja pliku 2... * Lokalizacja pliku obrazka na dysku lub adres URL do pliku w Internecie wykadrowanego w odpowiedni sposób. Zostanie wyświetlony tylko jeden z podanych plików graficznych - pierwszy w kolejności który spełnia zapytanie mediów podane w atrybucie `media="..."` . * zapytanie mediów 1, zapytanie mediów 2... * Na przykład: "(max-width: 500px)" [zobacz: Zapytania mediów]. * lokalizacja pliku podstawowego * Lokalizacja pliku dla przeglądarek, które w ogóle nie obsługują znacznika `PICTURE` albo jeśli nie spełniają żadnego z zapytań mediów wymienionych w znacznikach SOURCE. * Tekst alternatywny * Tekst który zostanie wyświetlony, jeżeli przeglądarka nie zdoła wyświetlić żadnego obrazka. * Większość z nich nie została wcześniej oficjalnie ustandaryzowana, dlatego były interpretowane odmienne lub w ogóle nieobsługiwane w niektórych przeglądarkach. * Nie istniało standardowe API, dzięki któremu można by w prosty sposób wstawić na stronie odtwarzacz z własną skórką, realizować dynamiczne listy odtwarzania itp. * Wymagały do działania zainstalowanych wtyczek (np. Adobe Flash Player), przez co czasem nadmiernie obciążały procesor, a przy tym nie były w ogóle obsługiwane przez wiele urządzeń mobilnych (smartfony, tablety). Dodatkowo wymagały od webmastera znajomości środowiska Adobe Flash (i zakup komercyjnej licencji) albo konieczności korzystania jedynie z ogólnodostępnych odtwarzaczy Flash, bez możliwości dopasowania ich do własnych potrzeb. * Często działały tylko w systemie operacyjnym Microsoft Windows, uniemożliwiając obejrzenie filmów czy posłuchania muzyki użytkownikom <NAME> Linuksa. * Zdarzały się poważne trudności z ustawieniem warstw (otwierane menu, okna dialogowe) ponad oknem wyświetlanym przez wtyczkę. Często okno odtwarzania wtyczki po prostu zawsze przebijało przez taką warstwę. * Brakowało możliwości zmiany wyglądu przy pomocy CSS. * Nie było możliwe dołączenie do filmów własnych napisów. * Wymaga zainstalowanej na komputerze wtyczki. Nie każda przeglądarka obsługuje wszystkie rodzaje wtyczek. Nie każda wtyczka jest dostępna dla wszystkich rodzajów systemów operacyjnych. Nie każdy użytkownik wie, jak samodzielnie zainstalować wtyczkę. * Webmaster nadal nie dostaje standardowego API, dzięki któremu mógłby dynamicznie manipulować odtwarzanym materiałem multimedialnym. * Element EMBED nie posiada znacznika zamykającego, a element NOEMBED nadal nie został wprowadzony do specyfikacji. Zatem nie można zastosować żadnej automatycznej alternatywy, jeżeli przeglądarka użytkownika nie obsługuje żądanej wtyczki. * Tylko podstawowe atrybuty znacznika EMBED zostały opisane w specyfikacji. Pozostałe zależą od możliwości użytej wtyczki. * Element ten nie jest w żaden sposób zoptymalizowany do odtwarzania filmów ani muzyki. * Podstawowy odtwarzacz wideo (niezalecane!): > <video src="lokalizacja pliku">Treść alternatywna</video> * Podstawowy odtwarzacz audio (niezalecane!): > <audio src="lokalizacja pliku">Treść alternatywna</audio> * Odtwarzacz wielu formatów wideo: > <video> <source src="lokalizacja pliku w formacie 1" type='format 1'> <source src="lokalizacja pliku w formacie 2" type='format 2'> (...) Treść alternatywna </video> * Odtwarzacz wielu formatów audio: > <audio> <source src="lokalizacja pliku w formacie 1" type='format 1'> <source src="lokalizacja pliku w formacie 2" type='format 2'> (...) Treść alternatywna </audio> * lokalizacja pliku * Lokalizacja pliku multimedialnego na dysku lub adres URL do pliku w Internecie. * Treść alternatywna * Zawartość, która zostanie wyświetlona, jeżeli przeglądarka nie obsługuje tego znacznika. Może to być np. bezpośredni link do pobrania pliku multimedialnego na swój dysk lokalny albo zbiór znaczników realizujący uniwersalny sposób odtwarzania plików w HTML 4. Należy zwrócić uwagę, że treść alternatywna nie zostanie wyświetlona, jeżeli przeglądarka obsługuje znacznik AUDIO/VIDEO, a jedynie nie rozpoznaje podanego formatu pliku audio/wideo. * lokalizacja pliku w formacie 1, lokalizacja pliku w formacie 2... * Lokalizacja tego samego filmu bądź muzyki, zapisanych przy użyciu różnych formatów. Zostanie odtworzony tylko jeden z podanych plików - pierwszy w kolejności którego format jest obsługiwany przez przeglądarkę. Sposób ten nie służy do tworzenia list odtwarzania. * format 1, format 2... * Nazwa formatu (typ MIME), w którym został zapisany plik. Szczególnie dla formatów wideo powinno się dodatkowo podać nazwę kodeków, za pomocą których został skonwertowany obraz i dźwięk (zobacz przykłady poniżej: Kodeki MP4, Kodeki OGG/OGV). * none * Żadna część pliku nie zostanie załadowana, zanim nie rozpocznie się jego odtwarzanie. Opcja przydatna, jeżeli odtwarzacz jest na stronie elementem pobocznym i użytkownik może nigdy go nie użyć albo ewentualnie kiedy zależy nam na zminimalizowaniu transferu. * metadata * Pobiera tylko tzw. metadane zapisane w pliku (wymiary, lista ścieżek, czas trwania itp.) oraz możliwe, że kilka pierwszych klatek filmu. * auto * Przeglądarka może dowolnie pobierać plik - w szczególności załadować go w całości do pamięci, nawet jeśli nigdy nie zostanie odtworzony. * H.264 Constrained baseline profile video (main and extended video compatible) level 3 and Low-Complexity AAC audio in MP4 container * * napisy.vtt * Lokalizacja pliku tekstowego z napisami (*.vtt) - na dysku lub adres URL do pliku w Internecie. Dodanie atrybutu `default` jest konieczne. Inaczej napisy mogą nie zostać wyświetlone! * lokalizacja pliku w formacie 1, lokalizacja pliku w formacie 2..., format 1, format 2..., Treść alternatywna * Opisane w rozdziale: VIDEO, AUDIO, SOURCE. * Nazwa pliku musi mieć rozszerzenie *.vtt, a nie *.vtt.txt. Aby to zrobić w Notatniku, w oknie zapisywania pliku wybierz opcję: "Zapisz jako typ: Wszystkie pliki", a następnie wpisz pełną nazwę (np. napisy.vtt). * Plik napisów musi być zapisany przy użyciu kodowania znaków UTF-8 - nieważne przy użyciu jakiej strony kodowej został utworzony dokument HTML, w którym jest wstawiony odtwarzacz wideo z dołączonymi tymi napisami. Aby to zrobić w Notatniku, w oknie zapisywania pliku wybierz opcję: "Kodowanie: UTF-8". Jeżeli używasz innego edytora możesz posiadać dodatkowo opcję zapisu pliku bez tzw. znaku BOM (znacznik kolejności bajtów) - dla plików *.vtt może on zarówno zostać dodany, jak i pominięty. W tym przypadku raczej korzystniej będzie go dodać (Notatnik robi to automatycznie). * subtitles * Typowe napisy, które widzimy np. w kinie na obcojęzycznych filmach. Są po prostu tłumaczeniem na język rodzimy wszystkich kwestii wypowiadanych przez aktorów na ekranie. * captions * Opisuje nie tylko dialogi, ale również wszystkie istotne dźwięki w filmie, które są konieczne do pełnego zrozumienia fabuły. Tego typu napisy często są używane przez osoby niesłyszące. Jednak mogą być przydatne również w sytuacji, kiedy użytkownik sam wyciszy dźwięk. * descriptions * Tego typu napisy zwykle są odczytywane na głos przez syntezator mowy, a nie wyświetlane bezpośrednio na filmie. Zawierają tekstowy opis całego filmu, z którego często korzystają osoby niewidome. Może on być jednak przydatny również w sytuacji, kiedy z jakiegoś powodu wideo nie może być odtworzone - np. kiedy kierujemy samochodem. * align - ustawienie w poziomie * rl - napis przy lewej krawędzi * lr - napis przy prawej krawędzi Nadanie atrybutu `decoding="sync"` może spowolnić wyświetlanie całej strony - zwłaszcza w przypadku dużych obrazków. Zastosowanie: IMG. Oba te znaczniki tworzą nową sekcję w dokumencie, która w innym kontekście mogłaby funkcjonować niezależnie. Stosuj element ASIDE do oznaczania wszelkich elementów pobocznych, które można by było swobodnie usunąć z dokumentu bez żadnej utraty jego wewnętrznej spójności. Natomiast jeśli usunięcie samodzielnej sekcji spowodowałoby, że pozostała treść na stronie utraciłaby sens, właściwym wyborem będzie element ARTICLE. > <hgroup> <h1>tytuł</h1> <p>podtytuł</p> </hgroup> > <hgroup> <h2>tytuł</h2> <p>podtytuł</p> </hgroup> > <hgroup> <h3>tytuł</h3> <p>podtytuł</p> </hgroup> > <hgroup> <h4>tytuł</h4> <p>podtytuł</p> </hgroup> > <hgroup> <h5>tytuł</h5> <p>podtytuł</p> </hgroup> > <hgroup> <h6>tytuł</h6> <p>podtytuł</p> </hgroup* _blank - załadowanie do nowego okna * _parent - do ramki nadrzędnej * _self - do tej samej, w której znajduje się element * _top - do pełnego, oryginalnego okna Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Wymuszenie końca linii. Wyśrodkowanie (zdeprecjonowane).Znacznik otwierający: wymaganyZnacznik zamykający: wymaganyWyświetlanie: w bloku * auto - ramka będzie przewijana, kiedy to będzie konieczne (domyślnie) * no - ramka nie będzie przewijana * yes - ramka będzie przewijana zawsze * SRC="adres" * Podaje lokację inicjalizującego dokumentu ramki * STYLE="styl" * Informacje stylów (CSS) * TITLE="tekst" * Tekst pomocniczy Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Określa ustawienie ramek (FRAME). Zwykle zawiera również znacznik NOFRAMES (dla przeglądarek, które nie obsługują ramek). Atrybuty: onload, onunload Znacznik otwierający: wymaganyZnacznik zamykający: wymagany ) Znacznik otwierający: opcjonalnyZnacznik zamykający: opcjonalny Tworzy kontrolki w formularzu (FORM). Jednoliniowe pole tekstowe (zdeprecjonowane - należy używać INPUT). Atrybuty: Odnośnik, określa powiązania dokumentu. Występuje tylko w sekcji HEAD. Definiuje mapę odnośników klienta, wewnątrz której znajdują się obszary AREA. Aby dany element mógł się odwołać do takiej mapy, musi mieć atrybut USEMAP, o wartości zgodnej z atrybutem NAME mapy. * ltr - od lewej do prawej * rtl - od prawej do lewej * HTTP-EQUIV="nazwa" * Informacja nagłówkowa (może być używana w zamian NAME) * LANG="język" * Informacja o języku bazowym (np.: LANG="en" oznacza angielski, LANG="pl" - polski itd.) * NAME="nazwa" * Identyfikuje nazwę własności * SCHEME="schemat" * Schemat interpretacji własności Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony * data - wartość atrybutu VALUE zostanie przekazana do obiektu jako łańcuch znakowy (domyślnie) * object - VALUE jest identyfikatorem (ID) innego obiektu (OBJECT) w tym samym dokumencie * ref - VALUE wyznacza adres zasobu, gdzie są przechowywane wartości Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Wieloliniowe pole tekstowe, używane najczęściej w formularzach (FORM). Tytuł dokumentu. * ltr - od lewej do prawej * rtl - od prawej do lewej * LANG="język" * Informacja o języku bazowym (np.: LANG="en" oznacza angielski, LANG="pl" - polski itd.) Znacznik otwierający: wymaganyZnacznik zamykający: wymagany Jednak często zmiana strony kodowej dokumentu z formularzem nie jest najlepszym rozwiązaniem, ponieważ cała reszta serwisu byłaby zapisana inaczej niż ten jeden dokument. Zmiana kodowania znaków systemu odbierającego dane z formularza może w ogóle nie wchodzić w grę - możemy nie mieć wpływu na stronę kodową systemu operacyjnego, programu pocztowego czy skryptu na serwerze. W takiej sytuacji wystarczy zdefiniować, jakiej strony kodowej używa system odbierający dane, a przeglądarka podczas wysyłania formularza powinna automatycznie skonwertować cały tekst. Na przykład, jeśli nasza strona jest zapisana przy użyciu kodowania znaków utf-8, ale wiemy, że system, do którego wysyłamy formularz używa kodowania windows-1250, powinniśmy wpisać: > <form action="..." accept-charset="windows-1250">...</form> Niestety atrybut `accept-charset="..."` nie jest cudownym sposobem na zachowanie prawidłowych polskich znaków diakrytycznych w prostych formularzach pocztowych 🙁 Nie wiadomo z jakiego systemu operacyjnego ani z jakiego programu pocztowego korzysta użytkownik, który będzie wypełniał formularz, a więc nie można jednoznacznie ustalić docelowej strony kodowej wysyłanych danych. Dzięki temu dokument HTML zostanie wyświetlony w taki sposób, aby nie wymagał od użytkownika dalszego powiększania. W przeciwnym razie przeglądarka mobilna starałaby się wyświetlić stronę w rozdzielczości typowej dla przeglądarek używanych na standardowych komputerach, co zwykle oznaczałoby zdecydowanie zbyt mały rozmiar tekstu, aby nadawał się do wygodnego czytania. (interpretuje: Internet Explorer, Firefox, Opera 7, Chrome) > <head> <link rel="shortcut icon" href="adres ikony"> </headDate: 2002-02-01 Categories: Tags: Poniżej znajdziesz opis wszystkich znaczników i ich atrybutów według oryginalnej specyfikacji HTML 4.01, opracowanej przez organizację W3C. Całe to zestawienie zostało napisane w następujący sposób: * Opis każdego znacznika rozpoczyna się od jego nazwy. * Potem krótkie wytłumaczenie znaczenia i roli, jaką spełnia. * Dalej wszystkie atrybuty (w kolejności alfabetycznej). Nie każdy atrybut musi zostać użyty (można nawet nie używać żadnych). Dodatkowo kolejność ich wpisywania jest dowolna. * Następnie znajduje się spis generowanych przez element zdarzeń. * Informacja o konieczności (bądź nie) umieszczania znacznika otwierającego oraz zamykającego. * Sposób wyświetlania elementu: XXXXXXXXXXXXXXXXXXXXXXXXw bloku (DIV)XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX w bloku (z interlinią) XXXXXXXXXXXXXXXXXXXXXXXX lub XXXXXXXXXXXXXXXXXXXXXXXXw liniiXXXXXXXXXXXXXXXXXXXXXXXX ### Przykład <b title idZnacznik B można wpisać następująco: > <b title="Tytuł" id="identyfikator">Tekst pogrubiony</b>albo też: > <b>Tekst pogrubiony</b> przy czym znacznik `<b>` jest otwierający, natomiast `</b>` - zamykający. ### Wykaz atrybutów zdeprecjonowanych # Wskazuje formę skróconą. Wskazuje akronim - wyraz powstały z pierwszych liter innych wyrazów. Atrybuty: Umieszczanie informacji kontaktowych z autorem. * _blank - załadowanie do nowego okna * _parent - do ramki nadrzędnej * _self - do tej samej, w której znajduje się element * _top - do pełnego, oryginalnego okna Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Ustala atrybuty czcionki bazowej (zdeprecjonowane). Atrybuty: Włącza algorytm dwukierunkowego tekstu. Atrybuty: Wyświetla tekst dużą czcionką. Atrybuty: Cytat (wyświetlany w bloku). Odwołanie do innego źródła. Fragment kodu komputerowego. Pozwala zgrupować atrybuty dla kilku kolumn tabeli (TABLE). W odróżnieniu od COLGROUP nie grupuje kolumn strukturalnie. onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Pozwala zgrupować strukturalnie kilka kolumn tabeli (TABLE). Może zawierać znaczniki COL. onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: opcjonalny Opis terminu (DT) w liście definicyjnej (DL). onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: opcjonalny Używane do zaznaczenia sekcji dokumentu, które zostały usunięte w stosunku do innej wersji dokumentu. onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: wymagany Definicja załączonego terminu. Wielokolumnowy spis zawartości katalogu (LI) (zdeprecjonowane). Atrybuty: Blok. Lista definicyjna terminów (DT) i opisów (DD). Termin listy definicyjnej (DL). Pozwala autorowi pogrupować tematycznie kontrolki i etykiety formularza (FORM). Zawiera zwykle legendę (LEGEND). Zmienia atrubuty czcionki dla tekstu, który zawiera (zdeprecjonowane). Atrybuty: * auto - ramka będzie przewijana, kiedy to będzie konieczne (domyślnie) * no - ramka nie będzie przewijana * yes - ramka będzie przewijana zawsze * SRC="adres" * Podaje lokację inicjalizującego dokumentu ramki * STYLE="styl" * Informacje stylów (CSS) * TITLE="tekst" * Tekst pomocniczy Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Określa ustawienie ramek (FRAME). Zwykle zawiera również znacznik NOFRAMES (dla przeglądarek, które nie obsługują ramek). Atrybuty: onload, onunload Znacznik otwierający: wymaganyZnacznik zamykający: wymagany Nagłówek (tytuł rozdziału) poziomu od 1 do 6. * ltr - od lewej do prawej * rtl - od prawej do lewej * ID="nazwa" * Przypisuje nazwę elementowi (identyfikator), która nie może się powtarzać w całym dokumencie * LANG="język" * Informacja o języku bazowym (np.: LANG="en" oznacza angielski, LANG="pl" - polski itd.) * NOSHADE * Jednolity kolor (bez cienia) (zdeprecjonowane) * SIZE="piksele" * Wysokość w pikselach (zdeprecjonowane) * STYLE="styl" * Informacje stylów (CSS) * TITLE="tekst" * Tekst pomocniczy * WIDTH="długość" * Szerokość w pikselach lub w procentach (domyślnie 100%) (zdeprecjonowane) ) Znacznik otwierający: opcjonalnyZnacznik zamykający: opcjonalny Wyświetla tekst pochylony. onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Tworzy kontrolki w formularzu (FORM). Używane do zaznaczenia sekcji dokumentu, które zostały wstawione w stosunku do innej wersji dokumentu. onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: wymagany Jednoliniowe pole tekstowe (zdeprecjonowane - należy używać INPUT). Atrybuty: Tekst do wprowadzenia przez użytkownika. onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: opcjonalny Odnośnik, określa powiązania dokumentu. Występuje tylko w sekcji HEAD. onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Definiuje mapę odnośników klienta, wewnątrz której znajdują się obszary AREA. Aby dany element mógł się odwołać do takiej mapy, musi mieć atrybut USEMAP, o wartości zgodnej z atrybutem NAME mapy. Jednokolumnowy spis menu (LI) (zdeprecjonowane). Atrybuty: * ltr - od lewej do prawej * rtl - od prawej do lewej * HTTP-EQUIV="nazwa" * Informacja nagłówkowa (może być używana w zamian NAME) * LANG="język" * Informacja o języku bazowym (np.: LANG="en" oznacza angielski, LANG="pl" - polski itd.) * NAME="nazwa" * Identyfikuje nazwę własności * SCHEME="schemat" * Schemat interpretacji własności Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Określa zawartość, która powinna być wyświetlona tylko wtedy, gdy przeglądarka nie obsługuje ramek (FRAMESET). Atrybuty: Pozwala zdefiniować treść alternatywną na wypadek, gdy skrypt umieszczony na stronie (SCRIPT) nie może zostać uruchomiony. Atrybuty: Lista uporządkowana punktów (LI). * ltr - od lewej do prawej * rtl - od prawej do lewej * ID="nazwa" * Przypisuje nazwę elementowi (identyfikator), która nie może się powtarzać w całym dokumencie * LANG="język" * Informacja o języku bazowym (np.: LANG="en" oznacza angielski, LANG="pl" - polski itd.) * START="liczba" * Początkowa liczba dla pierszego punktu (domyślnie "1", co odpowiada: "1", "A", "a", "I" lub "i" - w zależności od typu) (zdeprecjonowane) * STYLE="styl" * Informacje stylów (CSS) * TITLE="tekst" * Tekst pomocniczy * TYPE="typ" * Typ listy (zdeprecjonowane): * 1 - liczby arabskie (1, 2, 3,...) * A - wielkie litery (A, B, C,...) * a - małe litery (a, b, c,...) * I - wielkie liczby rzymskie (I, II, III,...) * i - małe liczby rzymskie (i, ii, iii,...) Grupuje opcje (OPTION) w liście wyboru (SELECT). onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: wymagany Tworzy opcję w liście wyboru (SELECT). Opcje mogą być zgrupowane (OPTGROUP). * ltr - od lewej do prawej * rtl - od prawej do lewej * DISABLED * Blokada kontrolki * ID="nazwa" * Przypisuje nazwę elementowi (identyfikator), która nie może się powtarzać w całym dokumencie * LABEL="etykieta" * Etykieta dla grupy opcji * LANG="język" * Informacja o języku bazowym (np.: LANG="en" oznacza angielski, LANG="pl" - polski itd.) * SELECTED * Opcja jest zaznaczona * STYLE="styl" * Informacje stylów (CSS) * TITLE="tekst" * Tekst pomocniczy * VALUE="wartość" * Wartość inicjalizująca kontrolki (jeśli nie jest podana, przyjmuje zawartość elementu) * data - wartość atrybutu VALUE zostanie przekazana do obiektu jako łańcuch znakowy (domyślnie) * object - VALUE jest identyfikatorem (ID) innego obiektu (OBJECT) w tym samym dokumencie * ref - VALUE wyznacza adres zasobu, gdzie są przechowywane wartości Znacznik otwierający: wymaganyZnacznik zamykający: zabroniony Tekst preformatowany (interpretuje tabulację, dodatkowe spacje i znak końca linii). Cytat (wyświetlany w linii). Wyświetla tekst przekreślony (to samo co STRIKE) (zdeprecjonowane). Przykład. Wyświetla tekst małą czcionką. Rozciąganie stylu. Wyświetla tekst przekreślony (to samo co S) (zdeprecjonowane). Atrybuty: Mocne wyróżnienie tekstu. Indeks górny. Ciało (włściwa treść) tabeli (TABLE). Zawiera wiersze (TR). onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: opcjonalny Wieloliniowe pole tekstowe, używane najczęściej w formularzach (FORM). Stopka tabeli (TABLE). Zawiera wiersze (TR). onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: opcjonalny Obszar nagłówkowy tabeli (TABLE). Zawiera wiersze (TR). * ltr - od lewej do prawej * rtl - od prawej do lewej * LANG="język" * Informacja o języku bazowym (np.: LANG="en" oznacza angielski, LANG="pl" - polski itd.) Znacznik otwierający: wymaganyZnacznik zamykający: wymagany Wiersz w tabeli (TABLE). Zawiera komórki danych (TD) i komórki nagłówkowe (TH). onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup Znacznik otwierający: wymaganyZnacznik zamykający: opcjonalny Wyświetla tekst w trybie dalekopisu lub o stałych odstępach pomiędzy znakami. Atrybuty: Wyświetla tekst podkreślony (zdeprecjonowane). Lista nieuporządkowana punktów (LI). * circle - kształt okręgu * disc - kształt koła * square - kształt kwadratu Przykład zmiennej lub argumentu programu. W zasadzie aby rozpocząć przygodę z językiem CSS, wystarczy wstawić w nagłówku strony - tzn. w dowolnym miejscu pomiędzy znacznikami `<head>` oraz `</head>` - jedną dodatkową linijkę: > <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="description" content="Tu wpisz opis zawartości strony"> <title>Tu wpisz tytuł strony</title> <link rel="stylesheet" href="style.css"> </head> <body> Tu wpisuje się treść strony </body> </html> Dzięki znacznikowi `<link>` do dokumentu zostanie automatycznie dołączony arkusz stylów. W nim właśnie wpisuje się wszystkie polecenia zmieniające wygląd strony. Ważne jest tylko, aby ten plik posiadał rozszerzenie *.css. W powyższym przykładzie jest to plik pod nazwą "style.css", który znajduje się w tym samym katalogu co dokument *.html. Można go oczywiście zapisać w innej lokalizacji - wtedy zamiast "style.css" trzeba podać pełną ścieżkę dostępu (tworzy się ją w analogiczny sposób, jak przy wstawianiu obrazka). Warto podkreślić, że jeśli Twoja strona WWW składa się z wielu podstron, na każdej z nich możesz dołączyć ten sam plik arkusza stylów. Dzięki temu zmiany wykonane tylko w jednym miejscu - czyli w pliku arkusza stylów - wpłyną na wygląd od razu wszystkich podstron Twojego serwisu. Czyż to nie jest piękne? Już nigdy więcej nie będzie Cię czekać żmudne przerabianie każdej podstrony tylko po to, aby zmienić na niej np. kolor albo rozmiar tekstu 🙂 Dla zainteresowanychJeśli chcesz dowiedzieć się więcej na temat dodatkowych możliwości wstawiania stylów CSS na stronach internetowych, zobacz rozdział: Wstawianie stylów. Przeglądarki zwykle ustalają pewną szerokość marginesów strony. Nie zawsze jednak domyślne ustawienia będą dobrze współgrać np. z określonym przez nas rozmiarem czcionki. Na szczęście bardzo łatwo można to zmienić: > body { margin: szerokość; } Tapety graficzne umieszczone w tle są chętnie używanym elementem w każdym systemie operacyjnym. Podobne rozwiązanie można zastosować również na stronie internetowej. Tekst na stronie internetowej najlepiej jest wpisywać w akapitach. Dzięki temu będzie on bardziej czytelny dla użytkownika. W pojedynczym dokumencie HTML może się znajdować wiele oddzielnych akapitów. Co zrobić, aby tekst w każdym z nich był ułożony tak samo? Dzięki możliwościom jakie dają style CSS, nie musimy tego robić dla każdego akapitu osobno. Wystarczy że w arkuszu CSS wpiszemy następującą regułę stylów: > p { text-align: wyrównanie; } Praktycznym zastosowaniem klas selektorów mogą być np. ramki wizualnie wyróżniające tekst, który się w nich znajduje. Wystarczy, że raz zdefiniujemy ich wygląd w arkuszu stylów: > .nazwa-klasy { deklaracje stylów } To by było na tyle. Poznane tu polecenia powinny pozwolić Ci nie tylko na napisanie prostej strony WWW, ale zarazem określenie jej wyglądu w profesjonalny sposób. W dalszych rozdziałach Kursu CSS poznasz m.in. bardziej zaawansowane techniki tworzenia selektorów oraz rozbudowaną listę własności, dzięki którym zyskasz jeszcze większe możliwości stylizacji elementów Twojego serwisu.Zapraszam... To by było na tyle. Poznane tu polecenia powinny pozwolić Ci nie tylko na napisanie prostej strony WWW, ale zarazem określenie jej wyglądu w profesjonalny sposób. W dalszych rozdziałach Kursu CSS poznasz m.in. bardziej zaawansowane techniki tworzenia selektorów oraz rozbudowaną listę własności, dzięki którym zyskasz jeszcze większe możliwości stylizacji elementów Twojego serwisu. > selektor { list-style-type: typ } Selektorem mogą być znaczniki dotyczące wykazów: ul - wypunktowanie, ol - wykaz numerowany oraz li - pojedynczy punkt wykazu [zobacz: Wstawianie stylów].Natomiast "typ" odpowiada za wygląd wyróżnika wykazu (markera) i należy zamiast niego wpisać: Natomiast "typ" odpowiada za wygląd wyróżnika wykazu (markera) i należy zamiast niego wpisać: n | wzór | wynik | | --- | --- | --- | 0 | | 1 | 1 | | 3 | 2 | | 5 | itd. | W przypadku sąsiadowania ze sobą lub zagnieżdżania wewnątrz siebie elementów posiadających marginesy, może zajść proces załamywania marginesów zewnętrznych (ang. collapsing margins), polegający na połączeniu kilku sąsiadujących odstępów w jeden o rozmiarze pojedynczego marginesu, a nie sumy składowych. Według CSS 2.1 załamywane mogą być tylko marginesy pionowe w następujących przypadkach: Czy projektowanie wyglądu stron internetowych naprawdę jest tak trudne, jak mówią? * Edytory CSS Który edytor CSS wybrać: TopStyle Lite, Balthisar Cascade, Cascade DTP? * Wstawienie arkusza stylów Jak wygląda typowy sposób dołączania arkusza CSS? * Arkusz stylów Jak wygląda typowy arkusz CSS? * Kolor tła oraz tekstu W jaki sposób zmienić kolor tła oraz kolor tekstu na stronie WWW? * Czcionka W jaki sposób zmienić wielkość i rodzaj czcionki na stronie WWW? * Marginesy strony Jak ustawić marginesy strony WWW? Czy da się określić marginesy niesymetryczne? * Tapeta Jak ustawić tapetę graficzną w tle strony internetowej? W jaki sposób stworzyć tło w postaci zeszytu w kratkę, w linie albo ukośnej siatki? * Wyrównanie tekstu W jaki sposób układać tekst na ekranie? Jak wyśrodkować lub wyjustować tekst? * Kolor odsyłaczy Jak zmienić kolor odsyłaczy (odnośników hipertekstowych, hiperłączy, linków)? Jak zrobić podświetlany link (odsyłacz, odnośnik hipertekstowy, hiperłacze)? * Klasy selektorów W jaki sposób przypisać do dowolnego elementu zbiór reguł formatujących, znajdujących się w jednym miejscu, oszczędzając sobie tym samym pisania? * Ramki z tekstem Jak ująć tekst w ramkę w postaci obramowania z zaokrąglonymi narożnikami i tłem? * Podsumowanie CSS * Powtórka Istnieją specjalne edytory przeznaczone tylko do języka CSS. Nie są one jednak zbyt popularne i przez to często dawno przestały być już rozwijane. Najlepszym rozwiązaniem jest użycie edytora HTML, który ma wbudowaną obsługę również języka CSS. Na przykład Brackets to jeden z lepszych edytorów HTML i CSS. Posiada szereg wbudowanych funkcji przydatnych przy tworzeniu stron internetowych. Obsługuje instalowanie darmowych rozszerzeń, które mogą dodatkowo zwiększyć jego możliwości. Jest przy tym całkowicie darmowy i dostępny w wersjach dla każdego systemu operacyjnego. W zasadzie aby rozpocząć przygodę z językiem CSS, wystarczy wstawić w nagłówku strony - tzn. w dowolnym miejscu pomiędzy znacznikami `<head>` oraz `</head>` - jedną dodatkową linijkę: > <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="description" content="Tu wpisz opis zawartości strony"> <title>Tu wpisz tytuł strony</title> <link rel="stylesheet" href="style.css"> </head> <body> Tu wpisuje się treść strony </body> </html> Dzięki znacznikowi `<link>` do dokumentu zostanie automatycznie dołączony arkusz stylów. W nim właśnie wpisuje się wszystkie polecenia zmieniające wygląd strony. Ważne jest tylko, aby ten plik posiadał rozszerzenie *.css. W powyższym przykładzie jest to plik pod nazwą "style.css", który znajduje się w tym samym katalogu co dokument *.html. Można go oczywiście zapisać w innej lokalizacji - wtedy zamiast "style.css" trzeba podać pełną ścieżkę dostępu (tworzy się ją w analogiczny sposób, jak przy wstawianiu obrazka). Warto podkreślić, że jeśli Twoja strona WWW składa się z wielu podstron, na każdej z nich możesz dołączyć ten sam plik arkusza stylów. Dzięki temu zmiany wykonane tylko w jednym miejscu - czyli w pliku arkusza stylów - wpłyną na wygląd od razu wszystkich podstron Twojego serwisu. Czyż to nie jest piękne? Już nigdy więcej nie będzie Cię czekać żmudne przerabianie każdej podstrony tylko po to, aby zmienić na niej np. kolor albo rozmiar tekstu :-) Dla zainteresowanychJeśli chcesz dowiedzieć się więcej na temat dodatkowych możliwości wstawiania stylów CSS na stronach internetowych, zobacz rozdział: Wstawianie stylów. Arkusz stylów CSS jest plikiem tekstowym służącym do ustalania wyglądu strony internetowej. Zawiera on tzw. reguły stylów. Z kolei każda z nich składa się z selektora i deklaracji stylów. Poszczególne deklaracje obejmują listę poleceń, które określają, w jaki sposób chcemy zmienić wygląd elementu na stronie wskazanego przez selektor. Aby zmienić wygląd jakiegoś elementu na stronie, trzeba go najpierw wskazać. W języku CSS robi się to za pomocą tzw. selektora. W najprostszym przypadku jest to nazwa wybranego znacznika, który wcześniej wstawiliśmy do naszego dokumentu HTML. Wszystko co znajduje się wewnątrz tak wskazanego znacznika - czyli zarówno tekst, jak i inne znaczniki - otrzyma style podane w deklaracji. Przykładowo, aby zmienić kolor tła oraz teksu na całej stronie, możemy się posłużyć selektorem `body` , ponieważ właśnie wewnątrz znacznika `<body>...</body>` znajduje się cała zawartość strony. Zatem w arkuszu stylów wystarczy umieścić następujący kod: > body { background-color: black; color: white; } Zwróć uwagę, że deklaracja stylów, którą ujmuje się w nawiasy klamrowe, składa się tutaj z dwóch linijek. Każda z nich rozpoczyna się od podania tzw. cechy (inaczej własności), po której następuje wartość. Cecha określa, co chcemy zmienić w wyglądzie wybranego elementu, natomiast wartość - w jaki sposób ma się to zmienić. Zatem gdyby przetłumaczyć powyższą regułę stylów na bardziej zrozumiały język, brzmiałaby ona mniej więcej tak: dla całej zawartości znacznika `body` (selektor) zmień kolor tła (cecha `background-color` ) na czarny (wartość `black` ) i kolor tekstu (cecha `color` ) na biały (wartość `white` ). Pamiętaj, aby po wpisaniu cechy (własności) zawsze postawić znak dwukropka, a po każdej wartości - średnik. Zwróć również uwagę, że jeśli cecha (bądź wartość) zawiera znak myślnika (np. `background-color` ), to przed nim ani po nim nie może znajdować się spacja. Aby ustalić inny kolor tła albo tekstu, wystarczy że w miejsce wartości wstawisz wybraną definicję koloru - zobacz: Wykaz kolorów. ustawi czcionkę Arial dla tekstu na całej stronie. Stanie się to jednak tylko wtedy, gdy użytkownik odwiedzający stronę będzie miał zainstalowaną taką czcionkę w swoim systemie operacyjnym. W przeciwnym razie automatycznie zostanie użyta czcionka Helvetica, a jeśli i to nie będzie możliwe, tekst zostanie wyświetlony przy pomocy czcionki najbardziej zbliżonej wyglądem. Przeglądarki zwykle ustalają pewną szerokość marginesów strony. Nie zawsze jednak domyślne ustawienia będą dobrze współgrać np. z określonym przez nas rozmiarem czcionki. Na szczęście bardzo łatwo można to zmienić: > body { margin: szerokość; } ustawi wszystkie marginesy strony o szerokości i wysokości 2,5 centymetra. Należy jednak pamiętać, aby w razie potrzeby w wartościach liczbowych nie używać przecinka tylko kropki dziesiętnej. Ponadto przed nazwą jednostki nie może być spacji. W przeciwnym razie polecenie może nie zadziałać albo jego efekty będą inne niż oczekiwane! Tapety graficzne umieszczone w tle są chętnie używanym elementem w każdym systemie operacyjnym. Podobne rozwiązanie można zastosować również na stronie internetowej. . Tak wstawiona tapeta pozostanie nieruchoma przy przewijaniu strony, a przy tym wypełni całą powierzchnię strony z zachowaniem oryginalnych proporcji zdjęcia. Może być jednak przycięta po bokach albo na górze i na dole, jeśli nie będzie pasować do aktualnych proporcji wymiarów okna przeglądarki. Tekst na stronie internetowej najlepiej jest wpisywać w akapitach. Dzięki temu będzie on bardziej czytelny dla użytkownika. W pojedynczym dokumencie HTML może się znajdować wiele oddzielnych akapitów. Co zrobić, aby tekst w każdym z nich był ułożony tak samo? Dzięki możliwościom jakie dają style CSS, nie musimy tego robić dla każdego akapitu osobno. Wystarczy że w arkuszu CSS wpiszemy następującą regułę stylów: > p { text-align: wyrównanie; } . > a { color: kolor; } a:hover { color: podświetlenie; } . Przypisuje on do znacznika bloku podaną klasę CSS. Dzięki temu element ten wraz z całą jego zawartością przyjmie wygląd, który został określony w arkuszu stylów dla wskazanej klasy CSS. Praktycznym zastosowaniem klas selektorów mogą być np. ramki wizualnie wyróżniające tekst, który się w nich znajduje. Wystarczy, że raz zdefiniujemy ich wygląd w arkuszu stylów: > .nazwa-klasy { deklaracje stylów } . Jeśli na stronie chcemy wstawić więcej takich samych ramek, należy powielić tylko drugie polecenie. To by było na tyle. Poznane tu polecenia powinny pozwolić Ci nie tylko na napisanie prostej strony WWW, ale zarazem określenie jej wyglądu w profesjonalny sposób. W dalszych rozdziałach Kursu CSS poznasz m.in. bardziej zaawansowane techniki tworzenia selektorów oraz rozbudowaną listę własności, dzięki którym zyskasz jeszcze większe możliwości stylizacji elementów Twojego serwisu.Zapraszam... Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu CSS. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. . Jeśli na stronie chcemy wstawić więcej takich samych ramek, należy powielić tylko drugie polecenie. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. > Array.prototype.unshift() Array.prototype.unshift(item1) Array.prototype.unshift(item1, item2...) (child) Dany element jest nazywany dzieckiem innego elementu, jeżeli ten drugi element jest jego rodzicem. Identyfikator to wartość atrybutu `id="..."` nadanego selektorowi z poziomu języka HTML. Natomiast wyrazy "cecha" oraz "wartość" określają atrybuty elementu nadane poprzez style i zostaną opisane w dalszych rozdziałach. Jako identyfikator należy podać dowolny pojedynczy wyraz, który nie może zawierać znaków: spacji, kropki, przecinka, dwukropka, pytajnika, nawiasów, znaku równości, plusa itp. Może natomiast zawierać litery (A-Z, a-z), cyfry (0-9), myślniki ("-") i podkreślniki ("_"). Lepiej nie używać polskich liter. Nie może się on również rozpoczynać cyfrą ani myślnikiem. Jeśli koniecznie chcemy użyć "zakazanych" znaków, należy w deklaracji poprzedzić je odwróconym ukośnikiem "\", np. deklaracja: ``` selektor#B\&W\? { cecha: wartość } ``` odpowiada identyfikatorowi: `id="B&W?"` . Identyfikator może wystąpić tylko raz w hierarchii drzewa dokumentu, czyli w pojedynczym dokumencie nie mogą się znaleźć dwa elementy z takimi samymi identyfikatorami! Polecenie to pozwala, na nadanie określonych atrybutów formatowania dla elementu, który ma jednoznaczny identyfikator (ID), czyli występuje tylko raz w drzewie dokumentu (w odróżnieniu od klasy). Jeżeli w arkuszu stylów strony została umieszczona następująca reguła: > p#przyklad_identyfikator { color: red }to akapit o podanym identyfikatorze ID: > <p id="przyklad_identyfikator">To jest akapit.</p>zostanie wyświetlony w kolorze czerwonym: Dla porównania, to też jest akapit, ale bez podania identyfikatora i dlatego nie jest czerwony. Użycie selektora uniwersalnego pozwala przypisać styl do dowolnego znacznika z określonym identyfikatorem: > *#przyklad_uniwersalny { color: red } To jest pogrubienie, któremu został nadany identyfikator id="przyklad_uniwersalny". W tym przypadku gwiazdkę (*) w regule stylu można pominąć: > #przyklad_uniwersalny { color: red } (document tree) Drzewo elementów umieszczonych w dokumencie źródłowym. Każdy element w takim drzewie ma dokładnie jednego rodzica, oprócz elementu podstawowego, czyli korzenia drzewa (root). * Termin 1 * Definicja 1 Zwróć uwagę, że tylko termin drugiej z list jest podkreślony, ponieważ pierwsza lista posiada więcej niż jeden element `<dt>...</dt>` . Jednocześnie, ponieważ jedyny termin drugiej listy jest zarazem ostatnim takim elementem, przyjmie również określony wcześniej dodatkowy sposób formatowania - kursywę. Natomiast jedyna definicja drugiej listy jest zarazem na niej pierwsza, więc będzie pogrubiona. Jeżeli wciśniesz i przytrzymasz przycisk myszki nad tym odsyłaczem, to do chwili zwolnienia przycisku, będzie on pogrubiony. (CSS 3 - interpretuje Internet Explorer 9, Firefox, Opera, Chrome) > selektor:target { cecha: wartość } `id="..."` albo ewentualnie może to być element A posiadający atrybut `name="..."` [zobacz: Odsyłacz do etykiety i Wstawianie stylów]. Natomiast wyrazy "cecha" oraz "wartość" określają atrybuty elementu nadane poprzez style i zostaną opisane w dalszych rozdziałach. Czasami podział serwisu na podstrony jest niewystarczający. Zdarza się, że jeden artykuł jest podzielony dodatkowo na niewielkie sekcje - zbyt małe, aby tworzyć z każdej z nich osobną podstronę. Chcielibyśmy jednak mieć możliwość odesłania czytelnika bezpośrednio do podanej sekcji, żeby nie musiał jej szukać "ręcznie". W takiej sytuacji stosuje się etykiety (np.: WARTOŚĆscroll | fixed | inheritOPISZaczepienie tłaINICJALIZACJAscrollZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<kolor> | transparent | inheritOPISKolor tłaINICJALIZACJAtransparentZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<adres> | none | inheritOPISTło obrazkoweINICJALIZACJAnoneZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆrepeat | repeat-x | repeat-y | no-repeat | inheritOPISPowtarzanie tłaINICJALIZACJArepeatZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<border-style> | inheritOPISAtrybuty mieszane stylu górnego/prawego/dolnego/lewego obramowaniaINICJALIZACJAnoneZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<border-width> | inheritOPISAtrybuty mieszane szerokości górnego/prawego/dolnego/lewego obramowaniaINICJALIZACJAmediumZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆcollapse | separate | inheritOPISModel obramowania tabeliINICJALIZACJAcollapseZASTOSOWANIEtabeleDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆ<długość> <długość>? | inheritOPISOdstęp między komórkami tabeliINICJALIZACJA0ZASTOSOWANIEtabeleDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆtop | bottom | left | right | inheritOPISPozycja podpisu tabeliINICJALIZACJAtopZASTOSOWANIEpodpis tabeliDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆnone | left | right | both | inheritOPISPrzyleganie do elementu pływającegoINICJALIZACJAnoneZASTOSOWANIEelementy blokoweDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<shape> | auto | inheritOPISObcinanieINICJALIZACJAautoZASTOSOWANIEelementy blokowe i zastępowaneDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<kolor> | inheritOPISKolorINICJALIZACJAzależy od przeglądarkiZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆltr | rtl | inheritOPISKierunek tekstuINICJALIZACJAltrZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆ<kąt> | below | level | above | higher | lower | inheritOPISPodniesienie dźwięku przestrzennegoINICJALIZACJAlevelZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆshow | hide | inheritOPISObramowanie pustych komórek tabeliINICJALIZACJAshowZASTOSOWANIEkomórki tabeliDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆleft | right | none | inheritOPISUstawienieINICJALIZACJAnoneZASTOSOWANIEwszystkie elementy oprócz pozycjonowanychDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<liczba> | none | inheritOPISDopasowanie rozmiaru czcionkiINICJALIZACJAnoneZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆ<adres> | none | inheritOPISWyróżnik obrazkowy wykazuINICJALIZACJAnoneZASTOSOWANIEelementy wykazuDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆinside | outside | inheritOPISPozycja wyróżnika wykazuINICJALIZACJAoutsideZASTOSOWANIEelementy wykazuDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆ<margin-width> | inheritOPISSzerokość górnego/prawego/dolnego/lewego marginesuINICJALIZACJA0ZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYodnosi się do szerokości bloku obejmującegoMEDIAvisual WARTOŚĆ<długość> | auto | inheritOPISOdstęp wyróżnika wykazuINICJALIZACJAautoZASTOSOWANIEwyróżniki wykazuDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ[ crop || cross ] | none | inheritOPISZnaczniki strony (po wydrukowaniu)INICJALIZACJAnoneZASTOSOWANIEkontekst stronyDZIEDZICZENIEniePROCENTYnieMEDIAvisual, paged WARTOŚĆ<color> | invert | inheritOPISKolor obrysuINICJALIZACJAinveritZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual, interactive WARTOŚĆ<border-style> | inheritOPISStyl obrysuINICJALIZACJAnoneZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual, interactive WARTOŚĆ<border-width> | inheritOPISSzerokość obrysuINICJALIZACJAmediumZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual, interactive WARTOŚĆ<identyfikator> | autoOPISNazwa stronyINICJALIZACJAautoZASTOSOWANIEelementy blokoweDZIEDZICZENIEtakPROCENTYnieMEDIAvisual, paged WARTOŚĆavoid | auto | inheritOPISPrzełamanie strony wewnątrz blokuINICJALIZACJAautoZASTOSOWANIEelementy blokoweDZIEDZICZENIEtakPROCENTYnieMEDIAvisual, paged WARTOŚĆ<liczba> | inheritOPISOdchylenie częstotliwości od średniejINICJALIZACJA50ZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆ<adres> mix? repeat? | auto | none | inheritOPISTło dźwiękowe podczas wymowyINICJALIZACJAautoZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAaural WARTOŚĆstatic | relative | absolute | fixed | inheritOPISPozycja elementuINICJALIZACJAstaticZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<liczba> | inheritOPISBogactwo głosuINICJALIZACJA50ZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆnormal | none | spell-out | inheritOPISParametry mowyINICJALIZACJAnormalZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆonce | always | inheritOPISCzytanie na głos nagłówków tabeliINICJALIZACJAonceZASTOSOWANIEelementy z informacją nagłówkowąDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆdigits | continuous | inheritOPISWymowa liczebnikówINICJALIZACJAcontinuousZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆcode | none | inheritOPISWymowa interpunkcjiINICJALIZACJAnoneZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆ<liczba> | x-slow | slow | medium | fast | x-fast | faster | slower | inheritOPISPrędkość wymowyINICJALIZACJAmediumZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆ<liczba> | inheritOPISAkcentINICJALIZACJA50ZASTOSOWANIEwszystkie elementyDZIEDZICZENIEtakPROCENTYnieMEDIAaural WARTOŚĆauto | fixed | inheritOPISRozplanowanie tabeliINICJALIZACJAautoZASTOSOWANIEtabeleDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆ<długość> | <procent> | inheritOPISWcięcie tekstuINICJALIZACJA0ZASTOSOWANIEelementy blokoweDZIEDZICZENIEtakPROCENTYodnosi się do szerokości bloku obejmującegoMEDIAvisual WARTOŚĆnone | [<kolor> || <długość> <długość> <długość>? ,]* [<kolor> || <długość> <długość> <długość>?] | inheritOPISCień tekstuINICJALIZACJAnoneZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆnormal | embed | bidi-override | inheritOPISAlgorytm dwukierunkowego tekstuINICJALIZACJAnormalZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆvisible | hidden | collapse | inheritOPISWidzialnośćINICJALIZACJAinheritZASTOSOWANIEwszystkie elementyDZIEDZICZENIEniePROCENTYnieMEDIAvisual WARTOŚĆnormal | pre | nowrap | inheritOPISKontrola białych znakówINICJALIZACJAnormalZASTOSOWANIEelementy blokoweDZIEDZICZENIEtakPROCENTYnieMEDIAvisual WARTOŚĆauto | <liczba> | inheritOPISPozycja w stosie nakładających się elementówINICJALIZACJAautoZASTOSOWANIEelementy pozycjonowaneDZIEDZICZENIEniePROCENTYnieMEDIAvisual To jest akapit koloru zielonego, wewnątrz którego znajduje się: pochylenie oraz podkreślenie, którym nie zostały nadane żadne style, a więc dziedziczą je po przodku, czyli po akapicie (są również zielone).A to jest pogrubienie, które znajduje się także wewnątrz tego samego akapitu, ale został mu nadany atrybut koloru czcionki (biały) oraz koloru tła (niebieski) i dlatego nie odziedziczył stylu po przodku. Łańcuchy znakowe (tzw. strings) mogą być pisane w podwójnym cudzysłowie ( `"..."` ) lub w pojedynczym ( `'...'` ). Łańcuchy ograniczone podwójnym cudzysłowem nie mogą już zawierać wewnątrz takiego znaku - wtedy należy użyć znaku odwróconego ukośnika (backslash) przed cudzysłowem wewnątrz. Tzn. aby wpisać następujący string: `"123"123"` (niepoprawnie!), należy podać: `"123\"123"` (poprawnie). To samo dotyczy pojedynczego cudzysłowu (zamiast `'123'123'` należy wpisać `'123\'123'` ). Natomiast dozwolony jest zapis: `"123'123"` lub `'123"123'` . Niedozwolone jest bezpośrednie użycie znaku nowej linii (przez przełamanie linii klawiszem Enter). Należy zamiast tego użyć znaku \A. Poniżej znajdziesz wykaz wszystkich cech (własności) oraz ich wartości według oryginalnej specyfikacji CSS2, opracowanej przez organizację W3C. Wyjaśnienie znaczenia poszczególnych elementów opisu: * WARTOŚĆ * Wartości które może przyjąć cecha. Przyjęto tutaj następujące oznaczenia: * Słowa kluczowe zostały wpisane bez żadnych dodatkowych znaków (np. center, left-side). Wyraz inherit oznacza, że element przyjmuje wartość cechy, taką samą jak jego rodzic (zasada dziedziczenia). * Typy podstawowe zostały ujęte w znaki < oraz >. Są to: * `<liczba>` - pojedyncza liczba * `<długość>` - wartość długości * `<procent>` - wartość procentowa * `<kąt>` - kąt * `<czas>` - czas * `<częstotliwość>` - częstotliwość * `<łańcuch znakowy>` - łańcuch znakowy (string) * `<kolor>` - definicja koloru * `<adres>` - adres (ścieżka dostępu) w postaci: `url(adres)` * `<identyfikator>` - identyfikator elementu w postaci: `#nazwa` * Typy które przyjmują takie same wartości jak inne cechy, zostały ujęte w znaki <' oraz '> (np. <'background-color'>). Ich wartości należy szukać pod podaną nazwą. * Typy ujęte w znaki < oraz >, które nie zostały wymienione powyżej (np.: <absolute-size>), stanowią specjalne wartości, określone tylko dla danej cechy. Należy ich szukać w opisie danej cechy (po kliknięciu jej nazwy). * Znak "|" oddzielający dwie lub więcej wartości oznacza, że dokładnie jedna z nich musi się pojawić w deklaracji stylu, np. dla zestawienia: > scroll | fixed | inherit można podać: > fixed * Znak "||" oddzielający dwie lub więcej wartości oznacza, że jedna lub więcej z nich musi się pojawić w deklaracji stylu w dowolnym porządku, np. dla zestawienia: > <'background-color'> || <'background-image'> || <'background-repeat'> || <'background-attachment'> || <'background-position'> można podać: > <'background-repeat'> <'background-image'> * Nawiasy kwadratowe "[" oraz "]" służą do grupowania, np. wyrażenie: > a b | c || d e jest równoważne: > [ a b ] | [ c || [ d e ]] * Gwiazdka "*" wskazuje, że poprzedzający typ, wyraz lub grupa może się pojawić zero lub więcej razy. * Plus "+" oznacza, że poprzedzający typ, wyraz lub grupa może się pojawić raz lub więcej. * Pytajnik "?" wskazuje, że poprzedzający typ, wyraz lub grupa jest opcjonalna. * Para liczb w nawiasach klamrowych {A,B} oznacza, że poprzedzający typ, wyraz lub grupa musi się pojawić przynajmniej A razy, natomiast maksymalnie B razy. * OPIS * Tutaj znajdziesz krótki opis znaczenia cechy. Jeżeli szczegółowy opis jest dostępny, można się do niego przenieść klikając odnośnik. * INICJALIZACJA * Wartość domyślna cechy. * ZASTOSOWANIE * Elementy których dotyczy cecha. * DZIEDZICZENIE * Wskazuje, czy wartość jest dziedziczona od przodka. * PROCENTY * Określa czy dana cecha akceptuje wartości procentowe, a jeśli tak, to w jaki sposób są interpretowane. * MEDIA * Grupa mediów, do których cecha się stosuje. ``` scroll | fixed | inherit ``` ``` <kolor> | transparent | inherit ``` ``` repeat | repeat-x | repeat-y | no-repeat | inherit ``` * OPIS * Powtarzanie tła * INICJALIZACJA * repeat * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual * WARTOŚĆ * `<kolor> | inherit` * OPIS * Atrybuty mieszane koloru górnego/prawego/dolnego/lewego obramowania * INICJALIZACJA * wartość cechy `'color'` * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual ``` collapse | separate | inherit ``` * OPIS * Model obramowania tabeli * INICJALIZACJA * collapse * ZASTOSOWANIE * tabele * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` <kolor>{1,4} | transparent | inherit ``` ``` <długość> <długość>? | inherit ``` * OPIS * Odstęp między komórkami tabeli * INICJALIZACJA * 0 * ZASTOSOWANIE * tabele * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` <border-style>{1,4} | inherit ``` ``` <border-width>{1,4} | inherit ``` ``` top | bottom | left | right | inherit ``` * OPIS * Pozycja podpisu tabeli * INICJALIZACJA * top * ZASTOSOWANIE * podpis tabeli * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual * OPIS * Przyleganie do elementu pływającego * INICJALIZACJA * none * ZASTOSOWANIE * elementy blokowe * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual * WARTOŚĆ * `<kolor> | inherit` * OPIS * Kolor * INICJALIZACJA * zależy od przeglądarki * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` [ <'cue-before'> || <'cue-after'> ] | inherit ``` * OPIS * Sygnał wywoławczy przed i po... * INICJALIZACJA * zobacz cechy indywidualne * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * aural * WARTOŚĆ * `ltr | rtl | inherit` * OPIS * Kierunek tekstu * INICJALIZACJA * ltr * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` <kąt> | below | level | above | higher | lower | inherit ``` ``` show | hide | inherit ``` * OPIS * Obramowanie pustych komórek tabeli * INICJALIZACJA * show * ZASTOSOWANIE * komórki tabeli * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual * OPIS * Ustawienie * INICJALIZACJA * none * ZASTOSOWANIE * wszystkie elementy oprócz pozycjonowanych * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual ``` [[ <family-name> | <generic-family> ],]* [<family-name> | <generic-family>] | inherit ``` * OPIS * Rodzina czcionek * INICJALIZACJA * zależy od przeglądarki * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` <absolute-size> | <relative-size> | <długość> | <procent> | inherit ``` * OPIS * Rozmiar czcionki * INICJALIZACJA * medium * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * odnosi się do rozmiaru czcionki rodzica * MEDIA * visual ``` <liczba> | none | inherit ``` * OPIS * Dopasowanie rozmiaru czcionki * INICJALIZACJA * none * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` normal | small-caps | inherit ``` * OPIS * Wysokość linii * INICJALIZACJA * normal * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * odnosi się do rozmiaru czcionki elementu * MEDIA * visual * OPIS * Wyróżnik obrazkowy wykazu * INICJALIZACJA * none * ZASTOSOWANIE * elementy wykazu * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` inside | outside | inherit ``` * OPIS * Pozycja wyróżnika wykazu * INICJALIZACJA * outside * ZASTOSOWANIE * elementy wykazu * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` <margin-width>{1,4} | inherit ``` ``` <margin-width> | inherit ``` * OPIS * Szerokość górnego/prawego/dolnego/lewego marginesu * INICJALIZACJA * 0 * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * odnosi się do szerokości bloku obejmującego * MEDIA * visual ``` [ crop || cross ] | none | inherit ``` * OPIS * Znaczniki strony (po wydrukowaniu) * INICJALIZACJA * none * ZASTOSOWANIE * kontekst strony * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual, paged * OPIS * Minimalna szerokość * INICJALIZACJA * zależy od przeglądarki * ZASTOSOWANIE * wszystkie elementy oprócz niezastępowanych elementów inline i tabel * DZIEDZICZENIE * nie * PROCENTY * odnosi się do bloku obejmującego * MEDIA * visual ``` [ <'outline-color'> || <'outline-style'> || <'outline-width'> ] | inherit ``` ``` <color> | invert | inherit ``` * OPIS * Styl obrysu * INICJALIZACJA * none * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual, interactive * OPIS * Szerokość obrysu * INICJALIZACJA * medium * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual, interactive ``` visible | hidden | scroll | auto | inherit ``` * OPIS * Kontroluje przepełnienie elementu * INICJALIZACJA * visible * ZASTOSOWANIE * elementy blokowe i zastępowane * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual ``` <padding-width>{1,4} | inherit ``` ``` <padding-width> | inherit ``` ``` <identyfikator> | auto ``` * OPIS * Nazwa strony * INICJALIZACJA * auto * ZASTOSOWANIE * elementy blokowe * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual, paged * OPIS * Przełamanie strony przed blokiem * INICJALIZACJA * auto * ZASTOSOWANIE * elementy blokowe * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual, paged * OPIS * Przerwa przed wymawianym tekstem * INICJALIZACJA * zależy od przeglądarki * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * odnosi się do odwrotności wartości 'speech-rate' * MEDIA * aural * WARTOŚĆ * `<liczba> | inherit` * OPIS * Odchylenie częstotliwości od średniej * INICJALIZACJA * 50 * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * aural ``` <adres> mix? repeat? | auto | none | inherit ``` * OPIS * Tło dźwiękowe podczas wymowy * INICJALIZACJA * auto * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * aural ``` static | relative | absolute | fixed | inherit ``` * OPIS * Pozycja elementu * INICJALIZACJA * static * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual ``` [<łańcuch znakowy> <łańcuch znakowy>]+ | none | inherit ``` * OPIS * Określa znaki cudzysłowu * INICJALIZACJA * zależy od przeglądarki * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` normal | none | spell-out | inherit ``` ``` once | always | inherit ``` * OPIS * Czytanie na głos nagłówków tabeli * INICJALIZACJA * once * ZASTOSOWANIE * elementy z informacją nagłówkową * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * aural ``` digits | continuous | inherit ``` ``` code | none | inherit ``` ``` <liczba> | x-slow | slow | medium | fast | x-fast | faster | slower | inherit ``` * OPIS * Prędkość wymowy * INICJALIZACJA * medium * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * aural ``` auto | fixed | inherit ``` * OPIS * Rozplanowanie tabeli * INICJALIZACJA * auto * ZASTOSOWANIE * tabele * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual ``` left | right | center | justify | <łańcuch znakowy> | inherit ``` * OPIS * Wyrównanie tekstu * INICJALIZACJA * zależy od przeglądarki * ZASTOSOWANIE * elementy blokowe * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual * OPIS * Wcięcie tekstu * INICJALIZACJA * 0 * ZASTOSOWANIE * elementy blokowe * DZIEDZICZENIE * tak * PROCENTY * odnosi się do szerokości bloku obejmującego * MEDIA * visual ``` none | [<kolor> || <długość> <długość> <długość>? ,]* [<kolor> || <długość> <długość> <długość>?] | inherit ``` ``` normal | embed | bidi-override | inherit ``` * OPIS * Algorytm dwukierunkowego tekstu * INICJALIZACJA * normal * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual * OPIS * Widzialność * INICJALIZACJA * inherit * ZASTOSOWANIE * wszystkie elementy * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual ``` normal | pre | nowrap | inherit ``` * OPIS * Kontrola białych znaków * INICJALIZACJA * normal * ZASTOSOWANIE * elementy blokowe * DZIEDZICZENIE * tak * PROCENTY * nie * MEDIA * visual ``` auto | <liczba> | inherit ``` * OPIS * Pozycja w stosie nakładających się elementów * INICJALIZACJA * auto * ZASTOSOWANIE * elementy pozycjonowane * DZIEDZICZENIE * nie * PROCENTY * nie * MEDIA * visual ...i gotowe. Prawda że szybko poszło? 😉 Jeżeli nie odpowiada nam podstawowy wygląd menu, można go zmienić wykorzystując polecenia CSS. W tym celu w pliku menu.css należy wkleić np.: > #menu0 { width: 200px; margin: 10px; padding: 0; } #menu0 dt { background-color: #888; color: #fff; font-weight: bold; text-align: center; cursor: pointer; margin: 10px 0 0 0; padding: 2px; } #menu0 dd { background-color: #eee; color: #000; border-width: 0 1px 1px 1px; border-style: solid; border-color: #888; margin: 0; padding: 1px 5px; } #menu0 dd.active { font-weight: bold; } * Wstaw w nagłówku pliku jeden raz kod: > <script src="menu.js"></script> * W wybranych miejscach strony osadź bloki menu używając znaczników listy definicyjnej <dl>...</dl>, przy czym każdemu kolejnemu menu nadaj inny identyfikator `id="..."` - np. `id="menu0"` , `id="menu1"` , `id="menu2"` itd. * Pod każdym blokiem menu wstaw wywołanie skryptu (ostatni zaprezentowany wcześniej fragment kodu), pamiętając, aby w każdym z nich podać odpowiedni identyfikator (menu0, menu1, menu2 itd.). Warto nadmienić, że w przypadku kiedy elementy menu zawierają odsyłacze, gałąź menu, w której znajduje się odnośnik do aktualnie wczytanej strony, zostanie na starcie automatycznie rozwinięta. Dzięki temu użytkownik łatwiej odnajdzie punkt w nawigacji, w którym teraz się znajduje. Dodatkowo w takiej sytuacji elementowi `<dd>...</dd>` , w którym znajduje się bieżący odsyłacz, zostanie przypisana klasa CSS pod nazwą active, dzięki której można dodatkowo wyróżnić aktualną pozycję menu, dodając odpowiednie deklaracje CSS w arkuszu stylów, np.: > #menu0 dd.active { font-weight: bold; } oddzielone średnikami (";"). * Ochrona adresu e-mail * Zabezpieczenie naszego adresu e-mail przed robotami sieciowymi, czyli specjalnymi programami, które automatycznie gromadzą adresy pocztowe umieszczone na stronach WWW, a później używają ich do rozsyłania spamu. * Wczytanie stron do dwóch ramek * Załadowanie dwóch (lub więcej) ramek jednocześnie, po kliknięciu pojedynczego odsyłacza. * Ostrzeżenie przed ramką * Ostrzeżenie, że dana strona wchodzi w skład struktury ramek i aby zobaczyć pełny kontekst (spis treści), użytkownik powinien udać się na stronę główną. W innym wariancie skrypt automatycznie wczytuje stronę główną i ustawia podstronę, spod której wchodził użytkownik. * Sprawdzenie pól formularza * Sprawdzenie przed wysłaniem formularza pocztowego, czy wszystkie pola zostały wypełnione przez użytkownika. * Strona na hasło * Jeżeli nie chcesz, aby wszystkie informacje na Twojej stronie były publicznie dostępne, możesz zabezpieczyć wybrane podstrony hasłem. Prezentowany skrypt jest niezwykle prosty do wprowadzenia, ale jednocześnie bardzo skuteczny. * Dynamiczne blokowanie pól formularza * Blokowanie/odblokowywanie albo ukrywanie/wyświetlanie jednego lub kilku pól formularza dopiero po wcześniejszym wybraniu przez użytkownika określonej opcji. Funkcja niezwykle przydatna przy bardziej skomplikowanych formularzach. * Potwierdzenie wyczyszczenia formularza * Wyeliminowanie możliwości pomyłkowego naciśnięcia przycisku "reset" w formularzu (czyszczącego wszystkie dane), dzięki potwierdzeniu zamiaru użytkownika. * Usunięcie polskich znaków z formularza * Usunięcie polskich znaków z formularza pocztowego, a przez to uniknięcie błędnego ich zakodowania. * Alternatywny sposób wysłania formularza * Sposób na ominięcie błędu pojawiającego w niektórych wersjach systemu operacyjnego, powodującego, że zamiast wysłania formularza, otwiera się program pocztowy z pustą wiadomością. # Generator stron WWW Istrukcja obsługi Klikając przyciski z menu wprowadzamy do wpisywanego teksu znaczniki HTML czyli specjalne polecenia w nawiasach ostrych, które pozwalają zmieniać wygląd tekstu na ekranie, np.: ``` <b>Ten tekst zostanie pogrubiony</b>, to jest zwykły tekst... ``` Znaczniki HTML będą niewidoczne później na stronie, natomiast widoczny będzie tekst, który wpiszemy wewnątrz lub poza nimi (tekst wewnątrz dodatkowo zmieni wygląd). Po kliknięciu dowolnego przycisku (Czcionka, Hiperłącze lub Wyrównanie) w oknie edycji wpisujemy tekst, którego wygląd chcemy zmienić. Jednocześnie można zauważyć, że na przycisku który wybraliśmy, pojawił się symbol gwiazdki - przypomina nam on, że po wpisaniu całego tekstu, który ma być np. pogrubiony czy pochylony, musimy ponownie kliknąć ten sam przycisk, aby podawany dalej tekst miał już normalny wygląd (wtedy symbol gwiazdki zniknie z przycisku). # Generator szablonów WWW Tytuł: Opis: Lewa kolumna: Obramowanie zawartości z góry: px # Obramowanie zawartości z prawej: px # Obramowanie zawartości z dołu: px # Prawa kolumna: 1Strona Tak Znak wodny 2Ramka 3Wnętrze 4Logo 5Linki 6Nagłówek menu 7Zawartość menu Link podstawowy: # PodkreśleniePogrubieniePochylenie Link odwiedzony: # PodkreśleniePogrubieniePochylenie Podświetlenie: # PodkreśleniePogrubieniePochylenie 8Treść 9Stopka Obramowanie z lewej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF Tytuł: Tytuł: Opis: Opis: Lewa kolumna: Lewa kolumna: Szerokość: px Szerokość: px px px Margines nagłówka: pxpx pxpx Margines nagłówka: pxpx pxpx pxpx px px px px px Obramowanie nagłówka z góry: px # Obramowanie nagłówka z góry: px # Obramowanie nagłówka z prawej: px # Obramowanie nagłówka z prawej: px # Obramowanie nagłówka z dołu: px # Obramowanie nagłówka z dołu: px # Obramowanie nagłówka z lewej: px # Obramowanie nagłówka z lewej: px # Margines zawartości: pxpx pxpx Margines zawartości: pxpx pxpx pxpx px px px px px Obramowanie zawartości z góry: px # Obramowanie zawartości z góry: px # Obramowanie zawartości z prawej: px # Obramowanie zawartości z prawej: px # Obramowanie zawartości z dołu: px # Obramowanie zawartości z dołu: px # Obramowanie zawartości z lewej: px # Obramowanie zawartości z lewej: px # Prawa kolumna: Prawa kolumna: Szerokość: px Szerokość: px px px Margines nagłówka: pxpx pxpx Margines nagłówka: pxpx pxpx px px px px px px px px Obramowanie nagłówka z góry: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> Obramowanie nagłówka z góry: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Obramowanie nagłówka z prawej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # 0123<KEY> Obramowanie nagłówka z prawej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # 0123456789ABCDEF<KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Obramowanie nagłówka z dołu: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # 0<KEY> Obramowanie nagłówka z dołu: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # 0123456789ABCDEF0123456789ABCDEF<KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Obramowanie nagłówka z lewej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # 0<KEY> Obramowanie nagłówka z lewej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # 0<KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F Margines zawartości: pxpx pxpx Margines zawartości: pxpx pxpx px px px px px px px px Obramowanie zawartości z góry: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> Obramowanie zawartości z góry: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F Obramowanie zawartości z prawej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> Obramowanie zawartości z prawej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # <KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F Obramowanie zawartości z dołu: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> Obramowanie zawartości z dołu: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # 0123<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0<KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F Obramowanie zawartości z lewej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> Obramowanie zawartości z lewej: px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset # <KEY> px px nonehiddendasheddottedsoliddoublegrooveridgeinsetoutset none hidden dashed dotted solid double groove ridge inset outset # # <KEY> 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 1Strona 1Strona 1Strona Strona Czcionka: px serifsans-serifmonospacecursivefantasy Czcionka: px serifsans-serifmonospacecursivefantasy px px serifsans-serifmonospacecursivefantasy serif sans-serif monospace cursive fantasy Tło: # <KEY> Tło: # <KEY> # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło graficzne: Tak Znak wodny Tło graficzne: Tak Znak wodny Tak Znak wodny 2Ramka 2Ramka 2Ramka Ramka Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF<KEY> Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF<KEY> # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło graficzne: Tak Tło graficzne: Tak Tak 3Wnętrze 3Wnętrze 3Wnętrze Wnętrze Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło graficzne: Tak Tło graficzne: Tak Tak 4Logo 4Logo 4Logo Logo Czcionka: px serifsans-serifmonospacecursivefantasy Czcionka: px serifsans-serifmonospacecursivefantasy px px serifsans-serifmonospacecursivefantasy serif sans-serif monospace cursive fantasy Tekst: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF Tekst: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło graficzne: pxpx pxpx Margines wewnątrz: pxpx pxpx pxpx px px px px px 7Zawartość menu 7Zawartość menu 7Zawartość menu Zawartość menu Czcionka: px Czcionka: px Tekst: # Tekst: # Tło: # Tło: # Tło graficzne: pxpx pxpx Margines wewnątrz: pxpx pxpx pxpx px px px px px Link podstawowy: # PodkreśleniePogrubieniePochylenie Link podstawowy: # PodkreśleniePogrubieniePochylenie Podkreślenie Pogrubienie Pochylenie Link odwiedzony: # PodkreśleniePogrubieniePochylenie Link odwiedzony: # PodkreśleniePogrubieniePochylenie Podkreślenie Pogrubienie Pochylenie Podświetlenie: # PodkreśleniePogrubieniePochylenie Podświetlenie: # PodkreśleniePogrubieniePochylenie Podkreślenie Pogrubienie Pochylenie 8Treść 8Treść 8Treść Treść Czcionka: px serifsans-serifmonospacecursivefantasy Czcionka: px serifsans-serifmonospacecursivefantasy px px serifsans-serifmonospacecursivefantasy serif sans-serif monospace cursive fantasy Tekst: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF Tekst: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF Tło: # 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF # # 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło graficzne: # Generator META i BODY Generator META i BODY MetBod Nagłówek: Typ dokumentu: HTML XHTML Opis zawartości: Wyrazy kluczowe: Język: pl (polski) af (afrykanerski) sq (albański) en (angielski) en-au (angielski - Australia) en-bz (angielski - Belize) en-ie (angielski - Irlandia) en-jm (angielski - Jamajka) en-ca (angielski - Kanada) en-nz (angielski - Nowa Zelandia) en-za (angielski - Rep. Płd. Afryki) en-us (angielski - Stany Zjednoczone) en-tt (angielski - Trynidad) en-gb (angielski - Wielka Brytania) ar (arabski) ar-dz (arabski - Algieria) ar-sa (arabski - Arabia Saudyjska) ar-bh (arabski - Bahrajn) ar-eg (arabski - Egipt) ar-iq (arabski - Irak) ar-ye (arabski - Jemen) ar-jo (arabski - Jordan) ar-qa (arabski - Katar) ar-kw (arabski - Kuwejt) ar-lb (arabski - Liban) ar-ly (arabski - Libia) ar-ma (arabski - Maroko) ar-om (arabski - Oman) ar-sy (arabski - Syria) ar-tn (arabski - Tunezja) ar-ae (arabski - Zjed. Emiraty Arabskie) eu (baskijski) be (białoruski) bg (bułgarski) zh (chiński) zh-cn (chiński - Chiny) zk-hk (chiński - Hong Kong) zh-sg (chiński - Singapur) zh-tw (chiński - Tajwan) hr (chorwacki) cs (czeski) da (duński) et (estoński) fo (farerski) fi (fiński) fr (francuski) fr-be (francuski - Belgia) fr-ca (francuski - Kanada) fr-lu (francuski - Luksemburg) fr-ch (francuski - Szwajcaria) gd (gaelicki) el (grecki) he (hebrajski) hi (hindi) es (hiszpański) es-ar (hiszpański - Argentyna) es-bo (hiszpański - Boliwia) es-cl (hiszpański - Chile) es-do (hiszpański - Dominikana) es-ec (hiszpański - Ekwador) es-gt (hiszpański - Gwatemala) es-hn (hiszpański - Honduras) es-co (hiszpański - Kolumbia) es-cr (hiszpański - Kostaryka) es-mx (hiszpański - Meksyk) es-ni (hiszpański - Nikaragua) es-py (hiszpański - Panama) es-pe (hiszpański - Peru) es-pr (hiszpański - Puerto Rico) es-sv (hiszpański - Salwador) es-uy (hiszpański - Urugwaj) in (indonezyjski) is (islandzki) ja (japoński) ji (jidysz) ca (kataloński) ko (koreański) lt (litewski) lv (łotewski) mk (macedoński) ms (malezyjski) mt (maltański) nl (niderlandzki) nl-be (niderlandzki - Belgia) de (niemiecki) de-at (niemiecki - Austria) de-li (niemiecki - Liechtenstein) de-lu (niemiecki - Luksemburg) de-ch (niemiecki - Szwajcaria) no (norweski) fa (perski - Farsi) pt (portugalski) pt-br (portugalski - Brazylia) rm (retoromański) ru (rosyjski) ru-mo (rosyjski - Mołdawia) ro (rumuński) ro-mo (rumuński - Mołdawia) sr (serbski) sx (sutu) sv (szwedzki) sv-fi (szwedzki - Finlandia) sk (słowacki) sl (słoweński) th (tajlandzki) ts (tsonga) tn (tswana) tr (turecki) uk (ukraiński) ur (urdu) vi (wietnamski) it (włoski) it-ch (włoski - Szwajcaria) hu (węgierski) xh (xhosa) zu (zuluski) Autor: Twórca: Wydawca: Odświeżanie strony co: sek. Przejdź do strony: Użyty edytor: Roboty sieciowe: all - indeksuj wszystko none - nie indeksuj niczego index - indeksuj stronę noindex - nie indeksuj strony follow - indeksuj odsyłacze nofollow - nie indeksuj odsyłaczy noarchive - nie zapisuj w archiwum nosnippet - nie wyświetlaj opisu notranslate - nie proponuje tłumaczenia strony na inny język noimageindex - nie indeksuj obrazków nositelinkssearchbox - nie wyświetlaj pola wyszukiwania z linkami do podstron indexifembedded - indeksuj strony w ramkach Skalowanie: Szerokość: device-width (szerokość obszaru wyświetlania) inna (podaj wartość) Wysokość: device-height (wysokość obszaru wyświetlania) inna (podaj wartość) Skala początkowa: Skala minimalna: Skala maksymalna: Blokada skalowania Tytuł strony: Zewnętrzny arkusz stylów CSS: Plik: Media: all (wszystkie) screen (monitor kolorowy) print (drukarka) aural (syntezator mowy) braille (czytanie braillem) embossed (drukarka brailla) handheld (urządzenie ręczne) projection (projektor) tty (monotypiczne - dalekopis) tv (telewizor) Ikona strony: Ciało: Kolor tekstu : # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Kolor tła : # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło obrazkowe: Plik: Nieruchome Powtarzanie: repeat-x (w poziomie) repeat-y (w pionie) no-repeat (nie powtarzaj) Pozycja: center top right top right right bottom bottom left bottom left left top inna (podaj 1 lub 2 wartości) Od lewej: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Od góry: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Odnośniki: Podstawowy : # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Odwiedzony : # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Aktywny : # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Wszystkie: Krój: Rodzina ogólna: serif (szeryfowa) sans-serif (bezszeryfowa) monospace (monotypiczna) cursive (pochyła) fantasy (fantazyjna) Pogrubienie Kursywa Dekoracja: none (brak) underline (podkreślenie) overline (nadkreślenie) line-through (przekreślenie) blink (migotanie) Podświetlenie: Kolor : # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Tło : # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Dekoracja: none (brak) underline (podkreślenie) overline (nadkreślenie) line-through (przekreślenie) blink (migotanie) Marginesy: Symetryczne : Poziomy: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Pionowy: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Niesymetryczne : Lewy: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Prawy: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Górny: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Dolny: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Czcionka: Krój: Wyrównanie: left (do lewej) right (do prawej) center (wyśrodkowanie) justify (justowanie) Rozmiar: px (piksele) pt (punkty) in (cale) cm (centymetry) mm (milimetry) pc (pika) Rodzina ogólna: serif (szeryfowa) sans-serif (bezszeryfowa) monospace (monotypiczna) cursive (pochyła) fantasy (fantazyjna) Pogrubienie Kursywa Dekoracja: none (brak) underline (podkreślenie) overline (nadkreślenie) line-through (przekreślenie) Transformacja: uppercase (wielkie litery) lowercase (małe litery) capitalize (kapitalizacja) Wysokość linii: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Rozciągnięcie wyrazów: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Rozciągnięcie liter: px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) ch (szerokość cyfry zero) rem (wysokość czcionki korzenia) vw (% szerokość obszaru wyświetlania) vh (% wysokość obszaru wyświetlania) vmin (mniejsza z wartości: vw lub vh) vmax (większa z wartości: vw lub vh) in (cale) cm (centymetry) mm (milimetry) pt (punkty) pc (pika) Blokada (JavaScript): Menu kontekstowe (prawy klawisz) Zaznaczanie Przeciąganie Wygenerowana treść: Zobacz także Jak wyznaczyć kąt, utworzony między dodatnią poziomą półosią układu współrzędnych a prostą przechodzącą przez środek układu współrzędnych i zadany punkt? W jaki sposób objąć stylem kilka elementów tekstowych? W jaki sposób za pomocą CSS odnieść się do korzenia drzewa dokumentu? Jak wypełnić tło płynnym przejściem kilku kolorów w postaci gradientu? Jak ustawić szerokość (grubość) obramowania dla wszystkich krawędzi jednocześnie? © www.kurshtml.edu.pl # Konwerter HTML/Tekst Konwerter HTML/Tekst Kod źródłowy: Inteligentny tryb preformatowany Zamień sąsiadujące spacje i tabulacje na niełamliwe Zamień niełamliwe spacje na zwykłe Dodaj przełamania linii Usuń przełamania linii Zobacz także Jak przekształcić dowolną wartość na obiekt liczbowy? Co to jest obrys i czym się różni od obramowania? Jak przekształcić dowolną wartość na obiekt tekstowy? Jak zabezpieczyć się przed nieestetycznym przyleganiem dwóch elementów oblewanych tekstem (np. obrazki)? W jaki sposób nie dopuścić, aby obok tekstu znajdował się obrazek ani inny element? Ile wynosi logarytm naturalny z liczby 2? © www.kurshtml.edu.pl # Tester kolorów Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras scelerisque. Nulla facilisi. In interdum urna vitae nisl. Vestibulum at ipsum. Quisque consequat tortor vel urna aliquam accumsan. Etiam nulla lectus, consectetuer eu, hendrerit nec, ultrices eget, nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas facilisis ipsum quis enim. Pellentesque lectus enim, eleifend eu, facilisis ac, scelerisque et, sapien. Phasellus interdum. Nullam semper lectus nec odio. Ut placerat. Morbi nec turpis. In volutpat. Nulla venenatis nibh in augue. Cras id quam. Donec nonummy nonummy odio. Fusce in arcu ultricies tortor volutpat tristique. Curabitur condimentum odio id orci. Donec fringilla metus et enim. Nam feugiat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus ut libero non purus mattis adipiscing. Aliquam tortor lectus, vestibulum ac, porttitor at, adipiscing porta, leo. Mauris a metus. Nam venenatis pede at lorem. Morbi at neque. Proin consequat magna vitae est. In suscipit. Etiam tortor ante, blandit eu, gravida in, rhoncus ac, lectus. Proin posuere. Proin dignissim nisi vitae magna. Etiam ac lectus. Nunc placerat laoreet erat. Praesent lectus elit, nonummy in, egestas ut, tempus ac, quam. Możliwe jest określenie wyglądu nowego okna (rozmiarów, położenia, pokazanie/ukrycie pasków menu, narzędzi, statusu itp.), poprzez podanie w poleceniu dodatkowych parametrów. Zamiast opisu zamieszam poniżej generator. Otrzymany w nim kod, należy wpisać w miejsce wyróżnionego tekstu, np. jako wartość atrybutu `onload="..."` (pierwszy sposób). UWAGA! Jeśli chcesz otworzyć zwykłe okno po kliknięciu odsyłacza (trzeci wariant), czyli bez określania parametrów wyglądu, lepiej to zrobić w następujący sposób: > <a target="_blank" href="adres">opis</a# Generator pól formularza Generator pól formularza Typ: TEXT (pole tekstowe) PASSWORD (hasło) CHECKBOX (pole wyboru) RADIO (pole opcji) SELECT (lista rozwijalna) OPTION (opcja listy rozwijalnej) TEXTAREA (obszar tekstowy) FILE (selektor plików) SUBMIT (wysłanie formularza) RESET (wyczyszczenie danych) BUTTON (przycisk) <BUTTON> (przycisk rozbudowany) Kolor tekstu: # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Kolor tła: # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Rozmiar czcionki: pt (punkty) px (piksele) % (procent) em (wysokość czcionki) ex (wysokość małej litery) in (cale) cm (centymetry) mm (milimetry) pc (pika) Rodzaj(e) czcionki: Dekoracja: Pogrubienie Pochylenie Podkreślenie Przekreślenie Nadkreślenie Szerokość: px (piksele) pt (punkty) % (procent) em (wysokość czcionki) ex (wysokość małej litery) in (cale) cm (centymetry) mm (milimetry) pc (pika) Wysokość: px (piksele) pt (punkty) % (procent) em (wysokość czcionki) ex (wysokość małej litery) in (cale) cm (centymetry) mm (milimetry) pc (pika) Obramowanie: Styl: NONE (brak) SOLID (ciągłe) DASHED (kreskowe) DOTTED (kropkowe) DOUBLE (podwójne) GROOVE (rowek) RIDGE (grzbiet) INSET OUTSET Kolor: # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Szerokość: px (piksele) pt (punkty) % (procent) em (wysokość czcionki) ex (wysokość małej litery) in (cale) cm (centymetry) mm (milimetry) pc (pika) Podgląd: Brak obsługi ramek lokalnych! Wygenerowany kod: Zobacz także Jak obliczyć arcus tangens? W jaki sposób przekształcić tekst na liczbę? Jak połączyć kilka selektorów atrybutów w jednej regule stylów CSS? Co zrobić, aby liczby w kolumnach tabeli z danymi były ułożone równo pod sobą? W jaki sposób wyświetlić licznik i mianownik rozdzielone kreską ułamkową? Jak pobrać milisekundę z podanej daty? © www.kurshtml.edu.pl # Tester pliku robots.txt Tester pliku robots.txt robots.txt Adresy URL: User-Agent: Opcje: Pomiń dyrektywę: Allow Pomiń wzorzec dopasowania: * Pomiń wzorzec dopasowania: $ Allow: Disallow: Zobacz także Co zrobić, aby wokół pustych komórek tabeli wyświetlało się obramowanie? W jaki sposób poprawnie oznaczać datę i czas w dokumentach HTML5? W jaki sposób rozciągnąć lub ścieśnić czcionkę? Jak rozpocząć nową stronę papieru w określonym miejscu na wydruku? Jak zmienić wygląd odsyłaczy (odnośników hipertekstowych, hiperłączy, linków)? © www.kurshtml.edu.pl Generator gradientów CSS Typ liniowy promienisty Powtarzany Kierunek w górę w prawy-górny róg w prawo w prawy-dolny róg w dół w lewy-dolny róg w lewo w lewy-górny róg Kąt... Kąt stopnie gradusy radiany obroty Kształt elipsa okrąg Rozmiar bliższa krawędź dalsza krawędź bliższy narożnik dalszy narożnik Inny rozmiar... Inny rozmiar Poziom procenty cale centymetry milimetry punkty pika piksele wysokość czcionki wysokość małej litery szerokość cyfry "0" wysokość czcionki korzenia szer. obszaru wyświetlania wys. obszaru wyświetlania min szer/wys obszaru wyśw. max szer/wys obszaru wyśw. Pion procenty cale centymetry milimetry punkty pika piksele wysokość czcionki wysokość małej litery szerokość cyfry "0" wysokość czcionki korzenia szer. obszaru wyświetlania wys. obszaru wyświetlania min szer/wys obszaru wyśw. max szer/wys obszaru wyśw. Pozycja centrum na górze w prawym-górnym rógu po prawej w prawym-dolnym rogu na dole w lewym-dolnym rogu po lewej w lewym-górnym rogu Inna pozycja... Inna pozycja Od lewej procenty cale centymetry milimetry punkty pika piksele wysokość czcionki wysokość małej litery szerokość cyfry "0" wysokość czcionki korzenia szer. obszaru wyświetlania wys. obszaru wyświetlania min szer/wys obszaru wyśw. max szer/wys obszaru wyśw. Od góry procenty cale centymetry milimetry punkty pika piksele wysokość czcionki wysokość małej litery szerokość cyfry "0" wysokość czcionki korzenia szer. obszaru wyświetlania wys. obszaru wyświetlania min szer/wys obszaru wyśw. max szer/wys obszaru wyśw. Kolor czarny biały srebrny szary kasztanowy czerwony purpurowy fuksja zielony limonowy oliwkowy żółty granatowy niebieski zielonomodry akwamaryna pomarańczowy Inny kolor... Inny kolor # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Odległość procenty cale centymetry milimetry punkty pika piksele wysokość czcionki wysokość małej litery szerokość cyfry "0" wysokość czcionki korzenia szer. obszaru wyświetlania wys. obszaru wyświetlania min szer/wys obszaru wyśw. max szer/wys obszaru wyśw. Kolor czarny biały srebrny szary kasztanowy czerwony purpurowy fuksja zielony limonowy oliwkowy żółty granatowy niebieski zielonomodry akwamaryna pomarańczowy Inny kolor... Inny kolor # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F Odległość procenty cale centymetry milimetry punkty pika piksele wysokość czcionki wysokość małej litery szerokość cyfry "0" wysokość czcionki korzenia szer. obszaru wyświetlania wys. obszaru wyświetlania min szer/wys obszaru wyśw. max szer/wys obszaru wyśw. Dodaj kolor Wybierz Zobacz także Jak utworzyć nową instancję tablicy, która może przechowywać listę elementów? Co zrobić, aby wysokość i pionowe marginesy dopasowywały się do sąsiednich elementów, tak aby wyświetlanie zawsze było poprawne? Definicje CSS: dokument źródłowy (source document) Jak pobrać wszystkie dopasowania wzorca (wyrażenia regularnego) do podanego tekstu? Jak określić specjalny wygląd strony w wersji do wydruku czy na urządzenia przenośne? © www.kurshtml.edu.pl # Kalkulator (przelicznik) jednostek CSS Kalkulator (przelicznik) jednostek CSS Wartość * Jednostka in (cal) cm (centymetr) mm (milimetr) Q (ćwierćmilimetr) pt (punkt) pc (pika) px (piksel) deg (stopień) grad (gradus) rad (radian) turn (obrót) ms (milisekunda) s (sekunda) Hz (herc) kHz (kiloherc) dpi (plamki na cal) dpcm (plamki na centymetr) dppx (plamki na piksel) = * Wszystkie wyniki są zaokrąglane do trzeciego miejsca po przecinku. Zobacz także Jak przekształcić rzucony wyjątek na tekst, który można wyświetlić użytkownikowi? Jak pobrać dzień miesiąca z podanej daty w strefie czasowej południka zerowego (UTC)? Podstawowe definicje (terminy) dotyczące stylów CSS Jak zmienić miesiąc w podanej dacie? Jak przekształcić tekst w formacie JSON na obiekty i wartości JavaScript? © www.kurshtml.edu.pl # Znaki Unicode (utf-8) Znaki Unicode (utf-8) Wpisz znak Unicode: 0 [Łaciński podstawowy = 0] 100 [Łaciński-1 = 127] 200 [Łaciński rozszerzony-A = 256] 300 [Łaciński rozszerzony-B = 399] 400 500 600 700 [Litery modyfikujące odstępy = 710; Łączące znaki diakrytyczne = 768] 800 [Grecki podstawowy = 894] 900 1000 [Cyrylica = 1025] 1100 1200 1300 1400 [Hebrajski rozszerzony = 1456; Hebrajski podstawowy = 1488] 1500 [Arabski podstawowy = 1548] 1600 [Arabski rozszerzony = 1632] 1700 1800 1900 2000 2100 2200 2300 2400 2500 2600 2700 2800 2900 3000 3100 3200 3300 3400 3500 3600 3700 3800 3900 4000 4100 4200 4300 4400 4500 4600 4700 4800 4900 5000 5100 5200 5300 5400 5500 5600 5700 5800 5900 6000 6100 6200 6300 6400 6500 6600 6700 6800 6900 7000 7100 7200 7300 7400 7500 7600 7700 7800 [Łaciński rozszerzony dodatkowy = 7808] 7900 8000 8100 8200 [Standardowe znaki przestankowe = 8204] 8300 [Indeksy górne i dolne = 8319; Symbole waluty = 8355] 8400 [Symbole literopodobne = 8453] 8500 [Formy liczb = 8531; Strzałki = 8592] 8600 8700 [Operatory matematyczne = 8706] 8800 8900 [Różne techniczne = 8962] 9000 9100 9200 9300 9400 [Elementy ramek = 9472] 9500 9600 [Elementy blokowe = 9600; Kształty geometryczne = 9632] 9700 [Dingbats (różne) = 9786] 9800 9900 10000 10100 10200 10300 10400 10500 10600 10700 10800 10900 11000 11100 11200 11300 11400 11500 11600 11700 11800 11900 12000 12100 12200 12300 12400 12500 12600 12700 12800 12900 13000 13100 13200 13300 13400 13500 13600 13700 13800 13900 14000 14100 14200 14300 14400 14500 14600 14700 14800 14900 15000 15100 15200 15300 15400 15500 15600 15700 15800 15900 16000 16100 16200 16300 16400 16500 16600 16700 16800 16900 17000 17100 17200 17300 17400 17500 17600 17700 17800 17900 18000 18100 18200 18300 18400 18500 18600 18700 18800 18900 19000 19100 19200 19300 19400 19500 19600 19700 19800 19900 20000 20100 20200 20300 20400 20500 20600 20700 20800 20900 21000 21100 21200 21300 21400 21500 21600 21700 21800 21900 22000 22100 22200 22300 22400 22500 22600 22700 22800 22900 23000 23100 23200 23300 23400 23500 23600 23700 23800 23900 24000 24100 24200 24300 24400 24500 24600 24700 24800 24900 25000 25100 25200 25300 25400 25500 25600 25700 25800 25900 26000 26100 26200 26300 26400 26500 26600 26700 26800 26900 27000 27100 27200 27300 27400 27500 27600 27700 27800 27900 28000 28100 28200 28300 28400 28500 28600 28700 28800 28900 29000 29100 29200 29300 29400 29500 29600 29700 29800 29900 30000 30100 30200 30300 30400 30500 30600 30700 30800 30900 31000 31100 31200 31300 31400 31500 31600 31700 31800 31900 32000 32100 32200 32300 32400 32500 32600 32700 32800 32900 33000 33100 33200 33300 33400 33500 33600 33700 33800 33900 34000 34100 34200 34300 34400 34500 34600 34700 34800 34900 35000 35100 35200 35300 35400 35500 35600 35700 35800 35900 36000 36100 36200 36300 36400 36500 36600 36700 36800 36900 37000 37100 37200 37300 37400 37500 37600 37700 37800 37900 38000 38100 38200 38300 38400 38500 38600 38700 38800 38900 39000 39100 39200 39300 39400 39500 39600 39700 39800 39900 40000 40100 40200 40300 40400 40500 40600 40700 40800 40900 41000 41100 41200 41300 41400 41500 41600 41700 41800 41900 42000 42100 42200 42300 42400 42500 42600 42700 42800 42900 43000 43100 43200 43300 43400 43500 43600 43700 43800 43900 44000 44100 44200 44300 44400 44500 44600 44700 44800 44900 45000 45100 45200 45300 45400 45500 45600 45700 45800 45900 46000 46100 46200 46300 46400 46500 46600 46700 46800 46900 47000 47100 47200 47300 47400 47500 47600 47700 47800 47900 48000 48100 48200 48300 48400 48500 48600 48700 48800 48900 49000 49100 49200 49300 49400 49500 49600 49700 49800 49900 50000 50100 50200 50300 50400 50500 50600 50700 50800 50900 51000 51100 51200 51300 51400 51500 51600 51700 51800 51900 52000 52100 52200 52300 52400 52500 52600 52700 52800 52900 53000 53100 53200 53300 53400 53500 53600 53700 53800 53900 54000 54100 54200 54300 54400 54500 54600 54700 54800 54900 55000 55100 55200 55300 55400 55500 55600 55700 55800 55900 56000 56100 56200 56300 56400 56500 56600 56700 56800 56900 57000 57100 57200 57300 57400 57500 57600 57700 57800 57900 58000 58100 58200 58300 58400 58500 58600 58700 58800 58900 59000 59100 59200 59300 [Obszar do użytku własnego = 59393] 59400 59500 59600 59700 59800 59900 60000 60100 60200 60300 60400 60500 60600 60700 60800 60900 61000 61100 61200 61300 61400 61500 61600 61700 61800 61900 62000 62100 62200 62300 62400 62500 62600 62700 62800 62900 63000 63100 63200 63300 63400 63500 63600 63700 63800 63900 64000 64100 64200 [Formularze prezentacji alfabetycznej = 64257] 64300 [Formularze prezentacji arabskiej-A = 64342] 64400 64500 64600 64700 64800 64900 65000 65100 [Formularze prezentacji arabskiej-B = 65152] 65200 65300 65400 65500 [Specjalne = 65532] Brak obsługi skryptów! Brak obsługi pływających ramek! Zobacz także Jak ustawić bloki w wierszach na dole, na górze albo równomiernie na całej dostępnej wysokości? Co zrobić, aby Twoja strona była odnajdywana w wyszukiwarkach? Co zrobić, aby punkt wykazu (wyróżnik, marker) znajdował się wewnątrz tekstu? Jak zbudować bardziej profesjonalny serwis? Jak wprowadzić dłuższy cytat? © www.kurshtml.edu.pl # Test przeglądarki Date: 2001-01-31 Categories: Tags: Własność | Opis | Twoja przeglądarka | | --- | --- | --- | width | szerokość | 800 | height | wysokość | 600 | left | lewa krawędź | brak danych | top | górna krawędź | brak danych | availWidth | dostępna szerokość | 800 | availHeight | dostępna wysokość | 600 | availLeft | dostępna pozycja od lewej | 0 | availTop | dostępna pozycja od góry | 0 | colorDepth | głębia kolorów | 24 | pixelDepth | głębia pikseli | 24 | bufferDepth | głębokość buffora | brak danych | deviceXDPI | rozdzielczość DPI w poziomie | brak danych | deviceYDPI | rozdzielczość DPI w pionie | brak danych | logicalXDPI | logiczna rozdzielczość DPI w poziomie | brak danych | logicalYDPI | logiczna rozdzielczość DPI w pionie | brak danych | updateInterval | czas odświeżania w milisekundach | brak danych | fontSmoothingEnabled | wygładzanie czcionek | brak danych | Własność | Opis | Twoja przeglądarka | MSIE 6 | MSIE 5 | Mozilla 1 | Firefox 0.9 | Netscape 6 | Opera 7 | Opera 6 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | appName | nazwa | Netscape | Microsoft Internet Explorer | Microsoft Internet Explorer | Netscape | Netscape | Netscape | Microsoft Internet Explorer | Microsoft Internet Explorer | appVersion | wersja | 5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/119.0.6045.105 Safari/537.36 | 4.0 (compatible; MSIE 6.0; Windows NT 5.1) | 4.0 (compatible; MSIE 5.01; Windows NT 5.0) | 5.0 (Windows; PL) | 5.0 (Windows; pl-PL) | 5.0 (Windows; en-US) | 4.0 (compatible; MSIE 6.0; Windows NT 5.1) | 4.0 (compatible; MSIE 5.0; Windows XP) | appMinorVersion | zainstalowane aktualizacje | brak danych | ;SP1;Q837009;Q832894;Q831167; | ;SP1;Q837009;Q832894;Q831167; | brak danych | brak danych | brak danych | appCodeName | nazwa kodu | Mozilla | Mozilla | Mozilla | Mozilla | Mozilla | Mozilla | Mozilla | Mozilla | userAgent | przegladarka | Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/119.0.6045.105 Safari/537.36 | Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) | Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0) | Mozilla/5.0 (Windows; U; Windows NT 5.1; PL; rv:1.5) Gecko/20030925 | Mozilla/5.0 (Windows; U; Windows NT 5.1; pl-PL; rv:1.7) Gecko/20040707 Firefox/0.9.2 | Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; m18) Gecko/20010131 Netscape6/6.01 | Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Opera 7.23 [pl] | Mozilla/4.0 (compatible; MSIE 5.0; Windows XP) Opera 6.05 [pl] | platform | system operacyjny | Linux x86_64 | Win32 | Win32 | Win32 | Win32 | Win32 | Win32 | Win32 | cookieEnabled | obsługa cookie | tak | tak | tak | tak | tak | tak | tak | tak | javaEnabled() | obsługa Javy | nie | tak | tak | tak | tak | tak | tak | tak | taintEnabled() | oznaczenie danych jako niebezpieczne | brak danych | nie | nie | nie | nie | nie | nie | nie | language | język | en-US | brak danych | brak danych | PL | pl-PL | en-US | pl | pl | browserLanguage | język przeglądarki | brak danych | pl | pl | brak danych | brak danych | brak danych | pl | pl | systemLanguage | domyślny język systemu operacyjnego | brak danych | pl | pl | brak danych | brak danych | brak danych | brak danych | brak danych | userLanguage | ustawiony język systemu operacyjnego | brak danych | pl | pl | brak danych | brak danych | brak danych | pl | brak danych | oscpu | system operacyjny | brak danych | brak danych | brak danych | Windows NT 5.1 | Windows NT 5.1 | Windows NT 5.0 | brak danych | brak danych | vendor | producent | Google Inc. | brak danych | brak danych | Firefox | Netscape6 | brak danych | brak danych | vendorSub | numer wersji producenta | brak danych | brak danych | 0.9.2 | 6.01 | brak danych | brak danych | product | produkt | Gecko | brak danych | brak danych | Gecko | Gecko | Gecko | brak danych | brak danych | productSub | numer wersji produktu | 20030107 | brak danych | brak danych | 20030925 | 20040707 | 20010131 | brak danych | brak danych | securityPolicy | polityka bezpieczeństwa | brak danych | brak danych | brak danych | brak danych | brak danych | cpuClass | klasa procesora | brak danych | x86 | x86 | brak danych | brak danych | brak danych | brak danych | brak danych | onLine | tryb online | tak | tak | tak | brak danych | brak danych | brak danych | brak danych | brak danych | userProfile | profil użytkownika | brak danych | obiekt dostępny | obiekt dostępny | brak danych | brak danych | brak danych | brak danych | brak danych | opsProfile | informacje o użytkowniku | brak danych | wskaźnik dostępny | wskaźnik dostępny | brak danych | brak danych | brak danych | brak danych | brak danych | Język | Twoja przeglądarka | MSIE 6 | MSIE 5 | Mozilla 1 | Firefox 0.9 | Netscape 6 | Opera 7 | Opera 6 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | Javascript: | tak | tak | tak | tak | tak | tak | tak | tak | JavaScript1.1: | tak | tak | tak | tak | tak | tak | tak | tak | JavaScript1.2: | tak | tak | tak | tak | tak | tak | tak | tak | JavaScript1.3: | tak | tak | tak | tak | tak | tak | tak | tak | JavaScript1.4: | tak | nie | nie | tak | tak | tak | tak | tak | JavaScript1.5: | tak | nie | nie | tak | tak | tak | tak (7.5) | nie | JScript: | tak | tak | tak | nie | nie | nie | tak | tak | LiveScript: | tak | tak | tak | tak | tak | tak | tak | tak | VBScript: | nie | tak | nie | nie | nie | nie | nie | nie | Twoja przeglądarka | MSIE 6 | MSIE 5 | Mozilla 1 | Firefox 0.9 | Netscape 6 | Opera 7 | Opera 6 | | --- | --- | --- | --- | --- | --- | --- | --- | DOM Level 1 | DOM Level 1 | DOM Level 1 | DOM Level 1 | DOM Level 1 | DOM Level 1 | DOM Level 1 | DOM Level 1 | navigator: | appCodeName, appName, appVersion, clearAppBadge, clipboard, connection, cookieEnabled, credentials, deviceMemory, doNotTrack, geolocation, getBattery, getGamepads, getInstalledRelatedApps, getUserMedia, gpu, hardwareConcurrency, hid, ink, javaEnabled, keyboard, language, languages, locks, managed, maxTouchPoints, mediaCapabilities, mediaDevices, mediaSession, mimeTypes, onLine, pdfViewerEnabled, permissions, platform, plugins, presentation, product, productSub, registerProtocolHandler, requestMIDIAccess, requestMediaKeySystemAccess, scheduling, sendBeacon, serial, serviceWorker, setAppBadge, storage, unregisterProtocolHandler, usb, userActivation, userAgent, userAgentData, vendor, vendorSub, vibrate, virtualKeyboard, wakeLock, webdriver, webkitGetUserMedia, webkitPersistentStorage, webkitTemporaryStorage, windowControlsOverlay, xr | | --- | --- | window: | PERSISTENT, TEMPORARY, addEventListener, alert, atob, blur, btoa, caches, cancelAnimationFrame, cancelIdleCallback, captureEvents, cdc_adoQpoasnfa76pfcZLmcfl_Array, cdc_adoQpoasnfa76pfcZLmcfl_JSON, cdc_adoQpoasnfa76pfcZLmcfl_Object, cdc_adoQpoasnfa76pfcZLmcfl_Promise, cdc_adoQpoasnfa76pfcZLmcfl_Proxy, cdc_adoQpoasnfa76pfcZLmcfl_Symbol, clearInterval, clearTimeout, clientInformation, close, closed, confirm, cookieStore, createImageBitmap, credentialless, crossOriginIsolated, crypto, customElements, devicePixelRatio, dhtml_level, dispatchEvent, document, documentPictureInPicture, external, fetch, find, focus, frameElement, frames, getComputedStyle, getScreenDetails, getSelection, history, indexedDB, innerHeight, innerWidth, isSecureContext, javascript13, javascript14, javascript15, launchQueue, length, localStorage, location, locationbar, matchMedia, menubar, moveBy, moveTo, name, navigation, navigator, onabort, onafterprint, onanimationend, onanimationiteration, onanimationstart, onappinstalled, onauxclick, onbeforeinput, onbeforeinstallprompt, onbeforematch, onbeforeprint, onbeforetoggle, onbeforeunload, onbeforexrselect, onblur, oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncontentvisibilityautostatechange, oncontextlost, oncontextmenu, oncontextrestored, oncuechange, ondblclick, ondevicemotion, ondeviceorientation, ondeviceorientationabsolute, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, onerror, onfocus, onformdata, ongotpointercapture, onhashchange, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onlanguagechange, onload, onloadeddata, onloadedmetadata, onloadstart, onlostpointercapture, onmessage, onmessageerror, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseout, onmouseover, onmouseup, onmousewheel, onoffline, ononline, onpagehide, onpageshow, onpause, onplay, onplaying, onpointercancel, onpointerdown, onpointerenter, onpointerleave, onpointermove, onpointerout, onpointerover, onpointerrawupdate, onpointerup, onpopstate, onprogress, onratechange, onrejectionhandled, onreset, onresize, onscroll, onscrollend, onsearch, onsecuritypolicyviolation, onseeked, onseeking, onselect, onselectionchange, onselectstart, onslotchange, onstalled, onstorage, onsubmit, onsuspend, ontimeupdate, ontoggle, ontransitioncancel, ontransitionend, ontransitionrun, ontransitionstart, onunhandledrejection, onunload, onvolumechange, onwaiting, onwebkitanimationend, onwebkitanimationiteration, onwebkitanimationstart, onwebkittransitionend, onwheel, open, openDatabase, opener, origin, originAgentCluster, outerHeight, outerWidth, pageXOffset, pageYOffset, parent, performance, personalbar, postMessage, print, prompt, queryLocalFonts, queueMicrotask, releaseEvents, removeEventListener, reportError, requestAnimationFrame, requestIdleCallback, resizeBy, resizeTo, ret_nodes, scheduler, screen, screenLeft, screenTop, screenX, screenY, scroll, scrollBy, scrollTo, scrollX, scrollY, scrollbars, self, sessionStorage, setInterval, setTimeout, showDirectoryPicker, showOpenFilePicker, showSaveFilePicker, speechSynthesis, status, statusbar, stop, structuredClone, styleMedia, toolbar, top, trustedTypes, visualViewport, webkitCancelAnimationFrame, webkitRequestAnimationFrame, webkitRequestFileSystem, webkitResolveLocalFileSystemURL, window | document: | ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_PRECEDING, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE, URL, activeElement, addEventListener, adoptNode, adoptedStyleSheets, alinkColor, all, anchors, append, appendChild, applets, baseURI, bgColor, body, captureEvents, caretRangeFromPoint, characterSet, charset, childElementCount, childNodes, children, clear, cloneNode, close, compareDocumentPosition, compatMode, contains, contentType, cookie, createAttribute, createAttributeNS, createCDATASection, createComment, createDocumentFragment, createElement, createElementNS, createEvent, createExpression, createNSResolver, createNodeIterator, createProcessingInstruction, createRange, createTextNode, createTreeWalker, currentScript, defaultView, designMode, dir, dispatchEvent, doctype, documentElement, documentURI, domain, elementFromPoint, elementsFromPoint, embeds, evaluate, execCommand, exitFullscreen, exitPictureInPicture, exitPointerLock, featurePolicy, fgColor, firstChild, firstElementChild, fonts, forms, fragmentDirective, fullscreen, fullscreenElement, fullscreenEnabled, getAnimations, getElementById, getElementsByClassName, getElementsByName, getElementsByTagName, getElementsByTagNameNS, getRootNode, getSelection, hasChildNodes, hasFocus, hasPrivateToken, hasRedemptionRecord, hasStorageAccess, head, hidden, images, implementation, importNode, inputEncoding, insertBefore, isConnected, isDefaultNamespace, isEqualNode, isSameNode, lastChild, lastElementChild, lastModified, linkColor, links, location, lookupNamespaceURI, lookupPrefix, nextSibling, nodeName, nodeType, nodeValue, normalize, onabort, onanimationend, onanimationiteration, onanimationstart, onauxclick, onbeforecopy, onbeforecut, onbeforeinput, onbeforematch, onbeforepaste, onbeforetoggle, onbeforexrselect, onblur, oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncontentvisibilityautostatechange, oncontextlost, oncontextmenu, oncontextrestored, oncopy, oncuechange, oncut, ondblclick, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, onerror, onfocus, onformdata, onfreeze, onfullscreenchange, onfullscreenerror, ongotpointercapture, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onload, onloadeddata, onloadedmetadata, onloadstart, onlostpointercapture, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseout, onmouseover, onmouseup, onmousewheel, onpaste, onpause, onplay, onplaying, onpointercancel, onpointerdown, onpointerenter, onpointerleave, onpointerlockchange, onpointerlockerror, onpointermove, onpointerout, onpointerover, onpointerrawupdate, onpointerup, onprerenderingchange, onprogress, onratechange, onreadystatechange, onreset, onresize, onresume, onscroll, onscrollend, onsearch, onsecuritypolicyviolation, onseeked, onseeking, onselect, onselectionchange, onselectstart, onslotchange, onstalled, onsubmit, onsuspend, ontimeupdate, ontoggle, ontransitioncancel, ontransitionend, ontransitionrun, ontransitionstart, onvisibilitychange, onvolumechange, onwaiting, onwebkitanimationend, onwebkitanimationiteration, onwebkitanimationstart, onwebkitfullscreenchange, onwebkitfullscreenerror, onwebkittransitionend, onwheel, open, ownerDocument, parentElement, parentNode, pictureInPictureElement, pictureInPictureEnabled, plugins, pointerLockElement, prepend, prerendering, previousSibling, queryCommandEnabled, queryCommandIndeterm, queryCommandState, queryCommandSupported, queryCommandValue, querySelector, querySelectorAll, readyState, referrer, releaseEvents, removeChild, removeEventListener, replaceChild, replaceChildren, requestStorageAccess, requestStorageAccessFor, rootElement, scripts, scrollingElement, startViewTransition, styleSheets, textContent, timeline, title, visibilityState, vlinkColor, wasDiscarded, webkitCancelFullScreen, webkitCurrentFullScreenElement, webkitExitFullscreen, webkitFullscreenElement, webkitFullscreenEnabled, webkitHidden, webkitIsFullScreen, webkitVisibilityState, write, writeln, xmlEncoding, xmlStandalone, xmlVersion | document.body: | ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_PRECEDING, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE, aLink, accessKey, addEventListener, after, animate, append, appendChild, ariaAtomic, ariaAutoComplete, ariaBrailleLabel, ariaBrailleRoleDescription, ariaBusy, ariaChecked, ariaColCount, ariaColIndex, ariaColSpan, ariaCurrent, ariaDescription, ariaDisabled, ariaExpanded, ariaHasPopup, ariaHidden, ariaInvalid, ariaKeyShortcuts, ariaLabel, ariaLevel, ariaLive, ariaModal, ariaMultiLine, ariaMultiSelectable, ariaOrientation, ariaPlaceholder, ariaPosInSet, ariaPressed, ariaReadOnly, ariaRelevant, ariaRequired, ariaRoleDescription, ariaRowCount, ariaRowIndex, ariaRowSpan, ariaSelected, ariaSetSize, ariaSort, ariaValueMax, ariaValueMin, ariaValueNow, ariaValueText, assignedSlot, attachInternals, attachShadow, attributeStyleMap, attributes, autocapitalize, autofocus, background, baseURI, before, bgColor, blur, checkVisibility, childElementCount, childNodes, children, classList, className, click, clientHeight, clientLeft, clientTop, clientWidth, cloneNode, closest, compareDocumentPosition, computedStyleMap, contains, contentEditable, dataset, dir, dispatchEvent, draggable, elementTiming, enterKeyHint, firstChild, firstElementChild, focus, getAnimations, getAttribute, getAttributeNS, getAttributeNames, getAttributeNode, getAttributeNodeNS, getBoundingClientRect, getClientRects, getElementsByClassName, getElementsByTagName, getElementsByTagNameNS, getInnerHTML, getRootNode, hasAttribute, hasAttributeNS, hasAttributes, hasChildNodes, hasPointerCapture, hidden, hidePopover, id, inert, innerHTML, innerText, inputMode, insertAdjacentElement, insertAdjacentHTML, insertAdjacentText, insertBefore, isConnected, isContentEditable, isDefaultNamespace, isEqualNode, isSameNode, lang, lastChild, lastElementChild, link, localName, lookupNamespaceURI, lookupPrefix, matches, namespaceURI, nextElementSibling, nextSibling, nodeName, nodeType, nodeValue, nonce, normalize, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, onabort, onafterprint, onanimationend, onanimationiteration, onanimationstart, onauxclick, onbeforecopy, onbeforecut, onbeforeinput, onbeforematch, onbeforepaste, onbeforeprint, onbeforetoggle, onbeforeunload, onbeforexrselect, onblur, oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncontentvisibilityautostatechange, oncontextlost, oncontextmenu, oncontextrestored, oncopy, oncuechange, oncut, ondblclick, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, onerror, onfocus, onformdata, onfullscreenchange, onfullscreenerror, ongotpointercapture, onhashchange, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onlanguagechange, onload, onloadeddata, onloadedmetadata, onloadstart, onlostpointercapture, onmessage, onmessageerror, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseout, onmouseover, onmouseup, onmousewheel, onoffline, ononline, onpagehide, onpageshow, onpaste, onpause, onplay, onplaying, onpointercancel, onpointerdown, onpointerenter, onpointerleave, onpointermove, onpointerout, onpointerover, onpointerrawupdate, onpointerup, onpopstate, onprogress, onratechange, onrejectionhandled, onreset, onresize, onscroll, onscrollend, onsearch, onsecuritypolicyviolation, onseeked, onseeking, onselect, onselectionchange, onselectstart, onslotchange, onstalled, onstorage, onsubmit, onsuspend, ontimeupdate, ontoggle, ontransitioncancel, ontransitionend, ontransitionrun, ontransitionstart, onunhandledrejection, onunload, onvolumechange, onwaiting, onwebkitanimationend, onwebkitanimationiteration, onwebkitanimationstart, onwebkitfullscreenchange, onwebkitfullscreenerror, onwebkittransitionend, onwheel, outerHTML, outerText, ownerDocument, parentElement, parentNode, part, popover, prefix, prepend, previousElementSibling, previousSibling, querySelector, querySelectorAll, releasePointerCapture, remove, removeAttribute, removeAttributeNS, removeAttributeNode, removeChild, removeEventListener, replaceChild, replaceChildren, replaceWith, requestFullscreen, requestPointerLock, role, scroll, scrollBy, scrollHeight, scrollIntoView, scrollIntoViewIfNeeded, scrollLeft, scrollTo, scrollTop, scrollWidth, setAttribute, setAttributeNS, setAttributeNode, setAttributeNodeNS, setPointerCapture, shadowRoot, showPopover, slot, spellcheck, style, tabIndex, tagName, text, textContent, title, toggleAttribute, togglePopover, translate, vLink, virtualKeyboardPolicy, webkitMatchesSelector, webkitRequestFullScreen, webkitRequestFullscreen | screen: | addEventListener, availHeight, availLeft, availTop, availWidth, colorDepth, dispatchEvent, height, isExtended, onchange, orientation, pixelDepth, removeEventListener, width | Date: 2014-01-01 Categories: Tags: > <head> <meta name="description" content="Tu podaj opis twojej strony"> </head> Polecenie to należy wstawić między znacznikami: `<head>` oraz `</head>` . Pozwala ono opisać co znajduje się na Twojej stronie. Z informacji tej korzystają wyszukiwarki sieciowe, dlatego staraj się tutaj wpisać tekst, który jak najlepiej opisze zawartość strony i zachęci do jej odwiedzenia. Ciekawy, ale niezbyt długi, opis może zachęcić internautów do obejrzenia Twojej strony. Znacznik > <head> <meta name="keywords" content="wyraz1, wyraz2, wyraz3..."> </head> Polecenie to należy wstawić między znacznikami: `<head>` oraz `</head>` . Pozwala Ci ono podać wyrazy kluczowe, z których korzystają wyszukiwarki sieciowe. Dlatego staraj się tutaj wpisać wyrazy, które jak najlepiej opiszą zawartość Twojej strony. Dobrze dobrane wyrazy kluczowe, pomogą wyszukiwarkom odnaleźć Twoją stronę. Znacznik * RSS > <link rel="alternate" title="Tytuł kanału" href="adres kanału" type="application/rss+xml"> * Atom > <link rel="alternate" title="Tytuł kanału" href="adres kanału" type="application/atom+xml"> `title="..."` ), ponieważ inaczej użytkownik nie będzie mógł rozróżnić, co chciałby subskrybować. var data = new Date(); document.write(data); prof. WWW Umieszczanie na swojej stronie nieoznaczonych płatnych linków reklamowych jest niezgodne z wytycznymi Google. Karą za takie postępowanie może być ręczne obniżenie pozycji strony w wynikach wyszukiwania albo nawet usunięcie z nich całego serwisu. Dlatego jeśli chcemy umieścić na własnej stronie płatne odnośniki sponsorowane, koniecznie należy je oznaczyć atrybutem `rel="sponsored"` . W tym celu wewnątrz znacznika wybranej komórki `<td>...</td>` tabeli nadrzędnej wstawiamy znacznik tabeli podrzędnej `<table>...</table>` wraz z całą jego zawartością - tzn. wewnętrznymi wierszami `<tr>...</tr>` i zawartymi w nich komórkami wewnętrznymi. Każdy dokument podstrony musi posiadać odpowiadający sobie plik z różniącym się kodem nagłówkowym. Plik ten musi znajdować się w tym samym katalogu co podstrona i nazywać się identycznie, tylko do nazwy trzeba na końcu dodać przyrostek .html. Przykładowo: dokument podstrona.shtml musi posiadać w tym samym katalogu plik podstrona.shtml.html, którego zawartość może być następująca: > <title>Tytuł strony</title> UWAGA!Jeżeli zapomnisz utworzyć takiego pliku albo pomylisz jego nazwę, w szablonie strony wyświetlą się błędy, a nawet w ogóle może się on nie wyświetlić. Wybierz obrazek w formacie JPG, muzykę w dowolnym formacie albo plik w formacie GIF: To wbrew pozorom nie wszystkie miejsca, gdzie można umieścić ważne słowa kluczowe. Oczywiście niezwykle duże znaczenie mają słowa umieszczone bezpośrednio w treści strony (szczególnie głównej). Problem w tym, że nie możemy ich tam wpisywać tyle, ile byśmy chcieli, bo strona stanie się po prostu nieczytelna dla człowieka. Niektóre wyszukiwarki traktują jednak "mocniej" wyrażenia umieszczone w takich miejscach jak: tytuły (szczególnie pierwszego rzędu), treść alternatywna obrazków (atrybut `alt="..."` ), dymki narzędziowe odsyłaczy (atrybut `title="..."` ) albo tekst (opis) samych odsyłaczy. Dodatkowe punkty można również dostać, jeśli ważne słowo kluczowe znajduje się bezpośrednio w adresie strony. Lepiej jest także jeśli sam adres jest krótszy. W większości przedstawionych wcześniej metod możliwe jest pewne oszukiwanie wyszukiwarek, ponieważ to autor strony wpisuje słowa kluczowe, które przecież mogą nie mieć nic wspólnego z treścią. Można swobodnie wpisać wyrażenia, które są najczęściej wyszukiwane i tym sposobem próbować zwiększyć oglądalność strony. Na dłuższą metę nie jest to jednak dobre rozwiązanie, ponieważ jeśli czytelnik nie znajdzie na naszej stronie spodziewanych informacji, to prawdopodobnie więcej już na nią nie powróci. Poza tym jeśli wyszukiwarki zorientują się, że chcemy je oszukać, mogą na zawsze usunąć stronę z wszelkich wyników wyszukiwania! Sposoby wstawiania stylów do gotowych dokumentów są różne. Nie znaczy to, że jedne są lepsze od drugich. Każdy sposób jest przydatny w innych sytuacjach. Większość witryn stosuje jednocześnie wszystkie z przedstawionych metod osadzania CSS - w zależności od konkretnej potrzeby. To jest jakiś tekst Ten akapit ma zresetowane wszystkie style do wartości domyślnych, ponieważ została mu przypisana deklaracja "all: initial".A to jest pogrubienie, które znajduje się wewnątrz tego akapitu. Odziedziczyło ono zresetowany rodzaj czcionki. Ale jej waga nie została zmieniona - tekst nadal jest wizualnie wytłuszczony - ponieważ zostało to oddzielne przypisane do tego elementu. Atrybuty formatowania w języku CSS definiuje się za pomocą tzw. reguł stylów. Każda reguła odnosi się do konkretnego elementu (znacznika) i składa się z dwóch części: selektora i deklaracji. Selektor określa do jakich elementów ma zostać przypisane formatowanie, a deklaracja podaje to formatowanie i jest umieszczona w nawiasie klamrowym `{...}` . Każda deklaracja składa się przynajmniej z jednego zespołu cecha lub inaczej własność albo właściwość (ang. property) - wartość (ang. value), przy czym można podać dowolną liczbę, rozdzielając kolejne znakiem średnika (;). Średnik na końcu deklaracji nie jest konieczny. Każda grupa elementów (znaczników) ma określony zespół cech CSS, które można jej przypisać, a każda cecha ma ściśle wyszczególnioną listę wartości, które może przyjąć. Na przykład: cecha `text-align` (wyrównanie tekstu) może być przypisana tylko i wyłącznie do elementów blokowych, ponieważ podanie jej dla elementów wyświetlanych w linii nie miałoby sensu. Z drugiej strony cecha ta może przyjmować tylko wartości takie jak: `left` , `right` , `center` , `justify` . Przypisanie do niej np. wartości koloru nie miałoby sensu. W MSIE 8.0 i starszych jeden plik arkusza CSS może zawierać tylko 4095 selektorów, przy czym w listach każdy selektor liczy się osobno - następne deklaracje zostaną pominięte! W przypadku przekroczenia tej granicy, jedynym rozwiązaniem jest podział arkusza CSS na kilka osobnych plików, ale nie więcej niż 31. * Pseudoklasy dynamiczne * Pseudoklasa etykiety: :target * Pseudoklasa języka: :lang() * Pseudoklasy interfejsu użytkownika: * Pseudoklasy strukturalne: * Pseudoklasa negacji: :not() (CSS 3 - interpretuje Firefox 34) > selektor { font-variant-position: wariant } (interpretuje: Internet Explorer 10.0, Firefox 3.5, Opera 9.5, Chrome, Konqueror) > selektor { text-shadow: poziom pion rozmycie kolor,... } text-shadow: 3px 3px red, yellow -3px 3px 2px, 3px -3px A to jest zwykły akapit z tłem, bez określenia jakichkolwiek marginesów. Dlatego jego szerokość wynosi tyle co zwykłego tekstu, a także wewnątrz elementu (prostokąta) nie ma żadnego odstępu. (CSS 3 - interpretuje Firefox 32, Opera 12-) > selektor { box-decoration-break: dekoracja } (CSS 3 - interpretuje Firefox 33, Opera 77, Chrome 91) > selektor { list-style-position: pozycja } Selektorem mogą być znaczniki dotyczące wykazów: ul - wypunktowanie, ol - wykaz numerowany oraz li - pojedynczy punkt wykazu [zobacz: Wstawianie stylów].Natomiast "pozycja" określa, jak będą zawijane wiersze wykazu, które nie zmieszczą się w jednej linii. Możliwe są tutaj dwa przypadki: Natomiast "pozycja" określa, jak będą zawijane wiersze wykazu, które nie zmieszczą się w jednej linii. Możliwe są tutaj dwa przypadki: * Punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy. * Punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi. * Punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci. > selektor { list-style-image: url(ścieżka dostępu) } Selektorem mogą być znaczniki dotyczące wykazów: ul - wypunktowanie, ol - wykaz numerowany oraz li - pojedynczy punkt wykazu [zobacz: Wstawianie stylów].Natomiast jako "ścieżka dostępu" należy wpisać względną ścieżkę do obrazka, który ma się pojawić jako wyróżnik wykazu (marker). Wpisanie none usunie obrazek. Natomiast jako "ścieżka dostępu" należy wpisać względną ścieżkę do obrazka, który ma się pojawić jako wyróżnik wykazu (marker). Wpisanie none usunie obrazek. Sytuacja jest podobna jak w poprzednim punkcie za wyjątkiem tego, że element posiada wewnętrzną wysokość (zobacz punkt 8 podrozdziału: Szerokość i marginesy automatyczne). > selektor { max-height: wartość } Selektorem może być dowolny znacznik wyświetlany w bloku lub element zastępowany [zobacz: Wstawianie stylów].Natomiast jako "wartość" należy podać wartość maksymalnej dozwolonej wysokości, jaką może mieć element. Natomiast jako "wartość" należy podać wartość maksymalnej dozwolonej wysokości, jaką może mieć element. Polecenie nie odnosi się do elementów inline!UWAGA! Polecenie nie interpretuje MSIE 6, a MSIE 7.0 obsługuje, ale nie w trybie Quirks. Ten obrazek powinien mieć wysokość minimalną 150px (min-height: 150px): (CSS 3 - interpretuje Internet Explorer * , Firefox, Opera, Chrome) > selektor { text-overflow: sposób } > selektor { caption-side: ustawienie } Selektorem może być element CAPTION [zobacz: Wstawianie stylów].Natomiast jako "ustawienie" należy podać: Natomiast jako "ustawienie" należy podać: > selektor { border-spacing: odstęp } Selektorem może być element TABLE [zobacz: Wstawianie stylów].Natomiast jako "odstęp" należy podać wartość, korzystając z jednostek długości. Przy czy możliwe jest podanie: Natomiast jako "odstęp" należy podać wartość, korzystając z jednostek długości. Przy czy możliwe jest podanie: > selektor { empty-cells: sposób } Selektorem może być element TABLE, TD lub TH [zobacz: Wstawianie stylów].Natomiast jako "sposób" należy podać: Natomiast jako "sposób" należy podać: Do tabel (<table>...</table>), ich komórek (<td>...</td>), wierszy (<tr>...</tr>) oraz kolumn (<colgroup>...</colgroup>) można stosować parametry dotyczące szerokości i wysokości. Odnośnie komórek oraz całej tabeli można ustawić zarówno ich szerokość jak i wysokość. Natomiast dla wiersza możliwe jest określenie tylko wysokości, ponieważ szerokość jest jednocześnie szerokością tabeli. Podobnie dla kolumny można ustalić jedynie jej szerokość, bo wysokość jest wysokością tabeli. Przykład {width, height} <table style="width: 80%; height: 15em">komórka1komórka2komórka3komórka4 komórka1 komórka2 komórka3 komórka4 komórka5 komórka6 komórka7 komórka8 <td style="width: 20em; height: 10em" Nie można ustawić szerokości wiersza...komórka1komórka2komórka3komórka4komórka5komórka6<tr style="height: 10em"> Nie można ustawić wysokości kolumny...<colgroup style="width: 20em">komórka1komórka2komórka3komórka4komórka5komórka6 Pytania i odpowiedzi Jak ustawić szerokość tabeli? Aby uzyskać efekt autodopasowania rozmiaru tabeli do okna, który jest znany z programu Microsoft Word, można ustawić szerokość tabeli na 100% za pomocą właściwości width, co spowoduje, że tabela zajmie całą dostępna przestrzeń w poziomie, a kolumny dopasują się proporcjonalnie do zawartości. Przykład: <table style="width: 100%">...</table>. Do tabel (<table>...</table>), ich komórek ( `<td>...</td>` ), wierszy ( `<tr>...</tr>` ) oraz kolumn (<colgroup>...</colgroup>) można stosować parametry dotyczące szerokości i wysokości. Odnośnie komórek oraz całej tabeli można ustawić zarówno ich szerokość jak i wysokość. Natomiast dla wiersza możliwe jest określenie tylko wysokości, ponieważ szerokość jest jednocześnie szerokością tabeli. Podobnie dla kolumny można ustalić jedynie jej szerokość, bo wysokość jest wysokością tabeli. Gdyby w arkuszu stylów tej strony [zobacz: Wstawianie stylów], została umieszczona taka linijka: > h1 { position: relative; left: 50% }to teraz wszystkie tytuły `h1` byłyby pozycjonowane względnie. Ale jeśli chcielibyśmy zrezygnować z pozycjonowania dla kilku wybranych elementów, wystarczyłoby wpisać `position: static` w definicji inline. (CSS 3 - interpretuje Internet Explorer 9, Firefox 2, Opera, Chrome) > selektor { opacity: nieprzezroczystość } (interpretuje MSIE 6; Firefox, Opera 15 i Chrome tylko pliki *.cur - również w systemie Linux) (CSS 3 - interpretuje Firefox 53, Opera 44, Chrome 57) > selektor { caret-color: kolor } Jako "wartości atrybutów" można podać samą wartość szerokości kolumny, tylko liczbę kolumn lub obie wartości rozdzielone spacją. Ustalenie wartości auto usuwa kolumny. Polecenie jest przydatne, jeżeli chcemy skrócić zapis. Możemy też dzięki niemu szybko usunąć podział na kolumny, poprzez wpisanie " `columns: auto` ". column-span: all; To jest element rozciągający się ponad wszystkimi kolumnami tekstu. To jest przykładowa treść, ułożona w wielu sąsiadujących kolumnach. Tekst jest automatycznie przenoszony z końca jednej kolumny na początek sąsiedniej, leżącej po jej prawej stronie... To jest przykładowa treść, ułożona w wielu sąsiadujących kolumnach. Tekst jest automatycznie przenoszony z końca jednej kolumny na początek sąsiedniej, leżącej po jej prawej stronie... To jest przykładowa treść, ułożona w wielu sąsiadujących kolumnach. Tekst jest automatycznie przenoszony z końca jednej kolumny na początek sąsiedniej, leżącej po jej prawej stronie... (CSS 3 - interpretuje Internet Explorer 10, Firefox, Opera 12, Chrome) > selektor { margin-top: auto } selektor { margin-right: auto } selektor { margin-bottom: auto } selektor { margin-left: auto } selektor { margin: auto } # Przykład @media Przypominam, że naszym celem będzie stworzenie estetycznego i funkcjonalnego menu nawigacyjnego na bazie kodu HTML przedstawionego na wstępie w formie listy nieuporządkowanej - tylko poprzez dołączenie deklaracji CSS. Tym razem, na przekór domyślnej prezentacji pozycji listy, ułożymy odnośniki nawigacyjne poziomo - w formie zakładek. Takie ustawienie możemy uzyskać na dwa sposoby: Prawy margines pozycji listy ustala odstępy pomiędzy sąsiednimi zakładkami. * Kolumna menu nawigacyjnego powinna się znaleźć po prawej stronie, a w kodzie źródłowym znajduje się na początku, zatem zostaje jej przypisana własność `float: right` . * Kolumna dodatkowych informacji może pozostać w kolejności wynikającej z ułożenia w kodzie źródłowym, a zatem przypisujemy `float: left` . * Kolejność bloku treści strony, wynikająca z naturalnego ułożenia, również jest odpowiednia (powinien się wyświetlić po kolumnie dodatkowych informacji, która w kodzie źródłowym poprzedza blok treści), a zatem - `float: left` . Możliwe są również inne konfiguracje - np. czasami spotykane ułożenie obu wąskich kolumn po lewej, a treści po prawej stronie: > html, body { background-color: #fff; color: #000; margin: 0; padding: 0; text-align: center; } #top { width: 780px; margin-left: auto; margin-right: auto; text-align: left; } #NAGLOWEK { background-color: #888; } #MENU { width: 150px; float: left; overflow: hidden; background-color: #ccc; } #INFORMACJE { width: 150px; float: left; overflow: hidden; background-color: #ccc; } #TRESC { width: 480px; float: left; overflow: hidden; background-color: #fff; } #STOPKA { clear: both; width: 100%; background-color: #888; } W tym przypadku naturalna kolejność wyświetlania bloków, wynikająca z ułożenia elementów w kodzie źródłowym strony, jest odpowiednia. Przypisanie własności `float: left` , miało jedynie na celu ustawienie kolumn obok siebie, a nie pod sobą. Natomiast nie wpływa to na ich kolejność. Płynny szablon (ang. liquid layout) charakteryzuje się zmianą swoich poziomych proporcji przy zmianie rozmiaru okna przeglądarki lub rozdzielczości ekranu. Najczęściej w każdych warunkach zajmuje on całą dostępną szerokość w oknie. Jest on raczej rzadziej stosowany, ze względu na niemożliwe do przewidzenia ułożenie elementów treści. Poza tym tekst w zbyt długich linijkach zwykle gorzej się czyta, ponieważ trudniej przenieść wzrok z końca wiersza na początek następnego. Czasami jednak może być wygodny, np. kiedy zawiera jakieś szerokie elementy, które mogą nie zmieścić się w ustalonej szerokości dla stałego szablonu (czyli zwykle 780px minus szerokość kolumny menu i ewentualnie dodatkowych informacji). Date: 2014-10-07 Categories: Tags: Każdy programista wie, jaki przełom w rozwoju informatyki przyniosła koncepcja Programowania Zorientowanego Obiektowo (ang. Object Oriented Programming). Dlaczego by nie przenieść tego na grunt CSS? Może zabrzmi to zaskakująco, ale CSS już teraz daje taką możliwość. Nie są wymagane do tego żadne dodatkowe rozszerzenia w przeglądarkach, a jedynie zmiana sposobu myślenia webmasterów podczas projektowania arkuszy stylów. Paradoksalnie osobom, które nigdy nie programowały w językach proceduralnych, prawdopodobnie łatwiej przyjdzie zrozumienie założeń CSS Zorientowanych Obiektowo (ang. Object Oriented CSS), gdyż są one bardzo intuicyjne. ### Obiekty # Popatrz przez chwilę na dowolną stronę WWW (tak, możesz spojrzeć również na stronę, którą właśnie czytasz 🙂). Zwykle zawiera ona m.in.: * nagłówek * menu * artykuł * stopkę Każdy z tych elementów z naszego punktu widzenia jest właśnie obiektem. Obiekt CSS to wizualnie samodzielny element strony. Artykuł potrafi wyświetlić się poprawnie bez nagłówka ani stopki serwisu. Taki sposób przedstawiania elementów strony jest dla człowieka bardziej intuicyjny niż pojmowanie jej jako zbiór wielu DIV-ów, SPAN-ów i innych znaczników. Obiektowość CSS sprowadza się do nadawania formatowania w kontekście takich obiektów, a nie poszczególnych znaczników występujących w kodzie źródłowym dokumentu. Pojedynczemu obiektowi zwykle odpowiada klasa CSS albo selektor identyfikatora: > #Header { /* nagłówek */ } .Menu { /* menu */ } .Article { /* artykuł */ } #Footer { /* stopka */ } Warto zwrócić uwagę, że w przypadku stosowania systemów parsowania szablonów na serwerze (np. w języku PHP), każdy obiekt jest kandydatem na zapisanie jego znaczników w osobnym pliku szablonu. ### Atrybuty # Często obiekty nie są na tyle proste, aby można było określić ich wygląd przy pomocy pojedynczej reguły stylów (jednego selektora). Menu nawigacyjne będzie zawierać elementy podrzędne - listę odnośników - którym również musimy przypisać określony styl. Atrybuty stanowią zbiór wszystkich elementów (znaczników) potomnych obiektu, którym jest przypisany styl. > <div class="Menu"> <ul> <li><a href="...">...</a></li> <li><a href="...">...</a></li> <li><a href="...">...</a></li> </ul> </divPowyżej przedstawiony obiekt Menu może składać się z następujących atrybutów: * wykaz ul * punkt wykazu li (jeśli chodzi o stylizację, nie ma znaczenia, ile punktów ma wykaz, ponieważ wygląd dla nich określamy wspólnie) * odnośnik a W arkuszu CSS pełna definicja tej klasy może wyglądać na przykład tak: > .Menu { background-color: white; } .Menu ul, .Menu li { display: block; list-style: none; margin: 0; padding: 0; } .Menu li { float: left; margin-right: 1em; } .Menu a { color: blue; text-decoration: none; } ### Kompozycja # Zwróćmy uwagę, że typowy artykuł może zawierać informacje o: * autorze - np. z jego imieniem, nazwiskiem i zdjęciem * źródle - nazwa, logo i odnośnik Każdy z tych elementów można traktować jako osobny obiekt (zmiana wyglądu informacji o autorze nie powinna wpływać na wygląd samej treści artykułu), z których składa się (ang. composition) główny obiekt artykułu. Myślenie o skomplikowanym obiekcie jako o złożeniu kilku mniejszych, samodzielnych obiektów, ułatwia nam pojmowanie otaczającej nas rzeczywistości. Patrząc na typowy komputer widzimy, że składa się on m.in. z ekranu, klawiatury, urządzenia wskazującego (np. myszki), a nie z masy połączonych ze sobą tranzystorów i innych elementów elektronicznych. Przeciętny człowiek nie byłby w stanie przyswoić tak wielkiej złożoności w postaci pojedynczego modelu. Z punktu widzenia kompozycji w obiektowości CSS chodzi o to, aby rozbijać w myślach skomplikowane obiekty na mniejsze i stylizować je oddzielnie. Korzyścią takiego podejścia będzie możliwość osadzenia np. informacji o autorze na osobnej stronie albo na liście wszystkich autorów piszących w serwisie. Obiekty składowe są szczególnym przypadkiem złożonych atrybutów. > <div class="Article"> <div class="Source">...</div> ... <div class="Author">...</div> </div### Rozszerzanie # W programowaniu zorientowanych obiektowo termin ten tłumaczy się częściej jako "dziedziczenie", jednak celowo używam tutaj innego pojęcia (ang. extends), aby nie myliło się z dziedziczeniem CSS, związanym z kaskadowością stylów. Człowiek od zawsze miał potrzebę kategoryzowania otaczającej go rzeczywistości. Dzięki temu możemy łatwiej i precyzyjniej komunikować się ze sobą. Kategorie znaczeniowe, w jakie grupujemy otaczające nas obiekty, zwykle odzwierciedlają pewną hierarchię, opisującą różne poziomy ogólności poszczególnych pojęć. Na przykład laptop jest rodzajem komputera, a komputer jest rodzajem urządzenia elektronicznego. Z punktu widzenia rozszerzania obiektów w CSS chodzi o to, aby stylizować elementy na różnym poziomie ogólności w zależności od ich przeznaczenia w serwisie. Przykładowo jeśli mamy już gotowy ogólny artykuł: > <div class="Article">...</divale potrzebujemy jeszcze prawie identycznie wyglądającego artykułu recenzji (zawierającego dodatkowo np. ocenę redakcyjną), nie ma sensu tworzyć go od zera. Znacznie lepiej jest wykorzystać całą stylizację zapisaną w ogólnym artykule (Article), a osobno dodać tylko nowe rzeczy (Review): > <div class="Article Review">...</divMówimy, że Article jest klasą bazową, którą rozszerza klasa pochodna Review. Dzięki tej technice, unikając powtórzeń deklaracji, zmniejszysz rozmiary arkusza CSS (szybsze ładowanie, mniejszy transfer), a przede wszystkim przyspieszysz sposób zarządzania zmianami, ponieważ modyfikacja definicji klasy Article od razu zmieni elementy class="Article" oraz class="Article Review", tak aby pasowały do nowego szablonu witryny, a jednocześnie modyfikując klasę Review nie musisz się obawiać, że zepsujesz coś w elementach oznaczonych jako class="Article". Oczywiście możliwe jest rozszerzanie na większej liczbie poziomów zagnieżdżenia. ### Wielokrotne rozszerzanie # Teoretycznie klasa pochodna może rozszerzać więcej niż jedną klasę bazową. Może to jednak wywołać trudne do przewidzenia konsekwencje przy zmianach deklaracji w klasach bazowych. Jeśli koniecznie chcesz skorzystać z tej techniki, klasy bazowe powinny być raczej maksymalnie uproszczone. > <div class="Information Important Warning">...</divW powyższym przykładzie klasa pochodna Warning (ostrzeżenie) ma dwie klasy bazowe: Information (informacja) oraz Important (ważne). Jednocześnie Important nie jest pochodną Information ani na odwrót - są to zupełnie niezależne klasy. Klasa pochodna (Warning) przejmuje stylizację zarówno z klasy Information (np. tekst ujęty w ramkę) jak i Important (np. czerwony tekst albo wytłuszczenie). ### Przesłanianie # Co zrobić, jeśli recenzja - szczególny przypadek ogólnego artykułu - ma wyglądać jednak nieznacznie inaczej od swojego pierwowzoru (klasy bazowej)? Wybrane deklaracje z klasy bazowej można przesłonić (ang. override), przypisując im zmienione wartości w klasie pochodnej. Na przykład: > .Article { color: black; background-color: white; /* ... */ } .Review { color: green; font-size: 12px; /* ... */ } Pamiętaj jednak, że kolejność wymieniania nazw klas w atrybucie `class="..."` z punktu widzenia kaskadowości stylów nie ma znaczenia, dlatego należy zadbać, aby w arkuszu stylów definicja klasy Review znajdowała się później niż Article. Ten prosty zabieg pozwoli nam uzyskać recenzję z zielonym tekstem, przy zachowaniu białego tła oraz ewentualnych wielu innych deklaracji, zdefiniowanych w klasie bazowej. W ten sposób, nawet przy istnieniu drobnych różnic wyglądu, nadal możemy korzystać z techniki rozszerzania cech obiektów, oszczędzając sobie sporo niepotrzebnego pisania. Gdyby jednak oba rodzaje artykułu wyglądały zupełnie inaczej, nie postępuj w ten sposób, gdyż tylko utrudni Ci to pracę. ### Klasa abstrakcyjna # Klasa abstrakcyjna (ang. abstract class) jest przeznaczona wyłącznie do rozszerzania przez klasy pochodne, a nie do samodzielnego użycia w dokumencie. Jeśli w serwisie mamy więcej rodzajów publikacji, zapewne chcielibyśmy, aby każda z nich wyglądała podobnie. Takie wspólne deklaracje stylów możemy zdefiniować w klasie abstrakcyjnej Publication, a potem używać następująco: > <div class="Publication Article">...</div> <div class="Publication Article Review">...</divRożnica pomiędzy zwykłą klasą bazową (np. Article) a klasą abstrakcyjną jest taka, że nigdy w dokumencie nie pojawi się samodzielnie w postaci class="Publication". Mimo tego jest niezwykle przydatna, gdyż dzięki niej w jednym miejscu mamy zebrane deklaracje ogólnie stylizujące wszystkie publikacje w serwisie. ### Singleton # Singleton to jeden ze znanych wzorców projektowych w programowaniu zorientowanym obiektowo. Jego celem jest zapewnienie, że w danym programie nigdy nie powstanie więcej niż jedna instancja określonej klasy. Na gruncie CSS zorientowanego obiektowo można to przyrównać do selektora identyfikatora, ponieważ w pojedynczym dokumencie HTML nie mogą istnieć dwa elementy o takim samym identyfikatorze (z identycznym atrybutem `id="..."` ). ### Polimorfizm # Na koniec jeszcze jedna analogia do terminologii programowania zorientowanego obiektowo, znanego z niemal każdego nowoczesnego języka programowania. Stosowanie kontekstu selektorów można porównać do polimorfizmu, tzn. efekt działania tej samej deklaracji (klasy) zależy od typu elementu, do którego się odwołujemy. Na przykład: > <div class="Information Warning">...</divmoże działać inaczej niż > <span class="Information Warning">...</spanchociaż nazwa przypisanej klasy CSS jest w obu przypadkach identyczna: > .Information { background-color: white; } div.Warning { color: red; } span.Warning { font-weight: bold; } 07.10.2014 16:12 bardzo swietny poradnik Zobacz więcej * kurshtml 17.12.2012 13:02 W tradycyjnych językach programowania wygląda to tak samo. Jeżeli dwie klasy bazowe mają zaimplementowaną metodę o takiej samej sygnaturze, klasa pochodna w wyniku tego nie odziedziczy przecież obu tych metod, bo to jest niemożliwe. W takim przypadku konieczne jest rozstrzygnięcie... Zobacz więcej * Tom 17.12.2012 11:43 Witam Mam wrażenie, że w rozdziale "Wielokrotne rozszerzanie" jest pewien błąd logiczny. Kilka niezależnych klas bazowych sugeruje równoległe/niezależne ładowanie stylów kilku klas, podczas gdy w CSS kolejność jest zawsze ustalona. Jakimś wyjątkiem jest sytuacja, gdy stylizacja w... Zobacz więcej * kurshtml 04.11.2011 17:31 Wreszcie udało mi się zebrać i spisać ogólne wytyczne, którymi powinien kierować się każdy webmaster w swojej codziennej pracy zawodowej: Przykazania webmastera. Jeżeli komuś przyjdzie jeszcze coś na myśl, poza tematami tam poruszanymi, będę wdzięczny za dopisanie tego tutaj. Oczywiście zdaję... Zobacz więcej * jsmp 28.04.2009 17:13 dobry jest też tekst z wikipedi English o Progressive: http://en.wikipedia.org/wiki/Progressive_enhancement Jak widzę przy nim, polską wersję to jest taka uboga :| Zobacz więcej * kurshtml 28.04.2009 14:24 Graceful Degradation & Progressive Enhancement Zobacz więcej * Roberto 12.04.2009 22:01 ad 1 - dodatkowym plusem jest to, że nie musisz dodawać dodatkowej klasy dla inputów-przycisków (jasne - można użyć trochę bardziej 'skomplikowanych'[?] selektorów css, ale wtedy IE6 polegnie, a tego nie chcemy przecież). ad 2 - na pewno warto na to zwrócić uwagę. to już w sumie zostało... Zobacz więcej * kurshtml 12.04.2009 13:25 stray: "menu rozwijane byloby warto dodac, skoro juz o technikach w CSS". Nie jestem pewny, czy założony zakres tematyki to obejmuje. Może kiedyś pomyślę o szerszym rozdziale na temat technik CSS. "Image Replacement" wydaje mi się dobrą praktyką, a nie tylko techniką, o tyle, że można... Zobacz więcej * Roberto 11.04.2009 23:09 o, przypomniała mi się jeszcze jedna przydatna sprawa, a nawet dwie na tyle oczywiste (tak samo jak dropdown wspomniany już przez stray - coś takiego musi się w takim dziale znaleźć bo to podstawy są ;]), że o nich zapomniałem ;) tylko nie wiem czy to nie podchodzi już pod techniki czyli dawanie... Zobacz więcej * jsmp 11.04.2009 22:58 Ja myśle, że dobrze by było w jednym artykule zebrać "Dobre praktyki", czyli np. te markery ktore opisałem w moim tutorialu czy pare innych rzeczy które można wykorzystać w pisanym kodzie CSS. A jako osobny podrozdział już takie tricki czy kurshtml: "osobny rozdział o technikach CSS"... Zobacz więcej (element) Podstawowa konstrukcja składniowa dokumentu. Większość reguł stylów używa nazw tych elementów (takich jak P, TABLE, OL dla HTML), żeby określić ich wygląd. (replaced element) Element dla którego formater stylów zna tylko wymiar wewnętrzny. W języku HTML są to: IMG, INPUT, TEXTAREA, SELECT, OBJECT. Na przykład zawartość elementu IMG jest zastępowana przez obrazek, wyznaczony atrybutem src. (intrinsic dimensions) Szerokość i wysokość które zostały zdefiniowane przez sam element, nie narzucone przez otoczenie. W CSS2 jest założone, że tylko elementy zastępowane przychodzą z wewnętrznym rozmiarem. (attribute) Wartość powiązana z elementem, składająca się z nazwy i związanej wartości (tekstowej). W języku HTML może to być np. href elementu A, określający lokalizację zasobu sieciowego albo src elementu IMG, wskazujący lokalizację pliku obrazka. (content) Zawartość (treść) związana z elementem w dokumencie źródłowym. Nie wszystkie elementy mają zawartość - w takim wypadku są nazywane pustymi (empty). Zawartością elementu może być tekst jak również pewna liczba podelementów, wtedy element nazywany jest rodzicem (parent) tych podelementów. (rendered content) Zawartość elementu po zinterpretowaniu zgodnie z powiązanym arkuszem stylów. Zawartość zinterpretowana elementów zastępowanych przychodzi z zewnątrz dokumentu źródłowego. Zawartością taką może być także alternatywny tekst dla elementu (wartość atrybutu `alt` w składni HTML) czy pozycja wstawiona (domyślnie lub poprzez ścisłe określenie) przez arkusz stylów (np. numerowanie). (rendered content) Zawartość elementu po zinterpretowaniu zgodnie z powiązanym arkuszem stylów. Zawartość zinterpretowana elementów zastępowanych przychodzi z zewnątrz dokumentu źródłowego. Zawartością taką może być także alternatywny tekst dla elementu (wartość atrybutu > NaN > Infinity > undefined > eval(x) > parseInt(string) parseInt(string, radix) > parseFloat(string) > encodeURI(uri) > encodeURI("http://example.com/{test}"); // "http://example.com/%7Btest%7D" encodeURI("\uDC00"); // URIError > encodeURIComponent(uriComponent) > Object() Object(value) > new Object() new Object(value) > Object.prototype.toString() > Object.prototype.toLocaleString() > Object.prototype.valueOf() > Object.prototype.hasOwnProperty(V) > Object.prototype.isPrototypeOf(V) > Object.prototype.propertyIsEnumerable(V) Function() Function(body) Function(p1, p2... pn, body)Działa identycznie jak konstrukcja new Function(...). Komentarze # Zobacz więcej komentarzy > Function.length * Wartość: * `Number` - liczba 1 Ta wartość zawsze wynosi 1. Nie można jej zmienić. Jest niedostępna w pętli `for-in` . ### Przykład Function.length > Function.length; // 1 Function.length = 2; Function.length; // 1 Object.keys(Function); // [] Przejdź do treści > Function.length `Number` - liczba 1 Ta wartość zawsze wynosi 1. Nie można jej zmienić. Jest niedostępna w pętli `for-in` . > Function.length; // 1 Function.length = 2; Function.length; // 1 Object.keys(Function); // [] > Function.prototype.constructor > Function.prototype.toString() > Function.prototype.apply(thisArg) Function.prototype.apply(thisArg, argArray) > Function.prototype.call(thisArg) Function.prototype.call(thisArg, arg1, arg2... argn) > Array() Array(len) Array(item0) Array(item0, item1...) Działa identycznie jak konstrukcja new Array(...). (interpretuje: Internet Explorer 9, Firefox 4, Opera 10.50, Chrome) > Array.isArray(arg) * Parametry * arg - sprawdzany obiekt * Wartość: * `Boolean` - czy obiekt jest tablicą Pozwala sprawdzić, czy podany obiekt jest tablicą. ### Przykład Array.isArray > Array.isArray([]); // true Array.isArray(new Array()); // true Array.isArray(Array()); // true Array.isArray(Array); // false Array.isArray({}); // false Array.isArray(new Object()); // false Array.isArray(true); // false Array.isArray(1); // false Array.isArray("test"); // false Array.isArray(null); // false Array.isArray(undefined); // false Array.isArray(NaN); // false Array.isArray(Infinity); // false > Array.prototype.toString() > Array.prototype.toLocaleString() > Array.prototype.concat() Array.prototype.concat(item1) Array.prototype.concat(item1, item2...) > Array.prototype.join() Array.prototype.join(separator) > Array.prototype.push() Array.prototype.push(item1) Array.prototype.push(item1, item2...) > Array.prototype.reverse() > Array.prototype.slice() Array.prototype.slice(start) Array.prototype.slice(start, end) > Array.prototype.sort() Array.prototype.sort(comparefn) > Array.prototype.splice() Array.prototype.splice(start, deleteCount) Array.prototype.splice(start, deleteCount, item1) Array.prototype.splice(start, deleteCount, item1, item2...) > String() String(value) > String.fromCharCode() String.fromCharCode(char0) String.fromCharCode(char0, char1...) > String.prototype.charCodeAt() String.prototype.charCodeAt(pos) > String.prototype.localeCompare(that) > String.prototype.replace(searchValue, replaceValue) > String.prototype.search(regexp) > String.prototype.slice() String.prototype.slice(start) String.prototype.slice(start, end) > String.prototype.split() String.prototype.split(separator) String.prototype.split(separator, limit) > String.prototype.substring() String.prototype.substring(start) String.prototype.substring(start, end) > new Boolean() new Boolean(value) * Parametry: * value - wartość na podstawie której zostanie utworzony obiekt * Wartość: * `Boolean` - nowa instancja obiektu logicznego Inaczej niż funkcja Boolean, zawsze tworzy nową instancję obiektu logicznego, a nie tylko prostą wartość logiczną. ### Przykład new Boolean > // new Boolean(true): new Boolean(true); new Boolean(1); new Boolean(-1.2); new Boolean(Infinity); new Boolean(-Infinity); new Boolean("test"); new Boolean(" "); new Boolean("null"); new Boolean("false"); new Boolean("0"); new Boolean("undefined"); new Boolean("NaN"); new Boolean([]); new Boolean([false]); new Boolean({}); // new Boolean(false): new Boolean(); new Boolean(undefined); new Boolean(null); new Boolean(false); new Boolean(0); new Boolean(NaN); new Boolean(""); > Boolean.prototype.constructor > Boolean.prototype.toString() > Boolean.prototype.valueOf() > Number() Number(value) > new Number() new Number(value) > Number.MAX_VALUE > Number.MIN_VALUE > Number.NaN > Number.prototype.toString() Number.prototype.toString(radix) > Number.prototype.toLocaleString() > Number.prototype.valueOf() > Number.prototype.toFixed() Number.prototype.toFixed(fractionDigits) > Number.prototype.toExponential() Number.prototype.toExponential(fractionDigits) > Number.prototype.toPrecision() Number.prototype.toPrecision(precision) > Math.LN10 > Math.LOG2E > Math.PI > Math.abs(x) > Math.acos(x) > Math.asin(x) > Math.atan(x) > Math.atan2(y, x) > Math.ceil(x) > Math.cos(x) > Math.exp(x) > Math.floor(x) > Math.log(x) > Math.log(-Infinity); // NaN Math.log(-0.01); // NaN Math.log(0); // -Infinity Math.log(0.5); // -0.6931471805599453 Math.log(1); // 0 Math.log(Math.E); // 1 Math.log(Infinity); // Infinity Math.log(NaN); // NaN > Math.pow(x, y) > Math.sin(x) > Math.sqrt(x) > Math.tan(x) > Date() > Date(); // np.: "Sat Jan 04 2014 17:38:21 GMT+0100" Przejdź do treści > Date() `String` - aktualna data i czas Działa identycznie jak konstrukcja: , tzn. zwraca aktualną datę i czas w postaci tekstowej. > Date(); // np.: "Sat Jan 04 2014 17:38:21 GMT+0100" > new Date() new Date(value) new Date(year, month) new Date(year, month, date) new Date(year, month, date, hours) new Date(year, month, date, hours, minutes) new Date(year, month, date, hours, minutes, seconds) new Date(year, month, date, hours, minutes, seconds, ms) > Date.parse(string) > Date.now() > Date.prototype.toLocaleString() > Date.prototype.toLocaleDateString() > Date.prototype.toLocaleTimeString() > Date.prototype.getFullYear() > Date.prototype.getUTCFullYear() > Date.prototype.getMonth() > Date.prototype.getUTCMonth() > Date.prototype.getHours() > Date.prototype.getTimezoneOffset() > Date.prototype.setMinutes(min) Date.prototype.setMinutes(min, sec) Date.prototype.setMinutes(min, sec, ms) > Date.prototype.setUTCMinutes(min) Date.prototype.setUTCMinutes(min, sec) Date.prototype.setUTCMinutes(min, sec, ms) > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setUTCMinutes(15, 0, 500); // -17655021899500 x; // new Date("1410-07-15T13:15:00.500+02:00") x.setUTCMinutes(90); // -17655017399500 x; // new Date("1410-07-15T14:30:00.500+02:00") x.setUTCMinutes(-30); // -17655020999500 x; // new Date("1410-07-15T13:30:00.500+02:00") Date.prototype.setUTCMinutes.call(null, 0); // TypeError Date.prototype.setUTCMinutes.call(undefined, 0); // TypeError Date.prototype.setUTCMinutes.call(0, 0); // TypeError Date.prototype.setUTCMinutes.call("", 0); // TypeError Date.prototype.setUTCMinutes.call("2000", 0); // TypeError Date.prototype.setUTCMinutes.call({}, 0); // TypeError > Date.prototype.setDate(date) > Date.prototype.setUTCDate(date) > var x = new Date("1410-07-15T00:00:00.000+02:00"); x.setUTCDate(16); // -17654896800000 x; // new Date("1410-07-17T00:00:00.000+02:00") x.setUTCDate(32); // -17653600800000 x; // new Date("1410-08-02T00:00:00.000+02:00") x.setUTCDate(-2); // -17653773600000 x; // new Date("1410-07-30T00:00:00.000+02:00") Date.prototype.setUTCDate.call(null, 0); // TypeError Date.prototype.setUTCDate.call(undefined, 0); // TypeError Date.prototype.setUTCDate.call(0, 0); // TypeError Date.prototype.setUTCDate.call("", 0); // TypeError Date.prototype.setUTCDate.call("2000", 0); // TypeError Date.prototype.setUTCDate.call({}, 0); // TypeError > Date.prototype.setFullYear(year) Date.prototype.setFullYear(year, month) Date.prototype.setFullYear(year, month, date) > Date.prototype.setUTCFullYear(year) Date.prototype.setUTCFullYear(year, month) Date.prototype.setUTCFullYear(year, month, date) > Date.prototype.toJSON() Date.prototype.toJSON(key) > RegExp() RegExp(pattern) RegExp(pattern, flags) * Parametry: * `String|RegExp` pattern - wzorzec (domyślnie: "(?:)") * `String` flags - flagi: * g - dopasowanie globalne * i - ignorowanie wielkości liter * m - dopasowanie wielu linii * Wartość: * `RegExp` - instancja obiektu wyrażenia regularnego * Wyjątki: * `TypeError` - pattern jest typu `RegExp` i argument flags został zdefiniowany * `SyntaxError` - nieprawidłowy wzorzec lub flagi Jeżeli pattern jest instancją obiektu `RegExp` , a argument flags nie został podany (albo wynosi undefined), funkcja zwraca obiekt przekazany jako pattern. W przeciwnym razie następuje wywołanie: new RegExp(...). ### Przykład RegExp > var x = /abc/; RegExp(x) === x; // true RegExp("abc", "i"); // /abc/i RegExp(x, "i"); // TypeError RegExp("("); // SyntaxError RegExp("abc", "x"); // SyntaxError RegExp("abc", "gg"); // SyntaxError > RegExp.prototype.exec(string) > RegExp.prototype.test(string) > RegExp.prototype.toString() > Error() Error(message) Przejdź do treści > Error() Error(message) `String` message - komunikat błędu (domyślnie: "") `Error` - nowa instancja obiektu błędu Działa identycznie jak konstrukcja new Error(...). > Error.prototype.constructor > Error.prototype.name Przejdź do treści > Error.prototype.name `String` - nazwa błędu (domyślnie: "Error") Nazwa obiektu błędu, która zostanie użyta przez metodę toString. > Error.prototype.name; // "Error" new Error().name; // "Error" > Error.prototype.message > Error.prototype.toString() (interpretuje: Internet Explorer 8, Firefox 3.5, Opera 10.50, Chrome) > JSON.parse(text) JSON.parse(text, reviver) * Parametry: * `String` text - tekst w formacie JSON * `Function` reviver - funkcja przekształcająca wartości, przyjmująca argumenty: * `String` key - klucz danych albo pusty tekst * ``` Object|Array|String|Boolean|Number|Null ``` value - wartość danych * Wartość: * `Object` - obiekt * `Array` - tablica * `String` - tekst * `Boolean` - wartość logiczna * `Number` - liczba * `Null` - nic * Wyjątki: * `SyntaxError` - text zawiera błąd składni formatu JSON Przekształca tekst w formacie JSON (ang. JavaScript Object Notation) na wartości proste i obiekty obsługiwane przez JavaScript. JSON jest specjalnym formatem zapisu różnych danych o typach występujących w języku JavaScript, ale z dodatkowymi ograniczeniami. Polegają one m.in. na tym, że wszystkie wartości tekstowe - w tym klucze obiektów - muszą być ujęte w znaki cudzysłowu, a nie apostrofy. Dane muszą być zapisane wprost przy pomocy literałów, a nie z użyciem operatora `new` oraz tworzone w całości za jednym razem bez używania zmiennych pomocniczych. Ponadto w formacie JSON można zapisać tylko następujące typy danych: `Object` , `Array` , `String` , `Boolean` , `Number` , `Null` . Taki format zapisu danych stał się niezwykle przydatny w sytuacji, kiedy zachodzi potrzeba wymiany danych pomiędzy zdalnymi systemami, zaimplementowanymi w różnych językach. Ponieważ sposób zapisu JSON został określony standardem, w wielu językach programowania są dostępne gotowe biblioteki do jego obsługi. Dzięki temu możemy np. w skrypcie JavaScript odwołać się do aplikacji napisanej w PHP, która działa na serwerze, a następnie odczytać dane, które zostaną zwrócone z powrotem do naszego skryptu. Dzięki swojej prostocie, większej odporności na błędy oraz względnie niewielkim narzucie wydajnościowym i objętościowym, JSON w wielu miejscach wypiera XML jako uniweralny standard wymiany danych w heterogenicznym środowisku rozproszonym. Funkcja reviver pozwala dodatkowo przekształcić dane wejściowe. Jest ona wywoływana po kolei dla wartości każdej właściwości danych wejściowych. Wartość `this` w tej funkcji będzie stanowił obiekt, w którym jest zapisany podany klucz. Wartość zwrócona przez funkcję jest następnie umieszczana w danych wyjściowych. W przypadku właściwości obiektów, gdy funkcja zwrotna reviver zwróci wartość undefined albo nie zwróci nic jawnie, podany klucz zostanie usunięty z danych wyjściowych. Nie dotyczy to elementów tablic. ### Przykład JSON.parse > JSON.parse('{"a": 1}'); // {a: 1} var x = '{"a": 1, "b": 2, "c": 3}'; var f = function (key, value) { if (key == "") { return value; } if (value < 3) { return value * 2; } }; JSON.parse(x, f); // {a: 2, b: 4} JSON.parse("{"); // SyntaxError JSON.parse("{a: 1}"); // SyntaxError JSON.parse("{'a': 1}"); // SyntaxError Date: 2015-03-12 Categories: Tags: Przykład [Nowość] [To jest odsyłacz do strony z nowością] Możliwe jest otwarcie jednocześnie kilku nowych okien. Należy wtedy oddzielić średnikami (";") kolejne polecenia Dlatego dobrze się zastanów, czy otwieranie nowych okien na pewno jest Ci absolutnie niezbędne i czy nie przyniesie czasem więcej strat niż korzyści. Zresztą przez nadużywanie podobnych skryptów, przeglądarki zaczęły na stałe blokować otwieranie "wyskakujących okienek", które zwykle były używane w celach reklamowych. # Co to są klasy w CSS? Klasy w CSS to nazwy, które w postaci atrybutu `class="..."` przypisuje się elementom HTML w celu zastosowania do nich określonych stylów. Klasy pozwalają na definiowanie zbioru elementów, które mają być stylizowane w ten sam sposób. Przykład: # Jak wywołać klasę w CSS? Aby wywołać klasę w CSS, używa się kropki przed nazwą klasy. Następnie, w elemencie HTML, który ma zostać stylizowany, dodaje się atrybut `class="..."` z nazwą klasy. Przykład: i ``` <div class="klasa">Treść</div> ``` # Jak nazywać klasy w CSS? Klasy w CSS mogą być nazwane dowolnie, ale dobrze jest stosować opisowe i zrozumiałe nazwy, które odzwierciedlają funkcję lub rolę elementów. Na przykład, zamiast `.a` lepiej użyć `.naglowek` , co ułatwia zrozumienie kodu i stylów. # Czym się różni CLASS od ID? Różnica między CLASS a ID polega na tym, że atrybut `class="..."` może być używany wielokrotnie na stronie dla wielu elementów, podczas gdy `id="..."` powinno być unikalne i używane tylko raz dla danego elementu w tym samym pliku HTML. Klasy pozwalają na grupowanie elementów o podobnych właściwościach i stosowanie do nich tych samych stylów, natomiast ID identyfikuje unikalny element na stronie. > selektor.klasa { cecha: wartość } > <selektor class="klasa1 klasa2 klasa3...">...</selektor> > selektor.klasa1.klasa3 { cecha: wartość } Źródło: CSS Cascading and Inheritance Level 4 all # Resetowanie wszystkich cech Wartość Resetowanie wszystkich cech Aby zastosować taki skrypt, należy na stronie głównej do znacznika `<iframe>...</iframe>` dodać atrybut `id="autoiframe"` , np.: > <iframe src="..." name="..." id="autoiframe" width="100%" height="560">...</iframe> UWAGA!Pamiętaj, aby podać taką wysokość ramki ( `height="..."` ), która będzie wygodna w przypadku, gdyby skrypt nie zadziałał! Teraz na wszystkie podstrony, które będą wczytywane do ramki lokalnej, należy wstawić następujący kod (trzeba to zrobić koniecznie w nagłówku dokumentu, czyli w ramach <head>...</head>): > <script src="autoiframe.js"></script> Następnie na samym końcu podstrony (tuż przed znacznikiem zamykającym `</body>` ) należy wkleić kod: > <script> autoiframe(null, 200); </script> W wyróżnionym miejscu (w nawiasie) można podać wartość dodatkowego wstępnego "marginesu" pionowego na końcu podstrony. Jest on szczególnie przydatny, jeśli na stronie znajdują się zdjęcia o niezdefiniowanych wymiarach za pomocą atrybutów `width="..."` oraz `height="..."` znacznika <img>. W takim przypadku margines ten należy dobrać na tyle duży, aby podczas doczytywania obrazów - a tym samym stopniowej zmiany wysokości treści - nie pojawił się pionowy suwak do przewijania ramki. Jest to tylko wartość wstępna (tymczasowa), ponieważ po wczytaniu wszystkiego, wysokość i tak się automatycznie dopasuje w drugim kroku. Jeśli chcemy zrezygnować z podawania marginesu, należy po prostu zupełnie pominąć wstawianie tej części kodu na podstronach. Ostatnim krokiem będzie stworzenie nowego pliku autoiframe.js (w tym samym katalogu co podstrony) i zapisanie w nim: > /** * @author <NAME> {@link https://www.kurshtml.edu.pl} * @copyright NIE usuwaj tego komentarza! (Do NOT remove this comment!) */ // Domyślny identyfikator IFRAME: var autoiframe_id = 'autoiframe'; // Domyślny dolny margines: var autoiframe_margin = 50; var autoiframe_timer = null; function autoiframe(id, margin) { if (parent != self && document.body && document.body.offsetHeight && document.body.scrollHeight) { clearTimeout(autoiframe_timer) if (typeof id != 'undefined' && id) autoiframe_id = id; parent.document.getElementById(autoiframe_id).height = 1; autoiframe_timer = setTimeout("parent.document.getElementById(autoiframe_id).height = Math.max(document.body.offsetHeight, document.body.scrollHeight) + " + (typeof margin == 'undefined' || isNaN(parseInt(margin)) ? autoiframe_margin : parseInt(margin)), 1); } } if (window.addEventListener) window.addEventListener('load', function() { autoiframe(); }, false); else if (window.attachEvent) window.attachEvent('onload', function() { autoiframe(); }); * autoiframe * Domyślna wartość atrybutu `id="..."` ramki `<iframe>...</iframe>` na stronie nadrzędnej, której wysokością chcemy sterować. * 50 * Dodatkowy ostateczny "margines" pionowy na końcu podstrony, na wypadek gdyby dobrana automatycznie wysokość była jednak trochę za mała, co skutkowałoby wyświetleniem paska przewijania ramki lokalnej. Został on dobrany tak, aby nie był zbyt niski w większości przeglądarkach, jednak jeśli zajdzie potrzeba, można go oczywiście zwiększyć. Należy zauważyć, że zwykle będzie on miał wartość mniejszą niż analogiczny parametr wstępny wpisywany we wcześniejszym bloku kodu na końcu każdej z podstron, ponieważ określa margines już po wczytaniu wszystkich obrazów i innych elementów strony. Jest to wartość ostateczna tego parametru i nie będzie ona już dalej zmieniana. Czasami zachodzi potrzeba umieszczenia na jednej stronie kilku ramek `<iframe>...</iframe>` , których wysokość powinna się automatycznie dopasowywać do zawartości. Oczywiście dla każdej takiej ramki proces dostosowywania wysokości musi zachodzić niezależnie. Aby to zrobić, należy dla każdej takiej ramki należy ustawić odrębny identyfikator `id="..."` . Na przykład tak mógłby wyglądać fragment strony głównej serwisu: > <iframe src="..." name="..." id="autoiframe" width="100%" height="560">...</iframe> <iframe src="..." name="..." id="autoiframe2" width="100%" height="560">...</iframe> Nic nie stoi na przeszkodzie, aby wstawić więcej niż dwie ramki `<iframe>...</iframe>` - każda kolejna z innym identyfikatorem `id="..."` . Następnie na końcu wszystkich podstron wczytywanych do ramki `id="autoiframe"` - nazwijmy ją ramką główną - umieszczamy taki kod jak poprzednio, tzn.: > <script> autoiframe(null, 200); </script>lub > <script> autoiframe('autoiframe', 200); </script> Natomiast na podstronach, które będą wczytywane do ramki `id="autoiframe2"` , umieszczamy, również na końcu, nieco zmienioną formę kodu, podając w nim wartość identyfikatora tej właśnie ramki (wstawioną w apostrofach): > <script> autoiframe('autoiframe2', 200); </script* * * zastępuje dowolny fragment wyrazu (również pusty) * ? * zastępuję dokładnie jedną literę Wieloznaczniki są przydatne, jeśli znamy tylko pewną część wyrazu, co zwykle ma miejsce, kiedy chcemy odszukać wszystkie odmiany wybranego słowa. Dzięki temu po wpisaniu> języ* , odnalezione mogą być hasła, które zawierają wyrazy: > język , > językiem , > języku , > języczek itd. Natomiast > języ? pasuje tylko do > język . Wpisanie > wyraz* , spowoduje odszukanie zarówno po prostu słowa > wyraz , jak i np. > wyrazy , ale już zapis > wyraz? nie obejmuje słowa > wyraz . Symbole wieloznaczników można wykorzystywać w dowolnym miejscu szukanych wyrazów, nie tylko na końcu, np. > *języ* pasuje zarówno do słowa > język , jak i > wielojęzyczny . Po jego wpisaniu, na stronie nie zostanie wyświetlony normalny indeks, ale fragment kodu skryptu z hasłami ułożonymi alfabetycznie. Wystarczy ten kod skopiować, wkleić w odpowiednie miejsce do pliku indeks_hasla.js i na koniec usunąć wartość opcji (wraz z końcowym przecinkiem przed zamknięciem nawiasu). Date: 2023-06-04 Categories: Tags: Co to jest nagłówek, a co ciało dokumentu? Jak dodać do dokumentu dodatkowe informacje, mówiące o jego charakterze? * Język strony <html langJak określić w jakim języku (mówionym) jest napisana strona WWW? * Tytuł strony <titleJak zmienić tytuł strony, który wyświetla się na górze okna przeglądarki oraz w wyszukiwarkach sieciowych? * Deklaracja strony kodowej <meta charsetO czym nie należy zapominać pisząc stronę WWW po polsku? * Opis zawartości strony <meta descriptionW jaki sposób zachęcić internautów aby odwiedzili Twoją stronę? Jak wstawić opis, który wyświetli się w wyszukiwarkach (Google)? * Wyrazy kluczowe <meta keywordsW jaki sposób podwyższyć pozycję strony WWW w wyszukiwarkach (Google)? * Autor strony <meta author creator publisherGdzie wpisać autora strony WWW? * Edytor <meta generatorJak wstawić informację o edytorze użytym przy tworzeniu strony WWW? * Roboty <meta robots googlebotJak zablokować indeksowanie zdjęć lub plików z określonego katalogu? * Strona kanoniczna <link canonicalW jaki sposób pozbyć się zduplikowanych (powielonych) stron z wyników wyszukiwania? * Skalowanie strony <meta viewportW jaki sposób przeskalować rozmiar strony WWW? Jak przygotować stronę RWD (Responsive Web Design)? * Automatyczne odświeżanie strony <meta refreshCo zrobić, aby strona WWW była automatycznie odświeżana co określony czas? * Automatyczne wczytanie strony <meta refresh urlJak wstawić przekierowanie na stronie WWW, czyli automatycznie wczytać inną stronę? * Ikona strony <link iconW jaki sposób wstawić ikonę obok adresu strony WWW? * Nawigacja <link prev next help search author license alternatePolecenie to pozwala podać, w jakim języku jest napisana Twoja strona internetowa, np.: pl - polski, en - angielski, de - niemiecki, fr - francuski, it - włoski, es - hiszpański i inne [zobacz: Skróty nazw jezyków]. Nie należy również zapominać o zadeklarowaniu odpowiedniej dla wybranego języka strony kodowej. Zwracam uwagę, że w dokumencie HTML może się znajdować tylko jeden element `<html>` . Dlatego powyższy atrybut `lang="..."` należy przypisać do już istniejącego znacznika, a nie dodawać kolejnego. Wskazuje on na język, w jakim jest napisana treść zawarta na stronie. Na przykład `lang="pl"` oznacza język polski, `lang="en"` - angielski, `lang="de"` - niemiecki, `lang="fr"` - francuski, `lang="it"` - włoski, `lang="es"` - hiszpański. > <head> <title>Tytuł strony</title> </head. Należy jednak przy tym pamiętać, że w pliku *.html może się znajdować tylko jeden nagłówek dokumentu. Zatem deklarację strony kodowej dodajemy wewnątrz istniejącego elementu, a nie wstawiamy nowego! > <head> <meta name="description" content="Tu podaj opis twojej strony"> </head> Polecenie to należy wstawić między znacznikami: `<head>` oraz `</head>` . Pozwala ono opisać co znajduje się na Twojej stronie. Z informacji tej korzystają wyszukiwarki sieciowe, dlatego staraj się tutaj wpisać tekst, który jak najlepiej opisze zawartość strony i zachęci do jej odwiedzenia. Ciekawy, ale niezbyt długi, opis może zachęcić internautów do obejrzenia Twojej strony. Znacznik . Należy jednak przy tym pamiętać, że w pliku *.html może się znajdować tylko jeden nagłówek dokumentu. Zatem opis strony dodajemy wewnątrz istniejącego elementu, a nie wstawiamy nowego! Ponadto w pliku *.html powinien się znajdować tylko jeden opis strony. > <head> <meta name="keywords" content="wyraz1, wyraz2, wyraz3..."> </head> Polecenie to należy wstawić między znacznikami: `<head>` oraz `</head>` . Pozwala Ci ono podać wyrazy kluczowe, z których korzystają wyszukiwarki sieciowe. Dlatego staraj się tutaj wpisać wyrazy, które jak najlepiej opiszą zawartość Twojej strony. Dobrze dobrane wyrazy kluczowe, pomogą wyszukiwarkom odnaleźć Twoją stronę. Znacznik * Autor > <head> <meta name="author" content="Tu wpisz swoje imię i nazwisko"> </head> * Twórca > <head> <meta name="creator" content="Tu wpisz nazwę organizacji"> </head> * Wydawca > <head> <meta name="publisher" content="Tu wpisz nazwę wydawcy"> </head> Polecenie to należy wstawić między znacznikami: `<head>` oraz `</head>` . Pierwsze z nich ("author") pozwala podać informację o fizycznej osobie będącej autorem strony, natomiast drugie ("creator") i trzecie ("publisher") - odpowiednio: informację o nazwie organizacji i wydawcy strony. Wydawca to firma lub instytucja, której główną działalnością jest publikowanie treści, podczas gdy organizacja może się zajmować również czymś innym. > <head> <meta name="generator" content="nazwa edytora"> </headPozwala określić nazwę edytora HTML, który został wykorzystany do utworzenia dokumentu. Dzięki temu dokument HTML zostanie wyświetlony w taki sposób, aby nie wymagał od użytkownika dalszego powiększania. W przeciwnym razie przeglądarka mobilna starałaby się wyświetlić stronę w rozdzielczości typowej dla przeglądarek używanych na standardowych komputerach, co zwykle oznaczałoby zdecydowanie zbyt mały rozmiar tekstu, aby nadawał się do wygodnego czytania. > <head> <meta http-equiv="refresh" content="s"> </head> Polecenie to pozwala na automatyczne odświeżanie strony, co pewien określony przedział czasu (podany w sekundach). Powinno być wstawione w treści nagłówkowej dokumentu - między znacznikami: `<head>` oraz `</head>` . Nie należy przesadzać z odświeżaniem strony, ponieważ irytuje to użytkowników, a nawet może uniemożliwić czytanie! ### Przykład <meta refresh. Należy jednak przy tym pamiętać, że w pliku *.html może się znajdować tylko jeden nagłówek dokumentu. Zatem znacznik odświeżenia strony dodajemy wewnątrz istniejącego elementu, a nie wstawiamy nowego! Pamiętaj również, że zbyt krótki czas odświeżania strony może spowodować nadmierne użycie łącza internetowego użytkowników oraz dodatkowe obciążenie serwera z Twoją stroną, przez co strona może zacząć działać wolniej. > <head> <meta http-equiv="refresh" content="s; url=Tu podaj adres strony lub ścieżkę dostępu"> </head. Należy jednak przy tym pamiętać, że w pliku *.html może się znajdować tylko jeden nagłówek dokumentu. Zatem znacznik przekierowania dodajemy wewnątrz istniejącego elementu, a nie wstawiamy nowego! (interpretuje: Internet Explorer, Firefox, Opera 7, Chrome) > <head> <link rel="shortcut icon" href="adres ikony"> </head* RSS > <link rel="alternate" title="Tytuł kanału" href="adres kanału" type="application/rss+xml"> * Atom > <link rel="alternate" title="Tytuł kanału" href="adres kanału" type="application/atom+xml"> `title="..."` ), ponieważ inaczej użytkownik nie będzie mógł rozróżnić, co chciałby subskrybować. Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu HTML. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. . Trzeba jednak przy tym pamiętać, że w pliku *.html może się znajdować tylko jeden nagłówek dokumentu. Zatem ikonę dodajemy wewnątrz istniejącego elementu, a nie wstawiamy nowego! Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego HTML. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. * Wyświetlanie Jakie są podstawowe modele wyświetlania znaczników HTML? * Akapit <pW jaki sposób układać tekst na ekranie? Jak dodać nowy akapit? Czym różni się akapit od paragrafu? * Tytuł <h1, h2, h3, h4, h5, h6Jak wstawić tytuł (nagłówek) na stronie WWW? W jaki sposób wyświetlić "dymek narzędziowy" po wskazaniu tekstu myszką? * Blok <divJak zgrupować elementy w blok? * Koniec linii <brW jaki sposób pogrubić (wytłuścić) tekst na stronie WWW? * Pochylenie <iW jaki sposób pochylić tekst na stronie WWW (kursywa)? * Podkreślenie <uW jaki sposób podkreślić tekst na stronie WWW? * Przekreślenie <sW jaki sposób przekreślić tekst na stronie WWW? * Wyróżnienie <em, strongJak wyróżnić tekst na ekranie (emfaza)? * Indeks górny i dolny <sup, subJak wstawić indeks górny i dolny przy tekście? * Czcionka pomniejszona <smallW jaki sposób pomniejszyć tekst? * Tekst preformatowany <preJak wprowadzić tekst preformatowany, czyli taki, który wygląda identycznie jak w edytorze tekstowym? * Kod komputerowy <codeJak oznaczyć kod komputerowy? * Klawiatura <kbdJak oznaczyć tekst, który użytkownik powinien wprowadzić z klawiatury? * Przykład <sampJak oznaczyć tekst, będący przykładem działania programu lub skryptu? * Zmienna <varJak oznaczyć zmienną lub argument programu? * Cytat <cite, qJak powinno się wprowadzać cytaty i odniesienia do źródła? * Blok cytowany <blockquoteJak wprowadzić dłuższy cytat? * Adres <addressJak umieścić na stronie WWW informacje kontatkowe z autorem? * Zmiany <ins, delJak powinno się oznaczać skróty i akronimy? * Definicja <dfnJak oznaczyć definicję terminu? * Słownik <dl, dt, ddJak wprowadzić na stronę WWW słownik (listę definicyjną)? * Wykaz <ul, ol, liJak wprowadzić na stronę wykaz: wypunktowanie (lista nieuporządkowana) lub numerowanie (lista uporządkowana)? * Zagnieżdżanie wykazów W jaki sposób zrobić listę punków i podpunktów (wykaz)? * Pozioma linia <hrJak umieścić poziomą linię, oddzielającą sąsiednie akapity? * Komentarz HTML W jaki sposób ukryć przed użytkownikiem wybrany tekst? * Blokada indeksowania fragmentów treści <... data-nosnippetJak zablokować wybrane fragmenty treści na stronie przed pojawianiem się w wynikach wyszukiwania Google? * Kod poprawny semantycznie Co to znaczy, że kod HTML jest poprawny semantycznie i dlaczego jest to takie ważne? * Powtórka wyświetlanie: w bloku * Akapit jest to część tekstu objęta znacznikami: `<p>...</p>` . Następujące bezpośrednio po sobie akapity są oddzielone przerwą w tekście (pustą linią). Dzięki umieszczaniu w kolejnych akapitach treści nieco różniącej się tematycznie, strona stanie się bardziej estetyczna oraz czytelniejsza. Jeżeli przed akapitem lub serią akapitów postawimy znak paragrafu § (w kodzie źródłowym reprezentowany przez znak specjalny &sect;) z ewentualnym numerem porządkowym, to taki fragment tekstu nosi nazwę paragraf. Zwykle odnosi się on do przepisów prawnych. * Akapit (paragraf) jest znacznikiem specyficznym - jest wyświetlany w bloku, ale nie może zawierać innych elementów blokowych (włączając w to inne paragrafy). Może natomiast zawierać zwykły tekst oraz elementy wyświetlane w linii. ### Przykład <pPolecenie to wydziela większy blok tekstu. W odróżnieniu od akapitu, blok może zawierać wewnątrz siebie inne elementy wyświetlane w bloku. Kolejne bloki są oddzielane od siebie znakami nowej linii, ale nie są dodawane linijki przerwy (aby je dodać, należy zastosować znacznik <p>...</p> albo <br>). ### Przykład <divJest to bardzo przydatny znacznik. Używamy go, gdy chcemy natychmiast zakończyć linię i przejść do następnej (wszystkie normalne znaki końca liniii są ignorowane przez przeglądarkę). ### Przykład <br Tu jest pierwsza linia<br>Tu jest druga linia...<br><br><br> ...a tu następna. > <b>...</bZnacznik ten pozwala pogrubić (wytłuścić) część tekstu (ang. "bold"). Oznacza on treść, na którą należy zwrócić uwagę z powodów czysto użytkowych. Nie nadaje dodatkowej ważności treści ani nie stawia akcentu wypowiedzi. Przydatne przy oznaczaniu słów kluczowych w tekście albo wprowadzenia na początku artykułu. Ten tekst jest pogrubiony (wytłuszczony) > <i>...</iPozwala napisać tekst pismem pochylonym, czyli kursywą (ang. "italic"). Oznacza np. termin techniczny, idiom z innego języka albo fragment wtrąconego tekstu. Pozwala podkreślić fragment tekstu (ang. "underline"). Oznacza nieartykułowany tekst albo oznaczenie błędu ortograficznego. ### Podkreślenie innym kolorem # # Przykład <u {color}To jest czarne podkreślenie czerwoną linią > <s>...</sPozwala przekreślić część tekstu. Oznacza treść, która nie jest dłużej trafna lub istotna z punktu widzenia pozostałej zawartości dokumentu. ### Przykład <sTen tekst jest przekreślony ### Przekreślenie innym kolorem # ### Przykład <s {color}To jest czarne przekreślenie czerwoną linią Domyślnie tekst na stronie internetowej jest napisany zwykłą czcionką. Aby skreślić fragment tekstu, wystarczy umieścić go wewnątrz znacznika `<s>...</s>` . W ten sposób często oznacza się treść, która jest już nieaktualna albo przestała być istotna. wyświetlanie: w linii * Indeks górny > <sup>...</sup> * Indeks dolny > <sub>...</subUmożliwia wprowadzenie indeksów (górnych lub dolnych) przy cyfrach i literach. ### Przykład <sup, subindeks<sup>górny</supindeks<sub>dolny</sub. > <small>...</smallWprowadza tekst napisany pomniejszoną czcionką. Reprezentuje przypisy (wyjaśnienia, zastrzeżenia, ograniczenia prawne, prawa autorskie). Wpisując powyższe znaczniki (tego samego rodzaju) jeden wewnątrz drugiego (np.: ``` <small><small>...</small></small> ``` ), można zmniejszyć rozmiar tekstu o kilka wielkości. To jest zwykły tekst... a ten tekst jest napisany czcionką pomniejszoną (small) > <pre>...</prevar data = new Date(); document.write(data); > <kbd>...</kbdWprowadza na ekran tekst, wskazując, że użytkownik powinien wprowadzić go z klawiatury. Zwykle formatowanie tego elementu jest identyczne jak w przypadku kodu komputerowego. ### Przykład <kbdDla strony głównej serwisu internetowego należy utworzyć plik i nadać mu nazwę: <kbd>index.html</kbd> > <samp>...</sampPozwala wprowadzić do dokumentu tekst, będący przykładem wyniku wygenerowanego przez program, skrypt itp. Zwykle działa analogicznie jak <code>. ### Przykład <samp<samp>To jest przykład użycia znacznika "samp"</samp> > <var>...</var* Odniesienie do źródła > <cite>...</citeZwykle jest napisany kursywą. Można w nim umieścić np. tytuł książki, opracowania, wiersza, piosenki, filmu, gry komputerowej czy obrazu, do którego się odnosimy, ale nie sam cytat. * Krótki cytat > <q>...</qPrzeglądarki zwykle automatycznie ujmują tekst tego znacznika w znaki cudzysłowu (Internet Explorer 7.0 ani wcześniejsze wersje tego nie robią, natomiast w MSIE 8.0 wszystko jest już w porządku, ale tylko w trybie Standards Compliance), dlatego nie należy wstawiać dodatkowych cudzysłowów ręcznie. Umieszcza się w nim treść krótkich cytatów, które nie zawierają żadnych akapitów. Jeśli chcemy zacytować dłuższy fragment tekstu z kilkoma paragrafami, powinniśmy wykorzystać znacznik <blockquote>...</blockquote>. ### Przykład <cite, q > <cite><NAME></cite> powiedział: <q>Dwie rzeczy nie mają granic: wszechświat i ludzka głupota.</q> <NAME> powiedział:> Dwie rzeczy nie mają granic: wszechświat i ludzka głupota. > Więcej informacji znajduje się w opracowaniu <cite>[HTML 4.01 Specification]</citeWięcej informacji znajduje się w opracowaniu [HTML 4.01 Specification] Wprowadza blok informacji kontaktowych z autorem. Może to być np. adres e-mail lub zwykły adres pocztowy - o ile należy do autora artykułu. Nie należy stosować tego elementu do tworzenia listy adresów w formie książki adresowej. Blok taki nie uwzględnia tabulatorów, dodatkowych spacji ani znaków końca linii. W przeglądarkach najczęściej jest automatycznie napisany czcionką pochyłą. ### Przykład <addressAutor: <NAME> <EMAIL> * Treść wstawiona > <ins>opis</ins> * Treść usunięta > <del>opis</del> Pozwala podać informację o wprowadzonych na stronie zmianach. Jeśli ostatnio dodane zostały jakieś nowe rozdziały, aby o tym zakomunikować, opis tych zmian można wpisać do znacznika `<ins>` (taki tekst może zostać automatycznie podkreślony). Natomiast do znacznika `<del>` wpisujemy opis usuniętych rozdziałów, które nie są już dostępne (zwykle tekst przekreślony). ### Przykład <ins, del ~~Rozdział o trójwymiarowych całkach krzywoliniowych, nie jest już dostępny ;-)~~ prof. WWW > <dfn>...</dfnWprowadza definicję jakiegoś terminu, która zwykle jest napisana kursywą. (zobacz także: Słownik). Znacznikiem tym powinien być objęty tylko definiowany termin, a nie cała treść definicji. ### Przykład <dfn<dfn>Atrybut</dfn> to wartość powiązana z elementem, składająca się z nazwy i związanej wartości (tekstowej). > <dl> <dt>Pierwszy termin</dt><dd>Definicja pierwszego terminu</dd> <dt>Drugi termin</dt><dd>Definicja drugiego terminu</dd> <dt>Trzeci termin</dt><dd>Definicja trzeciego terminu</dd> </dl. > <!-- Treść komentarza --Jak stworzyć przejście do innej strony WWW (linki)? * Do podstrony <a hrefW jaki sposób przenieść użytkownika do jednej z podstron serwisu? * Do etykiety <a idJak stworzyć formę elektronicznej zakładki na stronie? * Do adresu internetowego <a http httpsW jaki sposób wstawić linki do innych stron w sieci? * Odsyłacz pocztowy <a mailtoJak wstawić adres e-mail na stronie WWW? * Odsyłacz FTP <a ftpJak zrobić bezpośredni odsyłacz do pliku na serwerze FTP? * Komunikatory internetowe <a gg skype xmpp icqW jaki sposób wstawić na stronie WWW odsyłacz: Gadu-Gadu, Skype, Jabber, ICQ? Jak wstawić status Gadu-Gadu, Tlen, Jabber itp. na stronie WWW? * Inne <a news nntp newsrc telnet ssh javascript wais gopherJak wstawić na stronie WWW odsyłacz: grupy dyskusyjnej (news), NNTP, newsrc, telnet, SSH, JavaScript, Gopher, WAIS? * Odsyłacz obrazkowy <a href, img, map, areaW jaki sposób wstawić na stronie WWW odnośnik (link, hiperłącze, odsyłacz hipertekstowy) obrazkowy (graficzny), czyli klikalny przycisk? * Blokada indeksowania odsyłaczy <a nofollow ugc sponsoredJak zablokować indeksowanie wybranych odnośników ze strony przez wyszukiwarki sieciowe? * Powtórka Umieszczanie na swojej stronie nieoznaczonych płatnych linków reklamowych jest niezgodne z wytycznymi Google. Karą za takie postępowanie może być ręczne obniżenie pozycji strony w wynikach wyszukiwania albo nawet usunięcie z nich całego serwisu. Dlatego jeśli chcemy umieścić na własnej stronie płatne odnośniki sponsorowane, koniecznie należy je oznaczyć atrybutem `rel="sponsored"` . Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu HTML. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. . Należy pamiętać, że w tym samym dokumencie HTML co prawda może być wstawiona dowolna liczba różnych map odsyłaczy, ale każda z nich musi mieć inną nazwę. W przeciwnym razie przeglądarka nie wiedziałaby, która z nich odnosi się do wskazanego obrazka. Nie można również przypisać więcej niż jednej mapy odsyłaczy do tego samego obrazka. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego HTML. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. * Struktura tabeli <table, tr, tdJak wstawić tabelkę na stronę WWW? * Komórki nagłówkowe tabeli <thJak powinno się tworzyć nagłówek tabeli? * Tytuł tabeli <captionJak wstawić tytuł (podpis) tabeli? * Łączenie komórek tabeli <td colspan rowspanW jaki sposób połączyć kilka komórek tabeli w jedną dużą? * Łączenie wierszy tabeli w grupy <thead, tbody, tfootW jaki sposób połączyć kilka wierszy tabeli w grupę funkcjonalną? Jak wydzielić nagłówek i stopkę tabeli? * Łączenie kolumn tabeli w grupy <colgroup, colW jaki sposób połączyć kilka kolumn tabeli w grupę funkcjonalną? * Zagnieżdżanie tabel Jak stworzyć tabelę podrzędną? * Powtórka W tym celu wewnątrz znacznika wybranej komórki `<td>...</td>` tabeli nadrzędnej wstawiamy znacznik tabeli podrzędnej `<table>...</table>` wraz z całą jego zawartością - tzn. wewnętrznymi wierszami `<tr>...</tr>` i zawartymi w nich komórkami wewnętrznymi. Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu HTML. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. * Obrazek <imgJak wstawić obrazek (grafikę, zdjęcie, fotografię, ilustrację) na stronę WWW? * Osadzenie pliku <embedJak osadzić na stronie WWW plik multimedialny: animację, film, muzykę (wav, mid, avi, ra, mp3, mpg, mov, asf i inne)? * Uniwersalny sposób odtwarzania plików <a jpg avi wav txt doc rtf xls pdf, objectJak wstawić odtwarzacz multimedialny (filmy, muzyka) na stronę WWW? Jak wstawić na stronę pliki do pobrania (dział download)? * Powtórka Jak wstawić na swojej stronie widżet (widget) - np. filmik z YouTube'a albo post z Facebooka czy Twittera? * Ramki lokalne <iframeJak wstawić ramkę (okienko, widżet) bezpośrednio w treści strony WWW? * Wczytywanie strony do ramki lokalnej <a targetCo zrobić, aby strony z menu wczytywały się do ramki umieszczonej bezpośrednio w treści? * Ostrzeżenie przed ramką Jak poinformować użytkownika, że spis treści ramek znajduje się na innej stronie? Jak nie dopuścić do wczytania niekompletnych ramek? * Szablon strony bez ramek Jak umieścić menu serwisu w osobnym pliku, tak aby w przypadku modyfikacji nie trzeba było go zmieniać na każdej podstronie? * Powtórka Każdy dokument podstrony musi posiadać odpowiadający sobie plik z różniącym się kodem nagłówkowym. Plik ten musi znajdować się w tym samym katalogu co podstrona i nazywać się identycznie, tylko do nazwy trzeba na końcu dodać przyrostek .html. Przykładowo: dokument podstrona.shtml musi posiadać w tym samym katalogu plik podstrona.shtml.html, którego zawartość może być następująca: > <title>Tytuł strony</title> UWAGA!Jeżeli zapomnisz utworzyć takiego pliku albo pomylisz jego nazwę, w szablonie strony wyświetlą się błędy, a nawet w ogóle może się on nie wyświetlić. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego HTML. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. Do czego są przydatne formularze elektroniczne na stronach WWW? * Ramy formularza <formJak wstawić formularz na stronę WWW? Co można uzyskać obsługując formularze przez skrypty? W jaki sposób sprawdzić, czy użytkownik wypełnił wszystkie pola formularza? * Pole tekstowe <input textJak wprowadzić pole, w którym można wpisać hasło? * Pole wyboru <input checkboxJak dać użytkownikowi możliwość wyboru kilku bądź jednej odpowiedzi? W jaki sposób zaznaczyć pole wyboru po kliknięciu tekstu opisu? W jaki sposób zdefiniować klawisz skrótu? Jak odblokować pole formularza dopiero po wybraniu określonej opcji? * Pole opcji <input radioJak wprowadzić na stronę WWW "przełącznik" (pole opcji)? * Lista rozwijalna <select, option, optgroupJak wprowadzić rozwijane menu? * Obszar tekstowy <textareaJak wprowadzić wieloliniowe pole tekstowe, w którym można wpisać dłuższy komentarz? * Selektor plików <input fileW jaki sposób umożliwić użytkownikowi wybranie pliku ze swojego dysku lokalnego? * Ukryte dane <input hiddenJak przesłać ukryte dane w formularzu? * Wysłanie formularza <input submit imageJak wysłać formularz? * Wyczyszczenie danych <input resetJak wyczyścić wszystkie wprowadzone dane w formularzu? W jaki sposób zapobiec omyłkowemu wyczyszczeniu danych formularza? * Przycisk <buttonJak wprowadzić przycisk na stronę WWW? * Grupowanie pól <fieldset, legendW jaki sposób zgrupować tematycznie klika pól formularza? * Forma odszyfrowana <form enctype accept-charsetCo zrobić, aby formularze były przesyłane w formie odszyfrowanej, którą łatwiej później odczytać? Jak usunąć polskie znaki z formularza? * Przykład formularza Jak wygląda przykładowy formularz? * Alternatywny sposób wysłania formularza W jaki sposób zabezpieczyć się przed błędem w niektórych systemach operacyjnych, uniemożliwiającym wysyłanie formularzy pocztowych? * Wysłanie formularza bez programu pocztowego Jak wysłać formularz na wskazany adres e-mail bez używania programu pocztowego? * Powtórka Jednak często zmiana strony kodowej dokumentu z formularzem nie jest najlepszym rozwiązaniem, ponieważ cała reszta serwisu byłaby zapisana inaczej niż ten jeden dokument. Zmiana kodowania znaków systemu odbierającego dane z formularza może w ogóle nie wchodzić w grę - możemy nie mieć wpływu na stronę kodową systemu operacyjnego, programu pocztowego czy skryptu na serwerze. W takiej sytuacji wystarczy zdefiniować, jakiej strony kodowej używa system odbierający dane, a przeglądarka podczas wysyłania formularza powinna automatycznie skonwertować cały tekst. Na przykład, jeśli nasza strona jest zapisana przy użyciu kodowania znaków utf-8, ale wiemy, że system, do którego wysyłamy formularz używa kodowania windows-1250, powinniśmy wpisać: > <form action="..." accept-charset="windows-1250">...</form> Niestety atrybut `accept-charset="..."` nie jest cudownym sposobem na zachowanie prawidłowych polskich znaków diakrytycznych w prostych formularzach pocztowych :-( Nie wiadomo z jakiego systemu operacyjnego ani z jakiego programu pocztowego korzysta użytkownik, który będzie wypełniał formularz, a więc nie można jednoznacznie ustalić docelowej strony kodowej wysyłanych danych. Jeśli jeszcze niezbyt dobrze rozumiesz formularze, specjalnie dla Ciebie napisałem ten przykład. Myślę, że po jego przeczytaniu, wyjaśni się wiele niezrozumiałych dotąd rzeczy. Wyróżnione fragmenty, można (a nawet trzeba) zastąpić innym tekstem. Są to np. pytania, poszczególne odpowiedzi, wartości parametrów i inne. Czcionką pogrubioną (pomiędzy znakami `<!--` a `-->` ) zaznaczono komentarze. Nie są one oczywiście konieczne (możesz je pominąć). Natomiast pozwalają zorientować się, czego dotyczy fragment kodu poniżej nich. > <form action="mailto:<EMAIL>" method="post" enctype="text/plain"><div> <!-- Podstawowe pole tekstowe --> <input name="Imię">Podaj swoje imię<br> <input name="Nazwisko">Podaj swoje nazwisko <!-- Pole typu RADIO --> <p>Podaj swoją płeć:</p> <input type="radio" name="Płeć" value="Kobieta">Kobieta <input type="radio" name="Płeć" value="Mężczyzna">Mężczyzna <!-- Pole typu RADIO --> <p>Ile masz lat?</p> <input type="radio" name="Wiek" value="mniej niż 15">mniej niż 15<br> <input type="radio" name="Wiek" value="15-19">15-19<br> <input type="radio" name="Wiek" value="20-29">20-29<br> <input type="radio" name="Wiek" value="30-39">30-39<br> <input type="radio" name="Wiek" value="40-60">40-60<br> <input type="radio" name="Wiek" value="więcej niż 60">więcej niż 60 <!-- Pole typu CHECKBOX --> <p>Jaką lubisz muzykę (możesz zaznaczyć więcej możliwości)?</p> <input type="checkbox" name="Muzyka" value="Rock">Rock<br> <input type="checkbox" name="Muzyka" value="Heavy Metal">Heavy Metal<br> <input type="checkbox" name="Muzyka" value="Pop">Pop<br> <input type="checkbox" name="Muzyka" value="Techno">Techno<br> <input type="checkbox" name="Muzyka" value="Muzyka poważna">Muzyka poważna<br> <input type="checkbox" name="Muzyka" value="Inna">Inna (podaj jaka): <input name="Muzyka"> <!-- Lista rozwijalna (typ podstawowy) z zaznaczoną opcją domyślną --> <p>Jakiej przeglądarki internetowej używasz?</p> <select name="Przeglądarka"> <option selected>Chrome</option> <option>Opera</option> <option>Firefox</option> <option>Edge</option> <option>Inna</option> </select> <!-- Lista rozwijalna (typ rozszerzony) z zaznaczoną opcją domyślną i zmniejszoną wysokością --> <p>Jakie znasz systemy operacyjne (możesz wybrać kilka opcji trzymając klawisz Ctrl)?</p> <select name="System operacyjny" multiple size="3"> <option selected>Windows</option> <option>DOS</option> <option>Linux</option> <option>Inny</option> </select> <!-- Pole komentarza (o powiększonych rozmiarach oraz z tekstem domyślnym) --> <p>Podaj swój komentarz:</p> <textarea name="Komentarz" cols="50" rows="10">Proszę, wpisz tutaj jakiś komentarz...</textarea> <br><br><br> <!-- Przycisk WYŚLIJ --> <input type="submit" value="Wyślij formularz"> <!-- Przycisk WYCZYŚĆ DANE --> <input type="reset" value="Wyczyść dane"> </div></formCo to jest promocja strony WWW? * Odpowiednia treść Jaką treść wybrać na stronę WWW? * Projekt graficzny Jak zaprojektować szatę graficzną strony WWW? * Rejestracja w wyszukiwarkach Jak podwyższyć pozycję strony WWW w wyszukiwarkach internetowych? * Linki W jaki sposób wyszukiwarka Google ustala wartościowość strony WWW? * Bannery i buttony Jak zrobić skuteczny banner? W jaki sposób zareklamować się za darmo? * Pop-up Jak otworzyć okienko reklamowe? * Spam Co to jest spam i dlaczego nie warto go stosować? * Konkursy i rankingi Jak można zwiększyć prestiż swojego serwisu WWW? * Powiedz o swojej stronie Jak można jeszcze zwrócić uwagę na swoją stronę WWW? * Tworzenie społeczności W jaki sposób przyciągną i zatrzymać użytkowników w swoim serwisie WWW? Jak wprowadzić interaktywność? * Darmowe gadżety Co jeszcze może przyciągnąć użytkowników do serwisu WWW? * Współpraca Jak zbudować bardziej profesjonalny serwis? * Udostępnianie materiałów Co zrobić, aby serwis WWW był bardziej znany? * Podsumowanie To wbrew pozorom nie wszystkie miejsca, gdzie można umieścić ważne słowa kluczowe. Oczywiście niezwykle duże znaczenie mają słowa umieszczone bezpośrednio w treści strony (szczególnie głównej). Problem w tym, że nie możemy ich tam wpisywać tyle, ile byśmy chcieli, bo strona stanie się po prostu nieczytelna dla człowieka. Niektóre wyszukiwarki traktują jednak "mocniej" wyrażenia umieszczone w takich miejscach jak: tytuły (szczególnie pierwszego rzędu), treść alternatywna obrazków (atrybut `alt="..."` ), dymki narzędziowe odsyłaczy (atrybut `title="..."` ) albo tekst (opis) samych odsyłaczy. Dodatkowe punkty można również dostać, jeśli ważne słowo kluczowe znajduje się bezpośrednio w adresie strony. Lepiej jest także jeśli sam adres jest krótszy. W większości przedstawionych wcześniej metod możliwe jest pewne oszukiwanie wyszukiwarek, ponieważ to autor strony wpisuje słowa kluczowe, które przecież mogą nie mieć nic wspólnego z treścią. Można swobodnie wpisać wyrażenia, które są najczęściej wyszukiwane i tym sposobem próbować zwiększyć oglądalność strony. Na dłuższą metę nie jest to jednak dobre rozwiązanie, ponieważ jeśli czytelnik nie znajdzie na naszej stronie spodziewanych informacji, to prawdopodobnie więcej już na nią nie powróci. Poza tym jeśli wyszukiwarki zorientują się, że chcemy je oszukać, mogą na zawsze usunąć stronę z wszelkich wyników wyszukiwania! Definicje kolorów przydają się np. do ustawiania koloru tekstu lub tła elementów na stronie. W miejsce wyrazu "kolor" należy wpisać o jaką barwę nam chodzi. Można to zrobić na dwa sposoby: podać słowną nazwę jednego z szesnastu kolorów podstawowych (patrz pierwsza część tabeli) lub odpowiednik dowolnego koloru w kodzie szesnastkowym (HEX). A teraz mała powtórka z fizyki (proszę, nie uciekaj jeszcze od komputera, to będzie baaardzo krótka powtórka :-)). Każdą barwę można utworzyć mieszając w odpowiednich proporcjach trzy kolory podstawowe: czerwony, zielony i niebieski (RGB - od angielskich słów: Red - czerwony, Green - zielony, Blue - niebieski). Nasycenie każdego z kolorów zapisujemy w definicji barwy w postaci: #RRGGBB, gdzie: RR - nasycenie koloru czerwonego; GG - nasycenie zielonego; BB - nasycenie niebieskiego (znak # oznacza, że definiujemy kolor w kodzie HEX). Wszystkie składowe muszą być podane w systemie szesnastkowym i poprzedzone znakiem #. Im większa liczba, tym jaśniejszy kolor. Zauważ, że liczba musi się składać z sześciu cyfr, nawet jeśli są to same zera! Przypominam, że w systemie szesnastkowym (HEX) jest szesnaście podstawowych cyfr: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Przykładowo: liczba B5 zapisana w kodzie HEX, oznacza w systemie dziesiętnym 181 (11*16 + 5 = 181). Konwersji DEC -> HEX (i odwrotnie) można dokonać np. w windowsowskim Kalkulatorze (trzeba włączyć widok profesjonalny). Oczywiście w tabeli poniżej nie zostały umieszczone wszystkie kolory, ponieważ całkowita ilość kolorów możliwych do uzyskania tą metodą wynosi: 16 777 216. Aby otrzymać inne barwy, wystarczy zmienić niektóre cyfry w zapisie (HEX). Najlepsze rezultaty (widoczne różnice) można otrzymać, zmieniając pierwszą, trzecią lub piątą cyfrę (w kolejności od lewej strony). Dowolny kolor tekstu oraz tła strony możesz sprawdzić tutaj. To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz___To_jest_bardzo_długi_wyraz Jeśli gdziekolwiek w powyższym akapicie wyraz został przedzielony, a na końcu linijki znajduje znak myślnika, to znaczy, że Twoja przeglądarka obsługuje miękki łącznik. Możesz zmniejszyć szerokość okna, aby zaobserwować, w jaki sposób przeglądarka dynamicznie dobiera miejsce przedzielenia wyrazu... Zwróć uwagę, że miękkie łączniki nie są wyświetlane na ekranie, jeśli nie nastąpiło przedzielenie wyrazu w ich miejscu. ### Znaki specjalne HTML # Co zrobić jeśli chcemy umieścić na swojej stronie np. taki tekst: `<p>` ? Niestety ponieważ wyraz ten jest znacznikiem używanym w składni języka HTML, nie jest możliwe wpisanie go po prostu z klawiatury. W takim razie zastanawiasz się na pewno, jak udało mi się go tutaj wpisać. Jeśli jeszcze nie wiesz, spójrz dalej. Znajdziesz tam tabelę z wykazem znaków specjalnych (tzw. encji), których nie można wpisać bezpośrednio z klawiatury. Stosuje się tu pewną "sztuczkę". Na przykład jeśli chcemy napisać tekst: `<p>` , wpisujemy zamiast niego: `&lt;p&gt;` lub `&#60;p&#62;` i gotowe. Przeglądarka sama zinterpretuje te znaki jako właściwe. Jak widać, każdy znak specjalny rozpoczyna się od ampersand ("&"), a kończy średnikiem (";"). Z tego powodu, jeśli chcemy, aby ampersand pojawił się na ekranie, powinniśmy użyć: &amp; lub &#38;. W pierwszej kolumnie tabeli zawartej dalej w tym rozdziale widnieje dziesiętny numer danego znaku, w drugiej - jego nazwa. Są one równoważne, dlatego możemy używać ich zamiennie, ale wydaje mi się, że ten drugi zapis jest bardziej czytelny, ponieważ jest skrótem od angielskiej nazwy danego symbolu. Zwróć także szczególną uwagę, że przy wpisywaniu nazwy znaku, ważna jest wielkość liter, np. &Alpha; to nie jest to samo co &alpha;! W kolumnie opis znajduje się pełna angielska nazwa wszystkich znaków, dalej - objaśnienie w języku polskim, a na końcu możesz zobaczyć jak będzie wyglądał wybrany symbol na ekranie. Wpisanie znaku w formacie `&#numer` pozwala podać numer w systemie dziesiętnym. Można również zrobić to za pomocą kodu szesnastkowego: `&#xHEX` lub `&#XHEX` , gdzie HEX jest maksymalnie dwubajtową liczbą szesnastkową (cztery cyfry 0-F). Przy konwersji z systemu dziesiętnego (DEC) na szesnastkowy (HEX) i odwrotnie pomocny może być dowolny bardziej rozbudowany kalkulator (np. systemowy). Niektóre spośród podanych poniżej znaków nie są interpretowane przez różne przeglądarki, a do wyświetlenia wybranych - zwłaszcza w drugiej części tabeli - może być potrzebna czcionka Unicode (np. 'Lucida Sans Unicode' - domyślnie dostępna w niektórych wersjach systemu Windows, 'Arial Unicode', 'Arial Unicode MS', 'Helvetica Unicode' 'Verdana Unicode', 'Times Unicode', 'Times New Roman Unicode', 'Courier Unicode', 'Courier New Unicode' i inne). Wygląd dowolnego znaku specjalnego możesz sprawdzić również tutaj. ### Niełamliwa spacja # Zwróć szczególną uwagę na symbol o nazwie: (czyli &#160;). Jest to dodatkowa niełamliwa spacja (odstęp), zwana również twardą spacją. W normalnym tekście nie mogą stać obok siebie dwie spacje. Nie może się także od niej rozpoczynać żaden wiersz. Dzięki symbolowi dodatkowej spacji, możesz pozbyć się wszystkich tych ograniczeń. Ponadto jeśli rozdzielisz dwa wyrazy symbolem dodatkowej spacji, masz pewność, że w tym miejscu nigdy nie zostanie przełamany wiersz (czyli nie zdarzy się tak, że pierwszy wyraz znajdzie się na końcu linii, a drugi na początku następnej). Właściwym przeznaczeniem niełamliwej spacji nie jest jednak wprowadzanie wcięć czy powiększonych odstępów w tekście. Znak ten pozwala poprawić estetykę typograficzną treści. Mianowicie powinno się unikać sytuacji, kiedy spójniki znajdują się na końcu linii. Dlatego zaleca się pisanie w następujący sposób: > biały i czarny Masa 10 kg Narzędzia automatycznie poprawiające estetykę typograficzną tekstu czasami się wbudowane w edytory HTML. ### Miękki łącznik # Innym przydatnym znakiem jest miękki łącznik, czyli &shy; lub &#173;. Znak ten służy do inteligentnego dzielenia długich wyrazów pomiędzy kolejne linijki tekstu. Wstawiając taki znak po określonej sylabie długiego wyrazu, dajemy przeglądarce możliwość przedzielenia go w tym miejscu do następnej linii. Jeśli zajdzie taka potrzeba, miękki łącznik wyświetlany jest na końcu linii jak tradycyjny myślnik ("-"), a dalszy ciąg wyrazu zostaje przeniesiony do następnej linijki. Jeśli natomiast układ tekstu w akapicie jest taki, że w miejscu wstawienia miękkiego łącznika linia nie musi być przedzielona, to w ogóle nie zostanie on wyświetlony. Nie jest on również uwzględniany przy przeszukiwaniu treści dokumentu. To, czy będzie uwzględniany przy kopiowaniu tekstu ze strony do schowka systemowego, zależy od przeglądarki - specyfikacja HTML 4.01 nic nie mówi na ten temat, przez co zachowanie przeglądarek nie jest określone. Jak łatwo zauważyć, działania miękkiego łącznika nie można zastąpić tradycyjnym myślnikiem, ponieważ wtedy bylibyśmy zmuszeni zawsze przełamać po nim linię poprzez użycie znacznika <br>, co niekoniecznie może być działaniem pożądanym, biorąc pod uwagę fakt, że użytkownik może zmienić rozmiar czcionki lub w ogóle nie posiadać ustalonego na stronie kroju czcionki, a wtedy układ akapitu może zmienić się tak, że przedzielenie w wybranym stałym miejscu będzie niewłaściwe, za to byłoby wymagane gdzie indziej. Chociaż rola, jaką spełnia miękki łącznik, jest niezastąpiona, niestety nie wszystkie przeglądarki obsługują ten znak :-( Jest obsługiwany m.in. przez Microsoft Internet Explorera, Operę, Chrome i Konquerora. Nie jest za to prawidłowo obsługiwany przez Mozillę Firefox 2 (nie wyświetla się, ale też nie powoduje inteligentnego przedzielania wyrazów), natomiast od wersji 3.0 wszystko jest już w porządku. # Przykład &shy; W tabeli poniżej znajdziesz skróty literowe nazw języków, które mają zastosowanie podczas definiowania języka, w którym napisana jest strona oraz jako wartość atrybutu `lang="..."` wskazującego język pojedynczego elementu strony. Kody języków mogą być jednoczłonowe lub dwuczłonowe: * Pierwszy człon (wymagany), najczęściej pisany małymi literami, zawsze określa język mówiony. * Drugi człon (opcjonalny), zwyczajowo pisany wielkimi literami, może wskazywać kraj, terytorium lub region, w którym mówi się w tym języku. Na przykład en oznacza ogólny język angielski, a en-US - język angielski jakim mówi się w Stanach Zjednoczonych. Jeśli w danym języku mówi się tylko w jednym kraju, terytorium bądź regionie, to co prawda możemy wtedy użyć formy dwuczłonowej (np. pl-PL), jednak najczęściej w takim przypadku korzysta się z krótszego zapisu jednoczłonowego (np. pl). Chociaż pierwszy człon (wymagany) nazwy kodowej języka zwyczajowo piszemy małymi literami, a drugi (opcjonalny) - wielkimi literami, taka konwencja nie jest jednak absolutnie wymagana. Na przykład czasami spotyka się oba człony pisane w całości małymi literami. Język | Skrót | | --- | --- | afrikaans | af | afrikaans (Namibia) | af-NA | afrikaans (Republika Południowej Afryki) | af-ZA | akan | ak | albański | sq | albański (Albania) | sq-AL | albański (Kosowo) | sq-XK | albański (Macedonia) | sq-MK | amharski | am | angielski | en | angielski (Anguilla) | en-AI | angielski (Antigua i Barbuda) | en-AG | angielski (Australia) | en-AU | angielski (Bahamy) | en-BS | angielski (Barbados) | en-BB | angielski (Belgia) | en-BE | angielski (Belize) | en-BZ | angielski (Bermudy) | en-BM | angielski (Botswana) | en-BW | angielski (Brytyjskie Terytorium Oceanu Indyjskiego) | en-IO | angielski (Brytyjskie W<NAME>ze) | en-VG | angielski (D<NAME>spy Mniejsze Stanów Zjednoczonych) | en-UM | angielski (<NAME>) | en-DG | angielski (Dominika) | en-DM | angielski (Erytrea) | en-ER | angielski (Falklandy) | en-FK | angielski (Fidżi) | en-FJ | angielski (Filipiny) | en-PH | angielski (Gambia) | en-GM | angielski (Ghana) | en-GH | angielski (Gibraltar) | en-GI | angielski (Grenada) | en-GD | angielski (Guam) | en-GU | angielski (Gujana) | en-GY | angielski (Indie) | en-IN | angielski (Irlandia) | en-IE | angielski (Jamajka) | en-JM | angielski (Kajmany) | en-KY | angielski (Kamerun) | en-CM | angielski (Kanada) | en-CA | angielski (Kenia) | en-KE | angielski (Kiribati) | en-KI | angielski (Lesotho) | en-LS | angielski (Liberia) | en-LR | angielski (Madagaskar) | en-MG | angielski (Malawi) | en-MW | angielski (Malezja) | en-MY | angielski (Malta) | en-MT | angielski (M<NAME>) | en-MP | angielski (Mauritius) | en-MU | angielski (Mikronezja) | en-FM | angielski (Montserrat) | en-MS | angielski (Namibia) | en-NA | angielski (Nauru) | en-NR | angielski (Nigeria) | en-NG | angielski (Niue) | en-NU | angielski (Norfolk) | en-NF | angielski (Nowa Zelandia) | en-NZ | angielski (Pakistan) | en-PK | angielski (Palau) | en-PW | angielski (Papua-Nowa Gwinea) | en-PG | angielski (Pitcairn) | en-PN | angielski (Portoryko) | en-PR | angielski (Republika Południowej Afryki) | en-ZA | angielski (Rwanda) | en-RW | angielski (Saint Kitts i Nevis) | en-KN | angielski (Saint Lucia) | en-LC | angielski (Saint Vincent i Grenadyny) | en-VC | angielski (Samoa Amerykańskie) | en-AS | angielski (Samoa) | en-WS | angielski (Seszele) | en-SC | angielski (Sierra Leone) | en-SL | angielski (Singapur) | en-SG | angielski (Sint Maarten) | en-SX | angielski (SRA Hongkong (Chiny)) | en-HK | angielski (SRA Makau (Chiny)) | en-MO | angielski (St<NAME>) | en-US | angielski (Suazi) | en-SZ | angielski (Sudan Południowy) | en-SS | angielski (Sudan) | en-SD | angielski (Tanzania) | en-TZ | angielski (Tokelau) | en-TK | angielski (Tonga) | en-TO | angielski (Trynidad i Tobago) | en-TT | angielski (Turks i Caicos) | en-TC | angielski (Tuvalu) | en-TV | angielski (Uganda) | en-UG | angielski (Vanuatu) | en-VU | angielski (<NAME>) | en-GB | angielski (Wyspa Bożego Narodzenia) | en-CX | angielski (Wyspa Guernsey) | en-GG | angielski (Wyspa Jersey) | en-JE | angielski (Wyspa Man) | en-IM | angielski (Wyspa Świętej Heleny) | en-SH | angielski (Wy<NAME>) | en-CK | angielski (Wyspy D<NAME>zonych) | en-VI | angielski (Wyspy Kokosowe) | en-CC | angielski (Wyspy Marshalla) | en-MH | angielski (Wy<NAME>) | en-SB | angielski (Zambia) | en-ZM | angielski (Zimbabwe) | en-ZW | arabski | ar | arabski (Algieria) | ar-DZ | arabski (Arabia Saudyjska) | ar-SA | arabski (Bahrajn) | ar-BH | arabski (Czad) | ar-TD | arabski (Dżibuti) | ar-DJ | arabski (Egipt) | ar-EG | arabski (Erytrea) | ar-ER | arabski (Irak) | ar-IQ | arabski (Izrael) | ar-IL | arabski (Jemen) | ar-YE | arabski (Jordania) | ar-JO | arabski (Katar) | ar-QA | arabski (Komory) | ar-KM | arabski (Kuwejt) | ar-KW | arabski (Liban) | ar-LB | arabski (Libia) | ar-LY | arabski (Maroko) | ar-MA | arabski (Mauretania) | ar-MR | arabski (Oman) | ar-OM | arabski (Sahara Zachodnia) | ar-EH | arabski (Somalia) | ar-SO | arabski (Sudan Południowy) | ar-SS | arabski (Sudan) | ar-SD | arabski (Syria) | ar-SY | arabski (Terytoria Palestyńskie) | ar-PS | arabski (Tunezja) | ar-TN | arabski (Zjednoczone Emiraty Arabskie) | ar-AE | asamski | as | azerski | az | bambara | bm | baskijski | eu | bengalski | bn | bengalski (Bangladesz) | bn-BD | bengalski (Indie) | bn-IN | białoruski | be | birmański | my | bośniacki | bs | bretoński | br | bułgarski | bg | chiński | zh | chiński (Chiny) | zh-CN | chiński (Singapur) | zh-SG | chiński (SRA Hongkong (Chiny)) | zh-HK | chiński (SRA Makau (Chiny)) | zh-MO | chiński (Tajwan) | zh-TW | chorwacki | hr | chorwacki (Bośnia i Hercegowina) | hr-BA | chorwacki (Chorwacja) | hr-HR | czeski | cs | duński | da | duński (Dania) | da-DK | duński (Grenlandia) | da-GL | dzongkha | dz | esperanto | eo | estoński | et | ewe | ee | ewe (Ghana) | ee-GH | ewe (Togo) | ee-TG | farerski | fo | fiński | fi | francuski | fr | francuski (Algieria) | fr-DZ | francuski (Belgia) | fr-BE | francuski (Benin) | fr-BJ | francuski (Burkina Faso) | fr-BF | francuski (Burundi) | fr-BI | francuski (Côte d’Ivoire) | fr-CI | francuski (Czad) | fr-TD | francuski (Demokratyczna Republika Konga) | fr-CD | francuski (Dżibuti) | fr-DJ | francuski (Francja) | fr-FR | francuski (Gabon) | fr-GA | francuski (<NAME>) | fr-GF | francuski (Gwadelupa) | fr-GP | francuski (Gwinea Równikowa) | fr-GQ | francuski (Gwinea) | fr-GN | francuski (Haiti) | fr-HT | francuski (Kamerun) | fr-CM | francuski (Kanada) | fr-CA | francuski (Komory) | fr-KM | francuski (Kongo) | fr-CG | francuski (Luksemburg) | fr-LU | francuski (Madagaskar) | fr-MG | francuski (Majotta) | fr-YT | francuski (Mali) | fr-ML | francuski (Maroko) | fr-MA | francuski (Martynika) | fr-MQ | francuski (Mauretania) | fr-MR | francuski (Mauritius) | fr-MU | francuski (Monako) | fr-MC | francuski (Niger) | fr-NE | francuski (Nowa Kaledonia) | fr-NC | francuski (Polinezja Francuska) | fr-PF | francuski (Republika Środkowoafrykańska) | fr-CF | francuski (Reunion) | fr-RE | francuski (Rwanda) | fr-RW | francuski (Saint-Barthélemy) | fr-BL | francuski (Saint-Martin) | fr-MF | francuski (Saint-Pierre i Miquelon) | fr-PM | francuski (Senegal) | fr-SN | francuski (Seszele) | fr-SC | francuski (Syria) | fr-SY | francuski (Szwajcaria) | fr-CH | francuski (Togo) | fr-TG | francuski (Tunezja) | fr-TN | francuski (Vanuatu) | fr-VU | francuski (Wallis i Futuna) | fr-WF | fulani | ff | fulani (Gwinea) | ff-GN | fulani (Kamerun) | ff-CM | fulani (Mauretania) | ff-MR | fulani (Senegal) | ff-SN | galicyjski | gl | ganda | lg | grecki | el | grecki (Cypr) | el-CY | grecki (Grecja) | el-GR | grenlandzki | kl | gruziński | ka | gudźaracki | gu | hausa | ha | hausa (Ghana) | ha-GH | hausa (Niger) | ha-NE | hausa (Nigeria) | ha-NG | hebrajski | he | hindi | hi | hiszpański | es | hiszpański (Argentyna) | es-AR | hiszpański (Boliwia) | es-BO | hiszpański (Ceuta i Melilla) | es-EA | hiszpański (Chile) | es-CL | hiszpański (Dominikana) | es-DO | hiszpański (Ekwador) | es-EC | hiszpański (Filipiny) | es-PH | hiszpański (Gwatemala) | es-GT | hiszpański (Gwinea Równikowa) | es-GQ | hiszpański (Hiszpania) | es-ES | hiszpański (Honduras) | es-HN | hiszpański (Kolumbia) | es-CO | hiszpański (Kostaryka) | es-CR | hiszpański (Kuba) | es-CU | hiszpański (Meksyk) | es-MX | hiszpański (Nikaragua) | es-NI | hiszpański (Panama) | es-PA | hiszpański (Paragwaj) | es-PY | hiszpański (Peru) | es-PE | hiszpański (Portoryko) | es-PR | hiszpański (Salwador) | es-SV | hiszpański (<NAME>) | es-US | hiszpański (Urugwaj) | es-UY | hiszpański (Wenezuela) | es-VE | hiszpański (Wyspy Kanaryjskie) | es-IC | igbo | ig | indonezyjski | id | irlandzki | ga | islandzki | is | japoński | ja | jidysz | yi | joruba | yo | joruba (Benin) | yo-BJ | joruba (Nigeria) | yo-NG | kannada | kn | kaszmirski | ks | kataloński | ca | kataloński (Andora) | ca-AD | kataloński (Francja) | ca-FR | kataloński (Hiszpania) | ca-ES | kataloński (Włochy) | ca-IT | kazachski | kk | keczua | qu | keczua (Boliwia) | qu-BO | keczua (Ekwador) | qu-EC | keczua (Peru) | qu-PE | khmerski | km | kikuju | ki | kinya-ruanda | rw | kirgiski | ky | koreański | ko | koreański (Korea Południowa) | ko-KR | koreański (Korea Północna) | ko-KP | kornijski | kw | laotański | lo | lapoński północny | se | lapoński północny (Finlandia) | se-FI | lapoński północny (Norwegia) | se-NO | lapoński północny (Szwecja) | se-SE | lingala | ln | lingala (Angola) | ln-AO | lingala (Demokratyczna Republika Konga) | ln-CD | lingala (Kongo) | ln-CG | lingala (Republika Środkowoafrykańska) | ln-CF | litewski | lt | luba-katanga | lu | luksemburski | lb | łotewski | lv | macedoński | mk | malajalam | ml | malajski | ms | malajski (Brunei Darussalam) | ms-BN | malajski (Malezja) | ms-MY | malajski (Singapur) | ms-SG | malgaski | mg | maltański | mt | manx | gv | marathi | mr | mongolski | mn | ndebele północny | nd | nepalski | ne | nepalski (Indie) | ne-IN | nepalski (Nepal) | ne-NP | niderlandzki | nl | niderlandzki (Aruba) | nl-AW | niderlandzki (Belgia) | nl-BE | niderlandzki (Curaçao) | nl-CW | niderlandzki (Holandia) | nl-NL | niderlandzki (Niderlandy Karaibskie) | nl-BQ | niderlandzki (Sint Maarten) | nl-SX | niderlandzki (Surinam) | nl-SR | niemiecki | de | niemiecki (Austria) | de-AT | niemiecki (Belgia) | de-BE | niemiecki (Liechtenstein) | de-LI | niemiecki (Luksemburg) | de-LU | niemiecki (Niemcy) | de-DE | niemiecki (Szwajcaria) | de-CH | norweski | no | norweski (bokmål) | nb | norweski (Norwegia) | nb-NO | norweski (nynorsk) | nn | norweski (Svalbard i <NAME>) | nb-SJ | orija | or | ormiański | hy | oromski | om | oromski (Etiopia) | om-ET | oromski (Kenia) | om-KE | osetyjski | os | osetyjski (Gruzja) | os-GE | osetyjski (Rosja) | os-RU | paszto | ps | pendżabski | pa | pendżabski (Indie) | pa-IN | pendżabski (Pakistan) | pa-PK | perski | fa | perski (Afganistan) | fa-AF | perski (Iran) | fa-IR | polski | pl | portugalski | pt | portugalski (Angola) | pt-AO | portugalski (Brazylia) | pt-BR | portugalski (Gwinea Bissau) | pt-GW | portugalski (Mozambik) | pt-MZ | portugalski (Portugalia) | pt-PT | portugalski (Republika Zielonego Przylądka) | pt-CV | portugalski (SRA Makau (Chiny)) | pt-MO | portugalski (<NAME>) | pt-TL | portugalski (Wyspy Świętego Tomasza i Książęca) | pt-ST | retoromański | rm | rosyjski | ru | rosyjski (Białoruś) | ru-BY | rosyjski (Kazachstan) | ru-KZ | rosyjski (Kirgistan) | ru-KG | rosyjski (Mołdawia) | ru-MD | rosyjski (Rosja) | ru-RU | rosyjski (Ukraina) | ru-UA | rumuński | ro | rumuński (Mołdawia) | ro-MD | rumuński (Rumunia) | ro-RO | rundi | rn | sango | sg | serbski | sr | serbski (Bośnia i Hercegowina) | sr-BA | serbski (Czarnogóra) | sr-ME | serbski (Kosowo) | sr-XK | serbski (Serbia) | sr-RS | serbsko-chorwacki | sh | słowacki | sk | słoweński | sl | somalijski | so | somalijski (Dżibuti) | so-DJ | somalijski (Etiopia) | so-ET | somalijski (Kenia) | so-KE | somalijski (Somalia) | so-SO | suahili | sw | suahili (Kenia) | sw-KE | suahili (Tanzania) | sw-TZ | suahili (Uganda) | sw-UG | syczuański | ii | syngaleski | si | szkocki gaelicki | gd | szona | sn | szwedzki | sv | szwedzki (Finlandia) | sv-FI | szwedzki (Szwecja) | sv-SE | szwedzki (Wyspy Alandzkie) | sv-AX | tagalski | tl | tajski | th | tamilski | ta | tamilski (Indie) | ta-IN | tamilski (Malezja) | ta-MY | tamilski (Singapur) | ta-SG | tamilski (Sri Lanka) | ta-LK | telugu | te | tigrinia | ti | tigrinia (Erytrea) | ti-ER | tigrinia (Etiopia) | ti-ET | tonga | to | turecki | tr | turecki (Cypr) | tr-CY | turecki (Turcja) | tr-TR | tybetański | bo | tybetański (Chiny) | bo-CN | tybetański (Indie) | bo-IN | ujgurski | ug | ukraiński | uk | urdu | ur | urdu (Indie) | ur-IN | urdu (Pakistan) | ur-PK | uzbecki | uz | uzbecki (Afganistan) | uz-AF | uzbecki (Uzbekistan) | uz-UZ | walijski | cy | węgierski | hu | wietnamski | vi | włoski | it | włoski (San Marino) | it-SM | włoski (Szwajcaria) | it-CH | włoski (Włochy) | it-IT | zachodniofryzyjski | fy | zulu | zu | Więcej kodów języków można znaleźć w standardzie ISO 639. Natomiast kody krajów opisane są w ISO 3166-1. Co to są Kaskadowe Arkusze Stylów CSS (Cascading Style Sheets)? * Dlaczego warto używać CSS? Do czego są potrzebne style CSS? Jakie są sposoby wstawiania (osadzania) stylów CSS na stronach WWW? * Styl lokalny <... styleW jaki sposób bezpośrednio przypisać styl do dowolnego znacznika? * Rozciąganie stylu <span styleW jaki sposób objąć stylem kilka elementów tekstowych? * Wydzielone bloki <div styleW jaki sposób objąć stylem grupę elementów blokowych? * Wewnętrzny arkusz stylów <styleJak osadzić arkusz stylów CSS bezpośrednio w dokumencie? * Zewnętrzny arkusz stylów <link stylesheet> @charset Jak dołączyć arkusz stylów CSS z zewnętrznego pliku? * Alternatywny arkusz stylów <link alternate stylesheetW jaki sposób dać użytkownikowi możliwość wyboru jednego z przygotowanych arkuszy CSS, czyli wyglądu strony? * Import arkusza stylów @import Jak zaimportować arkusz stylów z zewnętrznego dokumentu? * Kaskadowość stylów Co to jest kaskadowość stylów CSS? W jaki sposób złamać zasadę kaskadowości? * Powtórka Sposoby wstawiania stylów do gotowych dokumentów są różne. Nie znaczy to, że jedne są lepsze od drugich. Każdy sposób jest przydatny w innych sytuacjach. Większość witryn stosuje jednocześnie wszystkie z przedstawionych metod osadzania CSS - w zależności od konkretnej potrzeby. > <element style="cecha: wartość; cecha2: wartość2...">...</elementTo jest jakiś tekst > <span style="cecha: wartość; cecha2: wartość2...">...</span Zarówno znacznik `<span>` jak i `<div>` są znacznikami kontenerowymi w HTML, jednak różnią się głównie zastosowaniem i wpływem na strukturę dokumentu. `<span>` jest używany do stylizacji lub wyróżnienia fragmentów tekstu wewnątrz linii tekstu, podczas gdy `<div>` jest używany do tworzenia bloków kontenerowych, które mogą zawierać inne elementy HTML i służą do grupowania i układania zawartości strony. > <div style="cecha: wartość; cecha2: wartość2...">...</div Znacznik `<div>` w HTML jest elementem blokowym, który pozwala tworzyć kontenerowe bloki na stronie. Dzięki niemu można grupować inne elementy, tworzyć układy strony, stosować style CSS oraz manipulować zawartością za pomocą skryptów JavaScript, co umożliwia bardziej elastyczną i kontrolowaną strukturę strony internetowej. > <head> (...) <style> selektor { cecha: wartość; cecha2: wartość2... } selektor2 { cecha: wartość; cecha2: wartość2... } (...) </style> (...) </headSelektorem może być praktycznie dowolny znacznik, np. p (akapit), h1 (tytuł), td (komórka tabeli) i inne. To właśnie elementom, które znajdują się w kodzie źródłowym, pomiędzy tymi znacznikami, nadajemy atrybuty formatowania opisane w arkuszu. Jako "cecha" (w deklaracji stylu - powyżej) należy wpisać o jakie konkretnie atrybuty formatowania nam chodzi (opisane w kolejnych rozdziałach). Natomiast jako wyraz "wartość" wpisujemy dokładną wartość atrybutu. Zwróć uwagę, że jednemu selektorowi możemy nadać kilka atrybutów (cech). Są one wtedy rozdzielone średnikami. Wewnętrzny arkusz stylów wstawia się zawsze w części nagłówkowej dokumentu (pomiędzy znacznikami `<head>` a `</head>` ). Można go zastosować, gdy elementy które pragniemy poddać formatowaniu, występują wielokrotnie na stronie i wszystkim chcemy nadać takie same atrybuty (inne niż domyślne). Na przykład chcemy, aby wszystkie wykazy miały automatycznie kolor niebieski. Wystarczy wpisać odpowiednią deklarację stylów w arkuszu (w treści nagłówkowej) i nie trzeba już nic dopisywać przy samym elemencie. Komentarze w arkuszu stylów pisze się używając znaków: `/*` (otworzenie komentarza) oraz `*/` (zamknięcie komentarza), np.: `/*12345*/` . Wszystko pomiędzy tymi znakami jest ignorowane przez przeglądarkę. Komentarzy takich nie można zagnieżdżać, tzn. niedozwolony jest zapis: `/*123/*000*/456*/` . Komentarz może składać się z wielu linii, np.: > /* Ten tekst zostanie zignorowany przez przeglądarkę, ale może zawierać informacje cenne dla projektanta arkusza CSS */ Ponadto w języku HTML całą zawartość arkusza stylów, tzn. wnętrze znacznika `<style>...</style>` można ująć w komentarz HTML: > <style> <!-- /* To jest arkusz stylów kompatybilny wstecz */ --> </style> Dzięki nim treść arkusza nie będzie widoczna na ekranie starszych przeglądarek, które nie obsługują stylów. Aktualnie jednak trudno znaleźć przeglądarkę, która nie potrafiłaby zinterpretować znacznika STYLE. Oczywiście znaki `<!--` oraz `-->` znajdujące się na początku i na końcu arkusza, nie są znakami komentarza stylów lecz HTML i nie można ich używać wewnątrz arkusza w innych miejscach niż podane! W języku XHTML ukrywanie arkusza CSS w komentarzach `<!-- ... -->` jest niezalecane. XHTML jest zgodny z XML, gdzie panuje zasada, że przed etapem właściwego parsowania dokumentu, można z niego usunąć wszystkie komentarze. Oznaczałoby to, że tego typu skrypty i arkusze w ogóle nie byłyby brane pod uwagę przy renderowaniu strony! Znacznik STYLE może znajdować się tylko i wyłącznie w nagłówku dokumentu. ### Przykład <styleJeśli w treści nagłówkowej strony zostałby umieszczony następujący wewnętrzny arkusz stylów: > <style> h6 { color: red } </style>to po wpisaniu w dowolnym miejscu strony po prostu: > <h6>To jest tytuł rzędu 6</h6>otrzymalibyśmy tytuł rzędu szóstego koloru czerwonego ( `color: red` ) i to niezależnie od tego, ile będzie na stronie takich tytułów. Wygodne, prawda? :-) ### Zewnętrzny arkusz stylów <link stylesheet> # > <head> (...) <link rel="stylesheet" href="style.css"> (...) </headMożliwość wstawiania zewnętrznego arkusza jest chyba jedną z największych zalet stosowania stylów. Pozwala nam to zdefiniować takie samo formatowanie określonych elementów na wielu stronach jednocześnie. Dzięki temu, za pomocą tego jednego arkusza, wszystkie nasze strony w obrębie całego serwisu mogą mieć pewne wspólne cechy. Dodatkowo jeśli w ostatniej chwili zdecydujemy się zmienić np. rodzaj czcionki na wszystkich stronach, możemy to zrobić, modyfikując jedynie zewnętrzny arkusz stylów, bez konieczności zmiany każdej strony osobno. Pozwala to zaoszczędzić mnóstwo czasu (zwłaszcza niezdecydowanym ;-)). Wstawienie takiego zewnętrznego arkusza stylów jest bardzo proste. Wystarczy wpisać w treści nagłówkowej każdego z dokumentów (pomiędzy znacznikami `<head>` a `</head>` ), przedstawioną powyżej linijkę. Deklaracje stylów zawarte w zewnętrznym arkuszu, zostaną automatycznie przeniesione do podanej strony (podczas jej wyświetlania). Wszystkie podstrony serwisu z osadzonym w swoim nagłówku takim poleceniem, uzyskają wygląd, określony w załączonym arkuszu stylów. W pojedynczym dokumencie HTML można dołączyć dowolną liczbę zewnętrznych arkuszy stylów - każdy jako osobny element ``` <link rel="stylesheet"> ``` . W przypadku konfliktów, ważniejsze będą deklaracje z arkusza dołączonego później. Zwykle tworzy się pojedynczy zewnętrzny arkusz i załącza go w całym serwisie, czyli na wszystkich podstronach. Czasami jednak dodatkowo poza nim projektuje się osobne arkusze, ustalające wygląd np. odrębnych kategorii tematycznych serwisu. Mamy wtedy sytuację, gdy na stronie głównej jest dołączony tylko jeden arkusz stylów, a na podstronach kategorii tematycznych - po dwa. A teraz kilka słów o tym, jak napisać taki zewnętrzny arkusz stylów. Jest on po prostu zwykłym plikiem tekstowym. Aby go utworzyć, wystarczy zwykły edytor tekstu, w którym piszemy takie same deklaracje stylów ``` selektor { cecha: wartość } ``` , jak w przypadku wewnętrznego arkusza stylów. Oczywiście można się posłużyć specjalnym edytorem CSS. Należy jedynie pamiętać, że plik będący zewnętrznym arkuszem stylów musi mieć rozszerzenie *.css! Wstawienie białych znaków (spacje, tabulacje, znaki nowej linii) w arkuszu CSS nie ma wpływu na jego działanie. Dlatego możesz ułożyć wpisywane reguły CSS w taki sposób, aby były bardziej czytelne. Znacznik LINK może znajdować się tylko i wyłącznie w nagłówku dokumentu.W MSIE 8.0 i starszych można osadzić tylko 31 zewnętrznych arkuszy CSS - deklaracje z następnych plików zostaną pominięte! # Przykład <link stylesheetA oto przykładowy zewnętrzny arkusz stylów: > /* SELEKTORY: */ body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; color: #003868; background-color: #80B8E8; margin: 6mm; } p { text-align: justify; } pre, code { font-size: 8pt; } CiekawostkaPrzeglądarki zwykle umożliwiają formatowanie wszystkich oglądanych stron (bez względu na ich pochodzenie), przy użyciu arkusza stylów dostarczonego przez użytkownika. Pozwala to np. określić odpowiadającą nam wielkość czcionki, jej rodzaj, kolor tła oraz tekstu itd. Przykładowo, aby zaimplementować taką funkcję w przeglądarce Microsoft Internet Explorer, należy wybrać polecenie z menu programu: Narzędzia/Opcje internetowe... i kliknąć przycisk: Dostępność.... Następnie w otwartym oknie dialogowym należy zaznaczyć: Formatuj dokumenty używając mojego arkusza stylów, a poniżej wpisać ścieżkę do pliku arkusza (można również użyć przycisku Przeglądaj...). ### Strona kodowa @charset # Jeżeli arkusz stylów zawiera narodowe znaki diakrytyczne, konieczne może być określenie strony kodowej. Można to zrobić umieszczając na samym początku arkusza stylów deklarację: > @charset "strona kodowa"; Przed deklaracją strony kodowej w arkuszu stylów nie mogą się znajdować żadne znaki - nawet spacje, tabulatory ani puste linijki. Ostateczna strona kodowa zewnętrznego arkusza stylów, nawet jeśli nie określimy jej w sposób jawny, zostanie wyznaczona zgodnie z następującymi priorytetami: * Deklaracja charset wysłana przez serwer wraz z plikiem arkusza stylów * Znacznik BOM lub/i deklaracja `@charset` wstawione na początku arkusza stylów * Atrybut `charset="..."` znacznika LINK, który osadza zewnętrzny arkusz stylów * Deklaracja strony kodowej dokumentu HTML, w którym arkusz stylów został osadzony albo innego arkusza, w którym został zaimportowany * Jeżeli w żaden sposób nie udało się wyznaczyć strony kodowej, przyjmij UTF-8. Plik CSS można zapisać jako zwykły plik tekstowy z rozszerzeniem *.css. W edytorze tekstu należy utworzyć nowy plik, wpisać w nim reguły stylów, a następnie zapisać go z odpowiednią nazwą i rozszerzeniem, na przykład: "style.css". > <head> <link rel="stylesheet" href="style.css" title="Nazwa domyślna"> <link rel="alternate stylesheet" href="style1.css" title="Nazwa 1"> <link rel="alternate stylesheet" href="style2.css" title="Nazwa 2"> <link rel="alternate stylesheet" href="style3.css" title="Nazwa 3"> (...) </headPolecenie można wstawić zarówno w wewnętrznym jak i zewnętrznym arkuszu stylów. Pozwala wczytać zewnętrzny arkusz stylów, przy czym może się on znajdować na tym samym serwerze (wtedy można podać względną ścieżkę dostępu) lub w dowolnym miejscu w obrębie całego Internetu (wtedy podajemy adres internetowy). Po wczytaniu, zostanie on automatycznie dołączony do strony. Oprócz importu arkusza, możesz umieścić pomiędzy znacznikami `<style>` a `</style>` dodatkowo własne reguły stylów, a nawet polecenie importu drugiego arkusza (ich działania zostaną połączone, a w przypadku konfliktów pierwszeństwo będzie miała ostatnia w kolejności deklaracja importu). Import arkusza stylów działa bardzo podobnie jak dołączenie zewnętrznego arkusza - w obu przypadkach reguły CSS są zapisane w osobnym pliku *.css. Różnica w działaniu jest subtelna, ale ważna. Mianowicie importowany arkusz stylów ma taki sam priorytet kaskadowości (ważności), jak arkusz do którego został zaimportowany. Innymi słowy, jeśli chcemy, aby określony arkusz CSS był ważniejszy od wszystkich pozostałych zewnętrznych arkuszy, możemy go dołączyć poniżej innych odwołań do arkuszy lub zaimportować w wewnętrznym arkuszu. Import arkuszy może również być przydatny, jeśli chcemy oszczędzić wstawiania dodatkowych znaczników ``` <link rel="Stylesheet"> ``` . W takim przypadku dołącza się tylko jeden zewnętrzny plik *.css, a w nim importuje pozostałe arkusze. Jeżeli polecenie importu znajduje się w zewnętrznym arkuszu stylów, to relatywną ścieżkę dostępu do arkusza importowanego należy konstruować względem położenia arkusza CSS, w którym jest wstawione polecenie `@import` , a nie względem dokumentu HTML! UWAGA!Wszystkie polecenia importu (może ich być kilka) muszą się znajdować zaraz na początku arkusza stylów, tzn. przed właściwymi regułami CSS, znajdującymi się w arkuszu, do którego następuje import! W MSIE 8.0 i starszych można zagnieżdżać importowane arkusze CSS tylko do trzeciego poziomu, tzn. importowany na najwyższym poziomie arkusz może sam zaimportować nowy plik CSS, a ten z kolei jeszcze tylko jeden dodatkowy - deklaracje z następnych zagnieżdżonych plików zostaną pominięte! . Styl zdefiniowany w ten sposób ma pierwszeństwo nad stylami wewnętrznymi (osadzonymi) i zewnętrznymi. Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu CSS. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. . Styl zdefiniowany w ten sposób ma pierwszeństwo nad stylami wewnętrznymi (osadzonymi) i zewnętrznymi. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. Co oznacza termin dziedziczenie stylów CSS? * Przywrócenie wartości domyślnej {...: initial} Jak przywrócić domyślne formatowanie elementów na stronie? * Wymuszenie dziedziczenia {...: inherit} W jaki sposób wymusić przywrócenie dziedziczenia stylów CSS? * Odwołanie wartości {...: unset} Jak odwołać formatowanie wcześniej przypisane do elementu na stronie? * Przywrócenie wartości pierwotnej {...: revert} Jak przywrócić pierwotny wygląd wybranemu elementowi na stronie? * Resetowanie wszystkich wartości {all} To jest akapit koloru zielonego, wewnątrz którego znajduje się: pochylenie oraz podkreślenie, którym nie zostały nadane żadne style, a więc dziedziczą je po przodku, czyli po akapicie (są również zielone).A to jest pogrubienie, które znajduje się także wewnątrz tego samego akapitu, ale został mu nadany atrybut koloru czcionki (biały) oraz koloru tła (niebieski) i dlatego nie odziedziczył stylu po przodku. (CSS 3 - interpretuje Firefox 19, Opera 15, Chrome 4) > selektor { cecha: initial } Ten akapit ma zresetowane wszystkie style do wartości domyślnych, ponieważ została mu przypisana deklaracja "all: initial".A to jest pogrubienie, które znajduje się wewnątrz tego akapitu. Odziedziczyło ono zresetowany rodzaj czcionki. Ale jej waga nie została zmieniona - tekst nadal jest wizualnie wytłuszczony - ponieważ zostało to oddzielne przypisane do tego elementu. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. Co to są selektory w języku CSS i dlaczego są tak ważne? * Reguły stylów Co to są reguły stylów CSS? Z czego składa się deklaracja stylu i czym różni się od reguły? * Selektor typu Jak utworzyć selektor typu - podstawowy rodzaj selektora CSS? * Selektor uniwersalny W jaki sposób przypisać styl do wszystkich elementów? * Selektor potomka W jaki sposób nadać formatowanie znacznikowi dziecka znajdującemu się bezpośrednio wewnątrz elementu rodzica? * Selektor braci W jaki sposób nadać formatowanie znacznikowi znajdującemu się bezpośrednio po innym elemencie - bracie? * Ogólny selektor braci W jaki sposób nadać formatowanie znacznikom znajdującym się w dowolnym miejscu po innym elemencie - bracie? * Grupowanie selektorów W jaki sposób za jednym razem przypisać formatowanie różnym selektorom CSS? * Powtórka Siła CSS leży nie tylko w możliwości dostarczania deklaracji z różnych źródeł, ale także w różnorodnych sposobach precyzyjnego określania konkretnych elementów w kodzie źródłowym dokumentu HTML, którym będą przypisywane atrybuty formatowania, zmieniające ich wygląd. Umożliwiają to tzw. selektory. Ich wielość nie wynika ze złośliwości twórców języka CSS, którzy chcieli utrudnić Tobie drogi czytelniku naukę, ale z chęci dania większej swobody i elastyczności rozwiązań twórcom stron WWW podczas projektowania arkuszy CSS. Atrybuty formatowania w języku CSS definiuje się za pomocą tzw. reguł stylów. Każda reguła odnosi się do konkretnego elementu (znacznika) i składa się z dwóch części: selektora i deklaracji. Selektor określa do jakich elementów ma zostać przypisane formatowanie, a deklaracja podaje to formatowanie i jest umieszczona w nawiasie klamrowym `{...}` . Każda deklaracja składa się przynajmniej z jednego zespołu cecha lub inaczej własność albo właściwość (ang. property) - wartość (ang. value), przy czym można podać dowolną liczbę, rozdzielając kolejne znakiem średnika (;). Średnik na końcu deklaracji nie jest konieczny. Każda grupa elementów (znaczników) ma określony zespół cech CSS, które można jej przypisać, a każda cecha ma ściśle wyszczególnioną listę wartości, które może przyjąć. Na przykład: cecha `text-align` (wyrównanie tekstu) może być przypisana tylko i wyłącznie do elementów blokowych, ponieważ podanie jej dla elementów wyświetlanych w linii nie miałoby sensu. Z drugiej strony cecha ta może przyjmować tylko wartości takie jak: `left` , `right` , `center` , `justify` . Przypisanie do niej np. wartości koloru nie miałoby sensu. W MSIE 8.0 i starszych jeden plik arkusza CSS może zawierać tylko 4095 selektorów, przy czym w listach każdy selektor liczy się osobno - następne deklaracje zostaną pominięte! W przypadku przekroczenia tej granicy, jedynym rozwiązaniem jest podział arkusza CSS na kilka osobnych plików, ale nie więcej niż 31. Selektor taki pozwala ustalić określone atrybuty dla wszystkich elementów strony, a więc dla różnych selektorów typu. Możemy za pomocą tej komendy nadać to samo formatowanie dla wszystkich elementów na całej stronie, niezależnie od ich typu (p, h1, li itd.). Niestety jego działanie nie zawsze jest jednoznaczne, dlatego dużo bezpieczniej jest używać selektora typu dla elementu body, chyba że zastosujemy to polecenie w odniesieniu do klasy selektorów. Jeśli selektor uniwersalny chcemy zastosować do selektora innego niż selektor typu (w połączeniu z selektorami: atrybutów, specjalnymi, pseudoelementów lub pseudoklas), to gwiazdkę można pominąć. Selektor uniwersalny ma rolę zmiany stylów dla wszystkich elementów na stronie. Jest przydatny do zastosowań takich jak resetowanie domyślnych stylów przeglądarek, lub wprowadzanie globalnych zmian do marginesów czy paddingu. > przodek1 przodek2 ... potomek { cecha: wartość } Selektor tego typu pozwala nadać atrybuty elementom, które leżą o jeden rząd niżej w hierarchii drzewa dokumentu (zawierają się w innym zewnętrznym znaczniku). W odróżnieniu do poprzedniego przypadku, tutaj znacznik będący dzieckiem, musi znajdować się bezpośrednio wewnątrz znacznika rodzica. To jest akapit, a to jest pogrubienie (nie powinno być czerwone) umieszczone wewnątrz p, ale i wewnątrz znacznika pochylenia. Natomiast to jest pogrubienie (powinno być czerwone) umieszczone bezpośrednio wewnątrz znacznika akapitu. Zwróć uwagę na różnice w stosunku do selektora potomka. Jeśli używasz Internet Explorera 6, interpretacja powyższego przykładu prawdopodobnie nie będzie poprawna. Tylko pogrubienie, które zostało wpisane w drugiej kolejności, powinno być czerwone. > brat1 + brat2 { cecha: wartość } Selektor ten umożliwia nadanie określonych atrybutów jednemu z sąsiadujących ze sobą braci - temu, który w deklaracji został podany jako drugi (czyli brat2). Zwykły tekst znajdujący się pomiędzy braćmi nie ma wpływu na działanie selektora, tzn. jest ignorowany. Załóżmy, że w arkuszu stylów strony została umieszczona następująca reguła: > i + b { color: red }Dzięki temu, jeśli wewnątrz tego samego znacznika (rodzica), będą znajdowały się po sobie znaczniki i oraz b, to ten drugi uzyska określone atrybuty: To jest akapit, wewnątrz którego znajduje się: pochylenie (nie powinno być czerwone) oraz pogrubienie (powinno być czerwone) (zwróć uwagę, że pomiędzy znacznikami jest zwykły tekst - wyraz "oraz"; nie ma on wpływu na działanie selektora)... następne pogrubienie (nie powinno być czerwone). A to jest pogrubienie (nie powinno być czerwone) wewnąrz pochylenia (nie powinno być czerwone). Tutaj kończy się akapit. To jest następny akapit, a w nim kolejne pogrubienie (nie powinno być czerwone), które nie sąsiaduje bezpośrednio z żadnym pochyleniem. Jeśli używasz Internet Explorera 6, interpretacja powyższego przykładu prawdopodobnie nie będzie poprawna. Tylko pogrubienie, które zostało wpisane w pierwszym akapicie jako pierwsze w kolejności, powinno być czerwone. (CSS 3 - interpretuje Internet Explorer 7.0, Firefox, Opera, Chrome) > brat1 ~ brat2 { cecha: wartość } Selektor ten umożliwia nadanie określonych atrybutów wszystkim braciom - tym, których typ w deklaracji został podany jako drugi (czyli brat2). Zwykły tekst znajdujący się pomiędzy braćmi nie ma wpływu na działanie selektora, tzn. jest ignorowany. W odróżnieniu jednak od podstawowego selektora braci, w tym przypadku pomiędzy braćmi mogą się znajdować również elementy innego typu - zostaną pominięte. Nie obsługuje MSIE 6.0!. Załóżmy, że w arkuszu stylów strony została umieszczona następująca reguła: > i ~ b { color: red }Dzięki temu, jeśli wewnątrz tego samego znacznika (rodzica), będą znajdowały się znaczniki i oraz b, to te drugie uzyskają określone atrybuty: To jest akapit, wewnątrz którego znajduje się: pochylenie (nie powinno być czerwone), klawiatura (nie powinien być czerwony) oraz pogrubienie (powinno być czerwone)... następne pogrubienie (powinno być czerwone). A to jest pogrubienie (nie powinno być czerwone) wewnąrz pochylenia (nie powinno być czerwone). Tutaj kończy się akapit. Zwróć uwagę, że pomiędzy braćmi, oprócz zwykłego tekstu, znajduje się dodatkowo znacznik klawiatury (kbd) i mimo to nie zaburza on działania selektora, gdyż jest innego typu niż bracia wyszczególnieni w regule stylów. Ponadto warto zauważyć, że inaczej niż dla podstawowego selektora braci, w tym przypadku formatowanie otrzymują również wszystkie następne znaczniki typu brat2, a nie tylko pierwszy z nich. Właśnie dlatego w powyższym przykładzie drugie pogrubienie również jest czerwone. > selektor1, selektor2, selektor3... { cecha: wartość } ### Co to są reguły stylów CSS? Z czego składa się deklaracja stylu i czym różni się od reguły? Selektor uniwersalny ma rolę zmiany stylów dla wszystkich elementów na stronie. Jest przydatny do zastosowań takich jak resetowanie domyślnych stylów przeglądarek, lub wprowadzanie globalnych zmian do marginesów czy paddingu. Aby wybrać wszystkie elementy `<p>` znajdujące się wewnątrz elementu `<div>...</div>` , można użyć selektora potomka. Na przykład: `div p` zastosowany w regule CSS spowoduje, że zostaną wybrane wszystkie akapity wewnątrz kontenerów. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. ### W jaki sposób nadać formatowanie znacznikowi dziecka znajdującemu się bezpośrednio wewnątrz elementu rodzica? > rodzic > dziecko { cecha: wartość } ### W jaki sposób nadać formatowanie znacznikowi znajdującemu się bezpośrednio po innym elemencie - bracie? > brat1 + brat2 { cecha: wartość } ### W jaki sposób nadać formatowanie znacznikom znajdującym się w dowolnym miejscu po innym elemencie - bracie? > brat1 ~ brat2 { cecha: wartość } ### W jaki sposób za jednym razem przypisać formatowanie różnym selektorom CSS? * Prosty selektor atrybutu W jaki sposób określić formatowanie elementu, który posiada określony atrybut? * Selektor atrybutu o określonej wartości W jaki sposób określić formatowanie elementu, który posiada określony atrybut o odpowiedniej wartości? * Selektor atrybutu zawierającego określony wyraz W jaki sposób określić formatowanie elementu, który posiada określony atrybut zawierający podany wyraz? * Selektor atrybutu zawierającego łączniki Jak zmienić wygląd elementów, które mają podane atrybuty z określonymi łącznikami, np. "en-US"? * Selektor atrybutu o wartości rozpoczynającej się od... W jaki sposób zmienić wygląd elementu, który posiada atrybut o wartości rozpoczętej podanym tekstem? * Selektor atrybutu o wartości kończącej się na... W jaki sposób zmienić wygląd elementu, który posiada atrybut o wartości zakończonej podanym tekstem? * Selektor atrybutu zawierającego określony tekst W jaki sposób określić formatowanie elementu, który posiada określony atrybut zawierający podany tekst? * Łączenie selektorów atrybutów Jak połączyć kilka selektorów atrybutów w jednej regule stylów CSS? * Powtórka Atrybut oznacza konkretny parametr nadany znacznikowi z poziomu języka HTML (np. atrybut `title="..."` ). Natomiast wyrazy "cecha" oraz "wartość" określają atrybuty elementu nadane poprzez style i zostaną opisane w dalszych rozdziałach. Polecenie to może zostać wykorzystane dla elementów, którym z poziomu HTML został nadany określony atrybut (przy czym jego wartość nie ma znaczenia). Pozwala nadać konkretne cechy elementom, które posiadają właśnie taki atrybut. Na przykład znacznik może być automatycznie napisany czcionką koloru czerwonego, jeśli ma nadany atrybut `title="..."` (który powoduje wyświetlenie tekstu informacji, po wskazaniu myszką). W tym przypadku nie ma znaczenia jaką wartość ma atrybut, ważne jest jedynie, aby został on nadany. UWAGA! Polecenie nie interpretuje MSIE 6 (od wersji 7 wszystko jest już w porządku) .W języku XHTML wszystkie nazwy atrybutów w selektorach muszą być pisane małymi literami. Jeśli w arkuszu stylów strony została umieszczona następująca reguła: > p[title] { color: red }to każdy akapit, któremu został nadany atrybut `title="..."` , powinien mieć kolor czerwony: To jest akapit, któremu został nadany atrybut TITLE (aby to sprawdzić, wskaż go myszką) i dlatego powinien być koloru czerwonego. Dozwolone jest podanie kilku atrybutów. Wtedy element musi posiadać wszystkie z nich, aby otrzymał formatowanie: > p[title][lang] { color: red } To jest akapit z atrybutem TITLE oraz LANG (powinien być czerwony). To jest akapit tylko z atrybutem TITLE (nie powinien być czerwony). > selektor[atrybut="wartość atrybutu"] { cecha: wartość } Atrybut oznacza konkretny parametr nadany znacznikowi z poziomu HTML (np. atrybut `title="..."` ). "Wartość atrybutu" to określona wartość, która została nadana temu atrybutowi (np. treść atrybutu `title="..."` ). Natomiast wyrazy "cecha" oraz "wartość" określają atrybuty elementu nadane poprzez style i zostaną opisane w dalszych rozdziałach. Polecenie to może zostać wykorzystane dla elementów, którym z poziomu HTML został nadany atrybut, który ma określoną wartość. Pozwala nadać konkretne cechy elementom, które posiadają atrybut, właśnie z taką dokładnie wartością. Na przykład znacznik może być automatycznie napisany czcionką koloru czerwonego, jeśli ma nadany atrybut `title="..."` , o wartości podanej w deklaracji stylu. Znaczniki z atrybutem `title="..."` o innej wartości nie będą już czerwone. UWAGA! Polecenie nie interpretuje MSIE 6 (od wersji 7 wszystko jest już w porządku).W języku XHTML wszystkie nazwy atrybutów w selektorach muszą być pisane małymi literami. A to jest akapit z atrybutem TITLE o innej wartości niż w regule stylu. Dozwolone jest podanie kilku atrybutów. Wtedy element musi posiadać wszystkie z nich i każdy musi mieć przypisaną wyszczególnioną wartość, aby otrzymał formatowanie: > p[title="To jest akapit"][lang="pl"] { color: red } To jest akapit, któremu został nadany atrybut title="Akapit" oraz lang="pl" (nie powinien być czerwony). Inne przydatne zastosowanie tego selektora to np. zmiana sposobu formatowania elementów formularzy. Niemal wszystkie kontrolki formularza są tworzone przy użyciu znacznika `<input type="...">` . O tym jaki rodzaj pola zobaczymy na ekranie, decyduje atrybut `type="..."` . Jeśli chcielibyśmy zmienić rodzaj obramowania dla wszytkich pól tekstowych ( `type="text"` ), tak aby nie wpłynęło to na pola innego typu (np. na przycisk wysłania formularza - `type="submit"` ), należałoby wpisać np. taką regułę: > input[type="text"] { border: 1px solid black } Niestety również ta deklaracja nie jest interpretowana przez MSIE 6 :-(. Jedynym rozwiązaniem problemu wydaje się użycie klasy selektorowej dla każdego pojedynczego znacznika pola tekstowego w formularzu. Wtedy przynajmniej będzie można określić wszystkie własności formatowania elementu w jednym miejscu (arkuszu stylów), co znacznie ułatwi i przyspieszy ewentualne późniejsze modyfikacje. > selektor[atrybut~="wyraz"] { cecha: wartość } Atrybut oznacza konkretny parametr nadany znacznikowi z poziomu HTML (np. atrybut `title="..."` ), którego wartość składa się z wyrazów rozdzielonych spacjami. "Wyraz" to określone słowo, zawierające się w wartości atrybutu, które nie może zawierać spacji. Natomiast wyrazy "cecha" oraz "wartość" określają atrybuty elementu nadane poprzez style i zostaną opisane w dalszych rozdziałach. Polecenie to może zostać wykorzystane dla elementów, którym z poziomu HTML został nadany atrybut, o wartości składającej się z kilku wyrazów rozdzielonych spacjami. Deklaracja taka pozwala nadać konkretne cechy elementom, posiadającym atrybut, w którego wartości występuje podany wyraz (oprócz niego mogą występować tam również inne wyrazy). Wyraz nie może zawierać spacji! Na przykład deklaracja `title~="jest"` kojarzy atrybuty: ``` title="To jest akapit" ``` ``` title="To jest pogrubienie" ``` itd. UWAGA! Polecenie nie interpretuje MSIE 6 (od wersji 7 wszystko jest już w porządku).W języku XHTML wszystkie nazwy atrybutów w selektorach muszą być pisane małymi literami. Dozwolone jest podanie kilku atrybutów lub/i wyrazów. Wtedy element musi posiadać wszystkie z nich i każdy musi zawierać wyszczególniony wyraz, aby otrzymał formatowanie: > p[title~="jest"][lang~="pl"] { color: red } To jest akapit, któremu został nadany atrybut title="Akapit" i lang="pl" (nie powinien być czerwony). > p[title~="jest"][title~="akapit"] { color: red } To jest akapit, któremu został nadany atrybut title="akapit" (nie powinien być czerwony). > selektor[atrybut|="początek"] { cecha: wartość } Atrybut oznacza konkretny parametr nadany znacznikowi z poziomu HTML (np. atrybut `lang="..."` ), którego wartość składa się z wyrazów rozdzielonych łącznikami (myślnikami). "Początek" to określony wyraz, od którego rozpoczyna się wartość atrybutu. Natomiast wyrazy "cecha" oraz "wartość" określają atrybuty elementu nadane poprzez style i zostaną opisane w dalszych rozdziałach. Polecenie to może zostać wykorzystane dla elementów, którym z poziomu HTML został nadany atrybut, o wartości składającej się z kilku wyrazów rozdzielonych łącznikami (myślnikami). Reguła taka pozwala nadać konkretne cechy elementom, posiadającym atrybut, którego wartość rozpoczyna się od podanego wyrazu. Na przykład składnia `lang|="en"` kojarzy atrybuty: `lang="en-us"` lub `lang="en-au"` , jak również `lang="en"` . Selektor taki został przewidziany do obsługi języków (atrybut LANG), których skróty zawierają często łączniki (np. "en-US" to język angielski w Stanach Zjednoczonych, "en-AU" to język angielski w Australii). UWAGA! Polecenie nie interpretuje MSIE 6 (od wersji 7 wszystko jest już w porządku).W języku XHTML wszystkie nazwy atrybutów w selektorach muszą być pisane małymi literami. Jeżeli w arkuszu stylów strony została umieszczona następująca reguła: > p[title|="to"] { color: red }to każdy akapit, któremu został nadany atrybut TITLE z wartością, która rozpoczyna się od "to" (i może składać się z łączników), powinien mieć kolor czerwony: A to jest akapit z atrybutem title="także-i-to-jest-akapit" (nie powinien być czerwony) Atrybut oznacza konkretny parametr nadany znacznikowi z poziomu HTML (np. atrybut `title="..."` ). "Początek" to określony tekst, którym rozpoczyna się wartość atrybutu. Podobnie jak w przypadku selektora z łącznikami polecenie to pozwala wybrać element z atrybutem o wartości, która ma na początku wymagany tekst, ale po niej nie musi być już żadnego łącznika. Jeżeli w arkuszu stylów strony została umieszczona następująca reguła: > p[title^="to"] { color: red }to każdy akapit, któremu został nadany atrybut TITLE z wartością, która rozpoczyna się od "to", powinien mieć kolor czerwony: A to jest akapit z atrybutem title="także i to jest akapit" (nie powinien być czerwony) Atrybut oznacza konkretny parametr nadany znacznikowi z poziomu HTML (np. atrybut `title="..."` ). "Koniec" to określony tekst, którym kończy się wartość atrybutu. Jeżeli w arkuszu stylów strony została umieszczona następująca reguła: > p[title$="akapit"] { color: red }to każdy akapit, któremu został nadany atrybut TITLE z wartością, która kończy się na "akapit", powinien mieć kolor czerwony: A to jest akapit z atrybutem title="to jest akapit także" (nie powinien być czerwony) Atrybut oznacza konkretny parametr nadany znacznikowi z poziomu HTML (np. atrybut `title="..."` ). "Tekst" to określony napis, zawierający się w wartości atrybutu, który może zawierać również spacje. Działa podobnie jak selektor atrybutu z podanym wyrazem, jednak pozwala dopasować nie tylko pełne wyrazy, ale dowolną ich część (np. kilka sylab) czy nawet kilka wyrazów. Jeżeli w arkuszu stylów strony została umieszczona następująca reguła: > p[title*="jest aka"] { color: red }to każdy akapit, któremu został nadany atrybut `title="..."` o wartości, w której występuje tekst "jest aka", powinien mieć kolor czerwony: To jest akapit, któremu został nadany atrybut TITLE o wartości "To jest akapit" (aby to sprawdzić, wskaż go myszką) i dlatego jest koloru czerwonego. * Co to są pseudoelementy? Do czego przydają się pseudoelementy CSS? * Pierwsza linia :first-line W jaki sposób zmienić wygląd pierwszej linii tekstu? * Pierwsza litera :first-letter W jaki sposób zmienić wygląd pierwszej litery tekstu? * Przed... :before W jaki sposób wygenerować dynamicznie tekst przed określonym elementem? * Po... :after W jaki sposób wygenerować dynamicznie tekst po określonym elemencie? * Cudzysłowy {quotes} Pojedynczy cudzysłów ostrokątny można uzyskać w kodzie HTML za pomocą encji znakowej &lsaquo; (‹) i &rsaquo; (›). Natomiast aby uzyskać podwójny cudzysłów ostrokątny, wystarczy wpisać: &laquo; («) i &raquo; (»). W języku polskim kombinacji znaków `»...«` używa się, gdy występuje cudzysłów w cudzysłowie. Natomiast zapis `«...»` stosuje się do wskazania znaczeń w słownikach i opracowaniach naukowych. Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu CSS. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. * Co to są pseudoklasy? Do czego przydają się pseudoklasy CSS? * Odsyłacz podstawowy :link Jak zmienić wygląd odsyłaczy (odnośników hipertekstowych, hiperłączy, linków)? * Odsyłacz odwiedzony :visited Jak zmienić wygląd odwiedzonych odsyłaczy (odnośników hipertekstowych, hiperłączy, linków)? * Aktywacja :active Jak zmienić wygląd aktywnych elementów - np. odsyłaczy (odnośników hipertekstowych, hiperłączy, linków)? * Wskazanie myszką :hover Jak zrobić podświetlany link (odsyłacz, odnośnik hipertekstowy, hiperłacze)? * Zogniskowanie :focus W jaki sposób zmienić wygląd elementów, zawierających tekst w wybranym języku? * Pierwsze dziecko :first-child Jak zmienić wygląd pierwszego elementu dziecka, znajdującego się wewnątrz znacznika rodzica? * Ostatnie dziecko :last-child Jak zmienić wygląd ostatniego elementu dziecka, znajdującego się wewnątrz znacznika rodzica? * Jedyne dziecko :only-child Jak zmienić wygląd elementu dziecka, który nie ma braci? * Pseudoklasy typu :first-of-type :last-of-type :only-of-type W jaki sposób zmienić wygląd tylko pierwszego elementu określonego typu? * Etykieta :target Jak zmienić wygląd odnośników (odsyłaczy, linków) do etykiety (kotwica)? * Blokada :disabled :enabled Jak zmienić wygląd pól (kontrolek) formularza, które są zablokowane (wyszarzone)? * Tylko do odczytu :read-only :read-write Jak zmienić wygląd pól (kontrolek) formularza, które są zablokowane do zapisu? * Zaznaczenie :checked Jak zmienić wygląd pól (kontrolek) formularza, które są zaznaczone? * Domyślne :default Jak zmienić wygląd domyślnego przycisku formularza lub domyślnej opcji do wyboru? * Pusty element :empty W jaki sposób zmienić sposób formatowania elementów, które nie zawierają żadnej treści? * Korzeń :root W jaki sposób za pomocą CSS odnieść się do korzenia drzewa dokumentu? * Pseudoklasy cykliczne :nth-child :nth-last-child :nth-of-type :nth-last-of-type Jak zmienić wygląd parzystych lub nieparzystych wierszy tabeli? Jak pokolorować co trzeci wiersz? * Negacja :not W jaki sposób zmienić wygląd wszystkich elementów z wyjątkiem podanych? * Łączenie selektorów W jaki sposób połączyć kilka selektorów w jednej regule stylów CSS? Jak zmienić obramowanie obrazka po wskazaniu myszką? Jak dodać ciekawie wyglądający tekst po wskazaniu myszką? * Szczegółowość selektorów Jak określić ważność różnych selektorów w tym samym arkuszu stylów, odnoszących się do tych samych elementów i własności? * Powtórka * Pseudoklasy dynamiczne * Pseudoklasa etykiety: :target * Pseudoklasa języka: :lang() * Pseudoklasy interfejsu użytkownika: * Pseudoklasy strukturalne: * Pseudoklasa negacji: :not() > a:link { cecha: wartość } ### Przykład :link Jeżeli nie byłeś jeszcze na stronie głównej organizacji W3C, to ten odsyłacz powinien być pogrubiony. . > a:visited { cecha: wartość } ### Przykład :visited Jeżeli byłeś już na stronie głównej organizacji W3C, to ten odsyłacz powinien być pogrubiony. > selektor:active { cecha: wartość } Jeżeli wciśniesz i przytrzymasz przycisk myszki nad tym odsyłaczem, to do chwili zwolnienia przycisku, będzie on pogrubiony. > selektor:hover { cecha: wartość } * Dowolny rodzic: > dziecko:last-child { cecha: wartość } * Określony rodzic: > rodzic > dziecko:last-child { cecha: wartość } ### Przykład :last-child Polecenie pozwala nadać określone atrybuty formatowania dla elementu, który jest dzieckiem innego elementu - o jeden rząd niżej w hierarchii drzewa dokumentu, ale tylko jeśli rodzic nie ma już innych dzieci. ### Przykład :only-child Po wpisaniu w arkuszu stylów: > b:only-child { color: red }otrzymamy na stronie: To jest akapit, wewnątrz którego znajduje się pogrubienie (powinno być czerwone). Ten akapit ma tylko jedno dziecko. Dla porównania to jest akapit, wewnątrz którego znajduje się pierwsze pogrubienie (nie powinno być czerwone) oraz drugie pogrubienie (również nie powinno być czerwone). Ten akapit ma więcej niż jedno dziecko. * Termin 1 * Definicja 1 Zwróć uwagę, że tylko termin drugiej z list jest podkreślony, ponieważ pierwsza lista posiada więcej niż jeden element `<dt>...</dt>` . Jednocześnie, ponieważ jedyny termin drugiej listy jest zarazem ostatnim takim elementem, przyjmie również określony wcześniej dodatkowy sposób formatowania - kursywę. Natomiast jedyna definicja drugiej listy jest zarazem na niej pierwsza, więc będzie pogrubiona. (CSS 3 - interpretuje Internet Explorer 9, Firefox, Opera, Chrome) > selektor:target { cecha: wartość } `id="..."` albo ewentualnie może to być element A posiadający atrybut `name="..."` [zobacz: Odsyłacz do etykiety i Wstawianie stylów]. Natomiast wyrazy "cecha" oraz "wartość" określają atrybuty elementu nadane poprzez style i zostaną opisane w dalszych rozdziałach. Czasami podział serwisu na podstrony jest niewystarczający. Zdarza się, że jeden artykuł jest podzielony dodatkowo na niewielkie sekcje - zbyt małe, aby tworzyć z każdej z nich osobną podstronę. Chcielibyśmy jednak mieć możliwość odesłania czytelnika bezpośrednio do podanej sekcji, żeby nie musiał jej szukać "ręcznie". W takiej sytuacji stosuje się etykiety (np.: Niektóre z pól formularzy pełnią rolę przełączników - można je zaznaczać i odznaczać. W związku z tym może się okazać przydatne dodatkowe wizualne wyróżnienie tych kontrolek, które użytkownik zaznaczył. Zaznaczenie dla opcji listy rozwijalnej obsługuje tylko Firefox. ### Przykład :checked Po wpisaniu w arkuszu stylów: > input:checked, option:checked { margin-left: 30px }a w dowolnym miejscu strony: > <form action="?"> <fieldset> <input type="radio" checked name="pole_opcji"> <input type="radio" name="pole_opcji"> </fieldset> <fieldset> <input type="checkbox" checked> <input type="checkbox"> </fieldset> <select size="3"> <option selected>Opcja 1</option> <option>Opcja 2</option> <option>Opcja 3</option> </select> </form>otrzymamy formularz, w którym zaznaczone pola mają dodatkowy margines z lewej strony (aby to sprawdzić zmień zaznaczenie wybranych kontrolek): Zaznaczona opcja listy rozwijalnej (ostatnia z powyższych kontrolek) będzie wyróżniona najprawdopodobniej tylko w przeglądarce Firefox. Każdy dokument HTML ma w drzewie dokumentu dokładnie jeden korzeń, tzn. element najbardziej nadrzędny, który nie ma żadnego rodzica, za to zawiera w sobie (bezpośrednio lub poprzez zagnieżdżenie) wszystkie inne elementy dokumentu. W języku HTML korzeniem jest zawsze element HTML, zatem selektor ten jest w tym przypadku raczej mało przydatny, ponieważ ten sam efekt uzyskamy poprzez użycie najprostszego selektora typu: > html { cecha: wartość } Nie zapominajmy jednak, że CSS nadaje się do stylizowania również dokumentów XML, gdzie nie ma żadnego wymogu co do nazwy elementu-korzenia. ### Przykład :root Po wpisaniu w arkuszu stylów: > :root p { color: red }a w dowolnym miejscu strony: > <p>To jest akapit</p>powinniśmy otrzymać tekst koloru czerwonego: n | wzór | wynik | | --- | --- | --- | nwzórwynik02*0+1112*1+1322*2+15itd. , to `:nth-of-type(3)` wybierze ostatni element `<p>` (trzeci akapit), a `:nth-child(3)` dopasuje element `<div>` (trzecie dziecko). (CSS 3 - interpretuje Internet Explorer 9, Firefox, Opera, Chrome) > selektor:not(argument) { cecha: wartość } , to `:nth-of-type(3)` wybierze ostatni element `<p>` (trzeci akapit), a `:nth-child(3)` dopasuje element `<div>` (trzecie dziecko). Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. * Wielkość czcionki {font-size} Jak zmienić rozmiar (wielkość) czcionki? Jaki jest najlepszy sposób ustalania wielkości czcionki? * Rodzaj czcionki {font-family} W jaki sposób wczytać czcionkę z pliku? * Styl czcionki {font-style} W jaki sposób wprowadzić czcionkę pochyloną (kursywa)? Czym różni się styl "italic" od "oblique"? * Waga czcionki {font-weight} Jak wprowadzić czcionkę pogrubioną? Czy można wytłuścić tekst z różną intensywnością? * Wariant wielkości liter czcionki {font-variant-caps} W jaki sposób przekształcić zwykły tekst w kapitaliki, czyli napisany wielkimi literami, lecz czcionką o wysokości małych liter? * Wariant połączenia znaków czcionki {font-variant-ligatures} Co zrobić, aby liczby w kolumnach tabeli z danymi były ułożone równo pod sobą? W jaki sposób wyświetlić licznik i mianownik rozdzielone kreską ułamkową? * Wariant pozycji czcionki {font-variant-position} W jaki sposób dodać indeks dolny lub górny tak, aby sąsiednie linijki tekstu nie były między sobą nieestetycznie rozsunięte? * Atrybuty mieszane wariantu czcionki {font-variant} W jaki sposób określić w jednym poleceniu wiele własności wariantu czcionki: połączenie liter (ligatury), wielkość liter (kapitaliki), formatowanie liczb oraz wyglądu indeksów dolnych i górnych w tekście? * Atrybuty mieszane czcionki {font} W jaki sposób rozciągnąć lub ścieśnić czcionkę? * Proporcje czcionki {font-size-adjust} W jaki sposób regulować odległość pomiędzy sąsiednimi znakami tekstu (kerning) tak, aby wyglądał bardziej estetycznie i był czytelniejszy? * Powtórka . > selektor { font-style: styl } Aby zastosować kursywę w CSS, użyj właściwości `font-style` i ustaw wartość italic dla tekstu. Na przykład: " `font-style: italic` ". > selektor { font-weight: waga } Właściwość `font-variant` w CSS kontroluje wariant czcionki. Podstawowe dostępne wartości to: normal (domyślny wariant) oraz small-caps (kapitaliki). Wartość small-caps powoduje, że cały tekst będzie napisany wielkimi literami, ale o obniżonej wysokości. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. * Kolor tekstu {color} Jak zmienić kolor tekstu w dowolnym elemencie? * Dekoracja tekstu {text-decoration} Jak ustawić tekst po lewej, po prawej lub na środku (wyśrodkowanie, centrowanie)? Co zrobić, aby tekst był równo ułożony przy obu marginesach (justowanie)? * Wcięcie w tekście {text-indent} W jaki sposób prawidłowo dodawać wcięcia w akapitach? * Cień pod tekstem {text-shadow} Jak można by było dodać cień pod tekstem? * Wysokość linii tekstu {line-height} Jak zmienić odległość między linijkami tekstu (wysokość linii), tak aby stał się bardziej czytelny lub skondensowany? * Odstęp między wyrazami tekstu {word-spacing} Jak rozstrzelić lub ścieśnić tekst poprzez zwiększenie odległości między sąsiednimi wyrazami? * Odstęp między literami tekstu {letter-spacing} Jak rozstrzelić lub ścieśnić tekst poprzez zwiększenie odległości między literami? * Białe znaki w tekście {white-space} W jaki sposób zablokować zawijanie tekstu? Co zrobić, aby klawisze Enter i Tab były widoczne na ekranie? * Tryb pisania {writing-mode} Co zrobić, aby tekst na stronie był ułożony pionowo - z góry na dół? * Orientacja tekstu {text-orientation} Co zrobić, aby znaki w tekście były ułożone pionowo jeden pod drugim? * Powtórka . > selektor { text-transform: transformacja } . To spowoduje, że wszystkie litery w tekście będą wielkie. > selektor { text-align: wyrównanie } Polecenie pozwala wybrać jeden z możliwych sposobów wyrównania tekstu, czyli jego ułożenia na ekranie. ### Przykład {text-align} wyrównanie left (domyślnie)wyrównanie left - do lewego marginesu left wyrównanie tekstu rightwyrównanie right - do prawego marginesu right wyrównanie center (wyśrodkowanie)wyrównanie center - do środka center Wyrównanie tekstu justify - do obu marginesów jednocześnie... Wyrównanie tekstu justify - do obu marginesów jednocześnie... Wyrównanie tekstu justify - do obu marginesów jednocześnie... Wyrównanie tekstu justify - do obu marginesów jednocześnie... Wyrównanie tekstu justify - do obu marginesów jednocześnie... Wyrównanie tekstu justify - do obu marginesów jednocześnie... Wyrównanie tekstu justify - do obu marginesów jednocześnie... Wyrównanie tekstu justify - do obu marginesów jednocześnie... . > selektor { text-indent: wcięcie } Natomiast jako "wcięcie" należy podać konkretną wielkość wcięcia, używając jednostek długości. Wcięcie w tekście oznacza dodatkowy odstęp pierwszej linijki w bloku od lewego marginesu (jak tabulator). Stosuje się je, gdy rozpoczynamy nowy akapit (na inny temat). ### Przykład {text-indent} To jest akapit, w którego pierwszej linijce wcięcie wynosi 1cm... To jest akapit, w którego pierwszej linijce wcięcie wynosi 1cm... To jest akapit, w którego pierwszej linijce wcięcie wynosi 1cm... wcięcie o 20 pikseli. Natomiast jeśli chcesz wciąć wszystkie wiersze tekstu w całym akapicie, zastosuj właściwość margin-left. (interpretuje: Internet Explorer 10.0, Firefox 3.5, Opera 9.5, Chrome, Konqueror) > selektor { text-shadow: poziom pion rozmycie kolor,... } text-shadow: 3px 3px red, yellow -3px 3px 2px, 3px -3px > selektor { line-height: wysokość } Polecenie to pozwala ustalić odstęp pomiędzy wszystkimi poszczególnymi wyrazami w bloku. Dzięki temu wyrazy w linijkach mogą być bardziej ścieśnione lub rozciągnięte. UWAGA! Polecenie nie jest interpretowane przez MSIE 5, natomiast w MSIE 6 wszystko jest w porządku. ### Przykład {word-spacing} To jest akapit, w którym odstępy między wyrazami wynoszą 1cm > selektor { letter-spacing: odstęp } Aby rozstrzelić tekst w CSS, użyj właściwości `letter-spacing` i ustaw wartość dodatnią, np. " `letter-spacing: 1px` " dla odstępów między literami. Im większa wartość, tym większy efekt rozstrzelenia tekstu. To spowoduje, że litery będą od siebie bardziej oddzielone, tworząc efekt rozstrzelonego tekstu. > selektor { white-space: sposób } * Kolor tła {background-color} Jak zmienić kolor tła dowolnego elementu? * Tło obrazkowe {background-image} Jak ustawić tło graficzne (obrazek, zdjęcie) pod dowolnym elementem? Jak ustalić rozmiary obrazka w tle? * Powtarzanie tła obrazkowego {background-repeat} Jak ustawić obrazek (grafikę, zdjęcie) w tle w określonej pozycji? * Zaczepienie tła obrazkowego {background-attachment} Jak zrobić tło graficzne (obrazek, zdjęcie), które nie przesuwa się przy przewijaniu strony? * Przycinanie tła {background-clip} W jaki sposób usunąć tło spod wewnętrznych marginesów elementu, ale wyświetlić je pod treścią? * Pozycja początkowa tła obrazkowego {background-origin} W jaki sposób określić pozycję obrazka tła, względem której będą liczone wszelkie przesunięcia? * Rozmiary tła obrazkowego {background-size} W jaki sposób przeskalować obrazek wstawiony w tle, tak żeby pasował idealnie? * Atrybuty mieszane tła {background} Jak można najłatwiej ustawić kilka własności tła w jednym poleceniu? * Gradient liniowy {background: linear-gradient repeating-linear-gradient} Jak wypełnić tło płynnym przejściem kilku kolorów w postaci gradientu? * Gradient promienisty {background: radial-gradient repeating-radial-gradient} Jak usunąć wcześniej dodane tło? * Powtórka w deklaracji tła. (CSS 3 - interpretuje Internet Explorer 9, Firefox 4, Opera, Chrome) > selektor { background-clip: przycinanie } * border-box - tło wyświetli się pod obramowaniem, marginesem wewnętrznym i właściwą zawartością elementu (domyślnie) [Zobacz: Model pudełkowy] * padding-box - tło wyświetli się pod marginesem wewnętrznych i właściwą zawartością elementu * content-box - tło wyświetli się tylko pod właściwą zawartością elementu ### Przykład {background-clip} Natomiast jako "początek" należy wpisać: * border-box - pozycja tła będzie liczona względem krawędzi obramowania [Zobacz: Model pudełkowy] * padding-box - pozycja tła będzie liczona względem krawędzi marginesu wewnętrznego (domyślnie) * content-box - pozycja tła będzie liczona względem krawędzi właściwej zawartości elementu Zgodnie z komputerowym układem współrzędnych punkt zerowy znajduje się zawsze w lewym-górnym narożniku. W przypadku modelu pudełkowego możemy mieć jednak aż trzy takie narożniki - dla różnych obszarów wewnątrz elementu. Ustalenie położenia początkowego okazuje się szczególnie przydatne, jeśli korzystamy również z przycinania tła. ### Przykład {background-origin} Natomiast jako "rozmiary" należy wpisać: * contain - skaluje obrazek, zachowując proporcje, tak aby w całości zmieścił się w tle * cover - skaluje obrazek, zachowując proporcje, tak aby pokrył cały obszar tła (część grafiki może być niewidoczna) * auto - zachowanie domyślne * długość - obrazek zostanie przeskalowany do podanego wymiaru * wartość procentową - obrazek zostanie przeskalowany względem obszaru pozycjonowania tła Często zależy nam na wstawieniu w tle strony tylko jednego egzemplarza obrazka (bez jego powielania), ale w taki sposób aby idealnie dopasował się do rozmiarów okna przeglądarki - niezależnie od używanej rozdzielczości ekranu. Powyższe polecenie pozwala uzyskać taki efekt i to bez żadnych sztuczek ani obejść. Trzeba jednak pamiętać, że rozciąganie obrazka nie tylko zniekształca jego proporcje, ale również w przypadku powiększania wpłynie na utratę jakości grafiki. Pamiętaj również, aby nie wstawiać w tle zdjęć o przesadnie dużych wymiarach, ponieważ będą wydłużały czas wczytywania strony. ### Przykład {background-size} ### Atrybuty mieszane tła {background} # > selektor { background: wartości atrybutów } Natomiast jako "wartości atrybutów" należy wpisać konkretne wartości atrybutów, dotyczących tła, które będą oddzielone od siebie spacjami (przy czym można niektóre pominąć). Są to: * kolor tła * tło obrazkowe * powtarzanie tła * zaczepienie tła * pozycja tła lub pozycja tła / rozmiary tła (CSS 3 - Opera) * zaczepienie tła * przycinanie tła (CSS 3 - Opera) * pozycja początkowa tła (CSS 3 - Opera) Wartość rozmiarów tła ( `background-size` ) musi być poprzedzona znakiem ukośnika i musi się znajdować bezpośrednio po wartości pozycji ( `background-position` ), np.: "left top / contain". Nie można podać rozmiarów tła bez określenia pozycji, ale można samą pozycję bez rozmiarów. Polecenie to pozwala w wygodny sposób zdefiniować wszystkie atrybuty tła. Już nie musimy wypisywać kolejno wszystkich cech, a jedynie ich konkretne wartości. Wartością może być np.: url(obrazek) ( `background-image` ), no-repeat ( `background-repeat` ) czy left ( `background-position` ). Wszystkie wartości muszą być oddzielone od siebie spacjami. Nie ma wymogu, aby podawać w tej deklaracji pełną listę cech składowych, jednak jeśli jakąś opuścimy, zostanie jej przypisana wartość domyślna. Dlatego poniższa reguła stylów nie ustawi tła koloru czerwonego (red), ponieważ nie zostało to określone w deklaracji `background` , która tutaj unieważnia `background-color` : > p { background-color: red; background: url(tlo.gif) } Zgodnie z zasadą kaskadowości, oczekiwany skutek (czerwone tło) odniesiemy, podając deklaracje w odwrotnej kolejności: > p { background: url(tlo.gif); background-color: red } albo przenosząc wartość `background-color` (red) do zbiorczej deklaracji `background` : > p { background: red url(tlo.gif) } W przeglądarce MSIE 8, Firefox i Chrome wstawienie do atrybutów mieszanych wartości własności dostępnych dopiero od CSS 3 skutkuje zupełnym brakiem tła! Dlatego w ich wypadku bezpieczniej jest stosować standardową, a nie skróconą składnię. Po wpisaniu: > <p style="color: red; background: url(obrazek.jpg) no-repeat left"> To jest akapit z obrazkiem w tle. obrazek ma podaną w nawiasie ścieżkę dostępu, nie jest powtarzany (jest tylko jeden egzemplarz) oraz jest ustawiony po lewej stronie. </p>otrzymamy na ekranie: To jest akapit z obrazkiem w tle. Obrazek ma podaną w nawiasie ścieżkę dostępu, nie jest powtarzany (jest tylko jeden egzemplarz) oraz jest ustawiony po lewej stronie. ### Tło graficzne obok tekstu # Warto tutaj jeszcze wspomnieć o możliwości dodawania obrazków do dowolnego tekstu. Można w ten sposób stworzyć tekst, obok którego znajduje się jakaś grafika (np. po lewej stronie). Nie trzeba w takim wypadku dodawać znacznika <img>, odpowiadającego za wstawienie rysunku, ale wystarczy np. zadeklarować odpowiednią klasę w zewnętrznym arkuszu stylów, a grafika zostanie dodana jako tło (bez powtarzania). Dodatkowo tekst będzie przesunięty w prawo, aby nie zasłaniał obrazka. Sposób taki ma tą zaletę, że w każdej chwili możemy usunąć obrazek lub zmienić jego pozycję, bez potrzeby modyfikacji każdej strony, na której występuje taki element. Ma to duże znaczenie, jeśli powtarza się on na wielu stronach. Niestety podczas drukowania strony, obrazek taki zostanie pominęty. Również jeśli przeglądarka nie interpretuje stylów, obrazek nie pojawi się na ekranie. Jeśli nam to przeszkadza, należy stosować tradycyjny sposób (znacznik IMG). Po wpisaniu w arkuszu stylów: > *.obrazek { background: url(obrazek.jpg) no-repeat left top; padding-left: 110px }a następnie na stronie: > <p class="obrazek">Po lewej stronie tego tekstu znajduje się obrazek, który... (itd.)</p>otrzymamy: Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Po lewej stronie tego tekstu znajduje się obrazek, który został wstawiony automatycznie... Uwaga: Pogrubiona wartość 110 w deklaracji klasy powyżej, odpowiada za przesunięcie tekstu w prawo i nie powinna być ona mniejsza od szerokości obrazka (w pikselach), aby nie był on zasłonięty! ### Wielokrotne atrybuty mieszane # (CSS 3 - interpretuje Firefox, Opera, Chrome) > selektor { background: wartości atrybutów obrazka 1, wartości atrybutów obrazka 2... } Korzystając z rozszerzonej składni atrybutów mieszanych, możemy wstawić w tle elementu kilka obrazków i od razu określić dla nich dodatkowe własności, takie jak np. sposób powtarzania, zaczepienie, pozycja / rozmiary, przycinanie czy pozycja początkowa. Trzeba jednak pamiętać, że o ile w tle jednego elementu może być wstawionych kilka obrazków, to ustawienie więcej niż jednego jednolitego koloru tła nie ma sensu. Dlatego podanie jednolitego koloru tła jest dozwolone tylko jeden raz - na samym końcu, tzn. dla ostatniego elementu listy atrybutów mieszanych: > div { background: url(obrazek1.jpg), url(obrazek2.jpg), url(obrazek3.jpg) red } MSIE 8 w takim przypadku nie wyświetli żadnego tła - ani obrazkowego ani jednolitego koloru! Dla porównania - tak będzie wyglądał ten sam gradient, ale już bez powtarzania: > selektor { background: none } * Model pudełkowy Jakie są zasady obliczania faktycznych rozmiarów elementów na stronach WWW? Jakie są najczęstsze pułapki? * Wymiarowanie pudełka {box-sizing} Jak zmienić zasady obliczania faktycznych rozmiarów elementów na stronach WWW? * Górny margines {margin-top} Jak ustawić górny margines dowolnego elementu? * Dolny margines {margin-bottom} Jak ustawić dolny margines dowolnego elementu? * Lewy margines {margin-left} Jak ustawić lewy margines dowolnego elementu? * Prawy margines {margin-right} Jak ustawić prawy margines dowolnego elementu? * Atrybuty mieszane marginesu {margin} Jak ustawić jednocześnie wszystkie marginesy dla dowolnego elementu: górny, prawy, dolny, lewy? * Załamywanie marginesów Jak zachowują się marginesy sąsiadujących ze sobą elementów? * Górny margines wewnętrzny {padding-top} Jak dodać górny margines (odstęp) wewnątrz dowolnego elementu? * Dolny margines wewnętrzny {padding-bottom} Jak dodać dolny margines (odstęp) wewnątrz dowolnego elementu? * Lewy margines wewnętrzny {padding-left} Jak dodać lewy margines (odstęp) wewnątrz dowolnego elementu? * Prawy margines wewnętrzny {padding-right} Jak dodać prawy margines (odstęp) wewnątrz dowolnego elementu? * Atrybuty mieszane marginesu wewnętrznego {padding} Polecenie wprowadza dodatkowy odstęp między danym elementem a elementem poprzedzającym. Jeśli definiowane własności mają odnosić się do całej strony (np. marginesy strony), można użyć selektora BODY (zobacz także: Marginesy wewnętrzne). ### Przykład {margin-top} ...a to jest następny akapit z górnym marginesem margin-top: 2cm. Dlatego odstęp pomiędzy nimi wynosi 2cm. > selektor { margin-bottom: rozmiar } Polecenie wprowadza dodatkowy odstęp między danym elementem a następnym elementem. ### Przykład {margin-bottom} To jest pierwszy akapit z dolnym marginesem margin-bottom: 2cm... ...a to jest następny akapit. Dlatego odstęp pomiędzy nimi wynosi 2cm. > selektor { margin-left: rozmiar } Komenda pozwala wprowadzić lewy margines dla danego elementu, a więc np. dodatkową odległość od lewego brzegu strony. ### Przykład {margin-left} To jest akapit z lewym marginesem margin-left: 4cm i dlatego jest oddalony od lewej krawędzi strony o 4cm. > selektor { margin-right: rozmiar } Komenda pozwala wprowadzić prawy margines dla danego elementu, a więc np. dodatkową odległość od prawego brzegu strony. ### Przykład {margin-right} To jest akapit z prawym marginesem margin-right: 4cm i dlatego jest oddalony od prawej krawędzi strony o 4cm. > selektor { margin: wartości atrybutów } Natomiast jako "wartości atrybutów" należy podać: * Jedną wartość - wtedy wszystkie marginesy będą jednakowe. To jest akapit, który ma wszystkie marginesy równe 2cm (margin: 2cm) * Dwie wartości - z których pierwsza oznacza górny i dolny margines, natomiast druga - lewy i prawy. To jest akapit, który ma górny i dolny margines równy 2cm, a lewy i prawy 1cm (margin: 2cm 1cm) * Trzy wartości - z których pierwsza oznacza górny margines, druga - jednocześnie lewy i prawy, a ostatnia - dolny. To jest akapit, który ma górny margines równy 2cm, lewy i prawy 1cm, a dolny 3cm (margin: 2cm 1cm 3cm) * Cztery wartości - które oznaczają kolejno marginesy: górny, prawy, dolny, lewy. To jest akapit, który ma następujące marginesy: górny 2cm, prawy 5mm, dolny 3cm, lewy 1cm (margin: 2cm 5mm 3cm 1cm) We wszystkich przypadkach wartości należy podać, korzystając z jednostek długości. wyśrodkuje poziomo element `<div>` o szerokości 300 pikseli w jego rodzicu. W przypadku sąsiadowania ze sobą lub zagnieżdżania wewnątrz siebie elementów posiadających marginesy, może zajść proces załamywania marginesów zewnętrznych (ang. collapsing margins), polegający na połączeniu kilku sąsiadujących odstępów w jeden o rozmiarze pojedynczego marginesu, a nie sumy składowych. Według CSS 2.1 załamywane mogą być tylko marginesy pionowe w następujących przypadkach: A to jest zwykły akapit z tłem, bez określenia jakichkolwiek marginesów. Dlatego jego szerokość wynosi tyle co zwykłego tekstu, a także wewnątrz elementu (prostokąta) nie ma żadnego odstępu. > selektor { padding-bottom: rozmiar } ### Przykład {padding-bottom} ### Przykład {padding-left} Tekst w tej komórce tabeli jest oddalony od lewego brzegu obramowania o 2cm (padding-left: 2cm) | | --- | ### Przykład {padding-right} Tekst w tej komórce tabeli jest oddalony od prawego brzegu obramowania o 2cm (padding-right: 2cm) | | --- | " ustawia margines wewnętrzny o wymiarach 15 pikseli na górze i na dole oraz 20 pikseli po prawej i lewej stronie elementu. Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu CSS. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. " ustawia margines wewnętrzny o wymiarach 15 pikseli na górze i na dole oraz 20 pikseli po prawej i lewej stronie elementu. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. > selektor { box-sizing: rodzaj } ### Jak ustawić dolny margines dowolnego elementu? > selektor { margin-left: rozmiar } > selektor { margin-right: rozmiar } * Styl obramowania {border-...-style} Jak dodać obramowanie do dowolnego elementu: linia przerywana (kreskowa i kropkowa), linia ciągła, podwójne obramowanie, rowek, grzbiet, ramka, przycisk? * Atrybuty mieszane stylu obramowania {border-style} Jak ustawić styl obramowania dla wszystkich krawędzi jednocześnie? * Szerokość obramowania {border-...-width} Jak ustawić szerokość (grubość) obramowania dowolnego elementu? * Atrybuty mieszane szerokości obramowania {border-width} Jak ustawić szerokość (grubość) obramowania dla wszystkich krawędzi jednocześnie? * Kolor obramowania {border-...-color} Jak ustawić kolor obramowania dowolnego elementu? * Atrybuty mieszane koloru obramowania {border-color} Jak ustawić kolor obramowania dla wszystkich krawędzi jednocześnie? * Atrybuty mieszane obramowania {border} Jak ustawić szerokość (grubość), styl i kolor obramowania dowolnego elementu? * Styl obrysu {outline-style} Co to jest obrys i czym się różni od obramowania? * Szerokość obrysu {outline-width} W jaki sposób ustawić szerokość (grubość) obrysu dowolnego elementu? * Kolor obrysu {outline-color} W jaki sposób ustawić kolor obrysu dowolnego elementu? * Atrybuty mieszane obrysu {outline} Jak ustawić szerokość (grubość), styl i kolor obrysu dowolnego elementu? * Odstęp obrysu {outline-offset} W jaki sposób odsunąć ramkę obrysu od krawędzi elementu? * Zaokrąglenie obramowania {border-...-radius} W jaki sposób wstawić na stronę element z zaokrąglonymi narożnikami? * Atrybuty mieszane zaokrąglenia obramowania {border-radius} Jak ustawić zaokrąglenia dla wszystkich narożników jednocześnie? * Dekoracja przełamania obramowania {box-decoration-break} W jaki sposób pozbyć się nieestetycznego efektu zanikania obramowania podczas przełamania strony lub linii? * Cień {box-shadow} W jaki sposób podstawić efektownie wyglądający cień pod elementem? * Obramowanie obrazkowe {border-image-source} Jak udekorować ramkę na stronie obramowaniem graficznym? * Obcięcie obramowania obrazkowego {border-image-slice} Jak podzielić obramowanie graficzne na narożniki, krawędzie i środek? * Szerokość obramowania obrazkowego {border-image-width} W jaki sposób podać szerokość (grubość) obramowania obrazkowego? * Nawis obramowania obrazkowego {border-image-outset} Jak wysunąć obramowanie obrazkowe poza krawędzie elementu? * Powtarzanie obramowania obrazkowego {border-image-repeat} W jaki sposób powielić obrazek w postaci obramowania elementu? * Atrybuty mieszane obramowania obrazkowego {border-image} * Styl górnego obramowania: > selektor { border-top-style: styl } * Styl dolnego obramowania: > selektor { border-bottom-style: styl } * Styl lewego obramowania: > selektor { border-left-style: styl } * Styl prawego obramowania: > selektor { border-right-style: styl } * none - brak obramowania border-top-style: none * hidden - ukryte obramowanie (nie obsługuje MSIE 4) Przykład: * dashed - linia kreskowa (nie obsługuje MSIE 5) border-top-style: dashed * dotted - linia kropkowa (nie obsługuje MSIE 5) border-top-style: dotted * solid - linia ciągła border-top-style: solid * double - linia ciągła podwójna border-top-style: double * groove - "rowek" border-top-style: groove * ridge - "grzbiet" border-top-style: ridge * inset - "ramka" border-top-style: inset * outset - "przycisk" border-top-style: outset > selektor { border-style: wartości atrybutów } Natomiast jako "wartości atrybutów" należy wpisać kolejne wartości stylu obramowania (rozdzielone spacjami), analogicznie jak w przypadku stylu pojedynczego obramowania. ### Przykład {border-style} border-style: dashed border-style: double solid border-style: double solid dashed border-style: groove ridge inset outset * Szerokość górnego obramowania: > selektor { border-top-width: szerokość } * Szerokość dolnego obramowania: > selektor { border-bottom-width: szerokość } * Szerokość lewego obramowania: > selektor { border-left-width: szerokość } * Szerokość prawego obramowania: > selektor { border-right-width: szerokość } * thin - cienkie obramowanie * medium - średnie obramowanie * thick - grube obramowanie * lub konkretną wartość w jednostkach długości Pozwala zdefiniować szerokość dowolnego brzegu obramowania. ### Przykład {border-top-width} border-top-width: 5mm; border-top-style: solid border-top-width: thin; border-top-style: solid border-top-width: medium; border-top-style: solid border-top-width: thick; border-top-style: solid > selektor { border-width: wartości atrybutów } ### Przykład {border-width} border-width: 2mm; border-style: solid border-width: thin thick; border-style: solid border-width: thin thick medium; border-style: solid border-width: thin medium thick 3mm; border-style: solid * Kolor górnego obramowania: > selektor { border-top-color: kolor } * Kolor dolnego obramowania: > selektor { border-bottom-color: kolor } * Kolor lewego obramowania: > selektor { border-left-color: kolor } * Kolor prawego obramowania: > selektor { border-right-color: kolor } ### Przykład {border-top-color} border-top-color: red; border-top-style: solid > selektor { border-color: wartości atrybutów } ### Przykład {border-color} border-color: red; border-style: solid border-color: red blue; border-style: solid border-color: red blue green; border-style: solid border-color: red blue green #eb3; border-style: solid tworzy czarną ramkę o grubości 2 pikseli wokół obrazka. > selektor { outline-style: styl } * none - brak obrysu. outline-style: none * dashed - linia kreskowa. outline-style: dashed * dotted - linia kropkowa. outline-style: dotted * solid - linia ciągła. outline-style: solid * double - linia ciągła podwójna. outline-style: double * groove - "rowek". outline-style: groove * ridge - "grzbiet". outline-style: ridge * inset - "ramka" outline-style: inset * outset - "przycisk" outline-style: outset Obrys jest zbliżony swoim wyglądem do obramowania. Istnieją jednak pewne różnice: * Obrys nie zajmuje miejsca w modelu pudełkowym i dlatego nie wpływa na rozmiary ani pozycję żadnych elementów. * Obrys nie musi być prostokątem. * Jest tworzony zawsze na wierzchu elementu. * Można ustawiać atrybuty obrysu tylko w stosunku do wszystkich boków jednocześnie (nie da się tego robić oddzielnie dla każdego). > selektor { outline-width: szerokość } * thin - cienki obrys * medium - średni obrys * thick - gruby obrys * lub konkretną wartość w jednostkach długości UWAGA! Należy jednocześnie podać styl obrysu.Polecenie nie jest interpretowane przez MSIE 7.0. W MSIE 8.0 wszystko jest w porządku, ale tylko w trybie Standards Compliance. ### Przykład {outline-width} outline-width: 2mm > selektor { outline-color: kolor } Natomiast jako "kolor" należy wpisać definicję koloru. Wpisanie invert ustali kolor będący odwróceniem barw koloru tła. UWAGA! Należy jednocześnie podać styl obrysu.Polecenie nie jest interpretowane przez MSIE 7.0. W MSIE 8.0 wszystko jest w porządku, ale tylko w trybie Standards Compliance. ### Przykład {outline-color} outline-color: blue > selektor { outline: wartości atrybutów } Natomiast jako "wartości atrybutów" należy wpisać kolejne wartości (oddzielone spacjami) jakie mają przyjąć atrybuty obrysu. Polecenie pozwala podać kilka atrybutów obrysu w jednej komendzie (podobnie jak przy obramowaniu). ### Przykład {outline} outline: medium solid blue (CSS 3 - interpretuje Firefox, Opera, Chrome) > selektor { outline-offset: rozmiar } Natomiast jako "rozmiar" należy podać odstęp wyrażony w jednostkach długości. Standardowo obrys jest rysowany bezpośrednio na krawędzi elementu. Możemy go jednak nieco od niego odsunąć, jeśli uważamy, że dzięki temu będzie on wyglądał bardziej estytycznie. ### Przykład {outline-offset} outline-offset: 10px obrys bez odstępu * Zaokrąglenie górnego-lewego narożnika: > selektor { border-top-left-radius: zaokrąglenie } * Zaokrąglenie górnego-prawego narożnika: > selektor { border-top-right-radius: zaokrąglenie } * Zaokrąglenie dolnego-prawego narożnika: > selektor { border-bottom-right-radius: zaokrąglenie } * Zaokrąglenie dolnego-lewego narożnika: > selektor { border-bottom-left-radius: zaokrąglenie } Natomiast "zaokrąglenie" określa promień wyrażony w jednostkach długości albo w procentach (względem obszaru obramowania - zobacz: Model pudełkowy). Możliwe jest tutaj podanie: * jednej wartości - zaokrąglenie symetryczne * dwóch wartości - pierwsza określa poziomy promień ćwiartki elipsy zaokrąglenia, a druga - pionowy Zaokrąglone narożniki to bardzo ciekawy efekt wizualny, który może zwiększyć estetykę strony. Co ciekawe, element wcale nie musi mieć obramowania, aby miał zaokrąglone narożniki. Wystarczy jeśli będzie miał ustalone jakieś tło, aby efekt był widoczny na ekranie. Ale uwaga: tekst wewnątrz elementu nie zostanie zawinięty do zaokrąglonych rogów. Jeśli promień zaokrąglenia będzie zbyt duży, tekst wyjdzie na zewnątrz. ### Przykład {border-top-right-radius} border-top-right-radius: 10px zaokrągli rogi zdjęcia na pół obrazu, tworząc efekt zaokrąglonego wycinka. (CSS 3 - interpretuje Firefox 32, Opera 12-) > selektor { box-decoration-break: dekoracja } (CSS 3 - interpretuje Opera 15, Chrome) > selektor { border-image-width: szerokość } Natomiast jako "szerokość" należy podać konkretną wartość wyrażoną w jednostkach długości, procentach (względem całkowitego obszaru obramowania obrazkowego) lub jako liczba naturalna (podająca wielokrotność szerokości obramowania). Wpisanie auto ustali wartość automatyczną. * jednej wartości - określa jednakową szerokość wszystkich krawędzi * dwóch wartości - pierwsza określa szerokość górnej i dolnej krawędzi, natomiast druga - lewej i prawej * trzech wartości - pierwsza określa szerokość górnej krawędzi, druga - lewej i prawej, natomiast trzecia - dolnej * czterech wartości - ustala oddzielne szerokości kolejnych krawędzi: górnej, prawej, dolnej, lewej ### Przykład {border-image-width} Sterując szerokością obramowania obrazkowego możemy udekorować krawędzie elementu, który w ogóle nie posiada tradycyjnego obramowania. W takim przypadku grafika obramowania wchodzi pod zawartość tekstową - podobnie jakby była wstawiona w tle. Z drugiej strony, ustalając szerokość tradycyjnego obramowania większą niż szerokość obramowania obrazkowego, możemy odsunąć grafikę krawędzi od zawartości tekstowej elementu - podobnie jak to ma miejsce w przypadku marginesu wewnętrznego. Dla porównania - tak wygląda ten sam element, ale bez ustalania szerokości obramowania obrazkowego. * stretch - obrazek zostanie rozciągnięty, tak aby wypełnił całą powierzchnię (domyślnie) * repeat - obrazek zostanie powielony na całej powierzchni * round - powielenie z dopasowaniem rozmiarów (jeżeli długość krawędzi obramowania nie jest wielokrotnością wymiaru obrazka, zostanie on rozciągnięty w taki sposób, aby nie był przycięty) * space - powielenie z dopasowaniem odstępów (jeżeli długość krawędzi obramowania nie jest wielokrotnością wymiaru obrazka, pusta przestrzeń pomiędzy sąsiednimi powtórzeniami obrazka zostanie dobrana w taki sposób, aby obrazek nie był przycięty) ### Przykład {border-image-repeat} Domyślny sposób powtarzania obrazka w obramowaniu. Standardowe powielenie - część grafiki obramowania może być przycięta. Powielenie z dopasowaniem rozmiarów - grafika obramowania nie powinna być przycięta, a ewentualnie dopasowana poprzez rozciągnięcie. Powielenie z dopasowaniem odstępów - grafika obramowania nie powinna być przycięta, a ewentualnie zwiększona pusta przestrzeń pomiędzy sąsiednimi obrazkami w obramowaniu. (CSS 3 - interpretuje Internet Explorer 11, Firefox 15, Opera 15, Chrome) > selektor { border-image: wartości atrybutów } Natomiast jako "wartości atrybutów" należy wpisać kolejne wartości obramowani obrazkowego: źródło, obcięcie, szerokość, nawis i powtarzanie. Polecenie pozwala w sposób skrócony wypełnić wszystkie atrybuty obramowania obrazkowego. Ważne jest przy tym zachowanie właściwej kolejności oraz odpowiednich znaków rozdzielających kolejne wartości. Lista atrybutów może się składać z trzech części: * źródła * obcięcia / szerokości / nawisu - możliwe są kombinacje: > border-image-slice border-image-slice / border-image-width border-image-slice / border-image-width / border-image-outset * powtarzania Jedna lub więcej z tych części musi się pojawić na liście wartości atrybutów. Na przykład: > div { border-image: url(punkt.gif) 10 } /* border-image-source: url(punkt.gif); border-image-slice: 10 */ div { border-image: url(punkt.gif) 10 / 10px } /* border-image-source: url(punkt.gif); border-image-slice: 10; border-image-width: 10px */ div { border-image: url(punkt.gif) 10 / 10px / 5px } /* border-image-source: url(punkt.gif); border-image-slice: 10; border-image-width: 10px; border-image-outset: 5px */ div { border-image: url(punkt.gif) 10 / 10px / 5px repeat } /* border-image-source: url(punkt.gif); border-image-slice: 10; border-image-width: 10px; border-image-outset: 5px; border-image-repeat: reptat */ div { border-image: url(punkt.gif) 10 / 10px repeat } /* border-image-source: url(punkt.gif); border-image-slice: 10; border-image-width: 10px; border-image-repeat: reptat */ div { border-image: url(punkt.gif) 10 repeat } /* border-image-source: url(punkt.gif); border-image-slice: 10; border-image-repeat: reptat */ div { border-image: url(punkt.gif) repeat } /* border-image-source: url(punkt.gif); border-image-repeat: reptat */ ### Przykład {border-image} dodaje cień o przesunięciu 5 pikseli poziomo i pionowo, rozmyciu 10 pikseli oraz kolorystyce szaro-czarnej. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. * Typ stylu wykazu {list-style-type} W jaki sposób stworzyć własny, niestandardowy rodzaj (typ, styl) wykazu? Jak zrobić listę z punktami w postaci emotikon (emoji)? * Zawijanie tekstu w wykazie {list-style-position} Co zrobić, aby punkt wykazu (wyróżnik, marker) znajdował się wewnątrz tekstu? * Wyróżnik obrazkowy wykazu {list-style-image} Jak wstawić grafikę (obrazek) jak punkt wykazu (wyróżnik, marker)? * Atrybuty mieszane wykazu {list-style} Jak ustalić kilka własności wyglądu wykazu w jednym poleceniu? * Odstęp wyróżnika wykazu {marker-offset} W jaki sposób stworzyć automatyczną numerację punktów i podpunktów w stylu: 1, 1.1, 1.1.1 itd.? * Powtórka Natomiast "typ" odpowiada za wygląd wyróżnika wykazu (markera) i należy zamiast niego wpisać: Natomiast "pozycja" określa, jak będą zawijane wiersze wykazu, które nie zmieszczą się w jednej linii. Możliwe są tutaj dwa przypadki: * Punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy... punkt pierwszy. * Punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi... punkt drugi. * Punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci... punkt trzeci. > selektor { list-style-image: url(ścieżka dostępu) } Natomiast jako "ścieżka dostępu" należy wpisać względną ścieżkę do obrazka, który ma się pojawić jako wyróżnik wykazu (marker). Wpisanie none usunie obrazek. * Punkt pierwszy * Punkt drugi * Punkt trzeci > selektor { list-style: wartości atrybutów } * Blok obejmujący Jak wyznaczyć element, względem którego obliczana jest pozycja i rozmiary elementów? * Szerokość {width} W jaki sposób najprościej ustawić szerokość elementu? * Wysokość {height} W jaki sposób najprościej ustawić wysokość elementu? * Szerokość i marginesy automatyczne Co zrobić, aby szerokość i poziome marginesy dopasowywały się do sąsiednich elementów, tak aby wyświetlanie zawsze było poprawne? W jaki sposób wyśrodkować (wycentrować) tabelkę lub blok za pomocą CSS? Jak zbudować szkielet strony przy pomocy CSS? * Wysokość i marginesy automatyczne Co zrobić, aby wysokość i pionowe marginesy dopasowywały się do sąsiednich elementów, tak aby wyświetlanie zawsze było poprawne? * Maksymalna szerokość {max-width} Co zrobić, aby szerokość elementu nigdy nie przekroczyła ustalonej wartości? * Minimalna szerokość {min-width} Co zrobić, aby wysokość elementu nigdy nie przekroczyła ustalonej wartości? * Minimalna wysokość {min-height} Co zrobić, aby wysokość elementu nigdy nie była mniejsza od ustalonej wartości? * Przepełnienie {overflow} W jaki sposób dodać suwaki przewijania do dowolnego elementu? Co zrobić, aby zawartość elementu nigdy nie wychodziła poza jego obręb? * Przepełnienie tekstu {text-overflow} Co zrobić, kiedy tekst nie mieści się w ustalonej szerokości elementu na stronie? * Przeciąganie {resize} W jaki sposób zablokować możliwość zmiany rozmiaru (przeciągania) obszaru tekstowego w formularzu? * Powtórka . Możesz również stosować jednostki innych niż piksele, takie jak procenty lub em. > selektor { height: wysokość } Sytuacja jest podobna jak w poprzednim punkcie za wyjątkiem tego, że element posiada wewnętrzną wysokość (zobacz punkt 8 podrozdziału: Szerokość i marginesy automatyczne). > selektor { max-width: wartość } ### Przykład {max-width} Ten obrazek powinien mieć szerokość maksymalną 50px (max-width: 50px): > selektor { min-width: wartość } ### Przykład {min-width} Ten obrazek powinien mieć szerokość minimalną 200px (min-width: 200px): > selektor { max-height: wartość } Natomiast jako "wartość" należy podać wartość maksymalnej dozwolonej wysokości, jaką może mieć element. Polecenie nie odnosi się do elementów inline!UWAGA! Polecenie nie interpretuje MSIE 6, a MSIE 7.0 obsługuje, ale nie w trybie Quirks. Ten obrazek powinien mieć wysokość minimalną 150px (min-height: 150px): > selektor { overflow: sposób } W CSS, " `overflow: hidden` " to zastosowanie właściwości `overflow` z ustawieniem hidden. Oznacza to, że wszelki nadmiar zawartości, który wychodzi poza granice elementu, będzie ukryty i nie będzie widoczny dla użytkownika. Nie wyświetli się pasek przewijania ani część treści poza określoną przestrzenią elementu. (CSS 3 - interpretuje Internet Explorer * , Firefox, Opera, Chrome) > selektor { text-overflow: sposób } W CSS, " `overflow: hidden` " to zastosowanie właściwości `overflow` z ustawieniem hidden. Oznacza to, że wszelki nadmiar zawartości, który wychodzi poza granice elementu, będzie ukryty i nie będzie widoczny dla użytkownika. Nie wyświetli się pasek przewijania ani część treści poza określoną przestrzenią elementu. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. * Podpis tabeli {caption-side} W jaki sposób ustalić położenie podpisu (tytułu) tabeli? * Rozplanowanie tabeli {table-layout} W jaki sposób przeglądarka oblicza rozmiary poszczególnych komórek tabeli? W jaki sposób wyświetlić tabelę bardzo wydajnym algorytmem? * Obramowanie tabeli {border-collapse, border} Jak dodać efektowne obramowanie tabeli i jej komórek? Jak wprowadzić nowy, estetyczny model obramowania w tabeli za pomocą pojedynczych linii? * Odstępy między komórkami tabeli {border-spacing} Jak zmienić odstępy pomiędzy sąsiednimi komórkami tabeli? Jak ustawić pionowy odstęp inny niż poziomy? * Puste komórki tabeli {empty-cells} Co zrobić, aby wokół pustych komórek tabeli wyświetlało się obramowanie? * Rozmiary tabeli {width, height} Jak zmieniać rozmiary elementów tabeli: wierszy, kolumn, komórek? * Powtórka ### Model obramowani tabeli {table-layout} # Natomiast jako "model" należy podać: * collapse - pojedyncze obramowanie * separate - komórki są od siebie odseparowane Polecenie określa model wyświetlania obramowania tabeli pomiędzy komórkami. Możliwe jest użycie obramowania w postaci pojedynczej linii (collapse) albo obramowania dla każdej komórki osobno, które będą od siebie odseparowane (separate). UWAGA! MSIE 4 nie interpretują tego polecenia. W MSIE 5 mogą wystąpić pewne trudności przy przewijaniu tabeli z modelem collapse (czasem znikają linie obramowania). Natomiast w MSIE 6 oraz Operze 6 wszystko jest w porządku.Poza tym Opera 7 w przypadku collapse całkowicie ukrywa obramowanie poszczególnych komórek tabeli (można je pokazać określając obramowanie przy użyciu selektora TD). # Przykład {border-collapse} ### Styl, szerokość i kolor obramowania tabeli {border} # Do tabel (<table>...</table>) oraz ich komórek ( `<td>...</td>` ) można stosować wszystkie parametry dotyczące obramowania. komórka1 | komórka2 | | --- | --- | komórka3 | <td style="border: 3mm ridge yellow"> | Natomiast jako "odstęp" należy podać wartość, korzystając z jednostek długości. Przy czy możliwe jest podanie: Do tabel (<table>...</table>), ich komórek ( `<td>...</td>` ), wierszy ( `<tr>...</tr>` ) oraz kolumn (<colgroup>...</colgroup>) można stosować parametry dotyczące szerokości i wysokości. Odnośnie komórek oraz całej tabeli można ustawić zarówno ich szerokość jak i wysokość. Natomiast dla wiersza możliwe jest określenie tylko wysokości, ponieważ szerokość jest jednocześnie szerokością tabeli. Podobnie dla kolumny można ustalić jedynie jej szerokość, bo wysokość jest wysokością tabeli. ### W jaki sposób ustalić położenie podpisu (tytułu) tabeli? ### W jaki sposób przeglądarka oblicza rozmiary poszczególnych komórek tabeli? W jaki sposób wyświetlić tabelę bardzo wydajnym algorytmem? ### Jak zmienić odstępy pomiędzy sąsiednimi komórkami tabeli? Jak ustawić pionowy odstęp inny niż poziomy? > selektor { border-spacing: odstęp } ### Co zrobić, aby wokół pustych komórek tabeli wyświetlało się obramowanie? * Pozycja relatywna {position: relative} W jaki sposób przesunąć dowolny element strony o podaną odległość? * Pozycja absolutna {position: absolute} W jaki sposób ustawić dowolny element strony w żądanym miejscu na ekranie? * Pozycja ustalona {position: fixed} Jak ustawić element, aby nie przesuwał się podczas przewijania strony? * Pozycja statyczna {position: static} Jak przywrócić domyślny sposób ustawienia elementu wypozycjonowanego? * Przezroczystość {opacity} W jaki sposób wstawić na stronie półprzezroczyste warstwy? * Nakładanie {z-index} W jaki sposób automatycznie przyciąć do określonych rozmiarów obrazek (grafikę, zdjęcie) lub inny element strony (kadrowanie)? * Wyświetlanie {display} Jak ukryć dowolny element strony? W jaki sposób zmienić domyśle wyświetlanie dowolnych elementów strony, tak aby stały się wykazem czy tabelką? * Widzialność {visibility} W jaki sposób schować element, tak aby pozostało po nim puste miejsce? * Ustawienie {float, vertical-align} Gdyby w arkuszu stylów tej strony [zobacz: Wstawianie stylów], została umieszczona taka linijka: > h1 { position: relative; left: 50% }to teraz wszystkie tytuły `h1` byłyby pozycjonowane względnie. Ale jeśli chcielibyśmy zrezygnować z pozycjonowania dla kilku wybranych elementów, wystarczyłoby wpisać `position: static` w definicji inline. (CSS 3 - interpretuje Internet Explorer 9, Firefox 2, Opera, Chrome) > selektor { opacity: nieprzezroczystość } ". Ta deklaracja `clip` określa obszar, który ma być widoczny, a wartości to kolejno: górny margines, prawy margines, dolny margines i lewy margines. W tym przypadku, przycinamy górny lewy fragment o wymiarach 50px na 50px. > selektor { display: sposób } . > selektor { visibility: typ } " w CSS jest używana do wyrównania elementu w pionie względem innych elementów w linii. > selektor { clear: sposób } Deklaracja " `clear: both` " jest używana w CSS, gdy chcemy wymusić, aby element położony poniżej innych elementów, które mogą być ustawione na " `float: left` " lub " `float: right` ", nie opływał ich z boku i zaczynał się od nowego wiersza niezależnie od położenia innych elementów `float` . Jest to przydatne, gdy chcemy uniknąć zakłóceń spowodowanych elementami `float` , które mogą występować wizualnie nad innymi elementami. Poniżej znajdziesz wykaz najczęściej zadawanych pytań z tego rozdziału wraz ze zwięzłymi odpowiedziami i gotowymi do użycia przykładami kodu CSS. Aby sprawdzić bardziej szczegółowy opis, kliknij odnośnik "Zobacz więcej..." pod wybraną odpowiedzią. * Kształt kursora {cursor} Jak zmienić kursor (wskaźnik) myszki? * Kursor obrazkowy {cursor: url} Jak wczytać kursor (wskaźnik) myszki z pliku? * Kolor karetki tekstowej {caret-color} zmieni kursor na "łapkę" wskazującą możliwość przechwycenia i przesunięcia elementu. (interpretuje MSIE 6; Firefox, Opera 15 i Chrome tylko pliki *.cur - również w systemie Linux) ustawi niestandardowy obrazek jako kursor, a auto zostanie użyte, jeśli obrazek nie będzie dostępny. (CSS 3 - interpretuje Firefox 53, Opera 44, Chrome 57) > selektor { caret-color: kolor } ustawi niestandardowy obrazek jako kursor, a auto zostanie użyte, jeśli obrazek nie będzie dostępny. Sprawdź, czy pamiętasz, za co odpowiadają poniższe fragmenty kodu źródłowego CSS. W razie wątpliwości kliknij odnośnik "Zobacz więcej..." pod wybraną grupą przykładów. * Przełamanie strony {page-break-before, page-break-after} Jak rozpocząć nową stronę papieru w określonym miejscu na wydruku? * Blokada przełamania strony {page-break-inside} Jak nie dopuścić, aby na wydruku pierwsza część elementu znalazła się na jednej stronie papieru, a dalsza na drugiej? * Linijki na stronie {widows, orphans} W jaki sposób poprawić estetykę wydruku, kontrolując liczbę linijek wdowich (na górze) i sierocych (na dole)? * Kontekst strony @page Jak ustawić marginesy strony WWW na wydruku? * Wydruk @media print W jaki sposób dostosować stronę WWW do wydruku bez potrzeby tworzenia nowej wersji? W jaki sposób ukryć na wydruku niektóre elementy strony? * Powtórka Czym różni się układ wielokolumnowy od tradycyjnych tabel? * Szerokość kolumny {column-width} Jak ustalić szerokość kolumny tekstu? * Liczba kolumn {column-count} W jaki sposób podzielić tekst na kilka kolumn? * Atrybuty mieszane kolumn {columns} Jak za jednym razem ustalić szerokość kolumny i liczbę kolumn? * Odstęp kolumn {column-gap} W jaki sposób ustalić odstęp pomiędzy dwiema kolumnami tekstu? * Linia rozdzielająca kolumn {column-rule-color, column-rule-style, column-rule-width, column-rule} W jaki sposób dodać pionową linię rozdzielającą kolumny tekstu? * Przełamanie kolumny {break-before, break-inside, break-after} Jak zapewnić estetyczne przełamania kolumn tekstu na stronie? * Łączenie kolumn {column-span} W jaki sposób wstawić element rozciąjący się ponad kilkoma kolumnami tekstu? * Wypełnienie kolumn {column-fill} Jak określić wypełnienie elementu kolumnami tekstu? * Powtórka Jako "wartości atrybutów" można podać samą wartość szerokości kolumny, tylko liczbę kolumn lub obie wartości rozdzielone spacją. Ustalenie wartości auto usuwa kolumny. Polecenie jest przydatne, jeżeli chcemy skrócić zapis. Możemy też dzięki niemu szybko usunąć podział na kolumny, poprzez wpisanie " `columns: auto` ". (CSS 3 - interpretuje Internet Explorer 10, Firefox 52, Opera 11-12 i 37, Chrome 50) > selektor { column-gap: szerokość } column-span: all; To jest element rozciągający się ponad wszystkimi kolumnami tekstu. To jest przykładowa treść, ułożona w wielu sąsiadujących kolumnach. Tekst jest automatycznie przenoszony z końca jednej kolumny na początek sąsiedniej, leżącej po jej prawej stronie... To jest przykładowa treść, ułożona w wielu sąsiadujących kolumnach. Tekst jest automatycznie przenoszony z końca jednej kolumny na początek sąsiedniej, leżącej po jej prawej stronie... To jest przykładowa treść, ułożona w wielu sąsiadujących kolumnach. Tekst jest automatycznie przenoszony z końca jednej kolumny na początek sąsiedniej, leżącej po jej prawej stronie... (CSS 3 - interpretuje Internet Explorer 10, Firefox 52, Opera 11-12 i 37, Chrome 50) > selektor { column-fill: wypełnienie } Jakie zaawansowane możliwości daje elastyczny układ rozplanowania elementów na stronie? * Kontener elastyczny {display: flex inline-flex} Jak przełączyć sposób rozpalnowania elementów na układ elastyczny? * Przepływ elastyczny {flex-direction, flex-wrap, flex-flow} Jak zmienić kolejność wyświetlania elementów na stronie? * Elastyczność {flex-grow, flex-shrink, flex-basis, flex} Jak elastycznie dopasować margines elementu, tak aby wypełnił wolną przestrzeń? * Justowanie zawartości {justify-content} Jak równomiernie wyrównać elementy na stronie? * Wyrównanie wiersza {align-items, align-self} Co zrobić, aby wyśrodkować blok w pionie? * Wyrównanie wierszy {align-content} `flex-grow` to właściwość CSS używana w kontekście flexbox, która określa, jak elementy mają się rozszerzać, gdy istnieje dodatkowa dostępna przestrzeń w kontenerze. Domyślnie `flex-grow` ma wartość 0 (zero), co oznacza, że elementy nie będą się rozszerzać. Jeśli element ma wartość większą niż 0, to rozszerzy się proporcjonalnie do innych elementów w kontenerze w zależności od ich wartości `flex-grow` . (CSS 3 - interpretuje Internet Explorer 10, Firefox, Opera 12, Chrome) > selektor { margin-top: auto } selektor { margin-right: auto } selektor { margin-bottom: auto } selektor { margin-left: auto } selektor { margin: auto } Aby ustawić elementy obok siebie w kontekście flexbox CSS, można to osiągnąć ustawiając " `margin-right: auto` " na pierwszym elemencie lub " `margin-left: auto` " na drugim elemencie. To spowoduje, że pierwszy element przylegnie do lewej krawędzi kontenera, a drugi do prawej krawędzi, a dostępna przestrzeń zostanie równomiernie rozłożona między nimi. (CSS 3 - interpretuje Internet Explorer 10, Firefox, Opera 12, Chrome) > selektor { justify-content: justowanie } Justowanie: * flex-start - do początkowej krawędzi kontenera (domyślnie) * flex-end - do końcowej krawędzi kontenera * center - wyśrodkowanie * space-between - równe odstępy między elementami * space-around - równa przestrzeń wokół elementów Polecenie steruje justowaniem elementów kontenera elastycznego, gdy jest on zbyt duży, aby został wypełniony w całości. Działa analogicznie jak justowanie tekstu, ale może operować na blokach. ### Przykład {justify-content} ``` justify-content: flex-start ``` ``` justify-content: flex-end ``` ``` justify-content: center ``` ``` justify-content: space-between ``` ``` justify-content: space-around ``` . (CSS 3 - interpretuje Internet Explorer 10, Firefox, Opera 12, Chrome) > selektor { align-content: wyrównanie } * flex-start - wyrównanie wierszy do początkowej krawędzi kontenera * flex-end - do końcowej krawędzi kontenera * center - wyśrodkowanie wierszy (dla tekstu w języku polskim - w pionie) * space-between - równe odstępy między wierszami * space-around - równa przestrzeń wokół wierszy * stretch - rozciągnięcie wierszy do obu krawędzi jednocześnie (domyślnie) Polecenie steruje wyrównaniem wielu wierszy wewnątrz kontenera elastycznego, kiedy ich sumaryczna wysokość jest za mała, aby wypełnić całą dostępną przestrzeń. ### Przykład {align-content} ``` align-content: flex-start ``` ``` align-content: flex-end ``` ``` align-content: center ``` ``` align-content: space-between ``` ``` align-content: space-around ``` ``` align-content: stretch ``` W jaki sposób przygotować specjalne wersje strony przeznaczone do wydruku, dla urządzeń przenośnych, a nawet syntezatorów mowy, bez potrzeby tworzenia dodatkowych dokumentów HTML? * Wybór medium @media Jak określić specjalny wygląd strony w wersji do wydruku czy na urządzenia przenośne? * Typy mediów Do czego służą typy mediów CSS: all, aural, braille, embossed, handheld, print, projection, screen, tty, tv? * Grupy mediów Czym różnią się grupy od typów mediów CSS: continuous, paged, visual, aural, tactile, grid, bitmap, interactive, static, all? * Zapytania mediów Jak stworzyć stronę, która automatycznie dopasowuje się do możliwości urządzenia: komputer, tablet, smartphone, telewizor, projektor? Co to jest tryb Quirks i dlaczego ma kolosalne znaczenie przy wyświetlaniu elementów strony WWW w starszych przeglądarkach? Jak wprowadzić lub wyprowadzić przeglądarkę z trybu Quirks? * Co zmienia przejście z trybu Quirks do trybu zgodności ze standardami? O czym trzeba pamiętać, projektując stronę WWW dla starszych przeglądarek? * X-UA-Compatible Na co można sobie pozwolić, projektując stronę dla najnowszej wersji Internet Explorera? Jak wymusić tryb wstecznej kompatybilności na stronach, które wcześniej wyświetlały się prawidłowo? Dlaczego menu nawigacyjne powinno się wykonywać na liście (wykaz)? * Pionowe menu W jaki sposób wykonać pionowe menu nawigacyjne na liście (wykaz)? * Poziome menu W jaki sposób wykonać poziome menu nawigacyjne (zakładki) na liście (wykaz)? * Menu z nagłówkami W jaki sposób wykonać menu nawigacyjne z nagłówkami (tytułami działów) na liście definicyjnej (słownik)? Dlaczego szablon strony powinno się wykonywać na elementach DIV (bloki), a nie na tabelkach? * Stały szablon Jak wykonać szablon o szerokości niezależnej od rozdzielczości ekranu? * Płynny szablon Jak wykonać szablon o szerokości dopasowującej się do rozdzielczości ekranu? * Responsywny szablon Jak wykonać szablon strony automatycznie dopasowujący się do urządzenia, na którym jest wyświetlany (smartfon, smartphone, tablet, laptop, notebook, komputer stacjonarny)? * Kolumna menu nawigacyjnego powinna się znaleźć po prawej stronie, a w kodzie źródłowym znajduje się na początku, zatem zostaje jej przypisana własność `float: right` . * Kolumna dodatkowych informacji może pozostać w kolejności wynikającej z ułożenia w kodzie źródłowym, a zatem przypisujemy `float: left` . * Kolejność bloku treści strony, wynikająca z naturalnego ułożenia, również jest odpowiednia (powinien się wyświetlić po kolumnie dodatkowych informacji, która w kodzie źródłowym poprzedza blok treści), a zatem - `float: left` . Możliwe są również inne konfiguracje - np. czasami spotykane ułożenie obu wąskich kolumn po lewej, a treści po prawej stronie: > html, body { background-color: #fff; color: #000; margin: 0; padding: 0; text-align: center; } #top { width: 780px; margin-left: auto; margin-right: auto; text-align: left; } #NAGLOWEK { background-color: #888; } #MENU { width: 150px; float: left; overflow: hidden; background-color: #ccc; } #INFORMACJE { width: 150px; float: left; overflow: hidden; background-color: #ccc; } #TRESC { width: 480px; float: left; overflow: hidden; background-color: #fff; } #STOPKA { clear: both; width: 100%; background-color: #888; } W tym przypadku naturalna kolejność wyświetlania bloków, wynikająca z ułożenia elementów w kodzie źródłowym strony, jest odpowiednia. Przypisanie własności `float: left` , miało jedynie na celu ustawienie kolumn obok siebie, a nie pod sobą. Natomiast nie wpływa to na ich kolejność. Płynny szablon (ang. liquid layout) charakteryzuje się zmianą swoich poziomych proporcji przy zmianie rozmiaru okna przeglądarki lub rozdzielczości ekranu. Najczęściej w każdych warunkach zajmuje on całą dostępną szerokość w oknie. Jest on raczej rzadziej stosowany, ze względu na niemożliwe do przewidzenia ułożenie elementów treści. Poza tym tekst w zbyt długich linijkach zwykle gorzej się czyta, ponieważ trudniej przenieść wzrok z końca wiersza na początek następnego. Czasami jednak może być wygodny, np. kiedy zawiera jakieś szerokie elementy, które mogą nie zmieścić się w ustalonej szerokości dla stałego szablonu (czyli zwykle 780px minus szerokość kolumny menu i ewentualnie dodatkowych informacji). * Zamiennik obrazkowy Jak zaprojektować style CSS, aby udostępnić użytkownikom do wyboru różne style kolorystyczne serwisu? * "Duszki" CSS W jaki sposób przyspieszyć ładowanie grafiki na stronie WWW? Poniżej zostały podane podstawowe definicje dotyczące stylów CSS. Jeśli nie zrozumiesz niektórych, nie przerażaj się, nie wszystkie one są absolutnie konieczne do swobodnego posługiwania się stylami. Jednak przeczytanie ich, pozwoli Ci chociaż zaznajomić się z podstawowymi terminami. Zapoznaj się zwłaszcza z następującymi definicjami: * Element * Element zastępowany * Atrybut * Drzewo dokumentu - szczególnie ważne * Dziecko * Potomek * Przodek * Brat (element) Podstawowa konstrukcja składniowa dokumentu. Większość reguł stylów używa nazw tych elementów (takich jak P, TABLE, OL dla HTML), żeby określić ich wygląd. (replaced element) Element dla którego formater stylów zna tylko wymiar wewnętrzny. W języku HTML są to: IMG, INPUT, TEXTAREA, SELECT, OBJECT. Na przykład zawartość elementu `IMG` jest zastępowana przez obrazek, wyznaczony atrybutem `src` . (intrinsic dimensions) Szerokość i wysokość które zostały zdefiniowane przez sam element, nie narzucone przez otoczenie. W CSS2 jest założone, że tylko elementy zastępowane przychodzą z wewnętrznym rozmiarem. (attribute) Wartość powiązana z elementem, składająca się z nazwy i związanej wartości (tekstowej). W języku HTML może to być np. `href` elementu A, określający lokalizację zasobu sieciowego albo `src` elementu IMG, wskazujący lokalizację pliku obrazka. (content) Zawartość (treść) związana z elementem w dokumencie źródłowym. Nie wszystkie elementy mają zawartość - w takim wypadku są nazywane pustymi (empty). Zawartością elementu może być tekst jak również pewna liczba podelementów, wtedy element nazywany jest rodzicem (parent) tych podelementów. (rendered content) Zawartość elementu po zinterpretowaniu zgodnie z powiązanym arkuszem stylów. Zawartość zinterpretowana elementów zastępowanych przychodzi z zewnątrz dokumentu źródłowego. Zawartością taką może być także alternatywny tekst dla elementu (wartość atrybutu `alt` w składni HTML) czy pozycja wstawiona (domyślnie lub poprzez ścisłe określenie) przez arkusz stylów (np. numerowanie). (document tree) Drzewo elementów umieszczonych w dokumencie źródłowym. Każdy element w takim drzewie ma dokładnie jednego rodzica, oprócz elementu podstawowego, czyli korzenia drzewa (root). Niektóre polecenia stylów wykorzystują jako wartości liczby całkowite lub rzeczywiste. Są one precyzowane tylko w notacji dziesiętnej. Liczba całkowita składa się z jednej lub więcej cyfr z zakresu od 0 do 9. Liczba rzeczywista może być liczbą całkowitą albo mieć zero lub więcej cyfr po kropce dziesiętnej ("."). Zarówno liczby całkowite jak i rzeczywiste mogą zostać poprzedzone przez "-" lub "+", wskazującym ich znak. Wiele właściwości przyjmujących jako wartość liczbę całkowitą lub rzeczywistą, wymaga wartości z określonego przedziału, zwykle nie mniejszej od zera. Jeśli chcesz szybko przeliczyć wartości pomiędzy różnymi jednostkami częstotliwości, to tutaj możesz skorzystać ze specjalnego generatora. Łańcuchy znakowe (tzw. strings) mogą być pisane w podwójnym cudzysłowie ( `"..."` ) lub w pojedynczym ( `'...'` ). Łańcuchy ograniczone podwójnym cudzysłowem nie mogą już zawierać wewnątrz takiego znaku - wtedy należy użyć znaku odwróconego ukośnika (backslash) przed cudzysłowem wewnątrz. Tzn. aby wpisać następujący string: `"123"123"` (niepoprawnie!), należy podać: `"123\"123"` (poprawnie). To samo dotyczy pojedynczego cudzysłowu (zamiast `'123'123'` należy wpisać `'123\'123'` ). Natomiast dozwolony jest zapis: `"123'123"` lub `'123"123'` . Niedozwolone jest bezpośrednie użycie znaku nowej linii (przez przełamanie linii klawiszem Enter). Należy zamiast tego użyć znaku \A. Specyfikacja stylów wprowadza następujące sposoby podawania wartości kolorów: * 16 (17) kolorów podstawowych: black (#000000) silver (#C0C0C0) gray (#808080) white (#FFFFFF) maroon (#800000) red (#FF0000) purple (#800080) fuchsia (#FF00FF) green (#008000) lime (#00FF00) olive (#808000) yellow (#FFFF00) navy (#000080) blue (#0000FF) teal (#008080) aqua (#00FFFF) Ponadto CSS 2.1 definiuje jeszcze jeden dodatkowy kolor podstawowy: orange (#FFA500). CSS 3 określa dodatkowo 130 kolorów rozszerzonych. * #RRGGBB - podanie kolejno wartości każdej składowej kolorów podstawowych: czerwonego RR (red), zielonego GG (green) i niebieskiego BB (blue). Wszystkie te liczby muszą być dwucyfrowe i są zapisane w systemie szesnastkowym, w którym mamy 16 cyfr podstawowych: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Przykładowo: liczba szesnastkowa B5 oznacza w systemie dziesiętnym 181 (11*16 + 5 = 181). * #RGB - to samo co powyżej, lecz w tym wypadku jako składowe kolorów należy podawać liczby jednocyfrowe w zapisie szesnastkowym. Przykładowo kolor #FB0 odpowiada #FFBB00 z poprzedniego zapisu. * rgb(R, G, B) - pozwala podać oddzielnie każdą składową koloru w systemie dziesiętnym. Wszystkie liczby muszą się zawierać w zakresie 0...255 (255 = FF). * rgb(R%, G%, B%) - to samo co powyżej, lecz teraz należy podawać wartości procentowe (0%...100%). Znak procentu musi się pojawić na końcu każdej liczby i nie może być oddzielony od niej spacją ani żadnym białym znakiem! * 28 kolorów systemowych - (patrz: tabela w dalszej części tego rozdziału) czyli takich, które pochodzą z systemu operacyjnego (np. kolor pulpitu, okien, menu, przycisków i inne). Jeśli zmienimy kolory w swoim systemie, zmianie ulegną również przedstawione tutaj kolory systemowe. Dlatego każdy użytkownik może odebrać je inaczej. Z tego powodu należy uważać z ich stosowaniem, ponieważ nie da się przewidzieć efektu na komputerze innego użytkownika. * hsl(H, S%, L%) - (CSS 3) alternatywny do RGB model opisu kolorów, w którym kolejne składowe oznaczają: * H (ang. Hue) - barwa * Liczba całkowita określana w stopniach (z przedziału od 0 do 360) z tzw. koła barw: 0 - czerwony (Red), 120 - zielony (Green), 240 - niebieski (Blue) * S (ang. Saturation) - nasycenie * Wartość procentowa: 0% - szary, 100% - normalny * L (ang. Lightness) - jasność * Wartość procentowa: 0% - czarny, 50% - normalny, 100% - biały HSL jest bardzo intuicyjnym modelem opisu kolorów. Wystarczy wybrać określony odcień z koła barw (H), a następnie odpowiednio sterować nasyceniem (S) i jasnością (L), aby uzyskać pożądany kolor. Nie obsługuje MSIE 8.0 (od wersji 9.0 wszystko już jest w porządku)! Przykład Sterowanie nasyceniem barwy czerwonej Definicja Kolor hsl(0, 0%, 50%) hsl(0, 25%, 50%) hsl(0, 50%, 50%) hsl(0, 75%, 50%) hsl(0, 100%, 50%) Sterowanie jasnością barwy czerwonej Definicja Kolor hsl(0, 100%, 0%) hsl(0, 100%, 25%) hsl(0, 100%, 50%) hsl(0, 100%, 75%) hsl(0, 100%, 100%) * rgba(R, G, B, A), rgba(R%, G%, B%, A), hsla(H, S%, L%, A) - (CSS 3) kolor z przezroczystością, gdzie A (ang. alpha) to wartość określająca przezroczystość z przedziału od 0 (całkowita przezroczystość) do 1 (brak przezroczystości - domyślnie) Nie obsługuje MSIE 8.0 (od wersji 9.0 wszystko już jest w porządku)! Jeśli przeglądarka nie obsługuje przezroczystości, żaden kolor nie zostanie przypisany. * Słowa kluczowe: * transparent - przezroczystość (brak koloru). Jest to odpowiednik zapisu: `rgba(0, 0, 0, 0)` . Wartość ta przydaje się, kiedy chcemy odwołać wcześniejsze ustawienie koloru, który został odziedziczony albo przypisany np. przy pomocy klasy selektorów. W takiej sytuacji proste usunięcie wcześniejszej deklaracji koloru może być niemożliwe albo utrudnione. * currentColor - kolor taki sam jak ma tekst aktualnego elementu (czyli wartość cechy `color` ustawionej bezpośrednio albo odziedziczonej). Jest to bardzo wygodny sposób na przypisanie np. identycznego koloru obramowania co znajdujący się w nim tekst. Dzięki temu przy zmianie koloru tekstu nie będziemy musieli pamiętać, aby zaktualizować również obramowanie - wtedy stanie się to automatycznie. * transparent - przezroczystość (brak koloru). Jest to odpowiednik zapisu: Poniżej znajdziesz wykaz cech (własności) oraz ich wartości według oryginalnych specyfikacji CSS3, opracowanych przez organizację W3C. Aby zobaczyć wyjaśnienie znaczenia poszczególnych elementów opisu, zapoznaj się z rozdziałem: Komendy CSS 2 / Wstęp. ### text-overflow # * Wartość * `clip | ellipsis` * Inicjalizacja * clip * Zastosowanie * elementy blokowe * Dziedziczenie * nie * Procenty * nie * Media * visual ### widows # * ECMAScript Czym różni się ECMAScript od JavaScript, ActionScript i node.js? * Osadzenie skryptu W jaki sposób wstawić kod JavaScript na stronie internetowej? * NaN Po co wprowadzono w JavaScript wartość typu liczbowego, która jednak nie jest poprawną liczbą? * Infinity Jak w języku JavaScript zapisywana jest wartość nieskończona? * undefined Co zawiera zmienna, której nie przypisano żadnej wartości? * eval Jak napisać program, który pozwoli wykonać kod, wprowadzony przez użytkownika? * parseInt Co zrobić, żeby przekształcić wartość szesnastkową (heksadecymalną) lub ósemkową (oktalną) na liczbę dziesiętną? * parseFloat W jaki sposób przekształcić tekst na liczbę? * isNaN Jak sprawdzić, czy funkcja zwróciła prawidłową liczbę? * isFinite Jak sprawdzić, czy funkcja zwróciła liczbę skończoną? * decodeURI W jaki sposób zdekodować adres URI/URL? * decodeURIComponent W jaki sposób zdekodować wartość z adresu URI/URL? * encodeURI W jaki sposób zakodować tekst do postaci adresu URI/URL? * encodeURIComponent W jaki sposób zakodować tekst, tak aby można go było wstawić do adresu URI/URL? > NaN * Parametry: * `Number` number - sprawdzana liczba * Wartość: * `Boolean` - czy wartość number wynosi `NaN` Wiele funkcji, które normalnie powinny zwrócić wartość typu `Number` , może w pewnych przypadkach zwrócić specjalną wartość `NaN` (ang. not-a-number). Wskazuje to najczęściej, że do funkcji zostały przekazane niepoprawne parametry i w związku z tym nie może ona zwrócić wartości liczbowej. Ponieważ `NaN` porównana do dowolnej innej wartości - w tym nawet do `NaN` - zawsze zwraca `false` , jedynym pewnym sposobem sprawdzenia, czy funkcja zwróciła poprawną liczbę, jest wywołanie funkcji `isNaN` . ### Przykład isNaN > isNaN(parseInt("1")); // false isNaN(parseInt("test")); // true > isFinite(number) * Parametry: * `Number` number - sprawdzana liczba * Wartość: * `Boolean` - czy wartość number jest różna od `Infinity` Wiele funkcji, które normalnie powinny zwrócić wartość typu `Number` , może w pewnych przypadkach zwrócić specjalną wartość `Infinity` . Wskazuje to najczęściej, że do funkcji zostały przekazane takie parametry, że obliczona wartość jest nieskończona. Aby sprawdzić, czy wskazana wartość jest skończona, należy użyć funkcji `isFinite` . ### Przykład isFinite > isFinite(Infinity); // false isFinite(-Infinity); // false isFinite(1); // true isFinite(1 / 0); // false > decodeURI(encodedURI) ### Przykład decodeURI > decodeURI("http://example.com/%7Btest%7D"); // "http://example.com/{test}" decodeURI("%XX"); // URIError > decodeURIComponent(encodedURIComponent) ### Przykład decodeURIComponent > decodeURIComponent("%7Btest%7D"); // "{test}" decodeURIComponent("%XX"); // URIError > encodeURI(uri) > encodeURI("http://example.com/{test}"); // "http://example.com/%7Btest%7D" encodeURI("\uDC00"); // URIError > encodeURIComponent(uriComponent) * Object Jak przekształcić wartość prostą (logiczną, liczbę, tekst) na obiekt? * new Object Jak utworzyć nowy obiekt? * getPrototypeOf W jaki sposób pobrać prototyp podanej instancji obiektu? * getOwnPropertyDescriptor Jak pobrać deskryptor właściwości podanej instancji obiektu? * getOwnPropertyNames Jak pobrać listę nazw wszystkich właściwości, które posiada obiekt? * create Jak utworzyć obiekt bazujący na podanym wzorcu, ale bez wywoływania konstruktora? * defineProperty Jak w języku JavaScript utworzyć zmienną tylko do odczytu? * defineProperties Jak za jednym razem skonfigurować właściwości obiektu (np. tylko do odczytu)? * seal Co zrobić, aby opieczętować obiekt w taki sposób, aby jego struktura pozostała niezmienna w programie? * freeze Co zrobić, aby zamrozić obiekt w taki sposób, aby nie można go było już zmieniać? * preventExtensions Co zrobić, aby zablokować możliwość rozszerzania struktury obiektu? * isSealed Jak sprawdzić, czy obiekt jest opieczętowany, tzn. nierozszerzalny i niekonfigurowalny? * isFrozen Jak sprawdzić, czy obiekt jest zamrożony, tzn. nierozszerzalny, niekonfigurowalny i niezmienny? * isExtensible Jak sprawdzić, czy obiekt jest rozszerzalny, tzn. nie można nic nowego do niego dodawać? * keys W jaki sposób pobrać listę nazw wszystkich widocznych właściwości obiektu? > Object() Object(value) * Parametry: * `Object` O - obiekt * Wartość: * O - przekazany obiekt * Wyjątki: * `TypeError` - wartość O nie jest obiektem Wywołanie tej funkcji na podanym obiekcie sprawia, że nie będzie można dla niego definiować więcej żadnych deskryptorów właściwości, dodawać żadnych nowych właściwości ani usuwać istniejących. Natomiast będzie można normalnie zmieniać wartości właściwości, które obiekt posiadał już wcześniej. Mówimy, że obiekt został opieczętowany (ang. seal), tzn. jego struktura pozostanie niezmienna. ### Przykład Object.seal > var obj = Object.defineProperty({p: 1}, "x", {configurable: true}); delete obj.p; obj.p; // undefined obj.test = 3; Object.seal(obj); obj.test; // 3 obj.test = 2; obj.test; // 2 delete obj.test; obj.test; // 2 obj.p = 1; obj.p; // undefined Object.defineProperty(obj, "x", {configurable: true}); // TypeError Object.defineProperty(obj, "p", {}); // TypeError Object.seal(true); // TypeError Object.seal(1); // TypeError Object.seal("test"); // TypeError Object.seal(null); // TypeError * Parametry: * `Object` O - obiekt * Wartość: * O - przekazany obiekt * Wyjątki: * `TypeError` - wartość O nie jest obiektem Wywołanie tej funkcji na podanym obiekcie sprawia, że nie będzie można dla niego definiować więcej żadnych nowych deskryptorów właściwości ani dodawać żadnych nowych właściwości. Natomiast będzie można normalnie zmieniać wartości i deskryptory oraz usuwać właściwości, które obiekt posiadał już wcześniej. Mówimy, że obiekt przestał być rozszerzalny (ang. extensible), tzn. jego struktura nie może się rozszerzyć. ### Przykład Object.preventExtensions > var obj = Object.defineProperty({p: 1}, "x", {value: 2, writable: false, configurable: true}); delete obj.p; obj.test; // undefined obj.test = 3; Object.preventExtensions(obj); obj.test; // 3 obj.test = 2; obj.test; // 2 delete obj.test; obj.test; // undefined obj.p = 1; obj.p; // undefined obj.x = 1; obj.x; // 2 Object.defineProperty(obj, "x", {writable: true}); obj.x = 1; obj.x; // 1 Object.defineProperty(obj, "p", {}); // TypeError Object.preventExtensions(true); // TypeError Object.preventExtensions(1); // TypeError Object.preventExtensions("test"); // TypeError Object.preventExtensions(null); // TypeError * Parametry: * `Object` O - obiekt * Wartość: * `Boolean` - czy obiekt został opieczętowany * Wyjątki: * `TypeError` - wartość O nie jest obiektem Sprawdza, czy podany obiekt został opieczętowany, tzn. jest nierozszerzalny, a wszystkie jego właściwości są niekonfigurowalne [zobacz: Object.definePropert - configurable]. ### Przykład Object.isSealed > Object.isSealed({}); // false Object.isSealed(Object.seal({})); // true Object.isSealed(Object.freeze({})); // true Object.isSealed(Object.preventExtensions({})); // true var obj = Object.preventExtensions(Object.defineProperty({}, "x", {writable: false, configurable: false})); Object.isSealed(obj); // true obj = Object.preventExtensions(Object.defineProperty({}, "x", {writable: true, configurable: false})); Object.isSealed(obj); // true obj = Object.defineProperty({}, "x", {configurable: false}); Object.isSealed(obj); // false obj = Object.preventExtensions(Object.defineProperty({}, "x", {configurable: true})); Object.isSealed(obj); // false Object.isSealed(true); // TypeError Object.isSealed(1); // TypeError Object.isSealed("test"); // TypeError Object.isSealed(null); // TypeError * Parametry: * `Object` O - obiekt * Wartość: * `Boolean` - czy obiekt został zamrożony * Wyjątki: * `TypeError` - wartość O nie jest obiektem Sprawdza, czy podany obiekt został zamrożony, tzn. jest nierozszerzalny, a wszystkie jego właściwości są niekonfigurowalne i zablokowane przed zapisem [zobacz: Object.definePropert - configurable, writable]. ### Przykład Object.isFrozen > Object.isFrozen({}); // false Object.isFrozen(Object.seal({})); // true Object.isFrozen(Object.freeze({})); // true Object.isFrozen(Object.preventExtensions({})); // true var obj = Object.preventExtensions(Object.defineProperty({}, "x", {writable: false, configurable: false})); Object.isFrozen(obj); // true obj = Object.preventExtensions(Object.defineProperty({}, "x", {writable: true, configurable: false})); Object.isFrozen(obj); // false obj = Object.defineProperty({}, "x", {configurable: false}); Object.isFrozen(obj); // false obj = Object.preventExtensions(Object.defineProperty({}, "x", {configurable: true})); Object.isFrozen(obj); // false Object.isFrozen(true); // TypeError Object.isFrozen(1); // TypeError Object.isFrozen("test"); // TypeError Object.isFrozen(null); // TypeError Gdzie jest zapisany konstruktor obiektu ogólnego? * toString W jaki sposób przekształcić obiekt na prosty tekst? * toLocaleString W jaki sposób przekształcić obiekt na tekst zapisany w rodzimym języku użytkownika? * valueOf Jak przekształcić złożony obiekt na wartość prostą (logiczną, liczbę, tekst)? * hasOwnProperty W jaki sposób sprawdzić, czy obiekt posiada właściwość o podanej nazwie? * isPrototypeOf W jaki sposób sprawdzić, czy podany obiekt jest prototypem określonej instancji obiektu? * propertyIsEnumerable Jak sprawdzić, czy podana właściwość będzie dostępna w pętli? > Object.prototype.constructor * Wartość: * `Function` - konstruktor obiektu Zawiera konstruktor wbudowanego obiektu ogólnego `Object` . ### Przykład Object.prototype.constructor > Object.prototype.constructor === Object; // true new Object().constructor === Object; // true Object.prototype.constructor === Boolean; // false Object.prototype.constructor === Number; // false Object.prototype.constructor === String; // false Object.prototype.constructor === Array; // false > Object.prototype.toString() Jak pobrać kod (definicję) funkcji? * apply Jak wywołać dowolną funkcję z listą argumentów zapisaną w tablicy? * call Jak zbudować program, który pozwoli wybrać użytkownikowi funkcję, którą należy wykonać? * bind Co zrobić, żeby w metodzie była widoczna właściwa instancja obiektu? > Function.prototype.constructor Date: 2000-01-31 Categories: Tags: Gdzie jest zapisany konstruktor tablicy? * toString Jak przekształcić tablicę elementów na prosty tekst? * toLocaleString Jak przekształcić tablicę elementów na tekst zapisany w rodzimym języku użytkownika? * concat W jaki sposób połączyć dwie tablice w jedną? * join W jaki sposób przekształcić tablicę na tekst, w którym kolejne elementy będą oddzielone od siebie określonym separatorem? * pop Jak usunąć ostatni element z tablicy? * push Jak dodać nowy element na końcu tablicy? * reverse W jaki sposób odwrócić kolejność elementów w tablicy? * shift Jak usunąć pierwszy element z tablicy? * slice W jaki sposób wyciąć część elementów tablicy? * sort Jak posortować elementy tablicy w porządku alfabetycznym? * splice W jaki sposób wyciąć część elementów tablicy i zastąpić je innymi? * unshift Jak dodać nowy element na początku tablicy? * indexOf Jak sprawdzić, czy w tablicy występuje określony elementy? * lastIndexOf Jak przeszukać tablicę od końca, tak by sprawdzić, czy znajduje się w niej określony element? * every Jak sprawdzić, czy wszystkie elementy tablicy spełniają podany warunek? * some Jak sprawdzić, czy przynajmniej jeden element tablicy spełnia podany warunek? * forEach W jaki sposób przejść kolejno po wszystkich elementach tablicy? * map W jaki sposób przekształcić wszystkie elementy tablicy? * filter W jaki sposób odfiltrować elementy tablicy, które nie spełniają podanego warunku? * reduce Jak zredukować tablicę do pojedynczej prostej wartości? * reduceRight Jak wstecznie zredukować tablicę do pojedynczej prostej wartości? > Array.prototype.constructor ### Przykład Array.prototype.constructor > Array.prototype.constructor === Array; // true new Array().constructor === Array; // true Array.prototype.constructor === Object; // false > Array.prototype.toString() * Wartość: * ostatni element tablicy ### Przykład Array.prototype.pop > var items = [1, 2]; items.pop(); // 2 items; // [1] items.pop(); // 1 items; // [] items.pop(); // undefined > Array.prototype.push() Array.prototype.push(item1) Array.prototype.push(item1, item2...) * Wartość: * pierwszy element tablicy ### Przykład Array.prototype.shift > var items = [1, 2]; items.shift(); // 1 items; // [2] items.shift(); // 2 items; // [] items.shift(); // undefined > Array.prototype.slice() Array.prototype.slice(start) Array.prototype.slice(start, end) (interpretuje: Internet Explorer 9, Firefox, Opera, Chrome) > Array.prototype.indexOf(searchElement) Array.prototype.indexOf(searchElement, fromIndex) ### Przykład Array.prototype.indexOf > var items = [1, 2, 3, 1]; items.indexOf(1); // 0 items.indexOf(1, 1); // 3 items.indexOf(1, -3); // 3 == items.indexOf(1, 2) items.indexOf(1, -10); // 0 == items.indexOf(1, 0) items.indexOf(1, 10); // -1 == items.indexOf(1, 4) items.indexOf(0); // -1 (interpretuje: Internet Explorer 9, Firefox, Opera, Chrome) > Array.prototype.lastIndexOf(searchElement) Array.prototype.lastIndexOf(searchElement, fromIndex) ### Przykład Array.prototype.lastIndexOf > var items = [1, 2, 3, 1]; items.lastIndexOf(1); // 3 items.lastIndexOf(1, -2); // 0 == items.lastIndexOf(1, 2) items.lastIndexOf(1, 2); // 0 items.lastIndexOf(1, 10); // 3 items.lastIndexOf(1, -10); // -1 items.lastIndexOf(0); // -1 (interpretuje: Internet Explorer 9, Firefox, Opera, Chrome) > Array.prototype.every(callbackfn) Array.prototype.every(callbackfn, thisArg) ### Przykład Array.prototype.every (interpretuje: Internet Explorer 9, Firefox, Opera, Chrome) > Array.prototype.some(callbackfn) Array.prototype.some(callbackfn, thisArg) ### Przykład Array.prototype.some > var items = [3, 2, 1]; var f = function (x) { return x > 0; }; items.some(f); // true f = function (x) { return x < 0; }; items.some(f); // false var GreaterThan = function (value) { this.value = value; this.tests = 0; }; GreaterThan.prototype.test = function (value) { ++this.tests; return value > this.value; }; var tester = new GreaterThan(0); items.some(tester.test, tester); // true tester.tests; // 1 tester = new GreaterThan(4); items.some(tester.test, tester); // false tester.tests; // 3 items = [1, 2]; items[3] = 3; items.length; // 4 tester = new GreaterThan(4); items.some(tester.test, tester); // false tester.tests; // 3 items[2] = undefined; items.length; // 4 tester = new GreaterThan(4); items.some(tester.test, tester); // false tester.tests; // 4 items.some(null); // TypeError items.some(undefined); // TypeError items.some({}); // TypeError (interpretuje: Internet Explorer 9, Firefox, Opera, Chrome) > Array.prototype.map(callbackfn) Array.prototype.map(callbackfn, thisArg) * Parametry: * `Function` callbackfn - funkcja zwracająca nową wartość elementu i przyjmująca argumenty: * kValue - element tablicy * `Number` k - indeks elementu tablicy * `Array` O - oryginalna tablica * thisArg - wartość bieżącego obiektu `this` dostępnego w czasie wywołania wewnątrz ciała funkcji (domyślnie: undefined) * Wartość: * `Array` - nowa tablica * Wyjątki: * `TypeError` - callbackfn nie jest funkcją Pozwala przekształcić jedną tablicę w drugą, wykonując na każdym jej elemencie określoną funkcję. Elementy, które nie zostały jawnie dodane do tablicy, są pomijane. Nie zmienia oryginalnej tablicy, ale zwraca nową. (interpretuje: Internet Explorer 9, Firefox, Opera, Chrome) > Array.prototype.filter(callbackfn) Array.prototype.filter(callbackfn, thisArg) * kValue - element tablicy * `Number` k - indeks elementu tablicy * `Array` O - oryginalna tablica * thisArg - wartość bieżącego obiektu `this` dostępnego w czasie wywołania wewnątrz ciała funkcji (domyślnie: undefined) * Wartość: * `Array` - nowa tablica * Wyjątki: * `TypeError` - callbackfn nie jest funkcją Pozwala pobrać z tablicy elementy, które spełniają określony warunek. Elementy, które nie zostały jawnie dodane do tablicy, są pomijane. Nie zmienia oryginalnej tablicy, ale zwraca nową. ### Przykład Array.prototype.filter > var items = [3, 2, 1]; var f = function (x) { return x > 1; }; items.filter(f); // [3, 2] items; // [3, 2, 1] var GreaterThan = function (value) { this.value = value; this.tests = 0; }; GreaterThan.prototype.test = function (value) { ++this.tests; return value > this.value; }; tester = new GreaterThan(2); items.filter(tester.test, tester); // [3] tester.tests; // 3 items = [1, 2]; items[3] = 3; items.length; // 4 tester = new GreaterThan(0); items.filter(tester.test, tester); // [1, 2, 3] tester.tests; // 3 items[2] = undefined; items.length; // 4 tester = new GreaterThan(0); items.filter(tester.test, tester); // [1, 2, 3] tester.tests; // 4 items.filter(null); // TypeError items.filter(undefined); // TypeError items.filter({}); // TypeError * String Jak skonwertować dowolną wartość na prosty tekst? * new String Jak przekształcić dowolną wartość na obiekt tekstowy? * fromCharCode Jak przekształcić kod liczbowy na odpowiadający mu znak Unicode? > String() String(value) Jak zamienić obiekt tekstowy na prosty tekst, który można wyświetlić użytkownikowi? * valueOf Jak zamienić obiekt tekstowy na prostą wartość tekstową? * charAt Jak pobrać określony znak tekstu? * charCodeAt Jak pobrać kod liczbowy określonego znaku w tekście? * concat Jak połączyć dwa teksty w jeden? * indexOf W jaki sposób wyszukać określoną frazę w tekście? * lastIndexOf W jaki sposób znaleźć ostatnie wystąpienie podanej frazy w tekście? * localeCompare W jaki sposób ułożyć tekst w porządku alfabetycznym uwzględniając polskie znaki diakrytyczne? * match Jak sprawdzić, czy tekst pasuje do złożonego wzorca (wyrażenia regularnego)? * replace Co zrobić, aby zamienić w tekście wszystkie wystąpienia podanej frazy na inną? * search Jak wyszukać w tekście złożonego wzorca (wyrażenia regularnego)? * slice W jaki sposób wyciąć z tekstu jego część? * split Jak rozbić tekst na tablicę elementów? * substring Jak wyciąć z tekstu krótki fragment? * toLowerCase Jak zamienić tekst na małe litery? * toLocaleLowerCase Jak zamienić tekst na wielkie litery? * toLocaleUpperCase Jak usunąć niepotrzebne białe znaki na początku i na końcu tekstu? > String.prototype.constructor * Wartość: * `Function` - konstruktor obiektu Zawiera konstruktor wbudowanego obiektu tekstowego `String` . ### Przykład String.prototype.constructor > String.prototype.constructor === String; // true new String().constructor === String; // true String.prototype.constructor === Object; // false > String.prototype.toString() Działa identycznie jak funkcja String.prototype.valueOf. > String.prototype.valueOf() * Wartość: * prosta wartość tekstowa * Wyjątki: * `TypeError` - obiekt nie jest tekstem Przekształca obiekt tekstowy na prostą wartość tekstową (już nie obiekt). Działa identycznie jak funkcja String.prototype.toString. ### Przykład String.prototype.valueOf > new String("test").valueOf(); // "test" String.prototype.valueOf.call("test"); // "test" String.prototype.valueOf.call(null); // TypeError String.prototype.valueOf.call(undefined); // TypeError String.prototype.valueOf.call({}); // TypeError > String.prototype.charAt() String.prototype.charAt(pos) * Parametry: * `Number` pos - pozycja w tekście (liczba naturalna licząc od 0) * Wartość: * `String` - znak o podanej pozycji Zwraca znak o podanej pozycji w tekście. Pierwszy znak ma pozycję 0. Jeżeli podano pozycję poza ograniczonym zakresem (mniejszą od zera albo większą lub równą długości tekstu), zwracany jest pusty tekst. ### Przykład String.prototype.charAt > "abc".charAt(); // "a" "abc".charAt(0); // "a" "abc".charAt(" +0.9 "); // "a" "abc".charAt(null); // "a" "abc".charAt(undefined); // "a" "abc".charAt(NaN); // "a" "abc".charAt("test"); // "a" "abc".charAt(false); // "a" "abc".charAt(true); // "b" "abc".charAt(-1); // "" "abc".charAt(3); // "" "abc".charAt(Infinity); // "" "".charAt(0); // "" > String.prototype.charCodeAt() String.prototype.charCodeAt(pos) * Parametry: * `String` string1, `String` string2... - lista kolejnych wartości tekstowych * Wartość: * `String` - połączona wartość tekstowa Łączy kilka wartości - niekoniecznie tekstowych - w jeden tekst. Zatem działa identycznie jak operator `+` , w przypadku gdy przynajmniej jeden z jego argumentów jest tekstem. ### Przykład String.prototype.concat > "abc".concat(); // "abc" "abc".concat("def", "ghi"); // "abcdefghi" "test ".concat(null); // "test null" "test ".concat(false); // "test false" "test ".concat(undefined); // "test undefined" "test ".concat(+1.2); // "test 1.2" "test ".concat(NaN); // "test NaN" "test ".concat(Infinity); // "test Infinity" > String.prototype.indexOf(searchString) String.prototype.indexOf(searchString, position) * Parametry: * searchString - poszukiwany tekst * `Number` position - początkowa pozycja poszukiwań (domyślnie: 0) * Wartość: * `Number` - pozycja pierwszego znalezionego tekstu Przeszukuje tekst w kierunku jego końca pod kątem występowania w nim innego podanego tekst. Jeżeli tekst nie zostanie znaleziony, funkcja zwraca liczbę -1. Możliwe jest również ograniczenie zakresu poszukiwań do pozycji nie mniejszych niż podana (wartości ujemne są traktowane jak 0). ### Przykład String.prototype.indexOf > "abc def abc".indexOf("a"); // 0 "abc def abc".indexOf("abc"); // 0 "abc def abc".indexOf("abc", 1); // 8 "abc def abc".indexOf("abc", -8); // 0 == "abc def abc".indexOf("abc", 0) "abc def abc".indexOf("abc", 30); // -1 == "abc def abc".indexOf("abc", 11) "abc def abc".indexOf("ghi"); // -1 "abc def abc".indexOf("ABC"); // -1 > String.prototype.lastIndexOf(searchString) String.prototype.lastIndexOf(searchString, position) * Parametry: * searchString - poszukiwany tekst * `Number` position - początkowa pozycja poszukiwań (domyślnie: długość tekstu - 1) * Wartość: * `Number` - pozycja ostatniego znalezionego tekstu Przeszukuje tekst w kierunku jego początku pod kątem występowania w nim innego podanego tekst. Jeżeli tekst nie zostanie znaleziony, funkcja zwraca liczbę -1. Możliwe jest również ograniczenie zakresu poszukiwań do pozycji nie większych niż podana (wartości ujemne są traktowane jak 0). ### Przykład String.prototype.lastIndexOf > "abc def abc".lastIndexOf("a"); // 8 "abc def abc".lastIndexOf("abc"); // 8 "abc def abc".lastIndexOf("abc", 1); // 0 "abc def abc".lastIndexOf("abc", -8); // 0 == "abc def abc".lastIndexOf("abc", 0) "abc def abc".lastIndexOf("abc", 30); // 8 == "abc def abc".lastIndexOf("abc", 11) "abc def abc".lastIndexOf("ghi"); // -1 "abc def abc".lastIndexOf("ABC"); // -1 > String.prototype.localeCompare(that) * Parametry: * `RegExp` regexp - wyrażenie regularne * Wartość: * `Array` - tablica dopasowań * `Null` - tekst nie został dopasowany do wyrażenia regularnego Próbuje dopasować tekst do podanego wzorca - wyrażenia regularnego. Jeżeli się to uda, zwraca pierwszy dopasowany fragment tekstu oraz każdą jego część, która w wyrażeniu była zapisana w nawiasie (to działanie jest identyczne jak w przypadku funkcji RegExp.prototype.exec). Natomiast w przypadku dopasowania globalnego - kiedy wyrażenie regularne posiada flagę g - zwracane są wszystkie dopasowane fragmenty tekstu, ale już bez dodatkowych ich części, które w wyrażaniu były zapisane w nawiasach. Jeżeli chcesz tylko sprawdzić, czy określony tekst pasuje do wzorca - wyrażenia regularnego - użyj funkcji RegExp.prototype.test. ### Przykład String.prototype.match > "abcd efg abc".match(/abc/); // ["abc"] "abcd efg abc".match(/(ab)c/); // ["abc", "ab"] "ABCd efg abc".match(/abc/i); // ["ABC"] "ABCd efg abc".match(/(ab)c/i); // ["ABC", "AB"] "abcd efg abc".match(/abc/g); // ["abc", "abc"] "abcd efg abc".match(/(ab)c/g); // ["abc", "abc"] "ABCd efg abc".match(/abc/ig); // ["ABC", "abc"] "ABCd efg abc".match(/(ab)c/ig); // ["ABC", "abc"] "abcd efg abc".match(/hij/); // null "abcd efg abc".match(/ABC/); // null "abcd efg abc".match(/(AB)C/); // null "abcd efg abc".match(/hij/g); // null "abcd efg abc".match(/ABC/g); // null "abcd efg abc".match(/(AB)C/g); // null > String.prototype.replace(searchValue, replaceValue) Ta funkcja może nie działać prawidłowo dla alfabetu domyślnego języka systemu operacyjnego użytkownika (dla języka polskiego działa poprawnie). W takim przypadku użyj String.prototype.toLocaleLowerCase. ### Przykład String.prototype.toLowerCase > var str = "AĄBCĆDEĘFGHIJKLŁMNŃOÓPQRSŚTUVWXYZŹŻ"; str.toLowerCase(); // "aąbcćdeę<KEY>" "AbcQX 123".toLowerCase(); // "abcqx 123" > String.prototype.toLocaleLowerCase() ### Przykład String.prototype.toLocaleLowerCase > var str = "AĄBCĆDEĘFGHIJKLŁMNŃOÓPQRSŚTUVWXYZŹŻ"; str.toLocaleLowerCase(); // np.: "a<KEY>" "AbcQX 123".toLocaleLowerCase(); // np.: "abcqx 123" > String.prototype.toUpperCase() Ta funkcja może nie działać prawidłowo dla alfabetu domyślnego języka systemu operacyjnego użytkownika (dla języka polskiego działa poprawnie). W takim przypadku użyj String.prototype.toLocaleUpperCase. ### Przykład String.prototype.toUpperCase > var str = "a<KEY>"; str.toUpperCase(); // "AĄBCĆDEĘFGHIJKLŁMNŃOÓPQRSŚTUVWXYZŹŻ" "Abcqx 123".toUpperCase(); // "ABCQX 123" > String.prototype.toLocaleUpperCase() ### Przykład String.prototype.toLocaleUpperCase > var str = "aąbcćdeęfgh<KEY>źż"; str.toLocaleUpperCase(); // np.: "AĄBCĆDEĘFGHIJKLŁMNŃOÓPQRSŚTUVWXYZŹŻ" "Abcqx 123".toLocaleUpperCase(); // np.: "ABCQX 123" Gdzie jest zapisany konstruktor obiekt logicznego? * toString Jak przekształcić wartość logiczną na prosty tekst? * valueOf Jak przekształcić obiekt logiczny na prostą wartość logiczną - true/false (prawda/fałsz)? > Boolean.prototype.constructor * Number W jaki sposób skonwertować dowolną wartość na liczbę? * new Number Jak przekształcić dowolną wartość na obiekt liczbowy? * MAX_VALUE Jaką największą liczbę można zapisać w JavaScript? * MIN_VALUE Jaką najmniejszą wartość można zapisać w JavaScript? * NaN Jak zapisać wartość liczbową, która jednak nie jest poprawną liczbą? * NEGATIVE_INFINITY Jak zapisać ujemną nieskończość w języku JavaScript? * POSITIVE_INFINITY Jak zapisać wartość nieskończoną w języku JavaScript? > Number() Number(value) ### Przykład Number.NEGATIVE_INFINITY > Number.NEGATIVE_INFINITY; // -Infinity Number.NEGATIVE_INFINITY = 1; Number.NEGATIVE_INFINITY; // -Infinity > Number.NEGATIVE_INFINITY ### Przykład Number.POSITIVE_INFINITY > Number.POSITIVE_INFINITY; // Infinity Number.POSITIVE_INFINITY = 1; Number.POSITIVE_INFINITY; // Infinity Gdzie jest zapisany konstruktor obiektu liczbowego? * toString Co zrobić, żeby przekształcić liczbę dziesiętną na wartość szesnastkową (heksadecymalną) lub ósemkową (oktalną)? * toLocaleString W jaki sposób zapisać liczbę w formacie zgodnym w rodzimym językiem użytkownika? * valueOf Jak przekształcić obiekt liczbowy na prostą wartość liczbową? * toFixed Jak zapisać liczbę ze stałą liczbą miejsc po przecinku (np. kwota)? * toExponential Jak zapisać liczbę w notacji eksponencjalnej? * toPrecision Jak zapisać liczbę w precyzyjnym formacie - za pomocą określonej liczby cyfr? > Number.prototype.constructor * Wartość: * `Function` - konstruktor obiektu Zawiera konstruktor wbudowanego obiektu liczbowego `Number` . ### Przykład Number.prototype.constructor > Number.prototype.constructor === Number; // true new Number().constructor === Number; // true Number.prototype.constructor === Object; // false > Number.prototype.toString() Number.prototype.toString(radix) * E Ile wynosi liczba Eulera (podstawa logarytmu naturalnego)? * LN10 Ile wynosi logarytm naturalny z liczby 10? * LN2 Ile wynosi logarytm naturalny z liczby 2? * LOG2E Ile wynosi logarytm o podstawie 2 z liczby Eulera? * LOG10E Ile wynosi logarytm o podstawie 10 z liczby Eulera? * PI Ile wynosi liczba "pi"? * SQRT1_2 Ile wynosi pierwiastek kwadratowy z liczby 1/2? * SQRT2 Ile wynosi pierwiastek kwadratowy z liczby 2? * abs Jak obliczyć wartość bezwzględną liczby? * acos Jak obliczyć arcus cosinus? * asin Jak obliczyć arcus sinus? * atan Jak obliczyć arcus tangens? * atan2 Jak wyznaczyć kąt, utworzony między dodatnią poziomą półosią układu współrzędnych a prostą przechodzącą przez środek układu współrzędnych i zadany punkt? * ceil W jaki sposób zaokrąglić liczbę w górę? * cos Jak obliczyć cosinus? * exp Jak obliczyć wartość funkcji eksponencjalnej? * floor W jaki sposób zaokrąglić liczbę w dół? * log Jak obliczyć wartość logarytmu naturalnego? * max Jak wybrać największą liczbę ze zbioru? * min Jak wybrać najmniejszą liczbę ze zbioru? * pow Jak podnieść podaną liczbę do określonej potęgi? * random Jak wylosować liczbę? Czy można wylosować liczbę całkowitą z podanego przedziału wartości? * round Jak zaokrąglić liczbę? Czy można wykonać zaokrąglenie do podanego miejsca po przecinku? * sin Jak obliczyć sinus? * sqrt Jak obliczyć pierwiastek kwadratowy? * tan Jak obliczyć tangens lub cotangens? > Math.E * Wartość: * `Number` - podstawa logarytmu naturalnego (liczba Eulera = 2.718281828459045235...) Przechowuje wartość stałej matematycznej, będącej podstawą logarytmu naturalnego. Tej wartości nie można zmienić ani nie będzie dostępna w pętli `for-in` . ### Przykład Math.E > Math.E; // 2.718281828459045 Math.E = 1; Math.E; // 2.718281828459045 > Math.LN10 ### Przykład Math.LN2 > Math.LN2; // 0.6931471805599453 Math.LN2 = 1; Math.LN2; // 0.6931471805599453 > Math.LOG2E ### Przykład Math.LOG10E > Math.LOG10E; // 0.4342944819032518 Math.LOG10E = 1; Math.LOG10E; // 0.4342944819032518 > Math.PI ### Przykład Math.SQRT1_2 > Math.SQRT1_2; // 0.7071067811865476 Math.SQRT1_2 = 1; Math.SQRT1_2; // 0.7071067811865476 > Math.SQRT2 ### Przykład Math.SQRT2 > Math.SQRT2; // 1.4142135623730951 Math.SQRT2 = 1; Math.SQRT2; // 1.4142135623730951 > Math.abs(x) > Math.log(-Infinity); // NaN Math.log(-0.01); // NaN Math.log(0); // -Infinity Math.log(0.5); // -0.6931471805599453 Math.log(1); // 0 Math.log(Math.E); // 1 Math.log(Infinity); // Infinity Math.log(NaN); // NaN > Math.max() Math.max(value1) Math.max(value1, value2...) * Parametry: * `Number` value1, `Number` value2... - lista dowolnych liczb * Wartość: * `Number` - największa z podanych liczb Wyznacza największą z podanych liczb. Jeżeli do funkcji nie zostały przekazane żadne argumenty, zwracana jest wartość -Infinity. Jeżeli którakolwiek z podanych wartości wynosi NaN, funkcja zwraca wartość NaN (można to sprawdzić za pomocą funkcji isNaN). ### Przykład Math.max > Math.max(); // -Infinity Math.max(1); // 1 Math.max(1, 2); // 2 Math.max(-1.2, -1, 0, 1, 1.2); // 1.2 Math.max(-Infinity, Infinity); // Infinity Math.max(NaN); // NaN Math.max(NaN, 0); // NaN Math.max(0, NaN); // NaN Math.max(0, 1, NaN); // NaN Math.max(undefined); // NaN > Math.min() Math.min(value1) Math.min(value1, value2...) * Parametry: * `Number` value1, `Number` value2... - lista dowolnych liczb * Wartość: * `Number` - najmniejsza z podanych liczb Wyznacza najmniejszą z podanych liczb. Jeżeli do funkcji nie zostały przekazane żadne argumenty, zwracana jest wartość Infinity. Jeżeli którakolwiek z podanych wartości wynosi NaN, funkcja zwraca wartość NaN (można to sprawdzić za pomocą funkcji isNaN). ### Przykład Math.min > Math.min(); // Infinity Math.min(1); // 1 Math.min(1, 2); // 1 Math.min(-1.2, -1, 0, 1, 1.2); // -1.2 Math.min(-Infinity, Infinity); // -Infinity Math.min(NaN); // NaN Math.min(NaN, 0); // NaN Math.min(0, NaN); // NaN Math.min(0, 1, NaN); // NaN Math.min(undefined); // NaN > Math.pow(x, y) * Date Jak pobrać aktualną datę i czas? * new Date Jak utworzyć obiekt przechowujący datę i czas? * parse Jak przekształcić datę i czas w formie tekstowej na liczbę milisekund od północy 1 stycznia 1970 roku? * UTC Jak przekształcić podaną datę na liczbę milisekund od północy 1 stycznia 1970 roku? * now Jak pobrać aktualną datę i czas w formie liczby milisekund, które upłynęły od północy 1 stycznia 1970 roku? > Date() > Date(); // np.: "Sat Jan 04 2014 17:38:21 GMT+0100" > new Date() new Date(value) new Date(year, month) new Date(year, month, date) new Date(year, month, date, hours) new Date(year, month, date, hours, minutes) new Date(year, month, date, hours, minutes, seconds) new Date(year, month, date, hours, minutes, seconds, ms) Gdzie jest zapisany konstruktor obiektu daty i czasu? * toString Jak zamienić datę i czas na tekst, który można wyświetlić użytkownikowi? * toDateString Jak zamienić datę na tekst, który można wyświetlić użytkownikowi? * toTimeString Jak zamienić czas na tekst, który można wyświetlić użytkownikowi? * toLocaleString Jak zamienić datę i czas na tekst w formacie zgodnym z rodzimym językiem użytkownika? * toLocaleDateString Jak zamienić datę na tekst w formacie zgodnym z rodzimym językiem użytkownika? * toLocaleTimeString Jak zamienić czas na tekst w formacie zgodnym z rodzimym językiem użytkownika? * valueOf Jak pobrać liczbę milisekund, które upłynęły od północy 1 stycznia 1970 roku do podanej daty? * getTime Jak pobrać czas w postaci liczby milisekund, które upłynęły od północy 1 stycznia 1970 roku do podanej daty? * getFullYear Jak pobrać rok z podanej daty? * getUTCFullYear Jak pobrać rok z podanej daty w strefie czasowej południka zerowego (UTC)? * getMonth Jak pobrać miesiąc z podanej daty * getUTCMonth Jak pobrać miesiąc z podanej daty w strefie czasowej południka zerowego (UTC)? * getDate Jak pobrać dzień miesiąca z podanej daty? * getUTCDate Jak pobrać dzień tygodnia z podanej daty? * getUTCDay Jak pobrać dzień tygodnia z podanej daty w strefie czasowej UTC? * getHours Jak pobrać minutę z podanej daty? * getUTCMinutes Jak pobrać sekundę z podanej daty? * getUTCSeconds Jak pobrać sekundę z podanej daty w strefie czasowej południka zerowego (UTC)? * getMilliseconds Jak pobrać przesunięcie strefy czasowej dla podanej daty? * setTime Jak ustawić datę i czas poprzez podanie liczby milisekund, które upłynęły od północy 1 stycznia 1970 roku? * setMilliseconds Jak zmienić milisekundę w podanej dacie? * setUTCMilliseconds Jak zmienić sekundę w podanej dacie? * setUTCSeconds Jak zmienić sekundę w podanej dacie, określoną w strefie czasowej południka zerowego (UTC)? * setMinutes Jak zmienić minutę w podanej dacie? * setUTCMinutes Jak zmienić godzinę w podanej dacie? * setUTCHours Jak zmienić dzień miesiąca w podanej dacie? * setUTCDate Jak zmienić dzień miesiąca w podanej dacie, określony w strefie czasowej południka zerowego (UTC)? * setMonth Jak zmienić miesiąc w podanej dacie? * setUTCMonth Jak zmienić miesiąc w podanej dacie, określony w strefie czasowej południka zerowego (UTC)? * setFullYear Jak zmienić rok w podanej dacie? * setUTCFullYear Jak zmienić rok w podanej dacie, określony w strefie czasowej południka zerowego (UTC)? * toUTCString Jak zamienić datę i czas na tekst zapisany w formacie UTC (GMT)? * toISOString Jak zamienić datę i czas na tekst zapisany w formacie ze standardem ISO? * toJSON W jaki sposób następuje konwersja obiektu daty i czasu do formatu JSON? > Date.prototype.constructor ### Przykład Date.prototype.toDateString > new Date(1410, 6, 15).toDateString(); // np.: "Sun Jul 15 1410" Date.prototype.toDateString.call(null); // TypeError Date.prototype.toDateString.call(undefined); // TypeError Date.prototype.toDateString.call(0); // TypeError Date.prototype.toDateString.call(""); // TypeError Date.prototype.toDateString.call("2000"); // TypeError Date.prototype.toDateString.call({}); // TypeError > Date.prototype.toTimeString() ### Przykład Date.prototype.toTimeString > new Date(1410, 6, 15, 13, 30, 59).toTimeString(); // np.: "13:30:59 GMT+0200" Date.prototype.toTimeString.call(null); // TypeError Date.prototype.toTimeString.call(undefined); // TypeError Date.prototype.toTimeString.call(0); // TypeError Date.prototype.toTimeString.call(""); // TypeError Date.prototype.toTimeString.call("2000"); // TypeError Date.prototype.toTimeString.call({}); // TypeError > Date.prototype.toLocaleString() Działa tak samo jak Date.prototype.getTime. ### Przykład Date.prototype.valueOf > new Date(2000, 0, 1).valueOf(); // 946681200000 Date.prototype.valueOf.call(null); // TypeError Date.prototype.valueOf.call(undefined); // TypeError Date.prototype.valueOf.call(0); // TypeError Date.prototype.valueOf.call(""); // TypeError Date.prototype.valueOf.call("2000"); // TypeError Date.prototype.valueOf.call({}); // TypeError > Date.prototype.getTime() Działa tak samo jak Date.prototype.valueOf. ### Przykład Date.prototype.getTime > new Date(2000, 0, 1).getTime(); // 946681200000 Date.prototype.getTime.call(null); // TypeError Date.prototype.getTime.call(undefined); // TypeError Date.prototype.getTime.call(0); // TypeError Date.prototype.getTime.call(""); // TypeError Date.prototype.getTime.call("2000"); // TypeError Date.prototype.getTime.call({}); // TypeError > Date.prototype.getFullYear() Aby pobrać dzień tygodnia, użyj funkcji Date.prototype.getDay. ### Przykład Date.prototype.getDate > new Date("1410-07-15T13:30+02:00").getDate(); // 15 new Date(NaN).getDate(); // NaN Date.prototype.getDate.call(null); // TypeError Date.prototype.getDate.call(undefined); // TypeError Date.prototype.getDate.call(0); // TypeError Date.prototype.getDate.call(""); // TypeError Date.prototype.getDate.call("2000"); // TypeError Date.prototype.getDate.call({}); // TypeError > Date.prototype.getUTCDate() ### Przykład Date.prototype.getUTCDate > new Date("1410-07-15T13:30+02:00").getUTCDate(); // 15 new Date(NaN).getUTCDate(); // NaN Date.prototype.getUTCDate.call(null); // TypeError Date.prototype.getUTCDate.call(undefined); // TypeError Date.prototype.getUTCDate.call(0); // TypeError Date.prototype.getUTCDate.call(""); // TypeError Date.prototype.getUTCDate.call("2000"); // TypeError Date.prototype.getUTCDate.call({}); // TypeError > Date.prototype.getDay() Aby pobrać dzień miesiąca, użyj funkcji Date.prototype.getDate. ### Przykład Date.prototype.getDay > new Date("1410-07-15T13:30+02:00").getDay(); // 0 (niedziela) new Date(NaN).getDay(); // NaN Date.prototype.getDay.call(null); // TypeError Date.prototype.getDay.call(undefined); // TypeError Date.prototype.getDay.call(0); // TypeError Date.prototype.getDay.call(""); // TypeError Date.prototype.getDay.call("2000"); // TypeError Date.prototype.getDay.call({}); // TypeError > Date.prototype.getUTCDay() ### Przykład Date.prototype.getUTCDay > new Date("1410-07-15T13:30+02:00").getUTCDay(); // 0 (niedziela) new Date(NaN).getUTCDay(); // NaN Date.prototype.getUTCDay.call(null); // TypeError Date.prototype.getUTCDay.call(undefined); // TypeError Date.prototype.getUTCDay.call(0); // TypeError Date.prototype.getUTCDay.call(""); // TypeError Date.prototype.getUTCDay.call("2000"); // TypeError Date.prototype.getUTCDay.call({}); // TypeError > Date.prototype.getHours() > new Date("1410-07-15T13:30+02:00").getUTCHours(); // 11 new Date(NaN).getUTCHours(); // NaN Date.prototype.getUTCHours.call(null); // TypeError Date.prototype.getUTCHours.call(undefined); // TypeError Date.prototype.getUTCHours.call(0); // TypeError Date.prototype.getUTCHours.call(""); // TypeError Date.prototype.getUTCHours.call("2000"); // TypeError Date.prototype.getUTCHours.call({}); // TypeError > Date.prototype.getMinutes() ### Przykład Date.prototype.getMinutes > new Date("1410-07-15T13:30+02:00").getMinutes(); // 30 new Date(NaN).getMinutes(); // NaN Date.prototype.getMinutes.call(null); // TypeError Date.prototype.getMinutes.call(undefined); // TypeError Date.prototype.getMinutes.call(0); // TypeError Date.prototype.getMinutes.call(""); // TypeError Date.prototype.getMinutes.call("2000"); // TypeError Date.prototype.getMinutes.call({}); // TypeError > Date.prototype.getUTCMinutes() ### Przykład Date.prototype.getUTCMinutes > new Date("1410-07-15T13:30+02:00").getUTCMinutes(); // 30 new Date(NaN).getUTCMinutes(); // NaN Date.prototype.getUTCMinutes.call(null); // TypeError Date.prototype.getUTCMinutes.call(undefined); // TypeError Date.prototype.getUTCMinutes.call(0); // TypeError Date.prototype.getUTCMinutes.call(""); // TypeError Date.prototype.getUTCMinutes.call("2000"); // TypeError Date.prototype.getUTCMinutes.call({}); // TypeError > Date.prototype.getSeconds() ### Przykład Date.prototype.getSeconds > new Date("1410-07-15T13:30:59+02:00").getSeconds(); // 59 new Date(NaN).getSeconds(); // NaN Date.prototype.getSeconds.call(null); // TypeError Date.prototype.getSeconds.call(undefined); // TypeError Date.prototype.getSeconds.call(0); // TypeError Date.prototype.getSeconds.call(""); // TypeError Date.prototype.getSeconds.call("2000"); // TypeError Date.prototype.getSeconds.call({}); // TypeError > Date.prototype.getUTCSeconds() ### Przykład Date.prototype.getUTCSeconds > new Date("1410-07-15T13:30:59+02:00").getUTCSeconds(); // 59 new Date(NaN).getUTCSeconds(); // NaN Date.prototype.getUTCSeconds.call(null); // TypeError Date.prototype.getUTCSeconds.call(undefined); // TypeError Date.prototype.getUTCSeconds.call(0); // TypeError Date.prototype.getUTCSeconds.call(""); // TypeError Date.prototype.getUTCSeconds.call("2000"); // TypeError Date.prototype.getUTCSeconds.call({}); // TypeError > Date.prototype.getMilliseconds() ### Przykład Date.prototype.getMilliseconds > new Date("1410-07-15T13:30:59.500+02:00").getMilliseconds(); // 500 new Date(NaN).getMilliseconds(); // NaN Date.prototype.getMilliseconds.call(null); // TypeError Date.prototype.getMilliseconds.call(undefined); // TypeError Date.prototype.getMilliseconds.call(0); // TypeError Date.prototype.getMilliseconds.call(""); // TypeError Date.prototype.getMilliseconds.call("2000"); // TypeError Date.prototype.getMilliseconds.call({}); // TypeError > Date.prototype.getUTCMilliseconds() ### Przykład Date.prototype.getUTCMilliseconds > new Date("1410-07-15T13:30:59.500+02:00").getUTCMilliseconds(); // 500 new Date(NaN).getUTCMilliseconds(); // NaN Date.prototype.getUTCMilliseconds.call(null); // TypeError Date.prototype.getUTCMilliseconds.call(undefined); // TypeError Date.prototype.getUTCMilliseconds.call(0); // TypeError Date.prototype.getUTCMilliseconds.call(""); // TypeError Date.prototype.getUTCMilliseconds.call("2000"); // TypeError Date.prototype.getUTCMilliseconds.call({}); // TypeError > Date.prototype.getTimezoneOffset() * Parametry: * `Number` time - liczba milisekund od północy 1 stycznia 1970 w strefie czasowej południka zerowego * Wartość: * `Number` - ustawiona wartość time * Wyjątki: * `TypeError` - bieżący obiekt nie jest typu daty i czasu Ustawia pełną datę i czas poprzez określenie liczby milisekund, która upłynęła od północy 1 stycznia 1970 roku w strefie czasowej południka zerowego. ### Przykład Date.prototype.setTime > var x = new Date(2000, 0, 1); x.setTime(x.getTime() + 86400000); // 946767600000 x; // new Date(2000, 0, 2) Date.prototype.setTime.call(null, 0); // TypeError Date.prototype.setTime.call(undefined, 0); // TypeError Date.prototype.setTime.call(0, 0); // TypeError Date.prototype.setTime.call("", 0); // TypeError Date.prototype.setTime.call("2000", 0); // TypeError Date.prototype.setTime.call({}, 0); // TypeError > Date.prototype.setMilliseconds(ms) ### Przykład Date.prototype.setMilliseconds > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setMilliseconds(500); // -17655020940500 x; // new Date("1410-07-15T13:30:59.500+02:00") x.setMilliseconds(1250); // -17655020939750 x; // new Date("1410-07-15T13:31:00.250+02:00") x.setMilliseconds(-500); // -17655020940500 x; // new Date("1410-07-15T13:30:59.500+02:00") Date.prototype.setMilliseconds.call(null, 0); // TypeError Date.prototype.setMilliseconds.call(undefined, 0); // TypeError Date.prototype.setMilliseconds.call(0, 0); // TypeError Date.prototype.setMilliseconds.call("", 0); // TypeError Date.prototype.setMilliseconds.call("2000", 0); // TypeError Date.prototype.setMilliseconds.call({}, 0); // TypeError > Date.prototype.setUTCMilliseconds(ms) ### Przykład Date.prototype.setUTCMilliseconds > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setUTCMilliseconds(500); // -17655020940500 x; // new Date("1410-07-15T13:30:59.500+02:00") x.setUTCMilliseconds(1250); // -17655020939750 x; // new Date("1410-07-15T13:31:00.250+02:00") x.setUTCMilliseconds(-500); // -17655020940500 x; // new Date("1410-07-15T13:30:59.500+02:00") Date.prototype.setUTCMilliseconds.call(null, 0); // TypeError Date.prototype.setUTCMilliseconds.call(undefined, 0); // TypeError Date.prototype.setUTCMilliseconds.call(0, 0); // TypeError Date.prototype.setUTCMilliseconds.call("", 0); // TypeError Date.prototype.setUTCMilliseconds.call("2000", 0); // TypeError Date.prototype.setUTCMilliseconds.call({}, 0); // TypeError > Date.prototype.setSeconds(sec) Date.prototype.setSeconds(sec, ms) ### Przykład Date.prototype.setSeconds > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setSeconds(0, 500); // -17655020999500 x; // new Date("1410-07-15T13:30:00.500+02:00") x.setSeconds(90); // -17655020909500 x; // new Date("1410-07-15T13:31:30.500+02:00") x.setSeconds(-30); // -17655020969500 x; // new Date("1410-07-15T13:30:30.500+02:00") Date.prototype.setSeconds.call(null, 0); // TypeError Date.prototype.setSeconds.call(undefined, 0); // TypeError Date.prototype.setSeconds.call(0, 0); // TypeError Date.prototype.setSeconds.call("", 0); // TypeError Date.prototype.setSeconds.call("2000", 0); // TypeError Date.prototype.setSeconds.call({}, 0); // TypeError > Date.prototype.setUTCSeconds(sec) Date.prototype.setUTCSeconds(sec, ms) ### Przykład Date.prototype.setUTCSeconds > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setUTCSeconds(0, 500); // -17655020999500 x; // new Date("1410-07-15T13:30:00.500+02:00") x.setUTCSeconds(90); // -17655020909500 x; // new Date("1410-07-15T13:31:30.500+02:00") x.setUTCSeconds(-30); // -17655020969500 x; // new Date("1410-07-15T13:30:30.500+02:00") Date.prototype.setUTCSeconds.call(null, 0); // TypeError Date.prototype.setUTCSeconds.call(undefined, 0); // TypeError Date.prototype.setUTCSeconds.call(0, 0); // TypeError Date.prototype.setUTCSeconds.call("", 0); // TypeError Date.prototype.setUTCSeconds.call("2000", 0); // TypeError Date.prototype.setUTCSeconds.call({}, 0); // TypeError > Date.prototype.setMinutes(min) Date.prototype.setMinutes(min, sec) Date.prototype.setMinutes(min, sec, ms) > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setUTCMinutes(15, 0, 500); // -17655021899500 x; // new Date("1410-07-15T13:15:00.500+02:00") x.setUTCMinutes(90); // -17655017399500 x; // new Date("1410-07-15T14:30:00.500+02:00") x.setUTCMinutes(-30); // -17655020999500 x; // new Date("1410-07-15T13:30:00.500+02:00") Date.prototype.setUTCMinutes.call(null, 0); // TypeError Date.prototype.setUTCMinutes.call(undefined, 0); // TypeError Date.prototype.setUTCMinutes.call(0, 0); // TypeError Date.prototype.setUTCMinutes.call("", 0); // TypeError Date.prototype.setUTCMinutes.call("2000", 0); // TypeError Date.prototype.setUTCMinutes.call({}, 0); // TypeError > Date.prototype.setHours(hour) Date.prototype.setHours(hour, min) Date.prototype.setHours(hour, min, sec) Date.prototype.setHours(hour, min, sec, ms) ### Przykład Date.prototype.setHours > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setHours(12, 15, 0, 500); // -17655025499500 x; // new Date("1410-07-15T12:15:00.500+02:00") x.setHours(25); // -17654978699500 x; // new Date("1410-07-16T01:15:00.500+02:00") x.setHours(-2); // -17654989499500 x; // new Date("1410-07-15T22:15:00.500+02:00") Date.prototype.setHours.call(null, 0); // TypeError Date.prototype.setHours.call(undefined, 0); // TypeError Date.prototype.setHours.call(0, 0); // TypeError Date.prototype.setHours.call("", 0); // TypeError Date.prototype.setHours.call("2000", 0); // TypeError Date.prototype.setHours.call({}, 0); // TypeError > Date.prototype.setUTCHours(hour) Date.prototype.setUTCHours(hour, min) Date.prototype.setUTCHours(hour, min, sec) Date.prototype.setUTCHours(hour, min, sec, ms) ### Przykład Date.prototype.setUTCHours > var x = new Date("1410-07-15T13:30:59.000+02:00"); x.setUTCHours(12, 15, 0, 500); // -17655018299500 x; // new Date("1410-07-15T14:15:00.500+02:00") x.setUTCHours(25); // -17654971499500 x; // new Date("1410-07-16T03:15:00.500+02:00") x.setUTCHours(-2); // -17654982299500 x; // new Date("1410-07-16T00:15:00.500+02:00") Date.prototype.setUTCHours.call(null, 0); // TypeError Date.prototype.setUTCHours.call(undefined, 0); // TypeError Date.prototype.setUTCHours.call(0, 0); // TypeError Date.prototype.setUTCHours.call("", 0); // TypeError Date.prototype.setUTCHours.call("2000", 0); // TypeError Date.prototype.setUTCHours.call({}, 0); // TypeError > Date.prototype.setDate(date) > var x = new Date("1410-07-15T00:00:00.000+02:00"); x.setUTCDate(16); // -17654896800000 x; // new Date("1410-07-17T00:00:00.000+02:00") x.setUTCDate(32); // -17653600800000 x; // new Date("1410-08-02T00:00:00.000+02:00") x.setUTCDate(-2); // -17653773600000 x; // new Date("1410-07-30T00:00:00.000+02:00") Date.prototype.setUTCDate.call(null, 0); // TypeError Date.prototype.setUTCDate.call(undefined, 0); // TypeError Date.prototype.setUTCDate.call(0, 0); // TypeError Date.prototype.setUTCDate.call("", 0); // TypeError Date.prototype.setUTCDate.call("2000", 0); // TypeError Date.prototype.setUTCDate.call({}, 0); // TypeError > Date.prototype.setMonth(month) Date.prototype.setMonth(month, date) ### Przykład Date.prototype.setMonth > var x = new Date("1410-07-15T00:00:00.000+02:00"); x.setMonth(7, 3); // -17653428000000 x; // new Date("1410-08-03T00:00:00.000+02:00") x.setMonth(12); // -17640205200000 x; // new Date("1411-01-03T00:00:00.000+01:00") x.setMonth(-1); // -17642883600000 x; // new Date("1410-12-03T00:00:00.000+01:00") Date.prototype.setMonth.call(null, 0); // TypeError Date.prototype.setMonth.call(undefined, 0); // TypeError Date.prototype.setMonth.call(0, 0); // TypeError Date.prototype.setMonth.call("", 0); // TypeError Date.prototype.setMonth.call("2000", 0); // TypeError Date.prototype.setMonth.call({}, 0); // TypeError > Date.prototype.setUTCMonth(month) Date.prototype.setUTCMonth(month, date) ### Przykład Date.prototype.setUTCMonth > var x = new Date("1410-07-15T00:00:00.000+02:00"); x.setUTCMonth(7, 3); // -17653341600000 x; // new Date("1410-08-04T00:00:00.000+02:00") x.setUTCMonth(12); // 17640122400000 x; // new Date("1411-01-03T23:00:00.000+01:00") x.setUTCMonth(-1); // -17642800800000 x; // new Date("1410-12-03T23:00:00.000+01:00") Date.prototype.setUTCMonth.call(null, 0); // TypeError Date.prototype.setUTCMonth.call(undefined, 0); // TypeError Date.prototype.setUTCMonth.call(0, 0); // TypeError Date.prototype.setUTCMonth.call("", 0); // TypeError Date.prototype.setUTCMonth.call("2000", 0); // TypeError Date.prototype.setUTCMonth.call({}, 0); // TypeError > Date.prototype.setFullYear(year) Date.prototype.setFullYear(year, month) Date.prototype.setFullYear(year, month, date) Gdzie jest zapisany konstruktor obiektu wyrażenia regularnego? * exec Jak pobrać wszystkie dopasowania wzorca (wyrażenia regularnego) do podanego tekstu? * test Jak sprawdzić, czy tekst pasuje do wzorca (wyrażenia regularnego) * toString Jak przekształcić wyrażenie regularne na prosty tekst? > RegExp.prototype.constructor * Wartość: * `Function` - konstruktor obiektu Zawiera konstruktor wbudowanego obiektu wyrażenia regularnego `RegExp` . ### Przykład RegExp.prototype.constructor > RegExp.prototype.constructor === RegExp; // true new RegExp().constructor === RegExp; // true RegExp.prototype.constructor === Object; // false > RegExp.prototype.exec(string) * Error Jak utworzyć obiekt błędu (wyjątek)? * new Error Jak utworzyć nową instancję obiektu błędu (wyjątek)? Jak obsłużyć w programie swój własny rodzaj błędu? * EvalError Jaki wyjątek może zostać rzucony w przypadku błędu wykonania kodu? * RangeError Jaki wyjątek jest rzucany, jeżeli liczba przekracza dozwolony zakres? * ReferenceError Jaki wyjątek jest rzucany przy niewłaściwym odwołaniu do wartości? * SyntaxError Jaki wyjątek jest rzucany w przypadku błędu składni kodu? * TypeError Jaki wyjątek jest rzucany, gdy typ wartości jest niezgodny z oczekiwanym? * URIError Jaki wyjątek jest rzucany przy błędzie obsługi adresu URI/URL? > Error() Error(message) Gdzie jest zapisany konstruktor obiektu błędu (wyjątku)? * name Gdzie jest zapisana nazwa błędu (wyjątku)? * message Gdzie jest zapisany komunikat błędu (wyjątku)? * toString Jak przekształcić rzucony wyjątek na tekst, który można wyświetlić użytkownikowi? > Error.prototype.constructor # Konwerter Windows/Iso Konwerter Windows/Iso Kod źródłowy strony: Zobacz także Jak zrobić tło graficzne (obrazek, zdjęcie), które nie przesuwa się przy przewijaniu strony? Jak zmienić rok w podanej dacie, określony w strefie czasowej południka zerowego (UTC)? Czy projektowanie wyglądu stron internetowych naprawdę jest tak trudne, jak mówią? Jak osadzić na stronie WWW plik multimedialny: animację, film, muzykę (wav, mid, avi, ra, mp3, mpg, mov, asf i inne)? Jak wprowadzić na stronę wykaz: wypunktowanie (lista nieuporządkowana) lub numerowanie (lista uporządkowana)? © www.kurshtml.edu.pl ### Data aktualizacji strony # Często zdarza się, że internauta wchodzący na jakąś stronę, chciałby wiedzieć, kiedy była ona ostatnio aktualizowana. Dzięki takiej informacji mógłby wywnioskować, czy serwis jest aktualizowany na bieżąco i czy nie znajdzie w nim informacji, które dawno utraciły ważność, co w niektórych przypadkach może być bardzo ważne. Najprostszym sposobem określenia aktualności strony, jest podanie w widocznym miejscu (np. na samym początku) daty jej ostatniej modyfikacji. Można to zrobić oczywiście wpisując "ręcznie" datę, ale po którejś z kolei aktualizacji możesz zapomnieć o tej czynności, nie mówiąc już o tym, że jest to bardzo uciążliwe - szczególnie w przypadku większej ilości stron. Aby pozbyć się wszystkich tych problemów, wystarczy wstawić na każdą ze stron prościutki "skrypcik" (programik), który automatycznie wypisze datę ostatniej modyfikacji strony. UWAGA! Skrypt tego typu nie zawsze działa! Informacja o dacie modyfikacji dokumentu pochodzi z nagłówka HTTP wysyłanego przez serwer WWW, na którym znajduje się strona. Ponieważ wysyłanie tych nagłówków nie jest obowiązkowe, często odczytanie prawidłowej daty aktualizacji nie jest możliwe. Informacja ta będzie odczytana na pewno, jeśli strona zostanie załadowana nie z Internetu, ale z lokalnego systemu plików. Dlatego zawsze po umieszczeniu pliku na serwerze WWW sprawdzaj czy skrypt działa poprawnie! Alternatywą może być skrypt PHP, który będzie działał zawsze (musi być zapisany w pliku z rozszerzeniem *.php - np. index.php), jeżeli tylko serwer obsługuje tego typu skrypty: > <?php echo date('d.m.Y', filemtime($_SERVER['SCRIPT_FILENAME'])); ?>albo > <?php echo date('Y-m-d H:i:s', filemtime($_SERVER['SCRIPT_FILENAME'])); ?Jeżeli natomiast Twój serwer nie obsługuje PHP albo tworzysz stronę w wersji offline, uruchamianą z dysku lokalnego lub np. z płyty CD-ROM albo odpowiedni nagłówek HTTP z datą modyfikacji jest wysyłany przez serwer, możesz posłużyć się skryptem JavaScript. W tym celu najpierw zapisz poniższy kod w dowolnym pliku z rozszerzeniem *.js - np. date.js: > /** * @author <NAME> {@link https://www.kurshtml.edu.pl} * @copyright NIE usuwaj tego komentarza! (Do NOT remove this comment!) */ Date.prototype.date = function(format) { for (var i = 0, c = '', returner = '', formats = new Object(); i < format.length; i++) { c = format.charAt(i); if (c == '\\' && i + 1 < format.length) returner += format.charAt(++i); else if (typeof formats[c] != 'undefined') returner += formats[c]; else { switch (c) { case 'a': formats[c] = this.getHours() < 12 ? 'przed południem' : 'po południu'; break; case 'd': var day = this.getDate(); formats[c] = (day < 10 ? '0' : '') + day; break; case 'D': var days = new Array('Nie', 'Pon', 'Wto', 'Śro', 'Czw', 'Pią', 'Sob'); formats[c] = days[this.getDay()]; break; case 'E': var month = new Array('stycznia', 'lutego', 'marca', 'kwietnia', 'maja', 'czerwca', 'lipca', 'sierpnia', 'września', 'października', 'listopada', 'grudnia'); formats[c] = month[this.getMonth()]; break; case 'F': var month = new Array('Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'); formats[c] = month[this.getMonth()]; break; case 'g': formats[c] = (this.getHours() - 1) % 12 + 1; break; case 'G': formats[c] = this.getHours(); break; case 'h': var hour = (this.getHours() - 1) % 12 + 1; formats[c] = (hour < 10 ? '0' : '') + hour; break; case 'H': var hour = this.getHours(); formats[c] = (hour < 10 ? '0' : '') + hour; break; case 'i': var minute = this.getMinutes(); formats[c] = (minute < 10 ? '0' : '') + minute; break; case 'j': formats[c] = this.getDate(); break; case 'l': var days = new Array('Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'); formats[c] = days[this.getDay()]; break; case 'L': formats[c] = this.getFullYear() % 400 && (this.getFullYear() % 4 || !(this.getFullYear() % 100)) ? 0 : 1; break; case 'm': var month = this.getMonth() + 1; formats[c] = (month < 10 ? '0' : '') + month; break; case 'M': var month = new Array('Sty', 'Lut', 'Mar', 'Kwi', 'Maj', 'Cze', 'Lip', 'Sień', 'Wrz', 'Paź', 'Lis', 'Gru'); formats[c] = month[this.getMonth()]; break; case 'n': formats[c] = this.getMonth() + 1; break; case 'O': var O = -this.getTimezoneOffset() / 60; if (O < 0) { var sign = '-'; O = -O; } else sign = '+'; formats[c] = sign + (O < 10 ? '0' : '') + O + '00'; break; case 'r': formats[c] = this.date('D, d M Y H:i:s O'); break; case 's': var second = this.getSeconds(); formats[c] = (second < 10 ? '0' : '') + second; break; case 'S': if (this.getDate().toString().search(/(^|[02-9])1$/) != -1) formats[c] = '-wszy'; else if (this.getDate().toString().search(/(^|[02-9])2$/) != -1) formats[c] = '-gi'; else if (this.getDate().toString().search(/(^|[02-9])3$/) != -1) formats[c] = '-ci'; else if (this.getDate().toString().search(/(^|[02-9])[78]$/) != -1) formats[c] = '-my'; else formats[c] = '-ty'; break; case 't': var months = new Array(31, this.getFullYear() % 400 && (this.getFullYear() % 4 || !(this.getFullYear() % 100)) ? 28 : 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); formats[c] = months[this.getMonth()]; break; case 'U': formats[c] = Date.parse(this) / 1000; break; case 'w': formats[c] = this.getDay(); break; case 'W': var day = this.getDay() - 1; if (day == -1) day = 6; formats[c] = Math.round((this.date('z') - day + 6) / 7); if (formats[c] == 0) { var date = new Date(this.getFullYear() - 1, 11, 31, 23, 59, 59); day = date.getDay() - 1; if (day == -1) day = 6; formats[c] = Math.round((date.date('z') - day + 6) / 7); } else { var date = new Date(this.getFullYear(), 11, 31, 23, 59, 59); day = date.getDay() - 1; if (day == -1) day = 6; if (day < 3 && this.date('z') >= date.date('z') - day) formats[c] = 1; } break; case 'Y': formats[c] = this.getFullYear(); break; case 'y': formats[c] = this.getFullYear().toString().substring(2); break; case 'z': var months = new Array(31, this.getFullYear() % 400 && (this.getFullYear() % 4 || !(this.getFullYear() % 100)) ? 28 : 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); formats[c] = this.getDate(); for (var j = 0, month = this.getMonth(); j < month; j++) formats[c] += months[j]; break; case 'Z': formats[c] = -this.getTimezoneOffset() * 60; break; default: formats[c] = c; break; } returner += formats[c]; } } return returner; } Następnie w treści nagłówkowej dokumentu (wewnątrz <head>...</head>) wstaw jeden raz: > <script src="date.js"></scriptW wyróżnionym miejscu oczywiście należy podać lokalizację utworzonego wcześniej pliku date.js. Teraz wystarczy wkleić na stronie w wybranym miejscu przykładowy kod: > <script> document.write(new Date(document.lastModified).date('d.m.Y')); </script> Sposób wyświetlania daty można zmienić, podając w wyróżnionym miejscu inny szablon formatujący datę. Pojedyncze litery w tym tekście odpowiadają specjalnym kodom formatującym. Przykładowo: litera `d` zostanie zastąpiona dniem miesiąca, `m` - numerem miesiąca, natomiast `Y` - rokiem. W związku z tym wpisanie `d.m.Y` może poskutkować następującym wynikiem na ekranie: Lista wszystkich możliwych do użycia kodów w szablonie formatującym datę jest następująca: * `a` - "przed południem" lub "po południu" * `d` - dzień miesiąca, 2 cyfry z zerem na początku; tzn. od "01" do "31" * `D` - dzień tygodnia, tekst, 3 litery; np. "Pią" * `E` - miesiąc, tekst, pełna nazwa w dopełniaczu; np. "stycznia" * `F` - miesiąc, tekst, pełna nazwa; np. "Styczeń" * `g` - godzina, format 12-godzinny bez zera na początku; tzn. od "1" do "12" * `G` - godzina, format 24-godzinny bez zera na początku; tzn. od "0" do "23" * `h` - godzina, format 12-godzinny z zerem na początku; tzn. od "01" do "12" * `H` - godzina, format 24-godzinny z zerem na początku; tzn. od "00" do "23" * `i` - minuty; tzn. od "00" do "59" * `j` - dzień miesiąca bez zera na początku; tzn. od "1" do "31" * `l` - (mała litera 'L') dzień tygodnia, tekst, pełna nazwa; np. "Piątek" * `L` - "1" jeśli rok przestępny, "0" w przeciwnym razie * `m` - miesiąc; tzn. "01" to "12" * `M` - miesiąc, tekst, 3 litery; np. "Sty" * `n` - miesiąc bez zera na początku; tzn. "1" to "12" * `O` - różnica w stosunku do czasu Greenwich; np. "+0200" * `r` - data sformatowana; np. "Czw, 21 Gru 2000 16:01:07 +0200" * `s` - sekundy; np. "00" to "59" * `S` - standardowy sufiks liczebnika porządkowego, tzn. "-wszy", "-gi", "-ci" , "-ty" lub "my" * `t` - liczba dni w danym miesiącu; tzn. od "28" do "31" * `U` - liczba sekund od uniksowej Epoki (1 stycznia 1970 00:00:00 GMT) * `w` - dzień tygodnia, liczbowy, tzn. od "0" (Niedziela) do "6" (Sobota) * `W` - numer tygodnia w roku według ISO-8601, przedział od 1 do 53, gdzie tydzień 1 jest pierwszym tygodniem, który ma co najmniej 4 dni w aktualnym roku, przy czym pierwszym dniem tygodnia jest poniedziałek * `Y` - rok, 4 cyfry; np. "1999" * `y` - rok, 2 cyfry; np. "99" * `z` - dzień roku; tzn. od "1" do "365" ("366") * `Z` - ofset strefy czasowej w sekundach (tzn. pomiędzy "-43200" a "43200"). Ofset dla stref czasowych na zachód od UTC (południka zero) jest zawsze ujemny a dla tych na wschód od UTC jest zawsze dodatni. Aby normalnie wyświetlić na ekranie literę będącą kodem formatującym, należy ją poprzedzić podwójnym znakiem \\. Na przykład po wpisaniu: "\\d" zostanie wyświetlona po prostu litera "d", a nie dzień miesiąca. Ponadto jeśli w szablonie formatującym datę ma się wyświetlić znak \ trzeba go zamienić na cztery takie znaki: "\\\\". > <script> document.write(new Date(document.lastModified).date('Y-m-d H:i:s')); </script>2023-11-16 04:15:42 > <script> document.write(new Date(document.lastModified).date('l, j E Y, G:i')); </script>Czwartek, 16 listopada 2023, 4:15 > <script> document.write(new Date(document.lastModified).date('jS E Y \\r., \\go\\d\\z. g:i a (\\d\\z\\ień \\roku: z, \\t\\y\\d\\z\\ień \\roku: W)')); </script>16-ty listopada 2023 r., godz. 4:15 przed południem (dzień roku: 320, tydzień roku: 46) ### Aktualna data # Po niewielkiej modyfikacji można wyświetlić na ekranie bieżącą datę, a nie czas aktualizacji strony. Aby to zrobić wystarczy w drugiej części skryptu usunąć wyrażenie: ``` document.lastModified ``` > <b>Dzisiaj jest:</b> <script> document.write(new Date().date('l, j E Y')); </script>Dzisiaj jest:Czwartek, 16 listopada 2023 ### Jedno okno # * Po załadowaniu strony: > <body onload="window.open('adres', 'nazwa').focus()>...</body> * Przed załadowaniem strony: > <head> <script> window.open('adres', 'nazwa').focus(); </script> </head> * Po kliknięciu odsyłacza: > <a target="nazwa" href="adres" onclick="window.open('adres', 'nazwa').focus(); return false">opis</a* adres * Lokalizacja dowolnej podstrony serwisu lub adres internetowy. Jeśli nie chcemy wczytywać do nowego okna żadnego dokumentu, można tutaj wpisać: 'about:blank'. * nazwa * Nazwa nowego okna, która może być później wykorzystywana do wczytywania nowych stron do tego okna, bez konieczności otwierania następnych. Można otworzyć nowe okno, a później wczytywać do niego dokumenty, za pomocą odsyłaczy umieszczonych na głównej stronie. Jeśli nie mamy zamiaru wczytywać do otwartego okna żadnych stron, można nie podawać nazwy. Nazwa powinna spełniać takie same wymagania jak w przypadku znacznika <iframe>...</iframe>! UWAGA!Pierwsze dwa warianty są obecnie blokowane przez prawie wszystkie przeglądarki, z uwagi na dużą uciążliwość dla internautów. Oznacza to, że mogą w ogóle nie zadziałać, chyba że użytkownik wyrazi na to zgodę! ### Pop-under # Polecenie to pozwala automatycznie otworzyć nowe okno i określić jego wygląd (patrz dalej). W pierwszym wariancie okno zostanie otwarte dopiero po wczytaniu i wyświetleniu całej strony, w drugim - jeszcze zanim zostanie załadowana treść dokumentu, a w trzecim - po kliknięciu odpowiedniego odsyłacza, czyli specjalnie wyróżnionego tekstu. Wszystkie powyższe warianty otwierają okna typu pop-up tzn., że pokazują się one na wierzchu, zasłaniając sobą stronę główną. Jest to bardzo uciążliwe, ponieważ zmusza użytkownika do natychmiastowego zamknięcia lub zminimalizowania takiego okna, jeśli chce zobaczyć właściwą stronę. Jest jednak inny, mniej uciążliwy typ okien nazywany pop-under. Różni się on jedynie tym, że otwiera się pod spodem i nie drażni tak internautów. Użytkownik i tak zobaczy treść pop-undera, kiedy będzie wychodził z naszej strony, zamykając główne okno przeglądarki. Skuteczność tej metody może być równie wysoka, ponieważ po dłuższym czasie spędzonym na stronie, internauta może już nie pamiętać, czy okno ukryte pod spodem otworzył wcześniej on sam czy raczej otworzyło się samo. Aby otworzyć okno pop-under, wystarczy dla wszystkich powyższych wariantów (choć trzeci raczej mija się z celem) nieznacznie zmodyfikować wyróżniony fragment kodu: na końcu zamiast `focus()` wpisujemy `blur()` > window.open('adres', 'nazwa').blur() W niektórych systemach operacyjnych i przy pewnych ustawieniach w niektórych przeglądarkach, okna pop-under mogą działać identycznie jak pop-up. Kliknij tutaj, aby przejść na stronę, na której nastąpi automatyczne otwarcie nowego okna typu pop-up. Kliknij tutaj, aby przejść na stronę, na której nastąpi automatyczne otwarcie nowego okna typu pop-under. Kliknij tutaj, aby otworzyć nowe okno przy użyciu odsyłacza. Możliwe jest otwarcie jednocześnie kilku nowych okien. Należy wtedy oddzielić średnikami (";") kolejne polecenia Dlatego dobrze się zastanów, czy otwieranie nowych okien na pewno jest Ci absolutnie niezbędne i czy nie przyniesie czasem więcej strat niż korzyści. Zresztą przez nadużywanie podobnych skryptów, przeglądarki zaczęły na stałe blokować otwieranie "wyskakujących okienek", które zwykle były używane w celach reklamowych. Możliwe jest określenie wyglądu nowego okna (rozmiarów, położenia, pokazanie/ukrycie pasków menu, narzędzi, statusu itp.), poprzez podanie w poleceniu dodatkowych parametrów. Zamiast opisu zamieszam poniżej generator. Otrzymany w nim kod, należy wpisać w miejsce wyróżnionego tekstu, np. jako wartość atrybutu `onload="..."` (pierwszy sposób). UWAGA! Jeśli chcesz otworzyć zwykłe okno po kliknięciu odsyłacza (trzeci wariant), czyli bez określania parametrów wyglądu, lepiej to zrobić w następujący sposób: > <a target="_blank" href="adres">opis</aJeśli nie masz czasu czytać wprowadzenia, możesz przejść od razu do części właściwej ;-) Na wielu stronach w Internecie można spotkać galerię zdjęć, stosowaną do przedstawienia kolekcji zdjęć, zwykle o dużych rozmiarach. Najczęściej jest ona tworzona w ten sposób, że na głównej stronie umieszcza się pomniejszone kopie obrazków oraz odsyłacze, po kliknięciu których następuje wczytanie obrazka w pełnych rozmiarach. Pozwala to uchronić się od wczytywania wszystkich dużych obrazków jednocześnie (użytkownik powiększa tylko te, które mu odpowiadają), a także zachowuje estetykę strony. Uwaga! Miniaturki grafik muszą być pomniejszone fizycznie, tzn. nie mogą to być oryginalne duże obrazki ze zmniejszonymi rozmiarami wyświetlania za pomocą atrybutów `width="..."` oraz `height="..."` . Tylko wstawienie naprawdę pomniejszonych obrazków uchroni od niepotrzebnego wczytywania dużych plików. Zmniejszenia wymiarów obrazka można dokonać praktycznie w każdym programie graficznym. Najczęściej ustala się takie same rozmiary dla wszystkich miniatur, ponieważ ułatwia to utrzymanie estetyki strony. Obrazki w galerii zwykle ustawia się w komórkach tabeli (najczęściej bez obramowania), dzięki czemu można je dokładnie ustawić w rzędach i kolumnach. Jeżeli zamierzasz umieścić na swojej stronie obszerniejszą galerię grafik, zaleca się podzielenie jej na kilka części i stworzenie kilku podstron z miniaturkami. Wczytanie oryginalnego dużego obrazka następuje najczęściej po kliknięciu bezpośrednio jego miniaturki. Aby zastosować taki efekt, należy użyć odsyłacza obrazkowego (podstawowego). Prawie zawsze stosuje się również atrybut `target="_blank"` , który powoduje otwarcie nowego okna przeglądarki: > <a target="_blank" href="ścieżka do dużego obrazka"><img src="ścieżka do pliku miniaturki obrazka" alt="Tekst alternatywny" border="0"></aWiększość nowych przeglądarek potrafi automatycznie otworzyć obrazek w nowym oknie, jednaki nie będzie wtedy możliwości szybkiej nawigacji pomiędzy kolejnymi zdjęciami z galerii. Natomiast starsze przeglądarki po kliknieciu przez użytkownika takiego linka często najpierw wyświetlały okienko z pytaniem co zrobić z obrazkiem, tzn. otworzyć czy zapisać, a po wybraniu pierwszej opcji, następowało wczytanie pliku w zewnętrznym programie (jeśli użytkownik miał taki zainstalowany), co mogło potrwać kilka sekund i było trochę irytujące w przypadku dużej liczby zdjęć. Dlatego w klasycznej galerii zdjęć zwykle zamiast podawać link bezpośrednio do dużego obrazka, tworzy się dodatkową stronę z grafiką wstawioną na niej za pomocą znacznika <img> i dopiero taki dokument podaje się w linku: > <a target="_blank" href="ścieżka do strony z dużym obrazkiem"><img src="ścieżka do pliku miniaturki obrazka" alt="Tekst alternatywny" border="0"></aJak łatwo zauważyć, aby stworzyć klasyczną galerię zdjęć, trzeba napisać tyle stron, ile mamy obrazków - po jednej dla każdego dużego egzemplarza (a nawet co najmniej o jedną więcej). Istnieją specjalne programy, które potrafią stworzyć statyczną galerię grafik. Wystarczy wybrać zdjęcia za pomocą selektora plików, a program automatycznie wygeneruje miniatury zdjęć oraz wszystkie potrzebne dokumenty HTML. Pewną niedogodnością w przypadku programów tworzących statyczne galerie może jednak być utrudniona aktualizacja takiej galerii. Dodanie choćby jednego nowego zdjęcia zwykle będzie wiązało się z generowaniem galerii na nowo. Powyższych wad pozbawiony jest skrypt galerii zdjęć opisany dalej w tym rozdziale. ...i gotowe. Prawda że szybko poszło? ;-) W Internecie dosyć popularnym rozwiązaniem, stosowanym na wielu stronach, jest budowanie struktury serwisu w oparciu o tabele (lub elementy `<div>...</div>` ) i ramki <iframe>...</iframe> (przykład takiego właśnie szablonu znajdziesz w rozdziale Struktura tabeli). Jest to wygodne o tyle, że pozwala szybko zbudować stronę elastyczną w aktualizacji, bez wykorzystania języków skryptowych po stronie serwera (np. PHP). Niestety takie rozwiązanie ma przynajmniej jedną poważną wadę: trudno jest dopasować wysokość ramki IFRAME tak, aby była odpowiednia dla każdej rozdzielczości ekranu. Jeśli ustalimy za duży rozmiar, użytkownicy w niskiej rozdzielczości będą mieli problem z przewijaniem zawartości ramki. Natomiast jeśli ustalimy za mały, w wyższej rozdzielczości pojawi się niewielkie "okienko", w którym trudno nawigować. Pewnym rozwiązanie mogłoby być określenie na tyle dużej wysokości, aby treść ramki zawsze się w niej w całości mieściła bez konieczności pokazywania suwaków do przewijania - wtedy będzie tylko jeden suwak pionowy do przewijania całej strony głównej. Niestety takie rozwiązanie nie zawsze jest możliwe, bo na początku nie wiemy jak długie będą nasze podstrony. Poza tym jeśli ustalimy zbyt dużą wysokość, cała strona główna bardzo się rozciągnie, a po wczytaniu do ramki lokalnej krótkiej treści, na jej końcu pozostanie bardzo dużo wolnego miejsca, co będzie wyglądało dosyć dziwnie i na pewno nie będzie wygodne dla użytkownika. Czy można sobie zatem jakoś poradzić? Oczywiście! Skrypt przedstawiony na tej stronie potrafi całkowicie automatycznie dopasować wysokość ramki IFRAME do długości aktualnie wyświetlanej w niej treści podstrony. Robi to tak, aby nigdy nie pojawił się pionowy suwak do przewijania ramki lokalnej. Wysokość nie będzie ani za duża ani za mała, ale zawsze po prostu idealnie dopasowana. Aby zastosować taki skrypt, należy na stronie głównej do znacznika `<iframe>...</iframe>` dodać atrybut `id="autoiframe"` , np.: > <iframe src="..." name="..." id="autoiframe" width="100%" height="560">...</iframe> UWAGA!Pamiętaj, aby podać taką wysokość ramki ( `height="..."` ), która będzie wygodna w przypadku, gdyby skrypt nie zadziałał! Teraz na wszystkie podstrony, które będą wczytywane do ramki lokalnej, należy wstawić następujący kod (trzeba to zrobić koniecznie w nagłówku dokumentu, czyli w ramach <head>...</head>): > <script src="autoiframe.js"></script> Następnie na samym końcu podstrony (tuż przed znacznikiem zamykającym `</body>` ) należy wkleić kod: > <script> autoiframe(null, 200); </script> W wyróżnionym miejscu (w nawiasie) można podać wartość dodatkowego wstępnego "marginesu" pionowego na końcu podstrony. Jest on szczególnie przydatny, jeśli na stronie znajdują się zdjęcia o niezdefiniowanych wymiarach za pomocą atrybutów `width="..."` oraz `height="..."` znacznika <img>. W takim przypadku margines ten należy dobrać na tyle duży, aby podczas doczytywania obrazów - a tym samym stopniowej zmiany wysokości treści - nie pojawił się pionowy suwak do przewijania ramki. Jest to tylko wartość wstępna (tymczasowa), ponieważ po wczytaniu wszystkiego, wysokość i tak się automatycznie dopasuje w drugim kroku. Jeśli chcemy zrezygnować z podawania marginesu, należy po prostu zupełnie pominąć wstawianie tej części kodu na podstronach. Ostatnim krokiem będzie stworzenie nowego pliku autoiframe.js (w tym samym katalogu co podstrony) i zapisanie w nim: > /** * @author <NAME> {@link https://www.kurshtml.edu.pl} * @copyright NIE usuwaj tego komentarza! (Do NOT remove this comment!) */ // Domyślny identyfikator IFRAME: var autoiframe_id = 'autoiframe'; // Domyślny dolny margines: var autoiframe_margin = 50; var autoiframe_timer = null; function autoiframe(id, margin) { if (parent != self && document.body && document.body.offsetHeight && document.body.scrollHeight) { clearTimeout(autoiframe_timer) if (typeof id != 'undefined' && id) autoiframe_id = id; parent.document.getElementById(autoiframe_id).height = 1; autoiframe_timer = setTimeout("parent.document.getElementById(autoiframe_id).height = Math.max(document.body.offsetHeight, document.body.scrollHeight) + " + (typeof margin == 'undefined' || isNaN(parseInt(margin)) ? autoiframe_margin : parseInt(margin)), 1); } } if (window.addEventListener) window.addEventListener('load', function() { autoiframe(); }, false); else if (window.attachEvent) window.attachEvent('onload', function() { autoiframe(); }); * autoiframe * Domyślna wartość atrybutu `id="..."` ramki `<iframe>...</iframe>` na stronie nadrzędnej, której wysokością chcemy sterować. * 50 * Dodatkowy ostateczny "margines" pionowy na końcu podstrony, na wypadek gdyby dobrana automatycznie wysokość była jednak trochę za mała, co skutkowałoby wyświetleniem paska przewijania ramki lokalnej. Został on dobrany tak, aby nie był zbyt niski w większości przeglądarkach, jednak jeśli zajdzie potrzeba, można go oczywiście zwiększyć. Należy zauważyć, że zwykle będzie on miał wartość mniejszą niż analogiczny parametr wstępny wpisywany we wcześniejszym bloku kodu na końcu każdej z podstron, ponieważ określa margines już po wczytaniu wszystkich obrazów i innych elementów strony. Jest to wartość ostateczna tego parametru i nie będzie ona już dalej zmieniana. Czasami zachodzi potrzeba umieszczenia na jednej stronie kilku ramek `<iframe>...</iframe>` , których wysokość powinna się automatycznie dopasowywać do zawartości. Oczywiście dla każdej takiej ramki proces dostosowywania wysokości musi zachodzić niezależnie. Aby to zrobić, należy dla każdej takiej ramki należy ustawić odrębny identyfikator `id="..."` . Na przykład tak mógłby wyglądać fragment strony głównej serwisu: > <iframe src="..." name="..." id="autoiframe" width="100%" height="560">...</iframe> <iframe src="..." name="..." id="autoiframe2" width="100%" height="560">...</iframe> Nic nie stoi na przeszkodzie, aby wstawić więcej niż dwie ramki `<iframe>...</iframe>` - każda kolejna z innym identyfikatorem `id="..."` . Następnie na końcu wszystkich podstron wczytywanych do ramki `id="autoiframe"` - nazwijmy ją ramką główną - umieszczamy taki kod jak poprzednio, tzn.: > <script> autoiframe(null, 200); </script>lub > <script> autoiframe('autoiframe', 200); </script> Natomiast na podstronach, które będą wczytywane do ramki `id="autoiframe2"` , umieszczamy, również na końcu, nieco zmienioną formę kodu, podając w nim wartość identyfikatora tej właśnie ramki (wstawioną w apostrofach): > <script> autoiframe('autoiframe2', 200); </scriptPrzydatną funkcją na każdej stronie jest jakaś forma wyszukiwarki. Jej rola jest nie do przecenienia. Dzięki wyszukiwarce użytkownicy, którzy nie znają dobrze serwisu, mogą w mig odnaleźć interesujące ich informacje. Przedzieranie się przez spis treści nie każdemu odpowiada, a poza tym nie wszystko można tam odnaleźć. Specjalną formą wyszukiwarki jest indeks lub inaczej skorowidz. Można go znaleźć w niemal każdym podręczniku. "Papierowa" wersja skorowidza jednak nie do końca jest wygodna, ponieważ nadal zmusza do wertowania stron i szukania haseł według kolejności liter w alfabecie. Na szczęście komputer może to zrobić za nas. Wystarczy, że użytkownik zacznie wpisywać żądane hasło, a w miarę jak będzie to robił, odszukiwane będą pozycje coraz bardziej pasujące do zapytania. Dodatkowo skoro będziemy już mieli gotowy indeks, nic nie stoi na przeszkodzie, aby zbudować z niego normalną wyszukiwarkę. Dzięki temu będzie można odszukać hasła, które nie tylko rozpoczynają się od wpisywanych liter, ale również mogą figurować wewnątrz haseł zapisanych w skorowidzu. Taka funkcjonalność znacznie zwiększa możliwości. Warto dodać, że taki indeks wcale nie musi być alternatywą dla tradycyjnych wyszukiwarek. Może bardzo dobrze je uzupełniać, ponieważ oferuje inną funkcjonalność, dzięki której wyniki zwykle będą bardziej trafne, ponieważ hasła do indeksu dodaje człowiek, a nie komputer. ### Wyszukiwarka * * * zastępuje dowolny fragment wyrazu (również pusty) * ? * zastępuję dokładnie jedną literę Wieloznaczniki są przydatne, jeśli znamy tylko pewną część wyrazu, co zwykle ma miejsce, kiedy chcemy odszukać wszystkie odmiany wybranego słowa. Dzięki temu po wpisaniu> języ* , odnalezione mogą być hasła, które zawierają wyrazy: > język , > językiem , > języku , > języczek itd. Natomiast > języ? pasuje tylko do > język . Wpisanie > wyraz* , spowoduje odszukanie zarówno po prostu słowa > wyraz , jak i np. > wyrazy , ale już zapis > wyraz? nie obejmuje słowa > wyraz . Symbole wieloznaczników można wykorzystywać w dowolnym miejscu szukanych wyrazów, nie tylko na końcu, np. > *języ* pasuje zarówno do słowa > język , jak i > wielojęzyczny . Czasami może zdarzyć się tak, że wszystkie adresy do haseł z indeksu rozpoczynają się tak samo. Oczywiście w takim przypadku ten sam fragment ścieżki można dodawać w każdym kolejnym haśle, ale można również zrobić to tylko raz. W tym celu należy zmodyfikować wpis w pliku indeks_hasla.js: > var indeks = new Indeks('indeks'); indeks.wstaw(new Array( ['Hasło 1','adres1'], ['Hasło 2','adres2'], ['Hasło 3','adres3'] ), 'adres_bazowy'); Teraz nie trzeba już wpisywać tego prefiksu w adresach na liście haseł. Jeżeli zachodzi potrzeba zmiany wysokości okienka z hasłami, należy zmodyfikować wpis w pliku indeks_hasla.js: > var indeks = new Indeks('indeks'); indeks.wstaw(new Array( ['Hasło 1','adres1'], ['Hasło 2','adres2'], ['Hasło 3','adres3'] ), null, rozmiar); Po jego wpisaniu, na stronie nie zostanie wyświetlony normalny indeks, ale fragment kodu skryptu z hasłami ułożonymi alfabetycznie. Wystarczy ten kod skopiować, wkleić w odpowiednie miejsce do pliku indeks_hasla.js i na koniec usunąć wartość opcji (wraz z końcowym przecinkiem przed zamknięciem nawiasu). Wszystkie z przedstawionych powyżej opcji można łączyć, przy czym skrajane argumenty z prawej strony, których nie chcemy podawać, można po prostu pominąć. Dla pozostałych, które chcemy pominąć, wystarczy wpisać `null` (ale nie 'null'!), np.: > var indeks = new Indeks('indeks'); indeks.wstaw(new Array( ['Hasło 1','adres1'], ['Hasło 2','adres2'], ['Hasło 3','adres3'] ), null, 10); Aby otworzyć stronę w nowym oknie, należy zmienić plik indeks_hasla.js następująco: > var indeks = new Indeks('indeks', 'nazwaokna'); indeks.wstaw(new Array( ['Hasło 1','adres1'], ['Hasło 2','adres2'], ['Hasło 3','adres3'] )); * _blank * Wyniki będą za każdym razem otwierane w nowym oknie * _self * Odpowiednik self z poprzedniego punktu * _parent * Odpowiednik parent z poprzedniego punktu * _top * Odpowiednik top z poprzedniego punktu * nazwa * Wyniki będą otwierane w nowym, ale zawsze tym samym oknie. Innymi słowy: nigdy nie zostaną otwarte dwa okna z wynikami tego samego indeksu. Nazwa może zawierać tylko angielskie litery, cyfry (ale nie na początku) i podkreślniki ("_"). Jeżeli nie odpowiada nam podstawowy wygląd indeksu, można go zmienić wykorzystując polecenia CSS. W tym celu w pliku indeks.css należy wkleić np.: > #indeks { width: 300px; padding: 10px 0; background: #ccc; border: 2px outset #aaa; text-align: center; margin: 1em auto; } #indeks input.text { width: 290px; } #indeks select { width: 100%; margin: 2px 0 10px 0; } #indeks input.button { width: 100px; margin-left: 5px; margin-right: 5px; } W wyróżnionych miejscach wpisano identyfikator indeksu, zdefiniowany uprzednio w pliku indeks_hasla.js. Teraz w nagłówku dokumentu HTML (<head>...</head>), na którym wstawiony jest indeks haseł, wystarczy wstawić odwołanie do utworzonego właśnie zewnętrznego arkusza stylów: > <link rel="stylesheet" href="indeks.css"Bardzo pomocne dla użytkowników może okazać się wstawienie formularza wyszukiwania na wszystkich stronach serwisu. Aby to zrobić, należy wstawić w nagłówku strony (<head>...</head>) odwołanie do pliku indeks.js: > <script src="indeks.js"></scriptNie trzeba natomiast wstawiać odwołania do skryptu indeks_hasla.js, w którym znajduje się lista haseł. Następnie w wybranym miejscu strony wystarczy wkleić: > <script> var indeks = new Indeks('indeks'); indeks.wstawWyszukiwarke('adres'); </script* indeks * Identyfikator indeksu - musi być identyczny, jak podany w pliku indeks_hasla.js * adres * Lokalizacja dokumentu HTML, w którym został umieszczony indeks z hasłami Można również podać nazwę ramki lub wymusić otwieranie wyników z wyszukiwarki w nowym oknie - dokładnie jak w pliku indeks_hasla.js: > <script> var indeks = new Indeks('indeks', ramka); indeks.wstawWyszukiwarke('adres'); </script>lub > <script> var indeks = new Indeks('indeks', 'nazwaokna'); indeks.wstawWyszukiwarke('adres'); </scriptDemonstrację działania wyszukiwarki można obejrzeć w części Przykład tego rozdziału. Zwróć uwagę, że po wpisaniu hasła i kliknięciu przycisku "Szukaj", nastąpi wczytanie strony z indeksem, w którym automatycznie uruchomi się proces wyszukiwania wpisanych wyrazów. Kliknij poniższe nagłówki menu myszką: * Wstaw w nagłówku pliku jeden raz kod: > <script src="menu.js"></script> * W wybranych miejscach strony osadź bloki menu używając znaczników listy definicyjnej <dl>...</dl>, przy czym każdemu kolejnemu menu nadaj inny identyfikator `id="..."` - np. `id="menu0"` , `id="menu1"` , `id="menu2"` itd. * Pod każdym blokiem menu wstaw wywołanie skryptu (ostatni zaprezentowany wcześniej fragment kodu), pamiętając, aby w każdym z nich podać odpowiedni identyfikator (menu0, menu1, menu2 itd.). Warto nadmienić, że w przypadku kiedy elementy menu zawierają odsyłacze, gałąź menu, w której znajduje się odnośnik do aktualnie wczytanej strony, zostanie na starcie automatycznie rozwinięta. Dzięki temu użytkownik łatwiej odnajdzie punkt w nawigacji, w którym teraz się znajduje. Dodatkowo w takiej sytuacji elementowi `<dd>...</dd>` , w którym znajduje się bieżący odsyłacz, zostanie przypisana klasa CSS pod nazwą active, dzięki której można dodatkowo wyróżnić aktualną pozycję menu, dodając odpowiednie deklaracje CSS w arkuszu stylów, np.: > #menu0 dd.active { font-weight: bold; } Prezentowany skrypt obsługuje również wielopoziomowe struktury menu. Zasada zagnieżdżania polega na zbudowaniu najpierw pierwszego, płaskiego poziomu, a następnie wybraniu określonego elementu `<dd>...</dd>` i umieszczeniu w nim podrzędnej listy `<dl>...</dl>` , ze swoimi nagłówkami `<dt>...</dt>` i elementami `<dd>...</dd>` . Oczywiście ilość poziomów zagnieżdżenia nie jest niczym ograniczona. W celu osadzenia wielopoziomowego menu, należy powtórzyć wszystkie przedstawione wcześniej kroki. Zmianie ulegnie tylko kod HTML tworzący sam blok menu: > <dl id="menu0"> <dt>Nagłówek 1</dt> <dd> <dl> <dt>Nagłówek 1.1</dt> <dd> <dl> <dt>Nagłówek 1.1.1</dt> <dd>Element 1.1.1.1</dd> <dd>Element 1.1.1.2</dd> <dd>Element 1.1.1.3</dd> <dt>Nagłówek 1.1.2</dt> <dd>Element 1.1.2.1</dd> <dd>Element 1.1.2.2</dd> <dd>Element 1.1.2.3</dd> </dl> </dd> <dt>Nagłówek 1.2</dt> <dd>Element 1.2.1</dd> <dd>Element 1.2.2</dd> <dd>Element 1.2.3</dd> </dl> </dd> <dt>Nagłówek 2</dt> <dd> <dl> <dt>Nagłówek 2.1</dt> <dd>Element 2.1.1</dd> <dd>Element 2.1.2</dd> <dd>Element 2.1.3</dd> <dt>Nagłówek 2.2</dt> <dd>Element 2.2.1</dd> <dd>Element 2.2.2</dd> <dd>Element 2.2.3</dd> </dl> </dd> </dlAby przyspieszyć lub zwolnić rozwijanie/zwijanie pozycji menu, należy powtórzyć wszystkie przedstawione kroki, poza ostatnim (wywołanie skryptu), który tym razem należy wykonać następująco: > <script> new Menu('menu0', '', false, false, czasRozwin, czasZwin); </script* czasRozwin * Czas w milisekundach (1 s = 1000 ms), w którym następuje rozwinięcie pojedynczego elementu menu ( `<dd>...</dd>` ). Aby wymusić natychmiastowe rozwinięcie wszystkich elementów, należy podać wartość 0 (zero). * czasZwin * Czas w milisekundach, w którym następuje zwinięcie pojedynczego elementu menu. Aby wymusić natychmiastowe zwinięcie wszystkich elementów, należy podać wartość 0 (zero). Normalnie pozycje menu są rozwijane począwszy od pierwszej do ostatniej, a zwijane od ostatniej do pierwszej. Można odwrócić te kolejności, dzięki czemu uzyskamy efekt wysuwania: > <script> new Menu('menu0', '', false, true); </scriptCzasem przydatne jest wstawienie menu, które otwiera się po wskazaniu nagłówka myszką, a chowa automatycznie po usunięciu wskaźnika myszki z obrębu wybranego fragmentu menu. > <script> new Menu('menu0', '', true); </scriptWskaż poniższe nagłówki menu myszką: ### Opóźnienie przy otwieraniu/zamykaniu # Dla tej wersji menu można dodatkowo zmienić opóźnienie, które występuje bezpośrednio przed rozpoczęciem otwierania oraz zamykania menu. Czas ten jest konieczny, aby posługiwanie się takim menu przez użytkownika mogło przebiegać komfortowo. Zbyt małe opóźnienie - zwłaszcza przy zamykaniu - może znacznie utrudnić nawigację! > <script> new Menu('menu0', '', true, false, -1, -1, czasOtworz, czasZamknij); </script* czasOtworz * Czas opoźnienia w milisekundach (1 s = 1000 ms), który upływa od momentu wskazania nagłówka myszką, do rozpoczęcia otwierania menu. * czasZamknij * Czas opoźnienia w milisekundach, który upływa od momentu usunięcia wskaźnika myszki znad wybranego fragmentu menu, do rozpoczęcia jego zamykania. ### Kolekcje dokumentów # Zwykle kiedy publikowany artykuł jest dość długi, dzieli się go na osobne części, dzięki czemu czytelnik nie będzie musiał wczytywać całego tekstu od razu. W takim przypadku w menu umieszcza się najczęściej link tylko do pierwszej części artykułu, a na końcu treści wstawia nawigację stronicującą. Niestety ponieważ adres URL każdej kolejnej części podzielonego artykułu jest różny, właściwa gałąź menu zostanie otwarta i link zaznaczony tylko na pierwszej ze stron. Jeżeli jednak poinformujemy skrypt, które adresy wchodzą w skład kolekcji powiązanych dokumentów, po wejściu na kolejne części artykułu, wszystko będzie działać zgodnie z oczekiwaniami. Aby to zrobić, należy nadać właściwemu odnośnikowi z menu atrybut ``` rel="Collection(...)" ``` , w którym podaje się listę adresów URL wszystkich części podzielonego artykułu: > <dl id="menu0"> <dt>Nagłówek 1</dt> <dd><a href="czesc1.html" rel="Collection(czesc2.html,czesc3.html)">Artykuł stronicowany</a></dd> <dd><a href="...">Dokument 2</a></dd> <dd><a href="...">Dokument 3</a></dd> </dlZwracam uwagę, że w nawiasie nie może być żadnych spacji - nawet po znaku przecinka! Jeśli w nazwie plików z kolekcji znajduje się spacja, należy ją zastąpić przez: %20. Podobnie znaki przecinka, znajdujące się w nazwach plików, należy zastąpić przez %2C, nawias otwierający - %28, nawias zamykający - %29. ### Wyrażenia regularne # Występują sytuacje, kiedy dokumentów w kolekcji może być bardzo dużo albo nie wiemy z góry ile, wszystkie jednak pasują do określonego wzorca - np.: /artykul/czesc1.html, /artykul/czesc2.html, /artykul/czesc3.html itd. W takim przypadku dogodniejsze może być dopasowanie adresu przy użyciu wyrażeń regularnych. Aby to zrobić, adres w kolekcji należy objąć nawiasami kwadratowymi, w których wpisuje się treść wyrażenia, np.: ``` rel="Collection([/artykul/czesc\d+\.html])" ``` . Również w tym przypadku przypominam, że w nawiasie kolekcji nie może być żadnych spacji, dodatkowych przecinków ani nawiasów okrągłych! Jeżeli nie odpowiada nam podstawowy wygląd menu, można go zmienić wykorzystując polecenia CSS. W tym celu w pliku menu.css należy wkleić np.: > #menu0 { width: 200px; margin: 10px; padding: 0; } #menu0 dt { background-color: #888; color: #fff; font-weight: bold; text-align: center; cursor: pointer; margin: 10px 0 0 0; padding: 2px; } #menu0 dd { background-color: #eee; color: #000; border-width: 0 1px 1px 1px; border-style: solid; border-color: #888; margin: 0; padding: 1px 5px; } #menu0 dd.active { font-weight: bold; } # Logeen Home Page # Witam! Skoro odwiedzasz tę stronę, musi to znaczyć, że ostatnio stałem się bardzo sławny. Jeszcze nie wiem co takiego wielkiego udało mi się dokonać, ale to musiało być naprawdę coś ważnego, skoro poświęcasz swój czas na czytanie mojego życiorysu ;-) Zachęcam zatem do lektury i mam nadzieję, że w przyszłości na coś Ci się to przyda. Nazywam się <NAME> - dla przyjaciół Sławek. Prowadzony nieodpartą chęcią posiadania własnej strony domowej oraz mając na uwadze wysokie zainteresowanie moją osobą wśród społeczności internetowej, postanowiłem zamieścić tutaj kilka słów o sobie - a nuż przeczyta to jakiś łowca talentów ;-) Nie będę się już tutaj rozpisywał - po informacje zapraszam do kolejnych działów, do których linki znajdują się w menu. Dodam tylko, że w sieci używam często nicka logeen i przedstawionego obok emblematu (ładny, prawda?). Jeśli spotkasz taki na jakimś forum dyskusyjnym, jest duże prawdopodobieństwo, że to właśnie ja. 15 grudnia 2003 | | --- | Jest świetna (szczególnie forum!). Kurs jest dobry, ale byłby lepszy, gdyby przykłady do ćwiczeń był czytelniejsze. Byłem już na wielu stronach z kursem HTML-a, ale ta jest chyba najlepsza. Pozdro dla autora. | | 13 grudnia 2003 | | --- | Hejka! dzieki bardzo za te wspaniala stronke, jest naprawde extra! dzieki niej nauczylam sie budowac strony i zbudowalam wlasna. dzieki jeszcze raz i zapraszam do odwiedzenia mojej strony | | 13 grudnia 2003 | | --- | Ten kurs jest rewelacyjny - brak mi słów! | | 12 grudnia 2003 | | --- | Jest rewelacyjna | | 10 grudnia 2003 | | --- | superkurs i superstrona Pozdro dla właściciela | | 10 grudnia 2003 | | --- | Normalnie stronka daje radę ... 7 godzin szukałem jednego zagadnienia, a jak tu trafiłem to znalazłem po 1,5 minucie Tutaj wszystko jest w przystępnej formie, w pigułce, a do tego za free Pozdro dla Autora i oby tak dalej ... | | 10 grudnia 2003 | | --- | Fajna strona Polece ja mojemu znajomemu ktory mnie meczy zeby napisac mu strone | | 9 grudnia 2003 | | --- | Najlepsza strona dla początkujących webmasterów, przejrzysty język, kolorowa oprawa. Co sprawia, iż tworzenie www to czysta przyjemność. Lepszej nie spotkałem nigdy.Widać, że tak stronka nie była robiona tak żeby tylko istniała, lecz dla czytelników. Tak trzymać | | 8 grudnia 2003 | | --- | Jest spx dzieki za podpowiedzi na temat forum | | 6 grudnia 2003 | | --- | Co ja tu będę gadał dzięki panu nauczyłem sie tego przedtem to była dla mnie czarna magia naprawde. A strona najlepsza na swiecie o jezyku HTML | | 6 grudnia 2003 | | --- | Witam strona na pierwszy rzut oka mi się spodobała ze względów graficznych wiec zapisałem jej adres, po zapoznaniu się z zawartością przyznam że jest tu full informacji. powodzenia w jej prowadzeniu! Pozdrawiam! | | 5 grudnia 2003 | | --- | Jest super a nawet lepiej. Człowieku marnujesz sie przecierz Ciebie powinni wziąśćdo pisania stron np firmy Microsoft. Przeczytałem książke dotyczącą html ale były w niej braki twoja stronka pomogła mi. | | 4 grudnia 2003 | | --- | Strona naprawdą super Z Twojego kursu nauczyłem się tworzyć strony www - możesz zobaczyć wyniki i ocenić niczym nauczyciel (bo tak Cię mogę nazwać) ocenia ucznia - wpisując się do mojej Księgi Gości lub przesłać mi e-maila . ( Mója serwis będzie dostępny między 15 a 25 grudnia 2003 r. - jeszcze nie jest gotowy i nie chcem go umieszczać z kilkoma podstronami MUSI być kompletny, a nie na każdej podstronie strona w budowie i w budowie - to jest naprawdę denerwujące zwłaszcza dla posiadaczy modemów szukasz, szukasz i wkońcu znajdujesz taką stronę która cię interesuje wchodzisz na nią a tu znowu - w budowie sam się o tym przekonałem i Ci co robią takie strony niech lepiej się za to NIE biorą albo przynajmniej niech nie umieszczają ich na serwisach bo tylko zajmują domeny ) Pozdrawiam i Zapraszam do siebie. | | 4 grudnia 2003 | | --- | Szczerze jest to chyba najlepsza polskąjęzyczna strona jaką udało mi się znaleźć w sieci Jest zaje***ta! Na prawde... Tylko jeszcze jak by była tu informacja o obsłudze np. Macromedia Flasha to by było już wszystko co można by było umieścić na tej stronie Jak ktoś zna taką stronke z opisem do tego programu piszcie na E-maila: <EMAIL> | | 3 grudnia 2003 | | --- | To jest zdecydowanie NAJLEPSZA strona o tej tematyce jaką udało mi sie znależć. Na jej podstawie przygotowuje sobie konspekty zaęć dla uczniów z HTMLa. POprostu SUPER dzięki za pomoc | | 2 grudnia 2003 | | --- | Najlepsza storona o tematyce www jaką znalazłem, ciekawe i wyczerpujące opisy html i css. Sławek wykonałeś kawał dobrej roboty. Tak trzymaj. | | 30 listopada 2003 | | --- | jest bardzo ładna i fajna i super | | 30 listopada 2003 | | --- | Ta strona jest super. Uświadomiła mi że nie jest tak trudno napisać własną stronę. Chociaż nadal uważam że napisanie strony nie jest łatwe, ale nic nie jest łatwe czego nie umiemy. | | 25 listopada 2003 | | --- | czesc!uwazam,ze strona jest swietna.pomaga mi w przygotowaniu wlasnej strony internetowej (ktora musze wykonac na zaliczenie ).mam nadzieje ze juz wkrotce bede mogla was zaprosic na wlasna stronke/pozdrawiam.gg5256328 s<EMAIL>@<EMAIL> | | 24 listopada 2003 | | --- | Cze mam na imie Michał i jak do tej pory byłem zielony w obsłudze HATML. Po przeczytaniu kursu wiem wiele... | | 22 listopada 2003 | | --- | Strona jest bardzo ciekawa,a w tej ulepszonej wersji, jest godna zaglądnięcia na nią. | | 21 listopada 2003 | | --- | Sławek jesteś BBBBBBBB OOOO SSSS KKKK IIIIIII | | 21 listopada 2003 | | --- | Szukajcie, a znajdziecie - kwestia tylko jak długo to potrwa . Gdy tutaj trafiłam tylko jedno cisnęło mi się na usta - EUREKA! Stronę wyróżnia przede wszystkim podejście do początkujących - wszystko klarownie i przystępnie napisane, z dokładnymi przykładami, a Autor nie ma maniery tego-który-zjadł-wszystkie-mądrości. Korzystając z tego kursu wiedza szybko wchodzi do głowy, aż chce się samemu wypróbować w praktyce poznane ciekawostki. Za całokształt stawiam szóstkę, a z wdzięczności link na swojej stronie. | | 20 listopada 2003 | | --- | Jestem w szoku, takiej strony z kursem HTML po prostu jeszcze nigdzie nie widziałem Spoko czadowo, wszystko tu jest a nawet więcej pare rzeczy jakie tu są nigdy w życiu nie widziałem i nie wiedziełałem o ich istnieniu coool | | 18 listopada 2003 | | --- | Dzięki wielkie, że ją napisałeś. Nareszcie znalazłam to, czego potrzebuję, wyjaśnione "po ludzku"... Tak trzymaj | | 17 listopada 2003 | | --- | Cześć! Po prostu zaje... najlepsza strona z kursem HTML-a jaką do tej pory znalazłem. Miałem inne kursy, ale ta strona jest NAJLEPSZA. | | 11 listopada 2003 | | --- | Jest super wszzystko znalazlem co chcialem. Prucz podswietlania napisów.Jak to jest glajska.Szukalem od miesiecy cos o mp3 i dzisiaj jest ten dzien Jak znajdziecie jakies inne fajne www takie jak ta to piszcie na muj e-mail | | 9 listopada 2003 | | --- | Spoko stronka Brawo | | 4 listopada 2003 | | --- | extra, super, debest, masa ful wypas sajcik ja tez chce taka ksiege gosci dzieki stronom takim jak ta az chce sie zyc luknij na moja stronke swoim fachowym okiem (tylko sie nie smiej) i powiedz co poprawic | | 3 listopada 2003 | | --- | Ele super stronka! i jaki Ty jestes mądry hihi.. ja też robie prawie z epierwszy raz stronke.. Bardzo wyraźnie piszesz, no ale cóż.. jestem tak głupia ż ecoś mi nie wychodzi ;( buuuuuuuubbbbuuuuu chyba zostane przy moim blogu:/ chcoiaż nie powalcze... | | 1 listopada 2003 | | --- | stronka naprawde debesciak wlasnie bede robil swoja pierwsza strone i cos czuje ze bede tu czesto zagladal jest duzo fajnych skryptow jeszcze nie zdazylem przejrzec calej strony - zatrzymalem sie poki co na skryptach hehe a teraz gonie dalej czytac...... | | 31 października 2003 | | --- | Po prostu wypas - a ksiega gosci - mniam | | 31 października 2003 | | --- | Super stona dzięki niej zrobiłem swoją piewszą strona. Dzieki ze zrobiłeś taką strone | | 29 października 2003 | | --- | uwazam ze twoja stronka jest super dzieki niej (paragraf dla zielonych) byłem w stanie zrobic wlasną strone html a nie jest to latwa sprawa wielkie dzieki za pomoc | | 27 października 2003 | | --- | dzieki ci za wszystko ... dzieki tobie moja storna ozyla ... wiele zadzybistych skryptow .. i informacji kootrych sie nie znajdzie w innych kursach ..na www | | 27 października 2003 | | --- | stronka za***ista naprawde jestes spoko gościu należą ci sie wielkie gratulacje i wielkie dzięki tego szukałem | | 26 października 2003 | | --- | dzieki tym info na tej stronie zrobilem moja witryne dzieki | | 26 października 2003 | | --- | bardzo fajna strona, podoba mi się zwłaszcza wykaz kolorów - jest po prostu doskonały. Nigdzie nie znalazłam lepszego. Gratulacje. | | 26 października 2003 | | --- | zarąbista po paru latach dopiero dzisiaj (po przeczytaniu wszystkiego co tutaj jest) zrobiłem swoją stronkę dzięki serdeczne i trzymaj się ciepło | | 26 października 2003 | | --- | Kurs jest super. Naprawdę gratuluję Ci Bardzo mi to pomogło, Mam nadzieję, że będziesz ja cały czas ulepszać. Pozdrawiam i 3maj się | | 25 października 2003 | | --- | dzieki tej stronie zrobilem wlasna dodaje link do niej | | 21 października 2003 | | --- | Czesc, spoko strona. Duzo ciekawych informacji. Pozdrawiam | | 19 października 2003 | | --- | Dzięki za informacje na Twojej stronie. Sam zrobiłem jedną stronę- potwora z szablonu Wirtualnej Polski. Ale postanowiłem dalej nie iść na łatwiznę i chcę się uczyć html. Pozdrawiam serdecznie- <NAME> z Aten. | | 18 października 2003 | | --- | i znowu tu jestem ucze sie teraz html-a naraie na mojej stronce jest to co udalo mi sie zrobic | | 17 października 2003 | | --- | <NAME> z PW pozdrawiają młodszego kolegę z PK. Odwaliłeś kawał niezłej roboty z tą stronką. Po zakończeniu studiów na Politechnice Krakowskiej zapraszamy na Politechnikę Warszawską na doktorat z informy. Trzymaj się oby tak dalej. | | 17 października 2003 | | --- | naprawde super strona dużo przydatnych informacji gorące pozdrowienia dla <NAME> jak napiszę już stronę to wpisze się kolejny raz podając linka do tej strony pozdrawiam i dziękuje | | 17 października 2003 | | --- | świetna stronaka moze juz niedlugo bede mial wlasna pozdroffionka dla autorów! | | 17 października 2003 | | --- | Wspaniała stronka. Czegoś takiego właśnie szukałem. Jedyna ze znznaych mi na której spotkalem się z pełnym zrozumieniem początkujących-linuksowych webmasterów. Gratuluję cierpliwowości i samozaparcia. Tak trzymać ....... i nie puszczać. Pozdrawiam | | 11 października 2003 | | --- | Siemano! Strona jest full wypas jak dla mnie. Dopracowana w każdym szczególe i w ogóle super. A jeśli chodzi o treść samego kursu to ja do tej pory lepszego w sieci nie znalazłem. Pozdrawiam! | | 10 października 2003 | | --- | strona jest bardzo dobra właściciej widać że się zna na ty czym robi życze dalszego pomyślnego rozwojy strony | | 3 października 2003 | | --- | No strona jest naprawde profesjonalna... oby tak dalej | | 3 października 2003 | | --- | Stronka jest naprawdę bardzo użyteczna. Robię stronkę naszej klasy i korzystam z niej. Będę tu jeszcze zaglądać i wam też radzę. Papa i 3majcię się, internauci | | 30 września 2003 | | --- | Fajna stronka, kurs HTML jest bardzo konkretny. Korzystam z niego. To super, że komuś się chce udostępniać w sieci materiały o robieniu stron WWW. Teraz o to coraz trudniej. Wiem coś o tym, bo często sam szukam jakiś kursów lub free komponentów,i usług , różnie z tym bywa. | | 29 września 2003 | | --- | Strona jest po prostu super. Gratulacje dla autora | | 25 września 2003 | | --- | Wszystko OK, tylko kolory tekstów w przykładach HTML dość nieszczęśliwie dobrane, dla mnie niektore sie zlewaja z tlem | | 22 września 2003 | | --- | Przedewszystkim pozdrawiam wszystkich w ksiedze gosci oraz webmastera strona jest super | | 20 września 2003 | | --- | super stronka, moze kiedys naucze sie jezyka html jak bede mial czas. Pozdro dla Pinia. | | 19 września 2003 | | --- | Ten kurs to jest przewodnik jak zrobić dobrą stronę. Długo szukałem, ale to jest to! Bardzo mi się podoba. Ja niedługo też stworzę sobie stronkę. Aha, nie zapomnę o odsyłaczu do tego kursu pozdrowionka dla AUTORA | | 18 września 2003 | | --- | Dlugo poszukiwalem takiej strony .... w koncu znalazlem Pozdrawiam wszystkich, Tollis-ek | | 12 września 2003 | | --- | dzieki wielkie wlasnie prubuje sie nauczyc projektowac stronki a wasza stronka wydadnie sie przyda do mojej pracy , mam tylko nadzieje ze starczy mi zapalu , pozdrowka i narka | | 11 września 2003 | | --- | Naprawdę jestem pod wrażeniem - jedna z najlepszych stronek o webmasterstwie w polskim necie, lepsza chyba nawet od kursu <NAME>! Gratulacje | | 6 września 2003 | | --- | Gratuluję znakomitej strony. Zdziwię się, jak do końca Twoich studiów nie złapię Cię jakaś agencja headhunterska | | 5 września 2003 | | --- | gut stronka nawet sobie zrzucilem conieco na hd, ta ksiega gosci tez jest niezla | | 4 września 2003 | | --- | zero minusów dużo plusów. | | 2 września 2003 | | --- | ...dla takiego cymbała jak ja w sprawach HTML'a daje Ci Oskara Informatycznego...pozdrawiam i dzięki wielkie... | | 30 sierpnia 2003 | | --- | D twórcy strony: Zrobiłeś kawal dobrej roboty !, wszystko objaśnione jak należy ale przydało by sie więcej skryptów Pozdrawiam | | 24 sierpnia 2003 | | --- | Stronka świetna Znalazłem tu to czego szukałem juz długo, mianowicie fajoski skrypcik przycisków Pozdrawiam... | | 21 sierpnia 2003 | | --- | Jeżeli mam jakiś problem przy tworzeniu swojej strony zaglądam tu i nagle wszystko staje się jasne Gratulacje i szczere wyrazy uznania dla twórcy. | | 20 sierpnia 2003 | | --- | Co do strony autora jest naprawdę bardzo przydatna, tak dla początkujących i jak i starych wyjadaczy html itp. Kursów HTML jest sporo w sieci ale nie każdy aż tak przydatny i przejrzysty jak ten. Autorze strony! trzymaj tak dalej ! Ooo i jeszcze jest przyzwoite forum, może zarejestrujmy się na nim tam napewno łatwiej wymieniać informacje jak tu. Pozdrawiam | | 18 sierpnia 2003 | | --- | bardzo fajna strona, dużo pożytecznych informacji. pozdro | | 17 sierpnia 2003 | | --- | Strona jest super, jestem zachwycony, ktos polecił ją na forum KASSART jako przydatne strony dla webmastera i ja powiem jedno ta jest baardzo przydatna Aaa... pisałeś że można się w księdze pochwalić nową stroną , ja się nie chce chwalic za bardzo bo nie ma czym ale to moja pierwsza strona i postaram sie niedługo umiescic na niej link do Twojego kursu..... Pozdrawiam | | 9 sierpnia 2003 | | --- | Cool Najlepszy kurs na calym swiecie Kazdemu polecam twoja strone | | 8 sierpnia 2003 | | --- | extra stronka, naprawdę bardzo, bardzo dużo można z niej wynieść gratulacje i oby tak dalej | | 7 sierpnia 2003 | | --- | Twój kurs nie ma sobie równych! Wszystko jest tak jasno i prosto opisane... Wielkie dzięki Ci za to, pokazałeś mi, że nie mogę być gorsza... Niedługo pokażę, czego się u Ciebie nauczyłam! | | 6 sierpnia 2003 | | --- | cool strona | | 3 sierpnia 2003 | | --- | Stronka jest spoko. Bardzo przydatna Nareszcie morzna dowiedzieć się więcej rzeczy o tym języku trzymaj tak dalej. | | 17 lipca 2003 | | --- | Zapomniałabym o księdze... Jeżeli to Twoje dzieło to podwójne gratulacje. Bardzo podoba mi się jej estetyczna strona. Nietyopwa w pozytywnym znaczeniu. | | 17 lipca 2003 | | --- | Rewelacyjny kurs Jeszcze do lepszego nie dotarłam. Nawet książka HTML4 z serii Po Prostu (Helion), nie jest tak jasno i konkretnie napisana . I jeszcze jedno godne pochwały - aktualizacje i rozbudowa o nowe elementy. Gratulacje! | | 15 lipca 2003 | | --- | jeden z lepszy kursów html jaki widziałem. mnóstwo skryptów (ładna księga) wreszcie ktoś stworzył cos porządnego | | 15 lipca 2003 | | --- | ale rzes ksiazke gosci odwalił podziwiam | | 15 lipca 2003 | | --- | Tą księgę gości napisałem samodzielnie, a jej wygląd dostosowałem do własnych wymagań - również emotikony. Jeżeli korzystasz z darmowych komponentów i Twoja księga nie obsługuje emotikon, to raczej nic nie da sie zrobić | | 15 lipca 2003 | | --- | Jeden z najlepszych kursów jaki widziałam. Mam pytanko... jak można zrobić coś takiego, żeby w swojej księdze móc wstawić emotikony? | | 14 lipca 2003 | | --- | Najlepszy kurs jaki kiedykolwiek widziałam. | | 14 lipca 2003 | | --- | Kod źródłowy PHP tej księgi gości to całkowicie moje dzieło W końcu postanowiłem napisać coś, co mi odpowiada, a nie korzystać z nie zawsze dobrych darmowych komponentów. Szczególnie w tej dziedzinie jest straszna "dziura". Najczęściej darmowe księgi mają nieciekawy wygląd, którego w dodatku nie można modyfikować lub są napisane wręcz z poważnymi błędami. Możliwość używania "emotikon" to już prawdziwa rzadkość | | 14 lipca 2003 | | --- | no no, ksiega widze piewrsza klasa Sam ja robiles czy wylookales na jakiejs stronce | | 13 lipca 2003 | | --- | WŁAŚNIE RUSZYŁA NOWA, ULEPSZONA KSIĘGA GOŚCI Teraz możesz używać "emotikony", klikając podczas wpisywania ikony "buziek", znajdujące się obok pola wpisu: . Można również wpisywac adresy WWW np.: www.kurshtml.edu.pl, e-mail: <EMAIL> oraz FTP: ftp://sunsite.icm.edu.pl. Możesz również podać swój e-mail i adres Twojej strony WWW. WPISUJCIE SIĘ LUDZISKA, BO NAPRAWDĘ WARTO | | Date: 2023-11-15 Categories: Tags: WWW | 15.11.2023 | Wcześniej | W sumie | | --- | --- | --- | --- | https://www.kurshtml.edu.pl/kurs-html.pdf | 1 | 0 | 6254 | www.fotografia.kopernet.org | 0 | 0 | 1368 | https://www.kurshtml.edu.pl/kurshtml.zip | 0 | 0 | 7120 | www.kess.snug.pl | 0 | 0 | 16559 | www.kursexcel.net | 0 | 0 | 3044 | www.oferent.com.pl/aktualne-przetargi/ | 0 | 2 | 3022 | www.tymex.org | 0 | 0 | 11093 | Polityka prywatności ``` <ol type="1" start="3"> ``` ``` <ol type="A" start="3"> ``` * Punkt pierwszy * Punkt drugi * Punkt trzeci `<ol type="1">` # Tytuł pierwszego rzędu (h1)(w Internet Explorerze 32 piksele) # Tytuł pierwszego rzędu (h1) (w Internet Explorerze 32 piksele) ## Tytuł drugiego rzędu (h2) (24 piksele) ### Tytuł trzeciego rzędu (h3) (18 pikseli) # Tytuł czwartego rzędu (h4) (16 pikseli) # Tytuł piątego rzędu (h5) (12 pikseli) # Tytuł szóstego rzędu (h6) (10 pikseli) # To jest tytuł czwartego rzędu, wskaż na niego myszką aby zobaczyć jego opis... To jest przykład strony, która jest automatycznie odświeżana co 5 sekund. Ponieważ strona ma bardzo małą objętość, to możesz nie zauważyć momentu odświeżania (szczególnie jeśli masz zapisany ten kurs na dysku i nie korzystasz w tym momencie z Internetu). Aby sprawdzić, że ta strona jest naprawdę odświeżana co 5 sekund, przewiń jej zawartość suwakiem na sam dół i poczekaj chwilę... ..................... ..................... ..................... ..................... ..................... ..................... ..................... ..................... ..................... ..................... ... zaraz strona sama powróci na górę... (W niektórych przeglądarkach po odświeżeniu nie następuje powrót na początek strony, ale mimo tego strona jest prawidłowo odświeżana!) © www.kurshtml.edu.pl # Formularze Formularze DATALIST Ukończono: 50% <progress value="50" max="100">Ukończono: 50%</progress INPUT Formularze DATALIST ``` <input list="list1"> <datalist id="list1"> <option value="wartość1"> <option value="wartość2"> </datalist> ``` Ukończono: 50% <progress value="50" max="100">Ukończono: 50%</progress> PROGRESS Proszę czekać... ``` <progress>Proszę czekać...</progress> ``` ``` <progress value="0.5">Ukończono: 50%</progress> ``` ``` <progress value="50" max="100">Ukończono: 50%</progress> ``` ``` <meter value="0.5">0.5</meter> ``` ``` <meter value="50" min="0" max="100">50 (0...100)</meter> ``` 0.5 ``` <meter value="0.5" low="0.2" high="0.8">0.5</meter> ``` ``` <meter value="50" min="0" max="100" low="20" high="80" optimum="60">50 (0...100)</meter> ``` ``` <meter value="10" min="0" max="100" low="20" high="80">10 (0...100)</meter> ``` 90 (0...100) ``` <meter value="90" min="0" max="100" low="20" high="80">90 (0...100)</meter> ``` INPUT INPUT Elementy osadzone VIDEO 00:00:04.000 --> 00:00:04.500 KONIEC Elementy osadzone VIDEO Play/Pause Mute/Unmute Pobierz plik w formacie:MP4,OGV Pobierz plik w formacie: Pobierz plik w formacie: MP4, , OGV Play/Pause Mute/Unmute Play/Pause Mute/Unmute Pobierz plik w formacie:MP4,OGV Pobierz plik w formacie: Pobierz plik w formacie: MP4, , OGV 00:00:04.000 --> 00:00:04.500 KONIEC TRACK Pobierz plik w formacie:MP4,OGV;pobierz napisy Pobierz plik w formacie: Pobierz plik w formacie: MP4, , OGV; ; pobierz napisy ``` <style> ::cue { background: rgba(0, 128, 255, 0.8); color: white; } ::cue(b) { color: red; } ::cue(i) { color: lime; } ::cue(u) { color: aqua; } ::cue(# ``` druga-linia) { font-weight: bold; color: red; } ::cue(v[voice=" ) { font-weight: bold; color: red; } ::cue(v[voice=" echo"]) { color: yellow; font-weight: italic; } </style> [...] <video width="192" height="240" controls> <source src="plik.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> <source src="plik.ogv" type='video/ogg; codecs="theora, vorbis"'> "]) { color: yellow; font-weight: italic; } </style> [...] <video width="192" height="240" controls> <source src="plik.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> <source src="plik.ogv" type='video/ogg; codecs="theora, vorbis"'> <track src="plik.vtt" default> Pobierz plik w formacie: <a href="plik.mp4">MP4</a>, <a href="plik.ogv">OGV</a>; Pobierz plik w formacie: <a href="plik.mp4">MP4</a>, <a href="plik.ogv">OGV</a>; <a href="plik.vtt">pobierz napisy</a> </video> </video> plik.vtt ``` WEBVTT 00:00:04.000 --> 00:00:04.500 KONIEC echo >&lt;zażółć gęślą jaźń&gt; 00:00:04.000 --> 00:00:04.500 KONIEC # Ustalenie rozmiaru obrazka tła Tradycyjnymi metodami nie można zmieniać rozmiaru obrazka wstawionego w tle. Aby tego dokonać, trzeba posłużyć się pewną "sztuczką". Na tej stronie nie zostało ustalone żadne tło obrazkowe. Został tutaj wstawiony normalny obrazek za pomocą znacznika `<img />` . Dzięki temu można ustalić jego wymiary. Obrazek ten został następnie poddany pozycjonowaniu absolutnemu i nałożony pod właściwą treścią strony. Dzięki temu wygląda jak tło, ale faktycznie nim nie jest. Aby przekonać się, że obrazek w tle tej strony rzeczywiście dopasowuje się automatycznie, spróbuj zmienić rozmiar okna przeglądarki. Ten sposób nie jest jednak złotym środkiem na automatyczne dopasowywanie wymiarów obrazka w tle do rozmiarów okna przeglądarki. Jakakolwiek zmiana rozmiarów grafiki powoduje wyraźną utratę jej jakości. W przypadku powiększania otrzymujemy duże, zauważalne piksele, z których zbudowany jest obraz cyfrowy. W przypadku pomniejszania widoczne są zniekształcenia. Ponieważ w tym przypadku obraz jest skalowany nieproporcjonalnie, dodatkowo będzie on rozciągnięty w poziomie lub pionie, co wywoła nienaturalny wygląd. Poza tym w niektórych przeglądarkach mogą wystąpić problemy z przewijaniem strony za pomocą rolki myszki lub też może pojawić się podwójny pionowy suwak. Aby uzyskać taki efekt, należy posłużyć się następującym kodem: > <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl" lang="pl" style="height: 100%"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body style="margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden"> <div style="position: absolute; z-index: 2; width: 100%; height: 100%; overflow: auto"> <div style="margin: 10px"> Tu wpisuje się treść strony </div> </div> <div><img src="obrazek.jpg" alt="" style="width: 100%; height: 100%; position: absolute; left: 0; top: 0; z-index: 1" /></div> </body> </htmlPoniżej tekst "wypełniacz" - nie warto czytać :-) To jest przykład strony, na której nastąpi automatyczne wczytanie innej strony. Powrót do "Kursu HTML" nastąpi za: sek. Proszę czekać... © www.kurshtml.edu.pl # Sposoby osadzania plików na stronie WWW <embed src="plik.avi"<embed src="plik.wav"<embed src="plik.pdf" width="100%" height="300"<object data="plik.pdf" width="100%" height="300"> <a href="plik.pdf">Pobierz plik</a> </objectTo jest przykład obrazka w tle strony z użyciem polecenia background-attachment: fixed oraz background-repeat: no-repeat; background-position: center... Zauważ, że na środku ekranu znajduje się tylko jeden egzemplarz tła, który dodatkowo nie przewija się razem z tekstem (powinien być nieruchomy). Aby to sprawdzić, przewiń zawartość strony za pomocą suwaka... ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ...Jak już pisałem, tło nie przewija się razem z tekstem. © www.kurshtml.edu.pl Tu jest dziesięć spacji: ...ale ponieważ użyto white-space: normal, więc zostaną one zamienione na jedną (domyślnie). Tu jest dziesięć spacji: ...i ponieważ użyto white-space: pre, więc nie zostaną one zamienione na jedną (powinny być widoczne na ekranie). Dodatkowo wiersz nie zostanie przełamany, aż do momentu napotkania znaku końca linii (klawisz Enter wpisany w edytorze - nie trzeba stosować znacznika <br />). Tutaj znajduje się przełamanie linii ...a tutaj jest następna linijka rozpoczynająca się tabulatorem. Tu jest dziesięć spacji: ...ale ponieważ użyto white-space: nowrap, więc zostaną one zamienione na jedną. Natomiast ten wiersz nie powinien być nigdy przełamany... przełamany... przełamany... przełamany... przełamany... przełamany... przełamany... przełamany..., chyba że pojawi się znacznik<br />...wtedy tekst zostanie przeniesiony do następnej linii. Poniższe polecenia mogą być nieinterpretowane: Tu jest dziesięć spacji: ...i ponieważ użyto white-space: pre-wrap, więc nie zostaną one zamienione na jedną (powinny być widoczne na ekranie). ...a tutaj jest następna linijka rozpoczynająca się tabulatorem. Dodatkowo wiersz zostanie przełamany automatycznie, jeśli nie zmieści się w szerokości ekranu albo po napotkaniu znaku nowej linii (klawisz Enter). Tu jest dziesięć spacji: ...i ponieważ użyto white-space: pre-line, więc zostaną one zamienione na jedną. Dodatkowo wiersz zostanie przełamany automatycznie, jeśli nie zmieści się w szerokości ekranu albo po napotkaniu znaku nowej linii (klawisz Enter). # Pozycjonowanie absolutne { position: absolute } Jako przykład pozycjonowania absolutnego, spójrz na obrazek, znajdujący się w prawym-górnym rogu tej strony (na samej górze). Został on tam umieszczony na "sztywno" za pomocą polecenia: position: absolute; right: 20px; top: 10px mimo, że polecenie to zostało wpisane poniżej tego tekstu: ``` <img src="../../pliki/obrazek.jpg" alt="position: absolute; right: 20px; top: 10px" style="position: absolute; right: 20px; top: 10px" /> ``` position: fixed To jest przykład pozycjonowania ustalonego position: fixed... Zauważ, że czerwony tekst pozostaje zawsze w tym samym miejscu na ekranie i nie przewija się razem ze stroną. Aby to sprawdzić, przewiń zawartość strony za pomocą suwaka... ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ................ ...Jak już pisałem, czerwony tekst pozostaje w tym samym miejscu (nie obsługuje IE6). © www.kurshtml.edu.pl # Stały szablon (fixed layout) To jest stały szablon (fixed layout). Zwróć uwagę, że zmieniając rozmiary okna przeglądarki, szerokość szablonu pozostaje stała. W rozdzielczości wyższej niż 800x600, po prawej stronie szablonu pozostaje wolna przestrzeń. Jeżeli zmniejszysz szerokość okna do rozmiaru niższego niż 800 pikseli, zobaczysz poziomy pasek przewijania. > <div id="top"> <div id="NAGLOWEK">Nagłówek szablonu</div> <div id="MENU">Menu nawigacyjne</div> <div id="TRESC">Treść strony</div> <div id="STOPKA">Stopka serwisu</div> </div> > html, body { background-color: #fff; color: #000; margin: 0; padding: 0; } #top { width: 780px; } #NAGLOWEK { background-color: #888; } #MENU { width: 150px; float: left; overflow: hidden; background-color: #ccc; } #TRESC { width: 630px; float: left; overflow: hidden; background-color: #fff; } #STOPKA { clear: both; width: 100%; background-color: #888; } # Płynny szablon (liquid layout) To jest płynny szablon (liquid layout). Zwróć uwagę, że zmieniając rozmiary okna przeglądarki, kolumna z tą treścią, a także nagłówek i stopka szablonu, automatycznie dopasowują się, tak że zawsze zajmują pełną szerokość okna przeglądarki. Zauważ przy tym, że kolumna menu nie zmienia swoich rozmiarów. Spójrz na obszar strony pod kolumną menu - jest on pusty, tzn. treść, którą właśnie czytasz, nie oblewa normalnie bloku menu. > <div id="top"> <div id="NAGLOWEK">Nagłówek szablonu</div> <div id="MENU">Menu nawigacyjne</div> <div id="TRESC">Treść strony</div> <div id="STOPKA">Stopka serwisu</div> </div> > html, body { background-color: #fff; color: #000; margin: 0; padding: 0; } #NAGLOWEK { background-color: #888; } #MENU { width: 150px; float: left; overflow: hidden; position: relative; background-color: #ccc; } #TRESC { margin-left: 150px; background-color: #fff; } #STOPKA { clear: both; background-color: #888; } 5 lipca 2003 | | --- | Spoko ta twoja strona. Jest tu duzo ciekawych rzeczy dla poczatkujacych (i nie tylko) webmaster'ów | | 3 lipca 2003 | | --- | spoko stronka już | | 27 czerwca 2003 | | --- | może wrezcie zrobię coś ze swoją | | 22 czerwca 2003 | | --- | graficznie nie jest najlepsza ale za to kurs jest świetny dużo sie dowiedziłęm chociaż myślałem że wiem dużo o webmasteringu... | | 21 czerwca 2003 | | --- | stronka mi sie podoba: na temat, jest porządek, i sie przydała... | | 21 czerwca 2003 | | --- | Nawet papier toaletowy wie, że aby żyć, trzeba się rozwijać | | 21 czerwca 2003 | | --- | nie było mnie tu jakiś czas i musze przyznać że się tu pare rzeczy zmieniło na lepsze (wygląd) stronka jest bardzo pomocna dla osób, które tworzą pierwszy raz własna stronę | | 15 czerwca 2003 | | --- | Wystarczy przeczytać pierwszy rozdział: "Dla zielonych" i już możesz mieć własną stronę WWW! | | 15 czerwca 2003 | | --- | Heh... zastanawiam sie, czy mam zaczac robic swoja... ale tyle mam czytac?? heh | | 14 czerwca 2003 | | --- | Stonka jest naprawdę super! Bardzo pomaga przy tworzeniu własnej Pozdrawiam i życzę rónie udanych pomysłów na przyszłość!!! | | 10 czerwca 2003 | | --- | Ta strona to dla mnie coś wspaniałego. Jest rewelacyjna. Dzięki niej mogę zrobić prace na lekcje informatyki. Dzięki że ją zrobiłeś. Polecam ją wszystkim. | | 8 czerwca 2003 | | --- | Wchodze na ten kurs wieeele razy a ani razu nie wpisalem sie do ksiegi wiec oswiadczam ze to nalepszy kurs w necie pozdroowka dla autora | | 7 czerwca 2003 | | --- | Stronka jest poprostu zaj...sta. Na poczatku uczylem sie ze stronki www.html.xp.pl bo myślałem że jest najlepsza ale jak wszedłem na tą stronkę to aż mi się lepiej zrobiło | | 2 czerwca 2003 | | --- | Tamten wystruj był lepszy. Ale dzięki tej stronce wiele sie nauczyłam dzięki ci za to! | | 1 czerwca 2003 | | --- | fenomenalny kurs! nowe menu też ładne bardzo. "two thumbs up" dla autora | | 29 maja 2003 | | --- | Niezla stronka; bardzo mi pomogla; thx! | | 28 maja 2003 | | --- | Jest najlepsza w sieci bez kitu wielkie brawa dla autora! | | 27 maja 2003 | | --- | Rewelacyjny kurs, najlepszy chyba jaki widziałam zapraszam na moją stronke | | 25 maja 2003 | | --- | To prawda, tło w menu nie wygląda(ło) zbyt dobrze Od dawna próbowałem poprawić design strony... i dzisiaj wreszcie się udało! Zupełnie nowe menu w DHTML-u mam nadzieję, że przypadnie wszystkim do gustu. Piszcie, czy jest lepsze, wygodniejsze od poprzedniego... | | 23 maja 2003 | | --- | Świetny kurs, bardzo przyjemna strona. Jedynie tło za menu trochę rozmydla opcje - jednak nie czepiałbym się gdyby to nie była strona o tworzeniu WWW Za logo pasuje świetnie, ale za opcjami spisu treści tło powinno się "spłaszczyć". | | 23 maja 2003 | | --- | Bardzo dobry kurs html. Napewno kosztował Cię wiele pracy. | | 20 maja 2003 | | --- | Stronka jest naprawde spoka,ale najważniejsza jest treść kursu a ana jest super, nawet największa noga do internetu przy pomocy tego kursu sobie poradzi | | 18 maja 2003 | | --- | Świetna strona podziwiam wykonanie ale i wiedzę z HTML | | 11 maja 2003 | | --- | A ja myślę, że ta strona jednak czymś się wyróżnia. Bardzo przystępne wprowadzenie dla początkujących. Obliczyłam również, że wydruk całego kursu w formacie książkowym zajmuje ponad 500 stron , nie licząc dodatkowych przykładów i generatorów. | | 10 maja 2003 | | --- | HMmmmm .....stronka ujdzie w tumie mało się wyróżnia wsród innych ...! | | 10 maja 2003 | | --- | hehe stronka jest fool wypas tak trzymac dalej | | 10 maja 2003 | | --- | super strona prosze o kontakt autora strony | | 27 kwietnia 2003 | | --- | Jeśli chcesz zrobić własną KSIĘGĘ GOŚCI, zajrzyj do rozdziału pt.: "I co dalej/Dodatki" A poza tym po co jest wyszukiwarka w serwisie? Wystarczy wpisać szukany temat - księgę gości na pewno znajduje... | | 27 kwietnia 2003 | | --- | STRONA OK A<NAME>CIAŁ<NAME> ZROBIĆ WŁASNĄ KSIĘGE GOŚCI, JEST TAKA MOŻLIWOŚĆ | | 23 kwietnia 2003 | | --- | Wg mnie wasza strona jet naprawde ciekawa i tak zwanym "zielonym" zaczerpnąć więcej wiedzy o html | | 22 kwietnia 2003 | | --- | nooooo, jest qlasta zaczepicho, dobry kurs, wiele sie z niego nauczyłem, a nawet bardzo wiele, szczegolowe informacje, włozyłes w niom bardzo duzo pracy i pomogłeś wielu ludziom, gratulacje | | 17 kwietnia 2003 | | --- | no nie powiem kurde stroonka wy***ista komu sie chcialo tyle robic to nie wiem ale podziwiam bo... troche mial roboty ale kurs wyrabany nie widzialem lepszego... | | 17 kwietnia 2003 | | --- | elo kurs naprawde świetny najlepszy jaki widziałam... wiele z niego skorzystałam thx | | 13 kwietnia 2003 | | --- | stronka jest oki | | 30 stycznia 2003 | | --- | Merytoryczna zawartość strony jest na dobrym poziomie, rzeczowo i konkretnie poparte w przykładach. Kiedy zaczynałem przygodę z html'em za wzór poradników wszelakich uważałem: bardzo ciekawa strona. Powodzenia w dalszym jej prowadzeniu | | 26 stycznia 2003 | | --- | Z.A.R.Ą.B.I.S.T.A. strona. Dzięki Tobie już kapuje html'a | | 25 stycznia 2003 | | --- | Ta strona to jest majstersztyk, gdyby nie ona to bym ****o wiedział o stronach, teraz uczę się PHP, a gdybym miał do wszystkiego taki kurs to bym yahoo bez problemu napisał Kawał dobrej roboty | | 25 stycznia 2003 | | --- | Jest to absolutnie najlepszy kurs Nauczyłem się wszystkiego o stylach i dużo o html-u, jest przystępnie i ciekawie napisany, nie ma dłużyzn i może służyć jako leksykon, każdy, kto robi strony za pomocą notatnika powinien przejżeć te kurs Każdy powinien przejrzec ten kurs | | 7 stycznia 2003 | | --- | Swietna jest! dzieki, zaraz biore sie za projektowanie wlasnej stronki. bravo! | | 4 stycznia 2003 | | --- | ...........It web site is very cool Bravo for webmaster...... | | 4 stycznia 2003 | | --- | Szukalem jakiegos dobrze opracowanego kursu html i znalezelm go na tej stonce, kawal dobrej roboty autora | | 3 stycznia 2003 | | --- | JEJ ale mi się przydała Przejrzysta, logiczna, sensowna i zrozumiała^^ | | 30 grudnia 2002 | | --- | Co sądze? jest to najlepszy kurs html w necie. Bravo | | 29 grudnia 2002 | | --- | Ktos sie naprawde napracowal. Kawal dobrej roboty. Pozdrawiam | | 27 grudnia 2002 | | --- | hmmm....brak mi slow..... ta strona jest ZA***ISTA | | 27 grudnia 2002 | | --- | to jest chyba NAJLEPSZA strona KURSU HTML jaka znalazlem w NET. Strona bardzo przyjazna, sensowna a tresc zawierajaca wszystko o jezyku HTML. Autor tej strony jest wrecz godny PODZIWU | | 26 grudnia 2002 | | --- | Gdyby nie ta strona...Jednym slowem... Oby tak dalej! | | 25 grudnia 2002 | | --- | Fajna, nauczyłem sie tu htmla | | 22 grudnia 2002 | | --- | super strona jestem pełen podziwu | | 11 grudnia 2002 | | --- | Calkiem spoko stronka czasem korzystam z porad szczegolnie kolorow | | 10 grudnia 2002 | | --- | <NAME>, PRZEDEWSZYSTKIM DLA POCZĄTKUJĄCYCH "ZIELONYCH" ŚWIETNA TRZYMAJ TAK DALEJ | | 8 grudnia 2002 | | --- | Uważam że jest to jedna z naklepszych stron o tworzeniu własnego www na świecie! | | 8 grudnia 2002 | | --- | nigdy sie nie wpisuje do ksiegi gosci bo uwazam to za strate czasu ale dla tej strony robie duuzyyy wyjatek. nareszcie cos normalnego. | | 8 grudnia 2002 | | --- | No, ja już Ci mówiłem co myśle o tej wspaniałej zresztą stronce... Sam wiesz, że możesz smiało oknkurować z kursem na helionie... Pozdro | | 30 listopada 2002 | | --- | Bardzo dobra strona Rzadko się takie spotyka - zgodnie z hasłem NAJWAŻNIEJSZ JEST TREŚĆ | | 29 listopada 2002 | | --- | uczymy sie htmla z twojej strony i dostaniemy 5tke dzieki! | | 24 listopada 2002 | | --- | NIEZLA Dzieki tej stronie zrobilam se bloga i nie powiem, tez niezly wyszedl! I za to, dla was calusne caluski! cmok, cmok! thx! | | 23 listopada 2002 | | --- | Naprawdę jedna z lepszych | | 22 listopada 2002 | | --- | Jest spoko. Uczylem się z wielu stron ale żadna nie dorównuje tej. | | 12 listopada 2002 | | --- | najlepszy kurs w sieci | | 8 listopada 2002 | | --- | Strona-super,genialna,najlepsza,hiperowa. | | 8 listopada 2002 | | --- | Ta strona jest super Jest na niej wszystko to co potrzeba do zrobienia własnej strony. Dzięki niej zrobiłem już sobie strone! Dzięki za wszystko! | | 6 listopada 2002 | | --- | dużo pracy cię kosztowała. Super | | 2 listopada 2002 | | --- | Genialna.... | | 1 listopada 2002 | | --- | strona jest po prostu genialna. | | 1 listopada 2002 | | --- | Dokładnie! Milion kursów HTML'a i co? I TEN JEST NAJLEPSZY Dziękuję naprawde dziekuje Zmienie strone, caly design i zapraszam! Buziaczki, bardzo jestem wdzieczna! | | 28 października 2002 | | --- | Szukałem wiele stron, ale ta jest najlepsza! Normalnie jestem trochę w szoku! Mam nadzieję, że niezadługo pokażę co stworzyłem hehe. Dzieki | | 16 października 2002 | | --- | Normalnie zadziabiasta extra przez nią nauczylam się HTML i mam już swoją strone gratuluje | | 8 października 2002 | | --- | strona jest fajna pod wzglenem "kursu dla zielonych" | | 7 października 2002 | | --- | Dobrze i przejrzyście zrobiona strona - polecę ją znajmomym | | 4 października 2002 | | --- | Strona jest fantastyczna GRATULUJĘ | | 2 października 2002 | | --- | naprawde swietna stronka, tresc zrozumiala, konkretna tak ze mozna wiele sie nauczyc | | 1 października 2002 | | --- | To ciekawe - zaraz zacznę się uczyć | | 26 września 2002 | | --- | jasno, przejrzyscie i dokladnie, po prostu super | | 24 września 2002 | | --- | przydała sie dzieki | | 23 września 2002 | | --- | nawet mi się przydała, a HTML dobrze znam (I think ) życzę szybkiego rozwijania się strony | | 19 września 2002 | | --- | Nareszcie jedna jedyna strona dzięki której wreszcie skumałam o co chodzi | | 16 września 2002 | | --- | logiczna, przydatna,udana | | 10 sierpnia 2002 | | --- | Świetny kurs! Wszystko (z tego co dotychczas przeczytałem) jest wytłumaczone w prosty i czytelny sposób no i do tego mnóstwo przykładów. | | 5 sierpnia 2002 | | --- | Jest super i dzięki niej dużo się nauczyłam! | | 1 sierpnia 2002 | | --- | Stonka jet ok. dużo się z niej nauczyłem i dzięki temu powstała strona www.ssj4.xu.pl | | 23 lipca 2002 | | --- | Jest spox. Może stworze własną strone internetową! | | 21 lipca 2002 | | --- | Super! Niedługo jak się naucze więcej, to stworze nareszcie własną stronkę | | 20 lipca 2002 | | --- | Jest po prostu genialna | | 19 lipca 2002 | | --- | Strona dobrze zrobiona, wiele przydatnych informacji Byle tak dalej! | | 5 lipca 2002 | | --- | Wyśmienity kurs | |
ember-font-awesome
npm
JavaScript
ember-font-awesome === An [ember-cli](http://www.ember-cli.com) addon for using [Font Awesome](http://fortawesome.github.io/Font-Awesome/) icons in Ember applications. **WARNING**: *Please verify that you are reading the README corresponding with the version of `ember-font-awesome` you are using.* Table of Contents --- * [Ember Version Compatibility](#ember-version-compatibility) * [Installing the Add-on](#installing-the-add-on) * [Using the Add-on](#using-the-add-on) * [Customize with Sass/Scss or Less](#customize-with-sassscss-or-less) * [Excluding assets](#excluding-assets) ### Ember Version Compatibility Please consult the table to check which version of `ember-font-awesome` you should use: | Addon version | Ember version | Addon name | | --- | --- | --- | | `>= 4.0.0`, `< 5.0.0` | `>= 2.10.0` | `ember-font-awesome` | | `>= 2.0.0`, `< 4.0.0` | `>= 2.3.0` | `ember-font-awesome` | | `>= 1.0.0`, `< 2.0.0` | `>= 1.11.0` | `ember-cli-font-awesome` | | `>= 0.1.0`, `< 1.0.0` | `>= 1.13.0` | `ember-cli-font-awesome` | | `0.0.9` | `< 1.11.0` | `ember-cli-font-awesome` | ### V4.0.0, important notes Version 4.0.0 of this addon introduces an entirely new approach in which the addon contains no components and has 0 runtime overhead. Instead, all usages of `{{fa-icon}}`, `{{fa-list}}` and `{{fa-stack}}` are transformed into the right markup in compile-time. To achieve this we had to make the component a bit more constrained so it can be compiled statically. There is a few (edge) cases that we had to drop to achieve that: * `{{fa-icon tagName=boundValue}}`. You cannot pass a bound value to the tag name (you still can pass a fixed value like `{{fa-icon tagName="span"}}`) * Previously both `{{fa-icon "credit-card"}}` and `{{fa-icon "fa-credit-card"}}` were valid invocations. Now only the first one is. You should not include the `fa-` prefix on the icon names. * Previously both `{{fa-icon size="2"}}` and `{{fa-icon size="2x"}}` were valid sizes. Now only the first one is, you cannot pass a string ending in `x`. * It requires a Glimmer2 version of Ember (2.10 or bigger) * **It requires node >= 6** (working on making it 4.5+ soon) * If you use this addon from within another addon, you have to move it from `devDependencies` to `dependencies` in your `package.json`. * If you want to ensure the AST transforms of this addon are not being cached, you can pass a `EMBER_CLI_FONT_AWESOME_DISABLE_CACHE=true` environment variable to `ember build` In return you get a an addon with 0 runtime overhead, that ships 0 bytes of javascript code and (optionally) removes the CSS of unused icons in production, yielding to even more saved bytes. **NOTE**: If your addon is using `ember-try` to test against versions of ember lower than 2.10, you will need to make some adjustments. * Specify `ember-font-awesome` as a `peerDependency` in your addon's `ember-try`, using the correct version number according to the table above. * Specify `null` as the value for `ember-font-awesome` in the `dependencies` key for that older version of ember under test, otherwise the test build will not use the version specified as a `peerDependency` ``` // config/ember-try.jsmodule.exports = {  scenarios: [    {      name: 'ember-lts-2.8',      bower: {        dependencies: {          'ember': 'components/ember#lts-2-8'        },        resolutions: {          'ember': 'lts-2-8'        }      },      npm: {        dependencies: {          'ember-font-awesome': null // <---        },        peerDependencies: {          'ember-font-awesome': '^3.0.0' // <---        },        devDependencies: {          'ember-source': null        }      }    },    ... // other scenarios  ]}; ``` ### Installing the Add-on In your application's directory: ``` $ ember install ember-font-awesome ``` ### Using the Add-on Use the component in your Handlebars templates: ``` {{fa-icon "camera"}} ``` This will render: ``` <i class="fa fa-camera"></i> ``` To see which icons are available please check the [complete list of Font Awesome icons](https://fontawesome.com/v4.7.0/icons/). *Note: We are currently [working hard to get to version 5](https://github.com/martndemus/ember-font-awesome/issues/143). Until then we don't support the [Font Awesome 5 icons](https://fontawesome.com/icons?d=gallery).* The [Font Awesome examples](http://fortawesome.github.io/Font-Awesome/examples/) illustrate the various options and their effects. It should be fairly simple to map these options to their `{{fa-icon}}` counterparts. 🆘 Looking for Help? --- * ⚠️ **Bug reports**: If your bug hasn't been reported yet, please [**open an issue**](https://github.com/martndemus/ember-font-awesome/issues/new). Try to pick a short but descriptive title. Make sure you're using the latest version of *ember-font-awesome*. In the issue body, try to provide exact steps for reproduction, ideally with example code. If you can't, please include any and all error messages, as many details as possible and exact information on which Ember.js / ember-cli version and browser / OS you're using. * **Slack**: We're happy to help you in our [**#e-font-awesome**](https://embercommunity.slack.com/messages/C6UMSLS74/) Slack channel! You can [create an Ember Community Slack account](https://ember-community-slackin.herokuapp.com/) here for free. #### Larger Icons ``` {{fa-icon "star" size="lg"}}{{fa-icon "star" size=2}}{{fa-icon "star" size=3}}{{fa-icon "star" size=4}}{{fa-icon "star" size=5}} ``` #### Fixed Width Icons ``` <div class="list-group">  <a class="list-group-item" href="#">    {{fa-icon "home" fixedWidth=true}} Home  </a>  <a class="list-group-item" href="#">    {{fa-icon "book" fixedWidth=true}} Library  </a></div> ``` #### List Icons ``` {{#fa-list as |l|}}  <li>{{l.fa-icon "check-square"}}List icons</li>  <li>{{l.fa-icon "check-square"}}can be used</li>  <li>{{l.fa-icon "spinner" spin=true}}as bullets</li>  <li>{{l.fa-icon "square"}}in lists</li>{{/fa-list}} ``` #### Bordered & Pulled Icons ``` <p>{{fa-icon "quote-left" pull="left" border=true}}...tomorrow we will run faster, stretch out our arms farther...And then one fine morning— So we beat on, boats against thecurrent, borne back ceaselessly into the past.</p> ``` #### Animated Icons ``` {{fa-icon "spinner" spin=true}}{{fa-icon "circle-o-notch" spin=true}}{{fa-icon "refresh" spin=true}}{{fa-icon "cog" spin=true}}{{fa-icon "spinner" pulse=true}} ``` #### Rotate & Flipped ``` {{fa-icon "shield"}} normal{{fa-icon "shield" rotate=90}} rotated 90 degrees{{fa-icon "shield" rotate=180}} rotated 180 degrees{{fa-icon "shield" rotate=270}} rotated 270 degrees{{fa-icon "shield" flip="horizontal"}} flipped horizontal{{fa-icon "shield" flip="vertical"}} flipped vertical ``` #### Stacked Icons ``` {{#fa-stack size="lg" as |s|}}  {{s.stack-2x "square-o"}}  {{s.stack-1x "twitter"}}{{/fa-stack}} {{#fa-stack size="lg" as |s|}}  {{s.stack-2x "circle"}}  {{s.stack-1x "flag" inverse=true}}{{/fa-stack}} {{#fa-stack size="lg" as |s|}}  {{s.stack-2x "square"}}  {{s.stack-1x "terminal" inverse=true}}{{/fa-stack}} {{#fa-stack size="lg" as |s|}}  {{s.stack-2x "square"}}  {{s.stack-1x "terminal" class="text-danger"}}{{/fa-stack}} ``` #### The `aria-hidden` Attribute To better support accessibility (i.e. screen readers), the helper adds the `aria-hidden` attribute by default: ``` {{fa-icon "star"}} ``` Results in: ``` <i class="fa fa-star" aria-hidden="true"></i> ``` To remove the `aria-hidden` attribute: ``` {{fa-icon "star" ariaHidden=false}} ``` #### The `aria-label` Attribute To better support accessibility (i.e. screen readers), the helper adds an optional `aria-label` attribute: ``` {{fa-icon "star" ariaLabel="Click Me"}} ``` Results in: ``` <i class="fa fa-star" aria-label="Click Me"></i> ``` #### Actions You can respond to actions on the icon by passing on action handlers: ``` {{fa-icon "star" click=(action "myClickHandler")}} ``` #### Tag Name Use `tagName` to control the generated markup: ``` {{fa-icon "star" tagName="span"}} ``` Results in: ``` <span class="fa fa-star"></span> ``` #### Custom Class Names ``` {{fa-icon "bicycle" class="my-custom-class"}} ``` Results in: ``` <i class="fa fa-bicycle my-custom-class"></i> ``` #### Title attribute ``` {{fa-icon "edit" title="Edit the item"}} ``` Results in: ``` <i class="fa fa-edit" title="Edit the item"></i> ``` ### Customize with Sass/Scss or Less If you are using the ember-cli-sass or ember-cli-less addon, you can opt-in to the Scss or Less version of font-awesome by adding the following configuration in `ember-cli-build.js`: ``` var app = new EmberApp({  'ember-font-awesome': {    useScss: true, // for ember-cli-sass    useLess: true  // for ember-cli-less  }}); ``` Then in your `app.scss` or `app.less`: ``` @import "font-awesome"; ``` ### Excluding assets You can configure the addon to *not* import any assets (CSS or font files) by adding the following configuration in `ember-cli-build.js`: ``` var app = new EmberApp({  'ember-font-awesome': {    includeFontAwesomeAssets: false  }}); ``` You can also configure the addon to *only* import specific font formats by adding the following configuration in `ember-cli-build.js`: **Default:** `['eot', 'svg', 'ttf', 'woff', 'woff2', 'otf']` ``` var app = new EmberApp({  'ember-font-awesome': {    fontFormats: ['woff', 'woff2']  }}); ``` In addition, you can configure the addon to exclude the font file assets entirely by adding the following configuration in `ember-cli-build.js`: ``` var app = new EmberApp({  'ember-font-awesome': {    includeFontFiles: false  }}); ``` ### Remove unused icons This addon includes an experimental functionality to detect the used icons and remove the ones you don't use. By default this feature is disabled, but you enabled when `environment` is `'production'` by doing: ``` var app = new EmberApp({  'ember-font-awesome': {    removeUnusedIcons: EmberApp.env() === 'production' // The addon will remove unused icons in production  }}); ``` ### Including specific icons By default this addon detects which icons are used based on the invocation parameters of `{{fa-icon}}`, and removes the rest, but you can whitelist in `ember-cli-build.js` some specific icons to be always included regardless of if they are used or not: ``` var app = new EmberApp({  'ember-font-awesome': {    includeStaticIcons: ['sort'],  }}); ``` ### Add a component for compatibility Since all invocations of `{{fa-icon}}` are transformed to HTML tags at compile time, there's no need for an actual `{{fa-icon}}` component. Except for one edge case: Passing a component invoked via the `{{component}}` helper. ``` {{async-button  label="Submit"  icon=(component "fa-icon" "check")}} {{!-- or just --}} {{component "fa-icon" "rocket"}} ``` In your `ember-cli-build.js` you can enable the `includeComponent` option to include an `{{fa-icon}}` component for exactly that use case. You will still benefit from all compile time optimizations, however we'll add a bit of additional JS to your asset bundle size. ``` var app = new EmberApp({  'ember-font-awesome': {    includeComponent: true  }}); ``` ### Output path You can change the directory where the fonts are copied to using the following configuration: ``` var app = new EmberApp({  'ember-font-awesome': {    fontsOutput: "/some/dir/"  }}); ``` This is useful when you change the output paths for your ember app. By default, ember-font-awesome copies the font files to `/dist/fonts`. The addon produces a css file to load the fonts that will be included in the vendor css file and expect to find the fonts at `../fonts`. If the css directory is not at the same level as the fonts directory, the site won't load the fonts. For example, moving the css directory to `/dist/assets/css` would require the fonts directory to be `/dist/assets/fonts` and the configuration would look like this: ``` var app = new EmberApp({    outputPaths: {        app: {            css: {                  app: "/assets/css/app-name.css",            },            js: "/assets/js/app-name.js",        },         vendor: {            css: "/assets/css/vendor.css",            js: "/assets/js/vendor.js",        },    },    'ember-font-awesome': {        fontsOutput: "/assets/fonts"    }}); ``` License --- [Public Domain](https://github.com/martndemus/ember-font-awesome/blob/HEAD/UNLICENSE) Readme --- ### Keywords * ember-addon
dfcomb
cran
R
Package ‘dfcomb’ January 7, 2023 Type Package Title Phase I/II Adaptive Dose-Finding Design for Combination Studies Version 3.1-1 Date 2022-12-26 Author <NAME> and <NAME> Maintainer <NAME> <<EMAIL>> Copyright src/arms.c and src/arms.h are copyright Wally Gilks. All other files are copyright Sanofi-Aventis R&D, Institut de Recherches Internationales Servier and Institut national de la sante et de la recherche medicale. Description Phase I/II adaptive dose-finding design for combination studies where toxicity rates are supposed to increase with both agents. License GPL-3 Depends R (>= 3.2.3) LinkingTo BH (>= 1.55), Rcpp, RcppProgress (>= 0.2.1) NeedsCompilation yes Repository CRAN Date/Publication 2023-01-07 14:20:09 UTC R topics documented: dfcomb-packag... 2 CombIncrease_nex... 3 CombIncrease_si... 6 dfcomb-package Phase I/II Adaptive Dose-Finding Design for Combination Studies Description Phase I/II adaptive dose-finding design for combination studies where toxicity rates are supposed to increase with both agents. Details The DESCRIPTION file: Package: dfcomb Type: Package Title: Phase I/II Adaptive Dose-Finding Design for Combination Studies Version: 3.1-1 Date: 2022-12-26 Author: <NAME> and <NAME> Maintainer: <NAME> <<EMAIL>> Copyright: src/arms.c and src/arms.h are copyright Wally Gilks. All other files are copyright Sanofi-Aventis R&D, Description: Phase I/II adaptive dose-finding design for combination studies where toxicity rates are supposed to incr License: GPL-3 Depends: R (>= 3.2.3) LinkingTo: BH (>= 1.55), Rcpp, RcppProgress (>= 0.2.1) NeedsCompilation: yes Index of help topics: CombIncrease_next Combination determination with logistic model CombIncrease_sim Combination design Simulator using Logistic model dfcomb-package Phase I/II Adaptive Dose-Finding Design for Combination Studies Author(s) <NAME> and <NAME> Maintainer: <NAME> <<EMAIL>> References <NAME>, <NAME>, <NAME>, <NAME> (2014). A Bayesian dose-finding design for drug combina- tion clinical trials based on the logistic model. Pharm Stat, 13, 4:247-57. CombIncrease_next Combination determination with logistic model Description CombIncrease_next is used to determine the next or recommended combination in a phase I com- bination clinical trial using the design proposed by Riviere et al. entitled "A Bayesian dose-finding design for drug combination clinical trials based on the logistic model". Usage CombIncrease_next(ndose_a1, ndose_a2, target, target_min, target_max, prior_tox_a1, prior_tox_a2, cohort, final, pat_incl, dose_adm1, dose_adm2, tite=FALSE, toxicity, time_full=0, time_tox=0, time_follow=0, c_e=0.85, c_d=0.45, c_stop=0.95, c_t=0.5, c_over=0.25, cmin_overunder=2, cmin_mtd=3, cmin_recom=1, early_stop=1, alloc_rule=1, nburn=2000, niter=5000) Arguments ndose_a1 Number of dose levels for agent 1. ndose_a2 Number of dose levels for agent 2. target Toxicity (probability) target. target_min Minimum of the targeted toxicity interval. target_max Maximum of the targeted toxicity interval. prior_tox_a1 A vector of initial guesses of toxicity probabilities associated with the doses of agent 1. Must be of length ndose_a1. prior_tox_a2 A vector of initial guesses of toxicity probabilities associated with the doses of agent 2. Must be of length ndose_a2. cohort Cohort size. final A boolean with value TRUE if the trial is finished and the recommended com- bination for further phases should be given, or FALSE (default value) if the combination determination is performed for the next cohort of patients. pat_incl Current number of patients included. dose_adm1 A vector indicating the dose levels of agents 1 administered to each patient in- cluded in the trial. Must be of length pat_incl. dose_adm2 A vector indicating the dose levels of agents 2 administered to each patient in- cluded in the trial. Must be of length pat_incl. tite A boolean indicating if the toxicity is considered as a time-to-event outcome (TRUE), or as a binary outcome (default value FALSE). toxicity A vector of observed toxicities (DLTs) for each patient included in the trial. Must be of length pat_incl. This argument is used/required only if tite=FALSE. time_full Full follow-up time window. This argument is used only if tite=TRUE. time_tox A vector of times-to-toxicity for each patient included in the trial. If no toxicity was observed for a patient, must be filled with +Inf. Must be of length pat_incl. This argument is used/required only if tite=TRUE. time_follow A vector of follow-up times for each patient included in the trial. Must be of length pat_incl. This argument is used/required only if tite=TRUE. c_e Probability threshold for dose-escalation. The default value is set at 0.85. c_d Probability threshold for dose-deescalation. The default value is set at 0.45. c_stop Probability threshold for early trial termination. The default value is set at 0.95. c_t Probability threshold for early trial termination for finding the MTD (see de- tails). The default value is set at 0.5. c_over Probability threshold to control over-dosing (see details). cmin_overunder Minimum number of cohorts to be included at the lowest/highest combination before possible early trial termination for over-toxicity or under-toxicity (see details). The default value is set at 2. cmin_mtd Minimum number of cohorts to be included at the recommended combination before possible early trial termination for finding the MTD (see details). The default value is set at 3. cmin_recom Minimum number of cohorts to be included at the recommended combination at the end of the trial. The default value is set at 1. alloc_rule Interger (1, 2, or 3) indicating which allocation rule is used (see details). The default value is set at 1. early_stop Interger (1, 2, or 3) indicating which early stopping rule is used (see details). The default value is set at 1. nburn Number of burn-in for HMC. The default value is set at 2000. niter Number of iterations for HMC. The default value is set at 5000. Details Allocation rule: • alloc_rule=1 (Riviere et al 2014): If P(toxicity probability at combination (i,j) < target) > c_e: among combinations in the neighborhood (-1, +1), (0, +1), (+1, 0), (+1, -1), choose the combination with a higher estimated toxicity probability than the current combination and with the estimated toxicity probability closest to target. If P(toxicity probability at combi- nation (i,j) > target) > 1-c_d: among neighborhood (-1, +1), (-1, 0), (0, -1), (+1, -1), choose the combination with a lower estimated toxicity probability than the current combination and with the estimated toxicity probability closest to target. Otherwise, remain on the same combination. • alloc_rule=2: Among combinations already tested and combinations in the neighborhood (-1, 0), (-1, +1), (0, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1) of a combination tested, choose the combination with the highest posterior probability to be in the targeted interval [target_min, target_max] while controling overdosing i.e. P(toxicity probability at combination (i,j) > target_max) < c_over. • alloc_rule=3: Among combinations in the neighborhood (-1, 0), (-1, +1), (0, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1) of the current combination, choose the combination with the highest posterior probability to be in the targeted interval [target_min, target_max] while controling overdosing i.e. P(toxicity probability at combination (i,j) > target_max) < c_over. Early stopping for over-dosing: If the current combination is the lowest (1, 1) and at least cmin_overunder cohorts have been included at that combination and P(toxicity probability at combination (i,j) > target) >= c_stop then stop the trial and do not recommend any combination. Early stopping for under-dosing: If the current combination is the highest and at least cmin_overunder cohorts have been included at that combination and P(toxicity probability at combination (i,j) < target) >= c_stop then stop the trial and do not recommend any combination. Early stopping for identifying the MTD: • early_stop=1 (Riviere et al 2014): No stopping rule, include patients until maximum sample size is reached. • early_stop=2: If the next recommended combination has been tested on at least cmin_mtd cohorts and has a posterior probability to be in the targeted interval [target_min, target_max] that is >= c_t and also control overdosing i.e. P(toxicity probability at current combination > target_max) < c_over then stop the trial and recommend this combination. • early_stop=3: If at least cmin_mtd cohorts have been included at the next recommended combination then stop the trial and recommend this combination. Stopping at the maximum sample size: If the maximum sample size is reached and no stopping rule is met, then the recommended combination is the one that was tested on at least cmin_recom cohorts and with the highest posterior probability to be in the targeted interval [target_min, target_max]. Value An object of class "CombIncrease_next" is returned, consisting of determination of the next com- bination and estimations. Objects generated by CombIncrease_next contain at least the following components: n_pat_comb Number of patients per combination. n_tox_comb Number of observed toxicities per combination. pi Estimated toxicity probabilities (if the start-up ended). ptox_inf Estimated probabilities that the toxicity probability is inferior to target (if the start-up ended). ptox_inf_targ Estimated probabilities of underdosing, i.e. to be inferior to target_min (if the start-up ended). ptox_targ Estimated probabilities to be in the targeted interval [target_min,target_max] (if the start-up ended). ptox_sup_targ Estimated probabilities of overdosing, i.e. to be superior to target_max (if the start-up ended). (cdose1, cdose2) NEXT RECOMMENDED COMBINATION. inconc Boolean indicating if trial must stop for under/over dosing. early_conc Boolean indicating if trial can be stopped earlier for finding the MTD. Author(s) Jacques-<NAME> and <NAME> <<EMAIL>> References <NAME>., <NAME>., <NAME>., and <NAME>. (2014). A Bayesian dose-finding design for drug combination clinical trials based on the logistic model. Pharmaceutical Statistics. See Also CombIncrease_sim. Examples prior_a1 = c(0.12, 0.2, 0.3, 0.4, 0.5) prior_a2 = c(0.2, 0.3, 0.4) toxicity1 = c(0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1) dose1 = c(1,1,1,2,2,2,3,3,3,3,3,3,3,3,3,4,4,4) dose2 = c(1,1,1,2,2,2,3,3,3,2,2,2,1,1,1,1,1,1) t_tox = c(rep(+Inf,8),2.9,+Inf,4.6,+Inf,+Inf,+Inf,+Inf,+Inf,+Inf,5.2) follow = c(rep(6,15), 4.9, 3.1, 1.3) next1 = CombIncrease_next(ndose_a1=5, ndose_a2=3, target=0.3, target_min=0.2, target_max=0.4, prior_tox_a1=prior_a1, prior_tox_a2=prior_a2, cohort=3, final=FALSE, pat_incl=18, dose_adm1=dose1, dose_adm2=dose2, toxicity=toxicity1, c_over=1, cmin_overunder=3, cmin_recom=1, early_stop=1, alloc_rule=1) next1 next2 = CombIncrease_next(ndose_a1=5, ndose_a2=3, target=0.3, target_min=0.2, target_max=0.4, prior_tox_a1=prior_a1, prior_tox_a2=prior_a2, cohort=3, final=FALSE, pat_incl=18, dose_adm1=dose1, dose_adm2=dose2, tite=TRUE, time_full=6, time_tox=t_tox, time_follow=follow, c_over=1, cmin_overunder=3, cmin_recom=1, early_stop=1, alloc_rule=1) next2 CombIncrease_sim Combination design Simulator using Logistic model Description CombIncrease_sim is used to generate simulation replicates of phase I clinical trial for combination studies where the toxicity and efficacy of both agents is assumed to increase with the dose using the design proposed by Riviere et al. entitled "A Bayesian dose-finding design for drug combination clinical trials based on the logistic model". Usage CombIncrease_sim(ndose_a1, ndose_a2, p_tox, target, target_min, target_max, prior_tox_a1, prior_tox_a2, n_cohort, cohort, tite=FALSE, time_full=0, poisson_rate=0, nsim, c_e=0.85, c_d=0.45, c_stop=0.95, c_t=0.5, c_over=0.25, cmin_overunder=2, cmin_mtd=3, cmin_recom=1, startup=1, alloc_rule=1, early_stop=1, init_dose_1=1, init_dose_2=1, nburn=2000, niter=5000, seed=14061991) Arguments ndose_a1 Number of dose levels for agent 1. ndose_a2 Number of dose levels for agent 2. p_tox A matrix of the true toxicity probabilities associated with the combinations. True toxicity probabilities should be entered with agent 1 in row and agent 2 in col- umn, with increasing toxicity probabilities with both row and column numbers (see examples). target Toxicity (probability) target. target_min Minimum of the targeted toxicity interval. target_max Maximum of the targeted toxicity interval. prior_tox_a1 A vector of initial guesses of toxicity probabilities associated with the doses of agent 1. Must be of length ndose_a1. prior_tox_a2 A vector of initial guesses of toxicity probabilities associated with the doses of agent 2. Must be of length ndose_a2. n_cohort Total number of cohorts to include in the trial. cohort Cohort size. tite A boolean indicating if the toxicity is considered as a time-to-event outcome (TRUE), or as a binary outcome (default value FALSE). time_full Full follow-up time window. This argument is used only if tite=TRUE. poisson_rate A value indicating the rate for the Poisson process used to simulate patient ar- rival, i.e. expected number of arrivals per observation window. This argument is used only if tite=TRUE. nsim Number of simulations. c_e Probability threshold for dose-escalation. The default value is set at 0.85. c_d Probability threshold for dose-deescalation. The default value is set at 0.45. c_stop Probability threshold for early trial termination due to over-toxicity or under- toxicity (see details). The default value is set at 0.95. c_t Probability threshold for early trial termination for finding the MTD (see de- tails). The default value is set at 0.5. c_over Probability threshold to control over-dosing (see details). cmin_overunder Minimum number of cohorts to be included at the lowest/highest combination before possible early trial termination for over-toxicity or under-toxicity (see details). The default value is set at 2. cmin_mtd Minimum number of cohorts to be included at the recommended combination before possible early trial termination for finding the MTD (see details). The default value is set at 3. cmin_recom Minimum number of cohorts to be included at the recommended combination at the end of the trial. The default value is set at 1. startup Interger (0, 1, 2, or 3) indicating which start-up phase is used (see details). The default value is set at 1. alloc_rule Interger (1, 2, or 3) indicating which allocation rule is used (see details). The default value is set at 1. early_stop Interger (1, 2, or 3) indicating which early stopping rule is used (see details). The default value is set at 1. init_dose_1 Initial dose for agent 1. The default is 1. init_dose_2 Initial dose for agent 2. The default is 1. nburn Number of burn-in for HMC. The default value is set at 2000. niter Number of iterations for HMC. The default value is set at 5000. seed Seed of the random number generator. Default value is set at 14061991. Details Start-up phase: • startup=0: No startup phase: the first tested combination is forced to be the initial combina- tion. The following ones use the normal allocation rule.. • startup=1 (Riviere et al 2014): Begin at the initial combination and increase both agent (+1, +1) until the first toxicity is observed or maximum combination is reached. • startup=2: Begin at the initial combination and increase agent 1 (+1, 0) until a toxicity is observed or maximum dose is reached. Then begin at (init_dose1,init_dose2+1) and increase agent 2 (0, +1) until a toxicity is observed or maximum dose is reached. • startup=3: Begin at the initial combination and increase alternatively each agent (+1, 0) then (0, +1) until the first toxicity is observed or maximum combination is reached. Allocation rule: • alloc_rule=1 (Riviere et al 2014): If P(toxicity probability at combination (i,j) < target) > c_e: among combinations in the neighborhood (-1, +1), (0, +1), (+1, 0), (+1, -1), choose the combination with a higher estimated toxicity probability than the current combination and with the estimated toxicity probability closest to target. If P(toxicity probability at combi- nation (i,j) > target) > 1-c_d: among neighborhood (-1, +1), (-1, 0), (0, -1), (+1, -1), choose the combination with a lower estimated toxicity probability than the current combination and with the estimated toxicity probability closest to target. Otherwise, remain on the same combination. • alloc_rule=2: Among combinations already tested and combinations in the neighborhood (-1, 0), (-1, +1), (0, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1) of a combination tested, choose the combination with the highest posterior probability to be in the targeted interval [target_min, target_max] while controling overdosing i.e. P(toxicity probability at combination (i,j) > target_max) < c_over. • alloc_rule=3: Among combinations in the neighborhood (-1, 0), (-1, +1), (0, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1) of the current combination, choose the combination with the highest posterior probability to be in the targeted interval [target_min, target_max] while controling overdosing i.e. P(toxicity probability at combination (i,j) > target_max) < c_over. Early stopping for over-dosing: If the current combination is the lowest (1, 1) and at least cmin_overunder cohorts have been included at that combination and P(toxicity probability at combination (i,j) > target) >= c_stop then stop the trial and do not recommend any combination. Early stopping for under-dosing: If the current combination is the highest and at least cmin_overunder cohorts have been included at that combination and P(toxicity probability at combination (i,j) < target) >= c_stop then stop the trial and do not recommend any combination. Early stopping for identifying the MTD: • early_stop=1 (Riviere et al 2014): No stopping rule, include patients until maximum sample size is reached. • early_stop=2: If the next recommended combination has been tested on at least cmin_mtd cohorts and has a posterior probability to be in the targeted interval [target_min, target_max] that is >= c_t and also control overdosing i.e. P(toxicity probability at current combination > target_max) < c_over then stop the trial and recommend this combination. • early_stop=3: If at least cmin_mtd cohorts have been included at the next recommended combination then stop the trial and recommend this combination. Stopping at the maximum sample size: If the maximum sample size is reached and no stopping rule is met, then the recommended combination is the one that was tested on at least cmin_recom cohorts and with the highest posterior probability to be in the targeted interval [target_min, target_max]. Value An object of class "CombIncrease_sim" is returned, consisting of the operating characteristics of the design specified. Objects generated by CombIncrease_sim contain at least the following com- ponents: rec_dose Percentage of combination selection. n_pat_dose Mean number of patients at each combination. n_tox_dose Mean number of toxicities at each combination. inconc Percentage of inclusive trials. early_conc Percentage of trials stopping with criterion for finding MTD. nsim Number of simulations (if function stopped while executed, return the current number of simulations performed with associated other outputs). pat_tot Total mean number of patients accrued. tab_pat Vector with the number of patients included for each simulation. Author(s) <NAME> and <NAME> <<EMAIL>> References <NAME>., <NAME>., <NAME>., and <NAME>. (2014). A Bayesian dose-finding design for drug combination clinical trials based on the logistic model. Pharmaceutical Statistics. See Also CombIncrease_next. Examples p_tox_sc1 = matrix(c(0.05,0.10,0.15,0.30,0.45, 0.10,0.15,0.30,0.45,0.55, 0.15,0.30,0.45,0.50,0.60),nrow=5,ncol=3) prior_a1 = c(0.12, 0.2, 0.3, 0.4, 0.5) prior_a2 = c(0.2, 0.3, 0.4) sim1 = CombIncrease_sim(ndose_a1=5, ndose_a2=3, p_tox=p_tox_sc1, target=0.30, target_min=0.20, target_max=0.40, prior_tox_a1=prior_a1, prior_tox_a2=prior_a2, n_cohort=20, cohort=3, tite=FALSE, nsim=2000, c_over=1, cmin_overunder=3, cmin_recom=1, startup=1, alloc_rule=1, early_stop=1, seed=14061991) sim1 # Dummy example, running quickly useless = CombIncrease_sim(ndose_a1=3, ndose_a2=2, p_tox=matrix(c(0.05,0.15,0.30,0.15,0.30,0.45),nrow=3), target=0.30, target_min=0.20, target_max=0.40, prior_tox_a1=c(0.2,0.3,0.4), prior_tox_a2=c(0.2,0.3), n_cohort=2, cohort=2, nsim=1)
django-viewflow
readthedoc
Python
django-viewflow documentation ### Navigation * [django-viewflow documentation](index.html#document-index) » django-viewflow[¶](#django-viewflow) === Ad-hoc business process automation framework for Django. The process logic defined with django-viewflow is concentrated in one clearly defined flow. You can organize your views, background jobs, user permission checking in a simple, intuitive django-friendly way. Contents[¶](#contents) --- ### Introduction[¶](#introduction) #### Installation[¶](#installation) django-viewflow requires Python 3.3 or greater and django 1.7: ``` pip install django-viewflow ``` And add it into INSTALLED_APPS settings ``` INSTALLED_APPS = ( ... 'viewflow', 'viewflow.site' ) ``` ### Core concepts[¶](#core-concepts) #### Flow and Flow Tasks[¶](#flow-and-flow-tasks) django-viewflow introduces Flow classes as the single place to configure and setup task, dependenices, persistance, user rights checking and interface setup. Each flow should be subclass of [`viewflow.base.Flow`](#viewflow.base.Flow). *class* `viewflow.base.``Flow`[¶](#viewflow.base.Flow) Base class for flow definition | Parameters: | * **process_cls** – Defines model class for Process * **task_cls** – Defines model class for Task * **management_form_cls** – Defines form class for task state tracking over GET requests * **lock_impl** – Locking implementation for flow | `urls`[¶](#viewflow.base.Flow.urls) Provides ready to include urlpatterns required for this flow Each flow could contains several flow tasks. Flow task represents declaration of what should be performed on this step, and what next steps should be activated. Flow does not have specific declaration of task transitions, and all logic of task activation belongs to the task itself. This makes Flow code close to well-known BPMN notation, and helps to convert it to BPMN and vise versa. Flow class should have at least one of [`viewflow.flow.Start`](index.html#viewflow.flow.Start) task and at least one of [`viewflow.flow.End`](index.html#viewflow.flow.End) *class* `viewflow.flow.``Node`(*activation_cls=None*, ***kwargs*)[¶](#viewflow.flow.Node) Base class for flow task | Parameters: | * **task_type** – Human readable task type * **activation_cls** – Activation implementation specific for this node | `activate`(*prev_activation*, *token*)[¶](#viewflow.flow.Node.activate) Creates task activation See [*Flow Tasks*](index.html#document-flow_tasks) documentation for list of all available tasks. #### Activation[¶](#activation) *class* `viewflow.activation.``Activation`(**args*, ***kwargs*)[¶](#viewflow.activation.Activation) Base class for flow task activations. Activation responsible for flow task state management and persistance Each activation status chages restricted by a simple finite state automata Base class enshures that all tasks could be undone or cancelled. *classmethod* `activate`(*flow_task*, *prev_activation*, *token*)[¶](#viewflow.activation.Activation.activate) Instantiate and persist new flow task. #### Models[¶](#models) django-viewflow provides base model for tracking the process state. In most cases you should subclass [`viewflow.models.Process`](#viewflow.models.Process) to add additional data fields. In case if you need to track some execution info or add logging, you can do it by extending [`viewflow.models.Task`](#viewflow.models.Task) *class* `viewflow.models.``Task`(*id*, *flow_task*, *flow_task_type*, *status*, *created*, *started*, *finished*, *token*, *process*, *owner*, *external_task_id*, *owner_permission*, *comments*)[¶](#viewflow.models.Task) *class* `viewflow.models.``Process`(*id*, *flow_cls*, *status*, *created*, *finished*)[¶](#viewflow.models.Process) #### Views[¶](#views) #### Urls[¶](#urls) [`viewflow.base.Flow`](#viewflow.base.Flow) collects all urls required by View tasks, you just have to include it in urlpatters ``` urlpatterns = patterns('', url(r'^myflow/', include(MyFlow.instance.urls))) ``` ### Flow tasks[¶](#flow-tasks) #### Start[¶](#start) *class* `viewflow.flow.``Start`(**args*, ***kwargs*)[¶](#viewflow.flow.Start) Start process event Example: ``` start = flow.Start(StartView, fields=["some_process_field"]) \ .Available(lambda user: user.is_super_user) \ .Activate(this.first_start) ``` In case of function based view: ``` start = flow.Start(start_process) @flow_start_view() def start_process(request, activation): if not activation.has_perm(request.user): raise PermissionDenied activation.prepare(request.POST or None) form = SomeForm(request.POST or None) if form.is_valid(): form.save() activation.done() return redirect('/') return render(request, {'activation': activation, 'form': form}) ``` Ensure to include {{ activation.management_form }} inside template, to proper track when task was started and other task performance statistics: ``` <form method="POST"> {{ form }} {{ activation.management_form }} <button type="submit"/> </form> ``` `Available`(*owner=None*, ***owner_kwargs*)[¶](#viewflow.flow.Start.Available) Make process start action available for the User accepts user lookup kwargs or callable predicate :: User -> bool: ``` .Available(username='employee') .Available(lambda user: user.is_super_user) ``` `Permission`(*permission=None*, *auto_create=False*, *obj=None*, *help_text=None*)[¶](#viewflow.flow.Start.Permission) Make task available for users with specific permission, aceps permissions name of callable :: Process -> permission_name: ``` .Permission('my_app.can_approve') .Permission(lambda process: 'my_app.department_manager_{}'.format(process.depratment.pk)) ``` Task specific permission could be auto created during migration: ``` # Creates `processcls_app.can_do_task_processcls` permission do_task = View().Permission(auto_create=True) # You can specify permission codename and description right here # The following creates `processcls_app.can_execure_task` permission do_task = View().Permission('can_execute_task', help_text='Custom text', auto_create=True) ``` #### View[¶](#view) View task represents user task performed by interaction with django view. *class* `viewflow.flow.``View`(**args*, ***kwargs*)[¶](#viewflow.flow.View) View task Example: ``` task = flow.View(some_view) \ .Permission('my_app.can_do_task') \ .Next(this.next_task) ``` In case of function based view: ``` task = flow.Task(task) @flow_start_view() def task(request, activation): if not activation.flow_task.has_perm(request.user): raise PermissionDenied activation.prepare(request.POST or None) form = SomeForm(request.POST or None) if form.is_valid(): form.save() activation.done() return redirect('/') return render(request, {'activation': activation, 'form': form}) ``` Ensure to include {{ activation.management_form }} inside template, to proper track when task was started and other task performance statistics: ``` <form method="POST"> {{ form }} {{ activation.management_form }} <button type="submit"/> </form> ``` `Assign`(*owner=None*, ***owner_kwargs*)[¶](#viewflow.flow.View.Assign) Assign task to the User immediately on activation, accepts user lookup kwargs or callable :: Process -> User: ``` .Assign(username='employee') .Assign(lambda process: process.created_by) ``` `Permission`(*permission=None*, *auto_create=False*, *obj=None*, *help_text=None*)[¶](#viewflow.flow.View.Permission) Make task available for users with specific permission, aceps permissions name of callable :: Process -> permission_name: ``` .Permission('my_app.can_approve') .Permission(lambda process: 'my_app.department_manager_{}'.format(process.depratment.pk)) ``` Task specific permission could be auto created during migration: ``` # Creates `processcls_app.can_do_task_processcls` permission do_task = View().Permission(auto_create=True) # You can specify permission codename and description right here # The following creates `processcls_app.can_execure_task` permission do_task = View().Permission('can_execute_task', help_text='Custom text', auto_create=True) ``` `viewflow.flow.``flow_view`(***lock_args*)[¶](#viewflow.flow.flow_view) Decorator that locks and runs the flow view in transaction. Expects view with the signature (request, activation, **kwargs) or CBV view that implements TaskActivation, in this case, dispatch with would be called with (request, **kwargs) Returns (request, flow_task, process_pk, task_pk, **kwargs) Views decorated with flow_view decorator executed in transaction. If an error happens in view or during nexttask activation, database rollback will be performed and no changes will be stored. #### Job[¶](#job) Job task represents user task performed in background by celery `viewflow.flow.``flow_job`(***lock_args*)[¶](#viewflow.flow.flow_job) Decorator that prepares celery task for execution Makes celery job function with the following signature (flow_task-strref, process_pk, task_pk, **kwargs) Expects actual celery job function which has the following signature (activation, **kwargs) If celery task class implements activation interface, job function is called without activation instance (**kwargs) Process instance is locked only before and after the function execution. Please avoid any process state modification during the celery job. If any error will happens during job execution task would be moved to error state, and available for administrator desision in admin interface. If error will happens on next task ativation, for example, error raised on If conditions, job task will be commited and marked as done, but the failed for activation task would be created in error state. #### If[¶](#if) *class* `viewflow.flow.``If`(*cond*)[¶](#viewflow.flow.If) Activates one of paths based on condition Example: ``` check_decision = flow.If(lambda p: p.approved) \ .OnTrue(this.approved) \ .OnFalse(this.end) ``` #### Switch[¶](#switch) *class* `viewflow.flow.``Switch`[¶](#viewflow.flow.Switch) Activates first path with matched condition #### Split[¶](#split) *class* `viewflow.flow.``Split`[¶](#viewflow.flow.Split) Activates outgoing path in-parallel depends on per-path condition. Example: ``` split_on_decision = flow.Split() \ .Next(check_post, cond=lambda p: p,is_check_post_required) \ .Next(this.perform_task_always) ``` #### Join[¶](#join) *class* `viewflow.flow.``Join`(*wait_all=True*)[¶](#viewflow.flow.Join) Waits for one or all incoming links and activates next path. Join should be connected to one split task only Example: ``` join_on_warehouse = self.Join() \ .Next(this.next_task) ``` #### End[¶](#end) *class* `viewflow.flow.``End`[¶](#viewflow.flow.End) Ends process event. ### Locking[¶](#locking) To avoid raise conditions on update [`viewflow.flow.flow_view()`](index.html#viewflow.flow.flow_view) and [`viewflow.flow.flow_job()`](index.html#viewflow.flow.flow_job) decoratos grabs process-instance wide locks and instansiate database transaction. You could specify selected lock implementation in :attr:lock_impl of [`viewflow.base.Flow`](index.html#viewflow.base.Flow) class `viewflow.lock.``no_lock`(*flow*)[¶](#viewflow.lock.no_lock) No pessimistic locking, just execute flow task in transaction. Not suitable when you have Join nodes in your flow. `viewflow.lock.``select_for_update_lock`(*flow*, *nowait=True*, *attempts=5*)[¶](#viewflow.lock.select_for_update_lock) Uses select ... for update on process instance row for locking, bound to database transaction. Recommended for use with PostgreSQL. `viewflow.lock.``cache_lock`(*flow*, *attempts=5*, *expires=120*)[¶](#viewflow.lock.cache_lock) Use it if primary cache backend has transactional add functionality, like memcached. ### Administration[¶](#administration) *class* `viewflow.admin.``ProcessAdmin`(*model*, *admin_site*)[¶](#viewflow.admin.ProcessAdmin) List all of viewflow process *class* `viewflow.admin.``TaskAdmin`(*model*, *admin_site*)[¶](#viewflow.admin.TaskAdmin) List all of viewflow tasks ### Examples[¶](#examples) #### Hello, world[¶](#hello-world) This example demostrate basic flow construction #### Shipment[¶](#shipment) Standard BPMN example Shipment Process automated in hundred lines License[¶](#license) --- [The GNU Affero General Public License v3.0](http://www.gnu.org/licenses/agpl-3.0.html) ### [Table Of Contents](index.html#document-index) * [Introduction](index.html#document-introduction) + [Installation](index.html#installation) * [Core concepts](index.html#document-core_concepts) + [Flow and Flow Tasks](index.html#flow-and-flow-tasks) + [Activation](index.html#activation) + [Models](index.html#models) + [Views](index.html#views) + [Urls](index.html#urls) * [Flow tasks](index.html#document-flow_tasks) + [Start](index.html#start) + [View](index.html#view) + [Job](index.html#job) + [If](index.html#if) + [Switch](index.html#switch) + [Split](index.html#split) + [Join](index.html#join) + [End](index.html#end) * [Locking](index.html#document-locking) * [Administration](index.html#document-administration) * [Examples](index.html#document-examples) + [Hello, world](index.html#hello-world) + [Shipment](index.html#shipment) ### Quick search Enter search terms or a module, class or function name. ### Navigation * [django-viewflow documentation](index.html#document-index) »
pmhtutorial
cran
R
Package ‘pmhtutorial’ October 14, 2022 Type Package Title Minimal Working Examples for Particle Metropolis-Hastings Version 1.5 Author <NAME> Maintainer <NAME> <<EMAIL>> URL https://github.com/compops/pmh-tutorial-rpkg Description Routines for state estimate in a linear Gaussian state space model and a simple stochastic volatility model using particle filtering. Parameter inference is also carried out in these models using the particle Metropolis-Hastings algorithm that includes the particle filter to provided an unbiased estimator of the likelihood. This package is a collection of minimal working examples of these algorithms and is only meant for educational use and as a start for learning to them on your own. Depends R (>= 3.2.3) License GPL-2 Imports mvtnorm, Quandl, grDevices, graphics, stats Encoding UTF-8 LazyData true RoxygenNote 6.1.1 NeedsCompilation no Repository CRAN Date/Publication 2019-03-22 18:10:03 UTC R topics documented: example1_lgs... 2 example2_lgs... 3 example3_s... 4 example4_s... 6 example5_s... 7 generateDat... 9 kalmanFilte... 10 makePlotsParticleMetropolisHastingsSVMode... 11 particleFilte... 12 particleFilterSVmode... 13 particleMetropolisHasting... 14 particleMetropolisHastingsSVmode... 16 particleMetropolisHastingsSVmodelReparameterise... 17 example1_lgss State estimation in a linear Gaussian state space model Description Minimal working example of state estimation in a linear Gaussian state space model using Kalman filtering and a fully-adapted particle filter. The code estimates the bias and mean squared error (compared with the Kalman estimate) while varying the number of particles in the particle filter. Usage example1_lgss() Details The Kalman filter is a standard implementation without an input. The particle filter is fully adapted (i.e. takes the current observation into account when proposing new particles and computing the weights). Value Returns a plot with the generated observations y and the difference in the state estimates obtained by the Kalman filter (the optimal solution) and the particle filter (with 20 particles). Furthermore, the function returns plots of the estimated bias and mean squared error of the state estimate obtained using the particle filter (while varying the number of particles) and the Kalman estimates. The function returns a list with the elements: • y: The observations generated from the model. • x: The states generated from the model. • kfEstimate: The estimate of the state from the Kalman filter. • pfEstimate: The estimate of the state from the particle filter with 20 particles. Note See Section 3.2 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples example1_lgss() example2_lgss Parameter estimation in a linear Gaussian state space model Description Minimal working example of parameter estimation in a linear Gaussian state space model using the particle Metropolis-Hastings algorithm with a fully-adapted particle filter providing an unbiased estimator of the likelihood. The code estimates the parameter posterior for one parameter using simulated data. Usage example2_lgss(noBurnInIterations = 1000, noIterations = 5000, noParticles = 100, initialPhi = 0.5) Arguments noBurnInIterations The number of burn-in iterations in the PMH algorithm. This parameter must be smaller than noIterations. noIterations The number of iterations in the PMH algorithm. 100 iterations takes about ten seconds on a laptop to execute. 5000 iterations are used in the reference below. noParticles The number of particles to use when estimating the likelihood. initialPhi The initial guess of the parameter phi. Details The Particle Metropolis-Hastings (PMH) algorithm makes use of a Gaussian random walk as the proposal for the parameter. The PMH algorithm is run using different step lengths in the proposal. This is done to illustrate the difficulty when tuning the proposal and the impact of a too small/large step length. Value Returns the estimate of the posterior mean. Note See Section 4.2 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples example2_lgss(noBurnInIterations=200, noIterations=1000) example3_sv Parameter estimation in a simple stochastic volatility model Description Minimal working example of parameter estimation in a stochastic volatility model using the particle Metropolis-Hastings algorithm with a bootstrap particle filter providing an unbiased estimator of the likelihood. The code estimates the parameter posterior for three parameters using real-world data. Usage example3_sv(noBurnInIterations = 2500, noIterations = 7500, noParticles = 500, initialTheta = c(0, 0.9, 0.2), stepSize = diag(c(0.1, 0.01, 0.05)^2), syntheticData = FALSE) Arguments noBurnInIterations The number of burn-in iterations in the PMH algorithm. Must be smaller than noIterations. noIterations The number of iterations in the PMH algorithm. 100 iterations takes about a minute on a laptop to execute. noParticles The number of particles to use when estimating the likelihood. initialTheta The initial guess of the parameters theta. stepSize The step sizes of the random walk proposal. Given as a covariance matrix. syntheticData If TRUE, data is not downloaded from the Internet. This is only used when running tests of the package. Details The Particle Metropolis-Hastings (PMH) algorithm makes use of a Gaussian random walk as the proposal for the parameters. The data are scaled log-returns from the OMXS30 index during the period from January 2, 2012 to January 2, 2014. This version of the code makes use of a somewhat well-tuned proposal as a pilot run to estimate the posterior covariance and therefore increase the mixing of the Markov chain. Value The function returns the estimated marginal parameter posteriors for each parameter, the trace of the Markov chain and the resulting autocorrelation function. The data is also presented with an estimate of the log-volatility. The function returns a list with the elements: • thhat: The estimate of the mean of the parameter posterior. • xhat: The estimate of the mean of the log-volatility posterior. • thhatSD: The estimate of the standard deviation of the parameter posterior. • xhatSD: The estimate of the standard deviation of the log-volatility posterior. • iact: The estimate of the integrated autocorrelation time for each parameter. • estCov: The estimate of the covariance of the parameter posterior. • theta: The trace of the chain exploring the parameter posterior. Note See Section 5 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples ## Not run: example3_sv(noBurnInIterations=200, noIterations=1000) ## End(Not run) example4_sv Parameter estimation in a simple stochastic volatility model Description Minimal working example of parameter estimation in a stochastic volatility model using the particle Metropolis-Hastings algorithm with a bootstrap particle filter providing an unbiased estimator of the likelihood. The code estimates the parameter posterior for three parameters using real-world data. Usage example4_sv(noBurnInIterations = 2500, noIterations = 7500, noParticles = 500, initialTheta = c(0, 0.9, 0.2), syntheticData = FALSE) Arguments noBurnInIterations The number of burn-in iterations in the PMH algorithm. Must be smaller than noIterations. noIterations The number of iterations in the PMH algorithm. 100 iterations takes about a minute on a laptop to execute. noParticles The number of particles to use when estimating the likelihood. initialTheta The initial guess of the parameters theta. syntheticData If TRUE, data is not downloaded from the Internet. This is only used when running tests of the package. Details The Particle Metropolis-Hastings (PMH) algorithm makes use of a Gaussian random walk as the proposal for the parameters. The data are scaled log-returns from the OMXS30 index during the period from January 2, 2012 to January 2, 2014. This version of the code makes use of a proposal that is tuned using a run of example3_sv and therefore have better mixing properties. Value The function returns the estimated marginal parameter posteriors for each parameter, the trace of the Markov chain and the resulting autocorrelation function. The data is also presented with an estimate of the log-volatility. The function returns a list with the elements: • thhat: The estimate of the mean of the parameter posterior. • xhat: The estimate of the mean of the log-volatility posterior. • thhatSD: The estimate of the standard deviation of the parameter posterior. • xhatSD: The estimate of the standard deviation of the log-volatility posterior. • iact: The estimate of the integrated autocorrelation time for each parameter. • estCov: The estimate of the covariance of the parameter posterior. Note See Section 6.3.1 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples ## Not run: example4_sv(noBurnInIterations=200, noIterations=1000) ## End(Not run) example5_sv Parameter estimation in a simple stochastic volatility model Description Minimal working example of parameter estimation in a stochastic volatility model using the particle Metropolis-Hastings algorithm with a bootstrap particle filter providing an unbiased estimator of the likelihood. The code estimates the parameter posterior for three parameters using real-world data. Usage example5_sv(noBurnInIterations = 2500, noIterations = 7500, noParticles = 500, initialTheta = c(0, 0.9, 0.2), syntheticData = FALSE) Arguments noBurnInIterations The number of burn-in iterations in the PMH algorithm. Must be smaller than noIterations. noIterations The number of iterations in the PMH algorithm. 100 iterations takes about a minute on a laptop to execute. noParticles The number of particles to use when estimating the likelihood. initialTheta The initial guess of the parameters theta. syntheticData If TRUE, data is not downloaded from the Internet. This is only used when running tests of the package. Details The Particle Metropolis-Hastings (PMH) algorithm makes use of a Gaussian random walk as the proposal for the parameters. The data are scaled log-returns from the OMXS30 index during the period from January 2, 2012 to January 2, 2014. This version of the code makes use of a proposal that is tuned using a pilot run. Furthermore the model is reparameterised to enjoy better mixing properties by making the parameters unrestricted to a certain part of the real-line. Value The function returns the estimated marginal parameter posteriors for each parameter, the trace of the Markov chain and the resulting autocorrelation function. The data is also presented with an estimate of the log-volatility. The function returns a list with the elements: • thhat: The estimate of the mean of the parameter posterior. • xhat: The estimate of the mean of the log-volatility posterior. • thhatSD: The estimate of the standard deviation of the parameter posterior. • xhatSD: The estimate of the standard deviation of the log-volatility posterior. • iact: The estimate of the integrated autocorrelation time for each parameter. • estCov: The estimate of the covariance of the parameter posterior. Note See Section 6.3.2 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples ## Not run: example5_sv(noBurnInIterations=200, noIterations=1000) ## End(Not run) generateData Generates data from a linear Gaussian state space model Description Generates data from a specific linear Gaussian state space model of the form xt = φxt−1 + σv vt and yt = xt + σe et , where vt and et denote independent standard Gaussian random variables, i.e. N (0, 1). Usage generateData(theta, noObservations, initialState) Arguments theta The parameters θ = {φ, σv , σe } of the LGSS model. The parameter φ that scales the current state in the state dynamics is restricted to [-1,1] to obtain a stable model. The standard deviations of the state process noise σv and the observation process noise σe must be positive. noObservations The number of time points to simulate. initialState The initial state. Value The function returns a list with the elements: • x: The latent state for t = 0, ..., T . • y: The observation for t = 0, ..., T . Author(s) <NAME> <<EMAIL>> References <NAME>. & Schon, T. B. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. kalmanFilter Kalman filter for state estimate in a linear Gaussian state space model Description Estimates the filtered state and the log-likelihood for a linear Gaussian state space model of the form xt = φxt−1 + σv vt and yt = xt + σe et , where vt and et denote independent standard Gaussian random variables, i.e.N (0, 1). Usage kalmanFilter(y, theta, initialState, initialStateCovariance) Arguments y Observations from the model for t = 1, ..., T . theta The parameters θ = {φ, σv , σe } of the LGSS model. The parameter φ scales the current state in the state dynamics. The standard deviations of the state process noise and the observation process noise are denoted σv and σe , respectively. initialState The initial state. initialStateCovariance The initial covariance of the state. Value The function returns a list with the elements: • xHatFiltered: The estimate of the filtered state at time t = 1, ..., T . • logLikelihood: The estimate of the log-likelihood. Note See Section 3 in the reference for more details. Author(s) <NAME> <<EMAIL>> References Dahlin, J. & Schon, T. B. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples # Generates 500 observations from a linear state space model with # (phi, sigma_e, sigma_v) = (0.5, 1.0, 0.1) and zero initial state. theta <- c(0.5, 1.0, 0.1) d <- generateData(theta, noObservations=500, initialState=0.0) # Estimate the filtered state using Kalman filter kfOutput <- kalmanFilter(d$y, theta, initialState=0.0, initialStateCovariance=0.01) # Plot the estimate and the true state par(mfrow=c(3, 1)) plot(d$x, type="l", xlab="time", ylab="true state", bty="n", col="#1B9E77") plot(kfOutput$xHatFiltered, type="l", xlab="time", ylab="Kalman filter estimate", bty="n", col="#D95F02") plot(d$x-kfOutput$xHatFiltered, type="l", xlab="time", ylab="difference", bty="n", col="#7570B3") makePlotsParticleMetropolisHastingsSVModel Make plots for tutorial Description Creates diagnoistic plots from runs of the particle Metropolis-Hastings algorithm. Usage makePlotsParticleMetropolisHastingsSVModel(y, res, noBurnInIterations, noIterations, nPlot) Arguments y Observations from the model for t = 1, ..., T . res The output from a run of particleMetropolisHastings, particleMetropolisHast- ingsSVmodel or particleMetropolisHastingsSVmodelReparameterised. noBurnInIterations The number of burn-in iterations in the PMH algorithm. Must be smaller than noIterations. noIterations The number of iterations in the PMH algorithm. nPlot Number of steps in the Markov chain to plot. Value The function returns plots similar to the ones in the reference as well as the estimate of the integrated autocorrelation time for each parameter. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. particleFilter Fully-adapted particle filter for state estimate in a linear Gaussian state space model Description Estimates the filtered state and the log-likelihood for a linear Gaussian state space model of the form xt = φxt−1 + σv vt and yt = xt + σe et , where vt and et denote independent standard Gaussian random variables, i.e.N (0, 1). Usage particleFilter(y, theta, noParticles, initialState) Arguments y Observations from the model for t = 1, ..., T . theta The parameters θ = {φ, σv , σe } of the LGSS model. The parameter φ scales the current state in the state dynamics. The standard deviations of the state process noise and the observation process noise are denoted σv and σe , respectively. noParticles The number of particles to use in the filter. initialState The initial state. Value The function returns a list with the elements: • xHatFiltered: The estimate of the filtered state at time t = 1, ..., T . • logLikelihood: The estimate of the log-likelihood. • particles: The particle system at each time point. • weights: The particle weights at each time point. Note See Section 3 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples # Generates 500 observations from a linear state space model with # (phi, sigma_e, sigma_v) = (0.5, 1.0, 0.1) and zero initial state. theta <- c(0.5, 1.0, 0.1) d <- generateData(theta, noObservations=500, initialState=0.0) # Estimate the filtered state using a Particle filter pfOutput <- particleFilter(d$y, theta, noParticles = 50, initialState=0.0) # Plot the estimate and the true state par(mfrow=c(3, 1)) plot(d$x[1:500], type="l", xlab="time", ylab="true state", bty="n", col="#1B9E77") plot(pfOutput$xHatFiltered, type="l", xlab="time", ylab="paticle filter estimate", bty="n", col="#D95F02") plot(d$x[1:500]-pfOutput$xHatFiltered, type="l", xlab="time", ylab="difference", bty="n", col="#7570B3") particleFilterSVmodel Bootstrap particle filter for state estimate in a simple stochastic volatility model Description Estimates the filtered state and the log-likelihood for a stochastic volatility model of the form xt = µ + φ(xt−1 − µ) + σv vt and yt = exp(xt /2)et , where vt and et denote independent standard Gaussian random variables, i.e. N (0, 1). Usage particleFilterSVmodel(y, theta, noParticles) Arguments y Observations from the model for t = 1, ..., T . theta The parameters θ = {µ, φ, σv }. The mean of the log-volatility process is de- noted µ. The persistence of the log-volatility process is denoted φ. The standard deviation of the log-volatility process is denoted σv . noParticles The number of particles to use in the filter. Value The function returns a list with the elements: • xHatFiltered: The estimate of the filtered state at time t = 1, ..., T . • logLikelihood: The estimate of the log-likelihood. Note See Section 5 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples ## Not run: # Get the data from Quandl library("Quandl") d <- Quandl("NASDAQOMX/OMXS30", start_date="2012-01-02", end_date="2014-01-02", type="zoo") y <- as.numeric(100 * diff(log(d$"Index Value"))) # Estimate the filtered state using a particle filter theta <- c(-0.10, 0.97, 0.15) pfOutput <- particleFilterSVmodel(y, theta, noParticles=100) # Plot the estimate and the true state par(mfrow=c(2, 1)) plot(y, type="l", xlab="time", ylab="log-returns", bty="n", col="#1B9E77") plot(pfOutput$xHatFiltered, type="l", xlab="time", ylab="estimate of log-volatility", bty="n", col="#D95F02") ## End(Not run) particleMetropolisHastings Particle Metropolis-Hastings algorithm for a linear Gaussian state space model Description Estimates the parameter posterior for phi a linear Gaussian state space model of the form xt = φxt−1 + σv vt and yt = xt + σe et , where vt and et denote independent standard Gaussian random variables, i.e.N (0, 1). Usage particleMetropolisHastings(y, initialPhi, sigmav, sigmae, noParticles, initialState, noIterations, stepSize) Arguments y Observations from the model for t = 1, ..., T . initialPhi The mean of the log-volatility process µ. sigmav The standard deviation of the state process σv . sigmae The standard deviation of the observation process σe . noParticles The number of particles to use in the filter. initialState The inital state. noIterations The number of iterations in the PMH algorithm. stepSize The standard deviation of the Gaussian random walk proposal for φ. Value The trace of the Markov chain exploring the marginal posterior for φ. Note See Section 4 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples # Generates 100 observations from a linear state space model with # (phi, sigma_e, sigma_v) = (0.5, 1.0, 0.1) and zero initial state. theta <- c(0.5, 1.0, 0.1) d <- generateData(theta, noObservations=100, initialState=0.0) # Estimate the marginal posterior for phi pmhOutput <- particleMetropolisHastings(d$y, initialPhi=0.1, sigmav=1.0, sigmae=0.1, noParticles=50, initialState=0.0, noIterations=1000, stepSize=0.10) # Plot the estimate nbins <- floor(sqrt(1000)) par(mfrow=c(1, 1)) hist(pmhOutput, breaks=nbins, main="", xlab=expression(phi), ylab="marginal posterior", freq=FALSE, col="#7570B3") particleMetropolisHastingsSVmodel Particle Metropolis-Hastings algorithm for a stochastic volatility model model Description Estimates the parameter posterior for θ = {µ, φ, σv } in a stochastic volatility model of the form xt = µ + φ(xt−1 − µ) + σv vt and yt = exp(xt /2)et , where vt and et denote independent standard Gaussian random variables, i.e. N (0, 1). Usage particleMetropolisHastingsSVmodel(y, initialTheta, noParticles, noIterations, stepSize) Arguments y Observations from the model for t = 1, ..., T . initialTheta An inital value for the parameters θ = {µ, φ, σv }. The mean of the log-volatility process is denoted µ. The persistence of the log-volatility process is denoted φ. The standard deviation of the log-volatility process is denoted σv . noParticles The number of particles to use in the filter. noIterations The number of iterations in the PMH algorithm. stepSize The standard deviation of the Gaussian random walk proposal for θ. Value The trace of the Markov chain exploring the posterior of θ. Note See Section 5 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples ## Not run: # Get the data from Quandl library("Quandl") d <- Quandl("NASDAQOMX/OMXS30", start_date="2012-01-02", end_date="2014-01-02", type="zoo") y <- as.numeric(100 * diff(log(d$"Index Value"))) # Estimate the marginal posterior for phi pmhOutput <- particleMetropolisHastingsSVmodel(y, initialTheta = c(0, 0.9, 0.2), noParticles=500, noIterations=1000, stepSize=diag(c(0.05, 0.0002, 0.002))) # Plot the estimate nbins <- floor(sqrt(1000)) par(mfrow=c(3, 1)) hist(pmhOutput$theta[,1], breaks=nbins, main="", xlab=expression(mu), ylab="marginal posterior", freq=FALSE, col="#7570B3") hist(pmhOutput$theta[,2], breaks=nbins, main="", xlab=expression(phi), ylab="marginal posterior", freq=FALSE, col="#E7298A") hist(pmhOutput$theta[,3], breaks=nbins, main="", xlab=expression(sigma[v]), ylab="marginal posterior", freq=FALSE, col="#66A61E") ## End(Not run) particleMetropolisHastingsSVmodelReparameterised Particle Metropolis-Hastings algorithm for a stochastic volatility model model Description Estimates the parameter posterior for θ = {µ, φ, σv } in a stochastic volatility model of the form xt = µ + φ(xt−1 − µ) + σv vt and yt = exp(xt /2)et , where vt and et denote independent standard Gaussian random variables, i.e. N (0, 1). In this version of the PMH, we reparameterise the model and run the Markov chain on the parameters ϑ = {µ, ψ, ς}, where φ = tanh(ψ) and sigmav = exp(ς). Usage particleMetropolisHastingsSVmodelReparameterised(y, initialTheta, noParticles, noIterations, stepSize) Arguments y Observations from the model for t = 1, ..., T . initialTheta An inital value for the parameters θ = {µ, φ, σv }. The mean of the log-volatility process is denoted µ. The persistence of the log-volatility process is denoted φ. The standard deviation of the log-volatility process is denoted σv . noParticles The number of particles to use in the filter. noIterations The number of iterations in the PMH algorithm. stepSize The standard deviation of the Gaussian random walk proposal for θ. Value The trace of the Markov chain exploring the posterior of θ. Note See Section 5 in the reference for more details. Author(s) <NAME> <<EMAIL>> References <NAME>. & <NAME>. "Getting Started with Particle Metropolis-Hastings for Inference in Non- linear Dynamical Models." Journal of Statistical Software, Code Snippets, 88(2): 1–41, 2019. Examples ## Not run: # Get the data from Quandl library("Quandl") d <- Quandl("NASDAQOMX/OMXS30", start_date="2012-01-02", end_date="2014-01-02", type="zoo") y <- as.numeric(100 * diff(log(d$"Index Value"))) # Estimate the marginal posterior for phi pmhOutput <- particleMetropolisHastingsSVmodelReparameterised( y, initialTheta = c(0, 0.9, 0.2), noParticles=500, noIterations=1000, stepSize=diag(c(0.05, 0.0002, 0.002))) # Plot the estimate nbins <- floor(sqrt(1000)) par(mfrow=c(3, 1)) particleMetropolisHastingsSVmodelReparameterised 19 hist(pmhOutput$theta[,1], breaks=nbins, main="", xlab=expression(mu), ylab="marginal posterior", freq=FALSE, col="#7570B3") hist(pmhOutput$theta[,2], breaks=nbins, main="", xlab=expression(phi), ylab="marginal posterior", freq=FALSE, col="#E7298A") hist(pmhOutput$theta[,3], breaks=nbins, main="", xlab=expression(sigma[v]), ylab="marginal posterior", freq=FALSE, col="#66A61E") ## End(Not run)
promethee123
cran
R
Package ‘promethee123’ October 14, 2022 Type Package Title PROMETHEE I, II, and III Methods Version 0.1.0 Author <NAME> [aut, cre], <NAME> [aut], <NAME> [aut] Maintainer <NAME> <<EMAIL>> Description The PROMETHEE method is a multi-criteria decision- making method addressing with outranking problems. The method establishes a preference structure between the alternatives, having a preference func- tion for each criterion. IN this context, three variants of the method is carried out: PROMETHEE I (Par- tial Outranking), PROMETHEE II (Total Outranking), and PROMETHEE III (Outranking by Intervals). License GPL-3 Imports ggplot2,cowplot Encoding UTF-8 LazyData true NeedsCompilation no Repository CRAN Date/Publication 2020-12-21 10:30:03 UTC R topics documented: promethee12... 2 promethee123 PROMETHEE I, II, and III Methods Description The PROMETHEE method is a multti-criteria decision-making method addressing with outrank- ing problems. The method establishes a preference structure between the alternatives, having a preference function for each criterion. IN this context, three variants of the method is carried out: PROMETHEE I (Partial pre-ordering), PROMETHEE II (Total pre-ordering), and PROMETHEE III (pre-ordering by inervals). Usage promethee123(alternatives, criteria, decision_matrix, min_max, normalization_function, q_indifference, p_preference, s_curve_change, criteria_weights) Arguments alternatives The names respective to set of alternatives in evaluation criteria The names respective to set of criteria in evaluation decision_matrix A matrix where rows correspond to the criteria and columns correspond to al- ternatives, there is inputed the performance of alternatives in each criterion min_max A vector with objectives, minimize or maximize, to each criteria. normalization_function Numerical description relative to each type of normalization function to each criterion q_indifference Indifference threshold p_preference Preference threshold s_curve_change Threshold of changing in the curve criteria_weights Numerical representation of the respective importance for each criterion Details - For normalization function we have six types: [ 1 ] for USUAL (0 or 1) — [ 2 ] for U-SHAPE (0 or 1) q [ 3 ] for V-SHAPE (x/p or 1) p [ 4 ] for LEVEL (0, 0.5 or 1) q , p [ 5 ] for V-SHAPE I (0, (x- q)/(p-q) or 1) q , p [ 6 ] for GAUSSIAN (0 or 1-e^(-x^2/2*s^2)) s ———————————- q = indifference parameter p = preference parameter s = parameter to indicate change in the preference curve - The input of thresholds depends of the type of preference function used; - The sum of weights must be 1; Value - Performance in each criterion; - Global Index of Importance; - Importance Flows (Positive, Negative, and Net); - Preference relations in PROMETHEE I; - Total Outranking in PROMETHEE II; - Preference relations in PROMETHEE III; - Graphical representations of PROMETHEE I, II, and III. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL> <NAME> <<EMAIL>> References BRANS, Jean-Pierre; DE SMET, Yves. PROMETHEE methods. In: Multiple criteria decision analysis. Springer, New York, NY, 2016. p. 187-219. DOI: 10.1007/978-1-4939-3094-4_6. <https://link.springer.com/chapter/10.1007/978-1-4939-3094-4_6> Examples alternatives <- c("SARP", "ORAC", "TOTS", "MICRO", "IBRP") criteria <- c("Price", "Complexity", "Security", "Performance") decision_matrix <- matrix(c(15, 29, 38, 24, 25.5, 7.5, 9, 8.5, 8, 7, 1, 2, 4, 3, 3, 50, 110, 90, 75, 85), ncol = length(alternatives), nrow = length(criteria), byrow = TRUE) min_max <- c("min", "min", "max", "max") normalization_function <- c( 5 , 5 , 5 , 5 ) q_indifference <- c(2, 0.5 , 1 , 10) p_preference <- c(5 , 1 , 2 , 20) s_curve_change <- c("","","","") criteria_weights <- c(0.2 , 0.2 , 0.3 , 0.3) promethee123(alternatives, criteria, decision_matrix, min_max, normalization_function, q_indifference, p_preference, s_curve_change, criteria_weights)
github.com/zclconf/go-cty
go
Go
README [¶](#section-readme) --- ### cty `cty` (pronounced "see-tie", emoji: 👀 👔, [IPA](https://en.wikipedia.org/wiki/International_Phonetic_Alphabet): /si'tʰaɪ/) is a dynamic type system for applications written in Go that need to represent user-supplied values without losing type information. The primary intended use is for implementing configuration languages, but other uses may be possible too. One could think of `cty` as being the reflection API for a language that doesn't exist, or that doesn't exist *yet*. It provides a set of value types and an API for working with values of that type. Fundamentally what `cty` provides is equivalent to an `interface{}` with some dynamic type information attached, but `cty` encapsulates this to ensure that invariants are preserved and to provide a more convenient API. As well as primitive types, basic collection types (lists, maps and sets) and structural types (object, tuple), the `cty` type and value system has some additional, optional features that may be useful to certain applications: * Representation of "unknown" values, which serve as a typed placeholder for a value that has yet to be determined. This can be a useful building-block for a type checker. Unknown values support all of the same operations as known values of their type, but the result will often itself be unknown. * Representation of values whose *types* aren't even known yet. This can represent, for example, the result of a JSON-decoding function before the JSON data is known. Along with the type system itself, a number of utility packages are provided that build on the basics to help integrate `cty` into calling applications. For example, `cty` values can be automatically converted to other types, converted to and from native Go data structures, or serialized as JSON. For more details, see the following documentation: * [Concepts](https://github.com/zclconf/go-cty/blob/v1.14.1/docs/concepts.md) * [Full Description of the `cty` Types](https://github.com/zclconf/go-cty/blob/v1.14.1/docs/types.md) * [API Reference](https://godoc.org/github.com/zclconf/go-cty/cty) (godoc) * [Conversion between `cty` types](https://github.com/zclconf/go-cty/blob/v1.14.1/docs/convert.md) * [Conversion to and from native Go values](https://github.com/zclconf/go-cty/blob/v1.14.1/docs/gocty.md) * [JSON serialization](https://github.com/zclconf/go-cty/blob/v1.14.1/docs/json.md) * [`cty` Functions system](https://github.com/zclconf/go-cty/blob/v1.14.1/docs/functions.md) * [Compatibility Policy for future Minor Releases](https://github.com/zclconf/go-cty/blob/v1.14.1/COMPATIBILITY.md): please review this before using `cty` in your application to avoid depending on implementation details that may change. --- #### License Copyright 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. None
pinlabdoc
ctan
TeX
# pinlabel A TeX labelling package <NAME> pinlabel is a labelling package designed for attaching perfectly formatted TeX labels to figures and diagrams in both eps and pdf formats. It is a tool for use by both authors and editors and can be used both for labelling a new diagram and for relabelling an existing diagram. It is the recommended package for (re)labelling diagrams or figures in papers intended for publication by Mathematical Sciences Publishers. The main features of the package are that it uses coordinates read from the diagram in GhostView (or gv) and that labels are placed with automatic and consistent spacing from the object that they are labelling. Many adjustment and positioning options are provided. The end result is a package which is easy and quick to use and which provides accurate and eye-pleasing labelling, completely consistent with the text. For a comparison of pinlabel with other labelling packages which allow one to attach TeX labels, see Section 6. 68-01; 68N01 ## 1 Essential ingredients ### Input files To use pinlabel you need just one file pinlabel.sty. If you are using latex, then you need only add the line \usepackage{pinlabel} near the top of your file; if using plain tex then add the line \input pinlabel.sty instead. Occasionally there will be a paragraph labelled **Smallprint**, which can safely be omitted on first reading, but which you may need to read if problems arise. There is a whole section of smallprint near the end. **Smallprint** The package calls a standard latex package graphicx.sty which all recent tex installations will have available, so you should not have to worry about this. If you are using plain tex then it also calls miniltx.tex--a basic latex interpreter for plain tex--which should also be available, but if not, can be collected from the CTAN server. ### Graphics files Your figures must exist either as.eps or as.pdf files. If you are using only pdflatex then you can create and label using.pdf figures throughout if you wish. SmallprintThis is a major change introduced in version 1.2. In version 1.1 it was necessary to create.eps copies of all figure files. However this _does not mean_ that you can now safely discard the.eps versions for figures already labelled. There is a problem with bounding boxes and your labels are likely to move to unexpected places. Read smallprint note 4.4. If you are creating your figures from scratch, for example by using xfig (highly recommended) then export as "EPS (Encapsulated Postscript)" if you are using plain tex or if you may need to compile using latex, and as "PDF (Portable Document Format)" if you are using only pdflatex. If you want to be able to compile using both latex and pdflatex then export as EPS and create a PDF version by running epstopdf. The syntax is: epstopdf fig.eps NoteDo not use the similar sounding program eps2pdf which may change the bounding box. Do not draw your labels in your drawing package. ### GhostView You will also need a working copy of GhostView or gv or GSwiew for reading coordinate positions. Most univ or linux installations include this program, as does cywin running under Windows, and you can collect a stand-alone copy for Windows or Macintosh by visiting: [http://www.cs.wisc.edu/~ghost/gsview/](http://www.cs.wisc.edu/~ghost/gsview/) or [http://www.cs.wisc.edu/~ghost/macos/](http://www.cs.wisc.edu/~ghost/macos/) ## 2 Basic use ### Labelling a new figure Load your figure (the.eps version if you have made one, or the.pdf version if not) into GhostView or equivalent. You will notice that the cursor position is recorded (inPS points) either at the bottom or the side. This position is what you will read as your labelling coordinates. Assuming that you are using latex or pdflatex (the changes for plain tex are indicated later) then include your figure using instructions as in the following typical example: \begin{figure}[ht!] \labellist \small\hair 2pt \pinlabel $B^3_+$ at 57 246 \pinlabel $B^3_-$ [1] at 187 207 \pinlabel ${$(S^3 \times I,A)$} [tr] at 76 26 \pinlabel $O$ [t] at 233 63 \pinlabel $K$ [r] at 125 272 \pinlabel $S^3$ [b1] at 253 283 \pinlabel $A$ [r] at 125 153 \endlabellist \centering \includegraphics[scale=0.65]{fig6} \caption{A concordance between $K$ and the unknot} \label{fig:cobo} \end{figure} The result is shown in Figure 1, taken from Kim [1, Figure 6]. Let's look at this example line-by-line. _Mathematical Sciences Publishers: documentation_ Figure 1: A concordance between \ and the unknot <begin{figure}[ht!] opens the figure environment and instructs latex that we want the figure to be printed either here or at the top of the page (! and no-where else). <labellist opens the list of labels. <small and <hair 2pt are formatting commands which apply to all the labels: <small> typesets them approximately 1 point smaller than the text (recommended) and <hair 2pt> adjusts the spacing between the label and the point which is being labelled (more on this below). Now come the actual labels. The first label instruction: <pinlabel $B^3_+$ at 57246 is the simplest form. It tells latex to pin the label \(B^3_{+}\) with its centre at the point with coordinates \((57,246)\) in the figure. The remaining labels all have optional position codes. <pinlabel $B^3_-$ [1] at 187207 tells latex to pin the label \(B^3_{-}\) by the point centre-left of its bounding box (this is what the position code [1] tells it to do) at the point with with coordinates \((187,207)\). But pinlabel does not do this. It applies automatic spacing. The point with coordinates \((187,207)\) is the end of the arrow we are labelling. We want the label to be placed a little way away and this is what pinlabel does. It sets the label exactly 2 points away. The tex dimension <hair> is this spacing and we just set it equal to 2 points. The default for <hair> is 3pt>, but you can reset it to any dimension you like for a particular label (or set of labels). If you want no autospacing, then use the starred form of the command: <pinlabel* $B^3_-$ [1] at 187207 which will set the label with the centre-left of its bounding box _exactly_ at the point \((187,207)\). The next label: <pinlabel $(S^3 <times I,A)$> [tr] at 7626 introduces an important point. The label code $(S^3 <times I,A)$ has spaces in it. But pinlabel uses spaces to separate the various instructions, so to avoid pinlabel attempting to use $(S^3 as the label (and falling over in the process) the label must be enclosed in braces. The position code in this label is [tr] (top-right) and this makespinlabel pin this label by the point which is top-right of the label bounding box (with autospacing) at \((76,26)\), which are the coordinates read off from a point on the bottom curve of the figure. A full list of position codes will be given shortly. In Figure 2 is a screenshot showing how the coordinates are read in GSView. The label being processed is $S^3$, the end of the arrow is located at \((253,283)\) and these coordinates are being copied into the latex file. In the screenshot the text editor Emacs is the active window on top of GSView but the mouse is pointing at the point in GSView whose coordinates are being read (from the bottom of the GSView window). By using cursor keys in emacs, the mouse is not disturbed and the coordinates can be copied across very rapidly and accurately. In this example, the transcription of the coordinates took just a couple of minutes. Continuing with the example, there are further labels which do not introduce anything new and then the list of labels is closed with: \endlabellist Figure 2: Screenshot after which come the commands for including the figure, the caption, the label (for cross-referencing) and for closing the figure environment: \includegraphics[scale=0.65]{fig6} \caption{A concordance between $K$ and the unknot} \label{fig:cobo} \end{figure} Important noteThe filename of the figure to be included (ie fig6) _must be given without extension_. The program automatically looks for the correct file which would be fig6.ps or fig6.eps, if using tex or latex, and would be fig6.pdf if using pdflatex. If you type \includegraphics[scale=0.65]{fig6.eps} then the program will give a warning: cannot open figure fig6.eps.ps or.eps or.pdf on input line... and no figure will appear. ### Position codes Here is a full list of position codes: r=right, l=left, t=top, b=bottom and B=baseline. The default is centre and any sensible combination of two codes may be give (in either order) eg [tl]=[lt]=top-left of label bounding box. The baseline is the line that tex uses for lining up characters. In Figure 3 we illustrate all the possible position codes for a simple piece of text. If no position code is given then the label is pinned by the centre (unlabelled dot in the figure). Figure 3: Position codes ### Relabelling an existing figure Print the figure (with its labels) as a record of how the labels go. Then edit the.eps file to remove the given labels. This is usually easier than it sounds. Text in a PostScript file is usually enclosed in round brackets. For example here is an excerpt from the file put.eps used in Figure 3: % Polyline 7.500 slw [60] 0 sd n 5492 3949 m 7720 3949 l 7720 2577 l 5491 2576 l cp gs col0 s gr [] 0 sd /Helvetica-Bold ff 1500.00 scf sf 5422 3615 m gs 1 -1 sc (put) col11 sh gr % here ends figure; % % here starts figure with depth 0 % Polyline 7.500 slw n 5027 3649 m The text (put) is obvious and easily searchable. In this example "put" is in fact a graphic element, rather than a label, so we would not edit it out, but a label would be given in the file in a similar format. If "put" were a label to be removed, you would edit it out by replacing (put) with (). Do the same for all labels. Of course if you have the source code (eg the.fig file for xfig) then you can edit the figure directly and then re-export it as an.eps file. If your figure only exists as a.pdf file, then you can try coverting to.eps by running epstops -eps fig.pdf and then looking for text as above. After removing labels, convert back. If these dodges fail then you will have to remake the figure without labels using the original graphics program. Once the old labels have been removed, relabelling is identical to labelling a new figure as described above. ### Rotated and other exotic labels Nothing has been said so far about the actual label. As far as pinlabel is concerned the label is just a box. Any valid (la)tex code can be used inside that box. For example you can use a \rotatebox for your label which results in a rotated label: _Mathematical Sciences Publishers: documentation_ same. Probably you will have a figure inclusion macro included in whatever package you are using. Assuming this is \fig... \endfig a pinlabelled figure might look this: \fig \labellist\ninepoint\hair 2.5pt \pinlabel {$\partial_1 X$} [r] at 156 426 \pinlabel {$\partial_2 X$} [t1] at 334 429 \pinlabel $X_1$ at 431 513 \pinlabel $X_2$ at 428 460 \pinlabel $H_X$ [lb] at 311 622 \pinlabel* $H_X'$ [tr] at 178 370 \endlabellist \centerline{\includegraphics[width=3in]{decomp}} \centerline{Figure 23: Labelling the boundary components of $X$} \endfig ``` ## 3 Advanced features There are three features which give the package immense flexibility in pinning labels: pinning by coordinates, fine adjustment and the use of an external label file. ### Pinning by coordinates You can pin a label by _any_ point, not just by the 12 points illustrated in Figure 3. Intrinsic coordinates are defined in the "label-space" by taking the origin at the centre and using affine coordinates with horizontal unit half the width of the bounding box and vertical half the height plus depth. These are illustrated in Figure 5. Then the command: _Mathematical Sciences Publishers: documentation_ Figure 5: Intrinsic coordinates in label-space \pinlabel* $a^b$ by -1.5 0 at 231 47 will pin the label \(a^b\) so that the point \((-1.5,0)\) in label space (the "label-point") coincides with the point with (PostScript) coordinates \(231, 47) in the diagram (the "diagram point"). You can imagine a pin inserted through the label (on an extended transparent sheet if necessary) at the label-point and then this used to pin the label to the diagram at the diagram-point. This is the reason for the name that we have adopted for the package. We have used the starred form of \pinlabel in this example. If you use the unstarred form: \pinlabel $a^b$ by -1.5 0 at 231 47 then the label is pinned so that the point \((-1.5,0)\) in label space is pinned to a point exactly \hair away from the point \(231, 47) in the diagram. The direction of this autospacing is determined by the program. In practice you let the program decide on this direction, but if you want to know exactly how it decides, read part (2) of the next smallprint. You will now observe that there are several equivalent ways to pin labels using standard points. For example the following are all exactly equivalent: \pinlabel* $t-u^2$ by -1 -1 at 231 47 \pinlabel* $t-u^2$ [lb] at 231 47 \pinlabel* $t-u^2$ [bl] at 231 47 \hair Opt \pinlabel $t-u^2$ by -1 -1 at 231 47 \hair Opt \pinlabel $t-u^2$ [lb] at 231 47 \ \hair Opt \pinlabel $t-u^2$ [bl] at 231 47 } Note the space after the final coordinate in the above examples. The commands use spaces as separators and are syntax sensitive. There must be a space (or a line return) after the final coordinate. The program will attempt to recover if the syntax is wrong, but often crashes with strange errors. If you copy the syntax in the examples in this file, then all will be well. For more about syntax and errors see Section 4.1 and Section 4.3. Smallprint(1) The use of spaces as separators means that the commands will not work with \obeyspaces set. (2) There are eight directions for autospacing: E, NE, N, NW, W, SW, S, SE. The choice of a discrete set of directions makes the spacing look consistent over the diagram, whilst allowing sufficient flexibility to space labels away from the points being labelled. If you use the position code [tl] etc then the choice of direction is determined by the position code in the obvious way, eg [tl] determines NW, ie the label is set so that the diagram-point is \hair away from the label-point in the north-west direction. The position code [B] suppresses autospacing and [Bl] chooses W, [Br] chooses E as you would expect. When pinning by coordinates rather than by letters, the program uses the direction (of the eight available) closest to direction from \(0,0) to the label-point. If the label-point is \(0,0) then autospacing is again suppressed. The effect of these rules is that for example: \pinlabel {label} by 1 1 at 231 56 is not always equivalent to: \pinlabel {label} [tr] at 231 56 If the label is rather wide, then \((1,1)\) in diagram space may be closer to E than NE and the first command will autospace using E and the second NE. ### Fine adjustment There is an optional manual "fine adjustment" that can be applied to any label which moves the label a specified amount. This may be inserted before at or directly after the label. The adjustment goes inside diamond brackets <x-adj,y-adj> where x-adj and y-adj are arbitrary tex dimensions. For example the following commands are all equivalent: \pinlabel $a^b$ [l] <-2pt,1pt> at 231 47 \pinlabel $a^b$ by -1 0 <-2pt,1pt> at 231 47 \pinlabel $a^b$ <-2pt,1pt> [l] at 231 47 \pinlabel $a^b$ <-2pt,1pt> by -1 0 at 231 47 They all pin the label \(a^{b}\) by centre-left at \((231,47)\) with two adjustments: \hair (autospacing) and then (-2pt,1pt) manual (in other words the label is moved 2 points to the left and 1 point upwards). \pinlabel* $a^b$ [l] <-2pt,1pt> at 231 47 will do the same but with \hair set to 0pt (ie autospacing suppressed). In practice, you label your diagram as described in Section 2 using either position codes or coordinates. Then you inspect it in a viewer and make final adjustments by (a) adjusting \hair (this can be done for each label separately if necessary) and (b) adding a final manual adjustment <x-adj,y-adj> again, if necessary. For example, inspecting Figure 1, we see that the label \(B_{-}^{3}\) has been placed a little too far from the arrow tail, because of the sloping italic type, and that \(K\) is also a tad too far from its arrow because of the shape of the letter \(K\). So to perfect the labelling you could make fine adjustments as follows: _Mathematical Sciences Publishers: documentation_%nilabel$B^3_-$[1]<-1pt,Opt>at187207 %nilabel$(S^3\timesI,A)$][tr]at762 %nilabel$O$[t]at2336 %nilabel$K$[r]<1pt,Opt>at125272... It is worth stressing that both \hair and the fine adjustment <x-adj,y-adj> are absolute dimensions. They do not change if the figure is rescaled. By contrast the coordinates of the diagram point, at XXXYY, are given in PostScript points scaled by any scaling applied to the figure and are therefore instrinsic to the figure. This means that if the figure is rescaled, the diagram point moves with the scaling (as you would expect) but the spacing given by autospacing and fine adjustment stays fixed. Thus you can make last-minute changes of scale to a labelled diagram and the labels will continue to be perfectly positioned. ### Using a.lab file Labels can either be given as a list in the tex file (they must come between \labellist and \endlabellist) as described above or given in the form of an external.lab file. This is particularly useful if you have a complicated diagram with labels generated by an external program, for example the mathfig software, which automatically generates.lab files from Mathematica input. The syntax is identical but the commands \labellist and \endlabellist must not be given. The filename must be exactly the same as the figure being labelled (but with a.lab extension instead of a.eps or.ps or.pdf extension) and the label file must be in the same directory as the figure file. The program is based on psfig and uses psfig internally. In the examples above, we have used graphicx commands for figure insertion but we could equally well have used psfig commands. In the first example, Figure 1 we used: \includegraphics[scale=0.65]{fig6} but we could equivalently have used: \psfig{file=fig6,scale=65} This works because the program automatically translates to psfig (and adjusts the scale command correctly). However it only does this if there is a labellist waiting to be used. This is a feature that allows you to use \includegraphics in its full power (eg with rotation) for figures that are not being pinlabelled. But it means that if you use an external.lab file then you _must_ use psfig syntax. For example, suppose that your figure is diag.eps in the subdirectory figs then if you type: \centerline{psfig{file=figs/diag,width=.7\hsize}} and if the file figs/diag.lab reads: \small\hair 2pt \pinlabel $(-1,-1)$ [tr] at 29 4 \pinlabel $(0,1)$ [b] at 96 86 \normalsize\hair 3pt \pinlabel $(0,-1)$ [t] at 96 4 \pinlabel $(1,0)$ [l] at 162 45 \pinlabel $(-1,0)$ [r] at 29 45 \pinlabel $(Large.) at 162.3 86 \pinlabel {\Large.} at 162.3 3.7 Then these labels will be pinned to the diagram exactly as if they had been typed in the main file. Note the change of formatting instructions within this list of labels. The labels after the change will be typeslnormalsize instead of \small with \hair set to 3pt. Smallprint(1) Labelling instructions do not have to be given inside the figure environment. Indeed they can be given at any time before the next \includegraphics or \psfig command. If there are both a labellist pending _and_ an appropriate.lab file available, then the labellist will override the.lab file (and you will get a warning to that effect). Any formatting that is in force when the labellist is typed is ignored and the formatting that is in force inside the figure environment is used instead. For example the command \small can be given either at the start of the labellist or at the start of the.lab file or after \begin{figure}[ht!] with identical effect. (2) Formatting instructions can be given at any stage within the labellist or the.lab file as in the above example (the change of formatting in that example would work equally well within a labellist). There is a facility for setting a global format that automatically applies to all labels. If you type: \gdef\hyperactivelabelst{\small\sl\hair2.5pt} at the start of your file (or anywhere else you like) then all figures that come after that line will have formatting applied exactly as if you had typed: \small\sl\hair2.5pt at the start of the labellist or.lab file. This facility is extremely useful for machine generated.lab files. You can reset \hyperactivelabelst between figures. To cancel this automatic formatting between any two figures, type: _Mathematical Sciences Publishers: documentation_\global\let\hyperactivelabels\relax (3) You can force the program to use graphicx rather than autotranslating to the appropriate psfig command by typing \reallyincludegraphics. Since autotranslation only takes place when there is a labellist pending, this will only be necessary if, for some reason, a labellist has been supplied that applies to a later figure. Labelling will take not place if autotranslation is suppressed and the labellist will be saved and applied to the next figure. An example where this was essential was given in Section 2.4. When using a picture as a label, you need to suppress labelling in the label or TEX will go into an infinte loop (4) Autotranslation of \includegraphics is far from perfect. Many of the options are not supported. Read Section 5 (on bugs) below if you run into trouble. ## 4 Smallprint ### Syntax #### Basic syntax \pinlabel {label} by x-pin y-pin at x-location y-location or \pinlabel* {label} by x-pin y-pin at x-location y-location where x-pin y-pin is the point in intrinsic coords in label space where we are placing the pin and x-location y-location is the point in diagram space (in PS points as read in gv) where the label is pinned. \pinlabel uses \hair autospacing \pinlabel* does not. \mathsurround is set to Opt for parsing the label. If the label contains spaces, it _must_ be enclosed in braces {}. x-pin, y-pin, x-location and y-location are pure numbers, _not_ dimensions. The program converts them to the relevant dimension. The by and at are essential as are all the spaces. #### Options by x-pin y-pin may be omitted, the default is 0 0. by x-pin y-pin may be replaced by position codes [r], [Bl] etc (see Section 2.2 for full detail of these codes). A manual adjustment <x-adj, y-adj> may be added either after the label or before at. Here x-adj and y-adj are tex dimensions, eg 5pt or -2mm. Full examples (for more examples see earlier): \pinlabel $B^3_-$ <-1pt,Opt> by -1 0 at 187 207 \pinlabel* $K$ [r] <1pt,Opt> at 125 272 _Mathematical Sciences Publishers: documentation_ ### Old syntax pinlabel.sty is a revised version of geompsfi.sty and the old syntax remains available for backwards compatibility. The simplest version is: \setlabel{a^b}{321}{33}{1} which pins the label \(a^{b}\) by (1,1) (ie [tr]) to (321, 33) with autospacing applied. Note that the $$'s for math mode are not given with the label in this syntax. Two new options have been added to the old syntax. There is a starred form: \setlabel*{a^b}{321}{33}{1} which is the same but with autospacing suppressed, and fine adjustments may be added: \setlabel<-2pt,-1pt>{a^b}{321}{33}{1}{1} \setlabel*<-2pt,-1pt>{a^b}{321}{33}{1}{1} which are the same but with a (-2pt,-1pt) adjustment added. The old and new syntax may be mixed in a labellist or inside a.lab file. **Important notes** (1) \mathsurround is set to zero when parsing the label. This was not done in geompsfi, so the command is _not quite_ backwards compatible. If no \mathsurround is used there is no change in label positioning. If \mathsurround is used then labels may move a small amount horizontally. (2) The label is in horizontal mode in standard (\pinlabel) syntax but in math mode in the old (\setlabel) syntax, so care should be taken if the syntaxes are mixed. ### Errors The program will attempt to recover from syntax errors. Roughly speaking, provided the \pinlabel command terminates with at XXX YYY where there are spaces round the at and XXX, YYY are pure numbers, then the label (the code after \pinlabel up to the first unbraced space) will appear in the diagram. If the program does not recognise the syntax between the label and the at then you will get the following warning: I don't understand your positioning information for label #1 and shall ignore it; or perhaps your label has a space and needs braces. where #1 is replaced by the actual label code. If there is no at then the program has a harder time recovering but you should get the following warning: There is something wrong with your syntax for label #1; you must finish with " at XXX YYY" : the "at" and spaces are important! I'm going to try to ignore this label: don't blame me if there are some funny numbers in your diagram and later labels are out-of-position. _Mathematical Sciences Publishers: documentation_By looking at the finished diagram, you should be able to pick out where the error lies. If all that is wrong with the syntax is that the position code has been mistyped then you should just get the following warning: Unknown position code [#2]; I shall ignore it. where [#2] is the mistyped code. If you make a basic tex error (unmatched $.$'s for example) then you should get an error missing $ or similar. If all else fails, check each \pinlabel command against the samples given here. ### Bounding boxes In 1.2 it was mentioned that conversion from.eps to.pdf may change the bounding box. In a.pdf file the bounding box always has bottom-left corner at 0 0 but this is not true for an.eps file. The recommended converter epstopdf does not change the _size_ of the bounding box but merely moves the bottom-left corner to 0 0. This implies that an.eps file used to position labels can safely be discarded if and only if the bottom-left corner in the bounding box in the.eps file is in fact at 0 0. If you need to know the deep detail on how pinlabel reads the bounding box, read on. If a bounding box is supplied via options to \includegraphics or \psfig, eg \includegraphics[bbllx=10bp,bblly=12bp,bburx=150bp,bbury=273bp,width=2in]{fig}, which specifies the box 10 12 150 273 (the bp specifies postscript points), then this specification is used _whatever the actual bounding box is for the graphics files._ Otherwise pinlabel looks for a file named fig.ps or fig.eps or fig.pdf _in that order_. If it finds such a file, it reads the bounding box and uses that. If there is no file fig.ps or fig.eps or fig.pdf or if pinlabel cannot find a bounding box in the first of these that exists, then you get an error message and no figure is typeset. ## 5 Bugs No spaces are permitted in the file argument of \psfig. Autotranslation of graphicx means that no spaces are permitted in the file argument to \includegraphics. Thus \includegraphics[width=4in]{ foo } will produce errors. It should be typed \includegraphics[width=4in]{foo}. Spaces are permitted with other arguments. Many of the options in graphicx are not supported by autotranslation. The supported ones are: width, height, scale, bbllx, bbllly, bburx, bbury and clip. The syntax for clip is clip=. Replace keepaspectratio=true by proportional=. The arguments to bbllx etc must be specified in postscript points (see the example above). \graphicspath{} is not supported. Automatic configuration for dvips and pdflatex is included in the program. No support is provided for other drivers. The program is fully compatible with plain tex via the latex interpreter miniltx.tex written by <NAME>. It works with dvips but _not_ with pdfltex. For pdf output from plain tex use dvips followed by ps2pdf. **Note**\psfig ouputs a vbox, which is not centred in the latex {center} environment. Either use \centerline{} or type \leavevmode before \psfig{..}. The translator adds \leavevmode for \includegraphics, which therefore centres correctly as usual in the {center} environment. ## 6 Why pinlabel? This section reviews other labelling packages and attempts to answer the obvious question: why do we need a new package? Well the first obvious comment is that the package is not new. It is the old package geompfsi, rewritten, with extra functionality and new syntax. However it is fully backwardly compatible and all geompfsi diagrams should compile perfectly with pinlabel (with one small caveat, see note (1) in Section 4.2). ### rlepsf and psfrag Turning to other packages which are capable of perfect TeX formatted labels, there are two relabelling packages rlepsf and psfrag which replace dummy labels in the.eps file with tex labels specified in the.tex file. Both of these are incompatible with pdflatex, which makes them now unsuitable for figures created from scratch. They depend on low level interfacing with PostScript via \special commands. Indeed both are somewhat sensitive as to the precise nature of the.eps file being relabelled. If you have a file with figures relabelled using rlepsf or psfrag, the most robust way to make it pdflatex compatible is to relabel the figures using pinlabel. (But you can also treat the figures like pstricks figures etc, see Section 6.5.) ### Combined output from xfig xfig is capable of creating figures with properly formatted tex labels using combined ps/latex (pstex) or combined pdf/latex output. This works well, and existing figures using this system can be used with pdflatex with only minor changes: if you export as combined ps/latex (pstex) you have to rename the.pstex file (which is in fact an.eps file) to an.eps file and convert to.pdf and in both cases you have edit the \includegraphics{} command to remove the.pstex or.pdf extension. However starting from scratch, it is much more efficient to create unlabelled.eps or.pdf files in xfig and then add labels with pinlabel. The positioning of the labels in xfig is hit-and-miss and difficult to adjust: you have to keep the.fig file open, move the label a little, re-export, reconvert to.pdf, recompile, repeat.... Using pinlabel the label is usually positioned perfectly first time and can be adjusted without reopening xfig, which is far more efficient. ### overpic, labelfig, xyoverpic and WARMreader There are three packages which, like pinlabel add the labels as an overlay on an existing.eps figure and therefore produce robust code suitable for pdflatex. overpic is the most basic. Reading label positioning is pure guesswork (using a simple grid) and there are no fine adjustments for positioning, which makes the final tuning very time-consuming (and highly sensitive to any last-minute change of scale). labelfig is slightly more sophisticated, but reading label positioning is the same guesswork as for overpic, there are some position codes, but again there is no fine adjustment and moreover the syntax is _awful_: \SetLabels \E(.18*.68) $F$\ \E(.39*.68) $G$\... \E(.75*.2) or\ \E(.88*.2) $F$\ \endSetLabels %\ShowGrid \AffixLabels{\BoxedEPSF{Mutant.ARTscaled 500}}} xyoverpic is much more sophisticated, offering a good deal of the functionality of pinlabel. But accurate positioning of labels requires a preprocessor such as WARMreader. You can also read the label positions using ghostview but you have tobe clever to do this. Firstly you need to make sure that your.eps file has its bounding box starting at (0,0) then you need to supply the other bounding box coordinates directly after \begin{xyoverpic*} (they are (280,210) in the example below) to set the scaling; then the ghostview coordinates can be used. The syntax for the actual labels is, if anything, worse than labelfig but it does have both a position code and an element of fine positioning built in: \begin{xyoverpic*}{(280,210)}{scale=0.75}{figures/pgl-orbifold} ,(0,107)**++!R{4} ,(64,178)**++!DR{4} ,(278,107)**++!L{2} ,(130,136)**++!LD{2} ,(172,107)**++!U{3} \end{xyoverpic*}} By contrast, pinlabel uses ghostview coordinates for files whose bounding box does not start at (0,0) and the syntax is transparent. ### Summary To summarise the advantages of pinlabel over existing packages which do a broadly similar job: only xyoverpic with the the tweaks described above (or with WARMreader input) gets location in diagram accurate first time. But it is marred by impossible syntax and limited fine adjustment. pinlabel gets a similar accuracy in positioning and has transparent syntax and arbitrary fine adjustment. Moreover pinlabel has a powerful feature not shared by any other package: the ability to pin labels using arbitrary pin positions, specified in instrinsic coordinates in the label. This has not been stressed in this manual because it is rarely necessary in hand constructed diagrams, but for machine generated code it is very useful indeed. For example <NAME> (who originated this feature) writes: "_I find it very convenient to place (small,_mathematica-_generated_) _labels around a circle, say, by pinning the label at \((-\cos\theta,-\sin\theta)\) in label coordinates. This works very well._" ### spstricks, epic, specials Before leaving the topic of other packages, there are a number of packages which, like rlepsf and psfrag interface directly with PostScript. All are unsuitable for use with pdflatex for this reason. If faced with a file containing such figures, you need to precompile the figures using latex then dvips -E (or dvips followed by ps2epsi, which is more robust about bounding box placement) and then epstopdf to produce a.pdf file for inclusion in the usual way. ## 7 Pinlabeler and labelpin <NAME> has written an extremely useful extension to gv, called pinlabeler which automatically copies the coordinates of the cursor in gv to a text file open for editing. To be precise it writes a line like: \pinlabel {$$} [] at XXX YYY into the file at the position of the cursor (in the editor) where XXX YYY are the PS coordinates of the cursor in gv. It does this when you click on a point in the gv window. This makes transcribing coordinates much simpler: you just click on the label position and then fill in the label and positioning code. You can find full details (including installation instructions) at: [http://hans.math.upenn.edu/~pstorm/pinlabeler.html](http://hans.math.upenn.edu/~pstorm/pinlabeler.html) <NAME> has written a similar program labelpin, which is a python script and therefore, unlike Storm's program, does not need compilation. Both work perfectly with cygwin under Windows (pinlabeler comes ready compiled for cygwin) and both work perfectly with.pdf figures, moreover labelpin works on a Mac. The script and instructions for labelpin can be downloaded from: [http://www.math.uiuc.edu/~nmd/software/](http://www.math.uiuc.edu/~nmd/software/) ## 8 Acknowledgements and copyright notice pinlabel is based on geompsfi.sty written by Silvio Levy which in turn is based on psfig.sty written by <NAME>. Their agreement to this development is gratefully acknowledged. Silvio Levy has made several helpful suggestions and done extensive testing and debugging. Thanks also to <NAME>, <NAME>, <NAME> and <NAME> for helpful suggestions, testing and debugging, and also to <NAME> for providing the code that reads the bounding box from a.pdf file, thus making.eps versions of figure files unnecessary when using pdflatex. ### Copyright notice The following notice appears at the start of the source file: Copyright 2006-11 Mathematical Sciences Publishers (MSP) NOTICE This package may be distributed and/or modified under the conditions of the LaTeX Project Public License, either version 1.3 of this license or (at your option) any later version. The latest version of this license is in [http://www.latex-project.org/lppl.txt](http://www.latex-project.org/lppl.txt) and version 1.3 or later is part of all distributions of LaTeX version 2005/12/01 or later. This package has the LPPL maintenance status'maintained' and is currently maintained by MSP: <EMAIL> It comprises the files: pinlabel.sty (this file) and the manual pinlabdoc.pdf where full documentation may be found, together with the source files for the documentation. ## References * [1]**<NAME>**, _Modifying surfaces in 4-manifolds by twist spinning_, Geom. Topol. 10 (2006) 27-56 Mathematical Sciences Publishers, Department of Mathematics University of California, CA 94720-3840, USA <EMAIL> [http://www.mathscipub.org](http://www.mathscipub.org)
liayson
cran
R
Package ‘liayson’ October 13, 2022 Type Package Title Linking Singe-Cell Transcriptomes Atween Contemporary Subpopulation Genomes Version 1.0.5 Date 2022-09-17 Author <NAME> Maintainer <NAME> <<EMAIL>> Description Given an RNA-seq derived cell-by-gene matrix and an DNA-seq derived copy num- ber segmentation, LIAYSON predicts the number of clones present in a tu- mor, their size, the copy number profile of each clone and the clone membership of each sin- gle cell (<NAME>. & <NAME>., et al. (2018) <doi:10.1101/445932>). License GPL-2 URL https://github.com/noemiandor/liayson Depends R (>= 3.0) Imports phangorn, RColorBrewer, ape, parallel, plyr, matlab, biomaRt, distances, arules, e1071, proxy, gplots, methods Suggests mclust, fpc, NbClust, modeest, pastecs, vegan NeedsCompilation no Repository CRAN Date/Publication 2022-09-29 20:40:02 UTC RoxygenNote 6.1.1 R topics documented: aggregateSegmentExpressio... 2 assignCellsToCluster... 3 clusterCell... 4 cnp... 5 ep... 6 ep... 6 getNumRe... 7 runLIAYSO... 7 saveClusteredCell... 8 segmentExpression2CopyNumbe... 9 segment... 11 aggregateSegmentExpression Aggregating genes across copy number segments. Description Calculates average expression of genes grouped by common segment membership. Usage aggregateSegmentExpression(epg, segments, dataset="hsapiens_gene_ensembl", mingps = 20, GRCh = 37, host=NULL) Arguments epg Gene-by-cell matrix of expression. Recommendation is to cap extreme UMI counts (e.g. at the 99% quantile) and to include only cells expressing at least 1,000 genes. segments Matrix in which each row corresponds to a copy number segment as calculated by a circular binary segmentation algorithm. Has to contain at least the follow- ing column names: chr - chromosome; startpos - the first genomic position of a copy number segment; endpos - the last genomic position of a copy number segment; CN_Estimate - the copy number estimated for each segment. dataset Dataset to download from BioMart. mingps Minimum number of expressed genes a segment needs to contain in order to be included in output. GRCh Human reference genome version to be used for annotating gene coordinates. host Host address used by BioMart. Details Let S := { S1 , S2 , ...Sn } be the set of n genomic segments that have been obtained from DNA- sequencing a given sample (e.g. from bulk exome-sequencing, scDNA-sequencing, etc.). Genes are mapped to their genomic coordinates using the biomaRt package and assigned to a segment based on their coordinates. Genes are grouped by their segment membership, to obtain the average number of UMIs and the number of expressed genes per segment Sj per cell i. Value List with fields: eps Segment-by-cell matrix of expression values. gps Segment-by-cell matrix of the number of expressed genes. Author(s) <NAME> Examples data(epg) data(segments) X=aggregateSegmentExpression(epg, segments, mingps=20, GRCh=38) assignCellsToClusters Assigns cells to previously defined clones. Description Cells that have not been used to define clones (such as cycling or apoptotic cells) can retrospectively be assigned a clone membership. Usage assignCellsToClusters(outc, xps, similarity=T) Arguments outc List containing segment-by-cell matrix and clone membership of each cell. See clusterCells). xps Segment-by-cell matrix of expression- or copy number states. Columns repre- sent new cells to be assigned to existing clones. similarity Whether to use similarity (similarity=T) or distance (similarity=F), when com- paring cells to existing clones. Default similarity metric is "correlation. Default distance metric is "Euclidean". Details Let S := { S1 , S2 , ...Sn } be the set of n genomic segments obtained from bulk DNA-sequencing. Further, let SI ∈ S be the subset of segments for which cells within a clone have a well defined copy number state. Pearson Correlation Coefficients are calculated as similarity metric between each new cell and the consensus profile of each clone, based on segments s ∈ SI . Each cell is assigned to the clone to which it is most similar. Alternatively, if similarity is set to false, the Euclidean distance metric is used instead of the Pearson Correlation. Value List with same components as input: cnps Segment-by-cell matrix of copy number states, with new cells added as columns. sps The clone membership of each cell (that is columns in cnps). Author(s) <NAME> Examples data(cnps) data(eps) set.seed(3) rcells1 = sample(colnames(cnps), 120) rcells2 = setdiff(colnames(eps), rcells1) outc = clusterCells(cnps[apply(cnps, 1, var)>0, rcells1]) outc = assignCellsToClusters(outc, eps[,rcells2]) clusterCells Grouping cells into clones. Description Clusters cells according to their copy number profile. Usage clusterCells(cnps, k=NA, h=NA, weights=NULL, minSegLength=1E6, chrOrder=NULL, HFUN="ward.D2", crit="AIC",...) Arguments cnps Segment-by-cell matrix of copy number states (output of segmentExpression2CopyNumber). k Desired number of clusters (see also cutree). h Threshold used to define clones from hierarchical clustering result. A subtree is defined as a clone if the maximum distance between its cell members is less than 100*h% of the genome. weights Vector of weights assigning differential importance to segments (typically cal- culated based on segment lengths). minSegLength Minimum number of base pairs below which a segment is to be excluded when defining clones. chrOrder Specifies order in which chromosomes should be plotted. HFUN Agglomeration method used to compute the hierarchical clustering (see also hclust). crit Criterion used to opimize number of clusters. ... additional arguments passed on to heatmap.2 Details Let CNF be the matrix of copy number states per non-private segment per cell, with entries (i, j) pointing to the copy number state of cell j at locus i. Pairwise distances between cells are calculated in Hamming space of their segmental copy number profiles (rows in CNF), weighted by segment length. Hierarchical clustering is used to build a tree of the cells from the distance matrix. A subtree is defined as a clone if the maximum distance between its cell members is less than a user-defined fraction of the genome (h). Alternatively, if k is set, the tree is cut to obtain k clones. If neither h nor k are set, Akaike information criterion is used to decide on anywhere between 1 and 30 clones. Value List with three fields: cnps Segment-by-cell matrix of copy number states. sps The clone membership of each cell (that is, columns in cnps). tree An object of class hclust. Author(s) <NAME> References <NAME>.*, <NAME>.*, <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., et al. (2018) Joint single cell DNA-Seq and RNA-Seq of gastric cancer reveals subclonal signatures of genomic instability and gene expression. doi: https://doi.org/10.1101/445932 Examples data(cnps) set.seed(3) rcells = sample(colnames(cnps), 120) outc = clusterCells(cnps[apply(cnps, 1, var)>0, rcells]) cnps Segment-by-cell matrix of copy number states from NCI-N87 cell line. Description Matrix of segments (rows) x 200 cells (columns) with entries denoting inferred copy numbers. Usage data(cnps) Source Data obtained from Ji lab at Stanford. epg Gene-by-cell matrix of expression from NCI-N87 cell line. Description Matrix of genes (rows) x 200 cells (columns) with entries denoting UMI counts. Usage data(epg) Source Data obtained from Ji lab at Stanford. eps Segment-by-cell matrix of expression from NCI-N87 cell line. Description Matrix of segments (rows) x 200 cells (columns) with entries denoting average expression values. Usage data(eps) Source Data obtained from Ji lab at Stanford. getNumRes Clone size resolution. Description Informs user about resolution at which clone sizes are stored. Usage getNumRes() Details For internal and external use. Author(s) <NAME> runLIAYSON Main Function. Description Given an RNA-seq derived cell-by-gene matrix and an DNA-seq derived copy number segmenta- tion, LIAYSON predicts the number of clones present in a tumor, their size, the copy number profile of each clone and the clone membership of each single cell. Usage runLIAYSON(X, S, sName, mingps = 20, GRCh = 37, h = 0.2, minSegLength=1E6, outD = NULL) Arguments X Gene-by-cell matrix of expression. Recommendation is to cap extreme UMI counts (e.g. at the 99% quantile) and to include only cells expressing at least 1,000 genes. S Matrix in which each row corresponds to a copy number segment as calculated by a circular binary segmentation algorithm. Has to contain at least the follow- ing column names: chr - chromosome; startpos - the first genomic position of a copy number segment; endpos - the last genomic position of a copy number segment; CN_Estimate - the copy number estimated for each segment. sName Sample name. mingps Minimum number of expressed genes a segment needs to contain in order to be included in output. GRCh Human reference genome version to be used for annotating gene coordinates. h Height at which the tree should be cut (see also cutree). minSegLength Minimum number of base pairs below which a segment is to be excluded when defining clones. outD The output directory. Author(s) <NAME> See Also clusterCells segmentExpression2CopyNumber Examples data(epg) data(segments) out = runLIAYSON(epg, segments, sName="NCI-N87", GRCh = 38, h=0.05) saveClusteredCells Saving clones to user-defined output. Description Writes clone statistics, dendrogram and clone-specific mutation profiles. Usage saveClusteredCells(outc, expression, ccMembership, sName, outD) Arguments outc Output of clusterCells or assignCellsToClusters: list containing segment- by-cell matrix, clone membership of each cell and the underlying dendrogram. expression Gene-by-cell matrix of expression. ccMembership List with each entry containing all cell IDs associated with a given cell cycle state. Must include entry ’G1Malignant’, containing the IDs of G0G1 tumor cells. sName Prefix for the output files (typically the sample name). outD The output directory. Details Writes each of the following aspects of a sample’s clonal composition into an output file: 1. The clone membership of each cell (*.spstats) 2. The segment-by-cell matrix of copy number states (*.sc.cbs) 3. The consensus copy number profile of each detected clone, calculated as the average profile of cells that are members of the respective clone (*.sps.cbs) 4. The cell dendrogram (*.tree). 5. For each clone, a segment-by-cell matrix of copy number states for all cell members of that clone. Author(s) <NAME> segmentExpression2CopyNumber Calling CNVs. Description Maps single cell expression profiles to copy number profiles. Usage segmentExpression2CopyNumber(eps, gpc, cn, seed=0, outF=NULL, maxPloidy=8, Arguments eps Segment-by-cell matrix of expression. gpc Number of genes expressed per cell. cn Average copy number across cells for each segment (i.e. row in eps). seed The fraction of entries in a-priori segment-by-cell copy number matrix to be used as seed for association rule mining. outF Output file prefix in which to print intermediary heatmaps and histograms, or NULL (default) if no print. maxPloidy The maximum ploidy to accept as solution. nCores The numbers of threads used. stdOUT Log-file to which standard output is redirected during parallel processing. Details Let S := { S1 , S2 , ...Sn } be the set of n genomic segments obtained from bulk DNA-sequencing. Let Eij and Gij be the average number of UMIs and the number of expressed genes per segment i per cell j. The segment-by-cell expression matrix is first normalized by gene coverage. For each x ∈ S, the linear regression model: X Ex∗ ∼ Gi∗ i∈S , fits the average segment expression per cell onto the cell’s overall gene coverage. The model’s residuals Rij reflect inter-cell differences in expression per segment that cannot be explained by differential gene coverage per cell. A first approximation of the segment-by-cell copy number ma- trix CN is given by: CNij := Rij ∗ (cni /R¯i∗ ) , where cni is the population-average copy number of segment i derived from DNA-seq. Above transformation of Eij into CNij is in essence a numerical optimization, shifting the distribution of each segment to the average value expected from bulk DNA-seq. Let x0 ∈ CN be the measured copy number of a given segment-cell pair, and x its correspond- ing true copy number state. The probability of assigning copy number x to a cell j at locus i depends on: A. Cell j’s read count at locus i, calculated conditional on the measurement x0 . Using a Gaussian smoothing kernel, we compute the kernel density estimate of the read counts at locus i across cells to identify the major (M ) and the minor (m) copy number states of i as the highest and second highest peak of the fit respectively. Then we calculate the proportion of cells expected at state m as i −M f = cn m−M . The probability of assigning copy number x to a cell j at locus i is calculated as: PA (x|x0 ) ∼ : 0, if x ∈/ m, M : Pij (x0 |N (m, sd = f )), if x == m : Pij (x0 |N (M, sd = 1 − f )), if x == M B. Cell j’s read count at other loci, i.e. how similar the cell is to other cells that have copy number x at locus i. We use Apriori - an algorithm for association rule mining - to find groups of loci that tend to have correlated copy number states across cells. Let Vi,K→x be the set of rules concluding copy number x for locus i, where k ∈ K are copy number profiles of up to n = 4 loci in the form { S1 = x1 , S2 = x2 , ...Sn = xn }. Further let Cr be the confidence of a rule r ∈ Vi,K→x . P j ∈ J matching any of the copy number profiles in K, we calculate: For each cell PB (x) ∼ r∈Vi,K→x Cr , the cumulative confidence of the rules in support of x at i. We first obtain a seed of cell-segment pairs by assigning a-priori copy number states only when argmaxx∈[1,8] PA (x|x0 ) > t. We use this seed as input to B. Finally, a-posteriori copy number for segment i in cell j is calculated as: argmaxx∈[1,8] PA (x|x0 ) + PB (x) Value Segment-by-cell matrix of copy number states. Author(s) <NAME> References <NAME>.*, <NAME>.*, <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., et al. (2018) Joint single cell DNA-Seq and RNA-Seq of gastric cancer reveals subclonal signatures of genomic instability and gene expression. doi: https://doi.org/10.1101/445932 Borgelt C & <NAME>. (2002) Induction of Association Rules: Apriori Implementation. See Also apriori Examples ##Calculate number of genes expressed per each cell: data(epg) gpc = apply(epg>0, 2, sum) ##Call function: data(eps) data(segments) cn=segments[rownames(eps),"CN_Estimate"] cnps = segmentExpression2CopyNumber(eps, gpc, cn, seed=0.5, nCores=2, stdOUT="log") head(eps[,1:3]); ##Expression of first three cells head(cnps[,1:3]); ##Copy number of first three cells segments Bulk copy number profile of NCI-N87 cell line. Description Copy number segmentation matrix obtained as average among G0G1 cells. Usage data(segments) Format Matrix in which each row corresponds to a copy number segment as calculated by a circular binary segmentation algorithm. Has to contain at least the following column names: chr - chromosome; startpos - the first genomic position of a copy number segment; endpos - the last genomic position of a copy number segment; CN_Estimate - the copy number estimated for each segment. Source Data obtained from Ji lab at Stanford.
sigs.k8s.io/gateway-api
go
Go
README [¶](#section-readme) --- ### Kubernetes Gateway API The Gateway API is a part of [SIG Network](https://github.com/kubernetes/community/tree/master/sig-network), and this repository contains the specification and Custom Resource Definitions (CRDs). #### Status The latest supported version is `v1beta1` as released by the [v0.7.0 release](https://github.com/kubernetes-sigs/gateway-api/releases/tag/v0.7.0) of this project. This version of the API is has beta level support for the following resources: * `v1beta1.GatewayClass` * `v1beta1.Gateway` * `v1beta1.HTTPRoute` * `v1beta1.ReferenceGrant` For all other APIs we provide alpha level support. #### Documentation ##### Website The API specification and detailed documentation is available on the project website: [https://gateway-api.sigs.k8s.io](https://gateway-api.sigs.k8s.io/). ##### Concepts To get started, please read through [API concepts](https://gateway-api.sigs.k8s.io/concepts/api-overview) and [Security model](https://gateway-api.sigs.k8s.io/concepts/security-model). These documents give the necessary background to understand the API and the use-cases it targets. ##### Getting started Once you have a good understanding of the API at a higher-level, check out [getting started](https://gateway-api.sigs.k8s.io/v1alpha2/guides) to install your first Gateway controller and try out one of the guides. ##### References A complete API reference, please refer to: * [API reference](https://gateway-api.sigs.k8s.io/v1alpha2/references/spec) * [Go docs for the package](https://pkg.go.dev/sigs.k8s.io/gateway-api/apis/v1alpha2) #### Contributing Community meeting schedule, notes and developer guide can be found on the [community page](https://gateway-api.sigs.k8s.io/contributing/community). Our Kubernetes Slack channel is [#sig-network-gateway-api](https://kubernetes.slack.com/messages/sig-network-gateway-api). ##### Code of conduct Participation in the Kubernetes community is governed by the [Kubernetes Code of Conduct](https://github.com/kubernetes-sigs/gateway-api/blob/v0.8.1/code-of-conduct.md). None
hoodie
npm
JavaScript
hoodie === > A generic backend with a client API for Offline First applications Hoodie lets you build apps [without *thinking* about the backend](http://nobackend.org/) and makes sure that they work great [independent from connectivity](http://offlinefirst.org/). This is Hoodie’s main repository. It starts a server and serves the client API. Read more about [how the Hoodie server works](https://github.com/hoodiehq/hoodie/blob/HEAD/server). A good place to start is our [Tracker App](https://github.com/hoodiehq/hoodie-app-tracker). You can play around with Hoodie’s APIs in the browser console and see how it works all together in its [simple HTML & JavaScript code](https://github.com/hoodiehq/hoodie-app-tracker/tree/master/public). If you have any questions come say hi in our [chat](http://hood.ie/chat/). Setup --- This setup is working for all operating system, testing on Windows 8, Windows 8.1, Windows 10, Mac and Linux. Hoodie is a [Node.js](https://nodejs.org/en/) package. You need Node Version 4 or higher and npm Version 2 or higher, check your installed version with `node -v` and `npm -v`. First, create a folder and a [package.json](https://docs.npmjs.com/files/package.json) file ``` mkdir my-app cd my-app npm init -y ``` Next, install hoodie and save it as dependency ``` npm install --save hoodie ``` Now start up your Hoodie app ``` npm start ``` You can find a more thorough description in our [Getting Started Guide](http://docs.hood.ie/en/latest/guides/quickstart.html). Usage --- `hoodie` can be used standalone or as [hapi plugin](http://hapijs.com/tutorials/plugins). The options are slightly different. For the standalone usage, see [Hoodie’s configuration guide](http://docs.hood.ie/en/latest/guides/configuration.html). For the hapi plugin usage, see [Hoodie’s hapi plugin usage guide](http://docs.hood.ie/en/latest/guides/hapi-plugin.html) Testing --- Local setup ``` git clone https://github.com/hoodiehq/hoodie.git cd hoodie npm install ``` The `hoodie` test suite is run with `npm test`. You can [read more about testing Hoodie](https://github.com/hoodiehq/hoodie/blob/HEAD/test). You can start hoodie for itself using `npm start`. It will serve the contents of the [public folder](https://github.com/hoodiehq/hoodie/blob/HEAD/public). Backers --- [Become a backer](https://opencollective.com/hoodie#support) and show your Hoodie support! Official Sponsors --- Show your support for Hoodie and [help us sustain our inclusive community](http://hood.ie/blog/sustaining-hoodie.html). We will publicly appreciate your support and are happy to get your word out, as long as it aligns with our [Code of Conduct](http://hood.ie/code-of-conduct/). License --- [Apache 2.0](https://github.com/hoodiehq/hoodie/blob/HEAD/LICENSE) Readme --- ### Keywords * nobackend * offlinefirst
btxFAQ
ctan
TeX
# BiBTeX Tips and FAQ <NAME> See [http://www.michaelshell.org/](http://www.michaelshell.org/) for current contact information. <NAME> Manuscript created on January 10, 2007 based on a post by <NAME> on December 15, 1998 in the thread "Do we need a BibTeX FAQ?" in the newsgroup comp.text.tex. The latest version of this document can be obtained on CTAN [1]. This work is distributed under the LaTeX Project Public License (LPTL) ( [http://www.latex-project.org/](http://www.latex-project.org/) version 1.3. A copy of the LPTL, version 1.3, is included in the base LaTeX documentation of all distributions of LaTeX released 2003/12/01 or later. The opinions expressed here are entirely that of the authors. No warranty is expressed or implied. User assumes all risk. Below is a compilation of helpful practical tips and answers to frequently asked questions primarily concerning the use and operation of BibTeX, but with some related issues on bibliographies and citation as well. It should be noted that some of the advice given here is opinion and should not be taken as unbreakable rules. Nevertheless, by following the tips here, you may be able to avoid some of the problems that many BibTeX users often later confront as they use BibTeX and related tools in increasingly advanced ways. ## 2 Helpful Tips ### General Usage Tips **1. Put the authors' full names (and other information) into database whenever you can.** If you want only initials in the reference list, use an appropriate bibstyle (or create one, see Tip 14) to generate this. One broad principle to remember when entering information into a BibTeX database is that you should err on the side of including too much information rather than too little. Database information can always be omitted according to the BibTeX style file (which is often called a "bibstyle," or ".bst file" to distinguish it from a BibTeX style file), but missing information can't be generated. **2. Put all of the authors' names into the author list.** That is, do not put "and others", unless you don't actually know their names. You never know when you might want to search for one of these "other" authors' name(s). If you want "et al." to appear in the reference list instead of all the names, use an appropriate bibstyle to generate this (or create one, see Tip 14). **3. Put full stops (periods) after abbreviated words in journal names.** If you are required to supply abbreviated journal names without the full stops, use a bibstyle to create this (Tip 14). **4. Special characters are entered as {**"a} or {**"{a}**}**not **"{a}.** This is actually documented in the BibTeX user's manual [4], but it still trips people up. For more information, see Question 5. **5. Design for multiple database files.** Assume that you will eventually end up with more than one BibTeX database (.bib) file (perhaps with each covering a different subject area). You should therefore ensure that the key you choose for each item contains a part that identifies the file, so that there is no chance of ambiguous or duplicated keys when using multiple database files simultaneously. For example, say you have some electrical engineering references, in file elec.bib1, that are of the form @a rticle(elec:smith91,...) and have some software ones, in file soft.bib, that are of the form @article(soft :smith91,...) (assuming these are two different articles, probably by different Smiths). Don't put the same reference in more than one file. It may be a good idea to use a unique, private, id prefix, such as MY_, to help prevent namespace clashes with publicly released databases produced by others. Footnote 1: Note that it is the convention of this document not to hyphenate command or file names and to display them in typewriter font. Within such constructs, spaces are not implied at a line break and will be explicitly carried into the beginning of the next line. **6. Put your usual journal names into @string definitions, in a separate (.bib) file.** The standard bibstyles (plain, abbrv, unsrt, alpha) do contain some journal names, all computing-related. This is not really a sensible place because bibstyles are intended to set the format for the publication you are contributing _to_, not keeping a complete list of the publications you read and cite _from_. But, if you want the ability to choose full or abbreviated titles, you must go one step further and create two files. For example, in one file (say, jrnlfull.bib) you might have: @string{ieee-pas="{IEEE} Transactions on Power Apparatus and Systems"} and in the other (say, jrnlabbr.bib): @string{ieee-pas="{IEEE} Trans. Power App. Syst."} and many other entries. Note that both have the same id-strings. To select full or abbreviated titles, you can place the appropriate file (first) into the \bibliography\(\Omega\) list (Tip 8). IEEE authors should take note that (almost) all IEEE journal name definitions, both full and abbreviated, are included with the IEEEtran Bibstyle package [9]. Users should avoid (re)defining journal name strings that are covered by existing official string definition files already in public distribution. Furthermore, take care to use id-strings that are unlikely to clash with those provided by official files from other users (ieee-pas in the previous example is a poor choice in this regard). As with database entry keys, using a unique, private, id prefix, such as MY_, will help to prevent problems with such namespace clashes. ## 7 Create separate files for cross-referenced entries. Typically this will be for conferences (proceedings) or books. Again, you may wish to create two string definition files, one with full and one with abbreviated titles (if the titles in the cross referenced entries are not all handled by your existing string definition files). Because cross-referenced entries must appear _after_ entries that reference them, it is better to put them in a separate file. Then you need not be worried about using any database access software that might sort or re-order your database entries. ## 8 Use the form \bibliography{jrnl-names,other-database(s),cross-entries}. This ensures that all @strings are defined first and that all the cross-referenced entries appear after any entries that reference them. The selection of full or abbreviated titles is just a matter of selecting the appropriate files for this list. With this method, the abbreviation of titles does not need to be coupled to the abbreviation of authors' names to initials (the way standard bibstyle abbrv.bst works) so you will have much more flexibility. ### Citation Tips One of the aims of LaTeX is to enable the author to think about the structure of a piece of writing rather than its visual appearance. This principle should also apply to citations -- one should be able to write without considering the citation format until later. Unfortunately, this is not always possible. Indeed, one of the reasons for Patashnik's dislike of author-date referencing is that it affects one's writing style, encouraging vagueness and a passive voice [4, section 4]. However, if you have to use author-date referencing, it _might_ be worthwhile to try to structure your work so that the citation format can be easily changed at will. The following points relate to the appearance of the citations in the text and to writing for numerical and/or author-date referencing styles. Place \cite commands ahead of any punctuation like commas or full stops (periods), not just after them. This applies even if you are intending to use superscripts for your references, despite the fact that superscripts should appear after such punctuation (Tip 10). ## 10 Use Donald Arseneau's cite.sty or overcite.sty [10]. If you are using a numerical referencing style (the standard form) obtain and use one of these packages. Cite.sty and overcite.sty both order index numbers and replace consecutive numbers with a range (e.g., [7,9,5,6,4,3] becomes [3-7,9]). They also allow you to customize the punctuation and spacing of the citation numbers. Cite.sty will fix up any spacing problems, and overcite.sty will place superscripts after any punctuation (which is the correct behavior) even when you have followed Tip 9. Note that as of version 4.0 (2003-05-27) cite.sty contains all the functionality of overcite.sty. To invoke overcite mode, simply load cite.sty with its superscript package option. ## 11 Use <NAME>'s natbib.sty (or <NAME>' harvard.sty, etc.) for author-date references If you use an author-date style of citations, your choice of style will probably be dictated by the publications you write for. If there is an existing bibstyle that exactly suits your needs, use it in conjunction with the most recent author-date package(s) that support it. Otherwise, use makebst (Tip 14) to generate a suitable bibstyle that can then be used with natbib.sty or harvard.sty. Natbib is the most recent, powerful and widely used author-date citation package [11]. Harvard.sty [12] is also commonly used and respected -- although potential users should be warned that it was last updated in 1995. There may be limitations and problems when using author-date packages older than these. For instance, if you are also using chapterbib.sty, harvard.sty works without alteration, but chicago.sty [13] must be modified according to the instructions in chapterbib.sty. If you must use an older author-date package, you might still want to use makebst to create a modern bibstyle that is superior to the original. For example, chicago.bst does not handle cross references from inproceedings entries to proceedings entries correctly, but its makebst equivalent does. Don't bother with authordate1-4.sty because these have been vastly superseded by the more recent and/or powerful packages such as natbib.sty, harvard.sty, etc. ## 12 Writing for both numerical and author-date referencing styles: In principle, you should write so that you can change the referencing style when required without re-writing everything. A standard citation presents no problems: The phase-coordinate representation [18] requires... The phase-coordinate representation (Laughton 1968) requires... A standard \cite command will produce whichever of these is determined by the style/bibstyle combination. But, problems can arise when the authors' names are integrated into the text: Laughton [18] developed the theory... Laughton (1968) developed the theory... The author-date styles provide a means of generating both the authors' names and the date in this form, using variations of the \cite command, but the standard numerical styles do not. There are two approaches to getting around this problem when writing for both styles. One is not to use the facilities of author-date styles for supplying the names, but to type the names into the text explicitly just as you would have done if using only the numeric form of citation. This means you must check the consistency and spelling of the authors' names yourself. Following the authors' names must be a citation command that (if using numerical referencing) will generate a reference number in the usual way, but if using author-date referencing, will generate only a date (not a full reference). The first requires a \cite command, the second a \citeyear command from natbib.sty, harvard.sty, chicago.sty, etc. (Natbib also has a separate \citeyear command to get the year within parentheses.) This can be done by defining a new command, say \citey, and using that: Laughton \citey{soft:laughton68} developed the theory... For numerical referencing, you would define it as:\newcommand{\cite}}{\cite} and for author-date referencing, it would be: \newcommand{\cite}}{\citeyearpar}%natbib or: \newcommand{\cite}}{\citeyear} The second approach to this problem is to use a style that can supply authors' names integrated into the text -- even when using numerical referencing. <NAME>'s natbib.sty can do this. Natbib is very flexible in terms of citation style and it offers many forms of citation commands to choose from. In numerical mode, the standard \cite command produces a normal numeric reference. However, in author-date mode, it does not produce a standard reference, but instead places the author's name outside the parentheses. For example, the standard \cite command will produce the following when using natbib: The phase-coordinate representation [18] requires... The phase-coordinate representation Laughton (1968) requires... which is not what is desirable for transparent switching between numerical and author-date referencing styles. To get a reference with the authors' names in the text in both numerical and author-date referencing modes, the \citet command is provided. Page references can be accomplished by using \citet's second optional argument, e.g., \citet[][p. 35]{soft:laughton68}: ... the opposite view is taken by Laughton [18, p. 35]...... the opposite view is taken by Laughton (1968, p. 35)... It should also be mentioned that natbib.sty does not provide all of the functionality of cite.sty or overcite.sty in numerical mode. It does order the numbers and calculate ranges, but it does not fix spacing problems. In superscript form, it does not move the superscripts to the correct side of any punctuation the way that overcite.sty does. Some authors prefer to use the first approach to this problem (typing the authors' names explicitly and defining a \cite type command), while other authors prefer the second (Natbib) option. Thanks to <NAME> for posting some information to the newsgroup comp.text.tex on December 14, 1998 in the thread "Do we need a BibTeX FAQ?" that was used to revise this section. ### Internet and Other Special Reference Tips **13. If you must include URLs, use Donald Arseneau's url.sty to provide good formatting of them.** Think carefully about references to World Wide Web or other internet-based addresses. Your readers should be able to follow up the references you give them. If they might be reading years after you have written, will the URLs you give still exist? Will the contents at those addresses still be the same, or might someone have modified them? If you decide that it is appropriate to supply URLs (or e-mail addresses, or whatever), use url.sty [14] to control the format of them. Recent versions of makebst (Tip 14) can produce bibstyles that support a URL field. Harvard.sty also recognizes a URL field, and formats it using the \harvardurl command. The results are not as good as those produced by url.sty. However, url.sty can be used with harvard.sty. To do so, place \renewcommand{\harvardurl}{URL: \url} in your document preamble somewhere after loading harvard.sty. If you are using a bibstyle that does not recognize the URL field, you'll have to place \url{your-URL-string} into the note field (or make a new bibstyle with makebst). The recent version of hyperref.sty also provides a good \url command [15]. Also, see Section 3.3. ### Bibstyle Design Tips **14. Use <NAME>'s makeupst package to create custom.bst styles.** Not only can you make Bibstyles to order, but makeupst-created versions of the standard bibstyles are often better than the originals. Your bibstyles can strip periods from journal names (Tip 3), or generate limited author lists followed by "et al." (Tip 2) and many, many other variations. Makebst is part of the custom-bib package [16]. ## 3 Frequently Asked Questions ### General Usage Questions **Q1: Where do I go for support for BibTeX?** <EMAIL> no longer works. Instead, post your question to the Usenet group comp.text.tex. **Q2: When will the next version of BibTeX (e.g., BibTeX 1.00) be released?** When Oren is finished with it. ;) In the meantime, the above tips should be enough to get BibTeX 0.99c to serve as needed. The slides from Oren's 2003 TUG talk on the future of BibTeX are available online [17] for those of you who are interested. **Q3: Where can I find collections of BibTeX database files?** There are many of them scattered among the various schools and societies -- use your favorite internet search engine to find those most relevant to your work. However, <NAME>'s TeX User Group Bibliography Archive stands apart as one of the largest BibTeX database collections ever assembled [18]. **Q4: When should I enclose my.bib file entry fields with "" and when should I enclose them with!) and why?** Functionally, it does not matter whether braces or quotes are used to delimit the entire field. Some people prefer to use quotes for aesthetic reasons. However, with the current versions of BibTeX, if you need to use a " character within the field, then you'll have to enclose the " character in braces or use braces as delimiters for the entire field. In BibTeX, there are no other valid field delimiters besides quotes and braces. **Q5: I am confused about the difference between special characters and the use of braces to protect text from case changes. Also, when should I "shield" things with braces?** The rules that govern all this are simple, but confusing. BibTeX considers everything within a {\.. } construct at brace level 0 (and _only_ brace level 0), that is the top level of bracing of the field (which is not affected by whether quotes or braces are used to delimit the entire field), to be a "special character" and will treat is though the entire construct is a single character. Within special characters, control sequences (ETEX commands) will be preserved as is, but all other text may be case changed or otherwise processed as needed. Furthermore, within special characters, additional levels of braces do _not_ increment the brace level. On the other hand, {.. } constructs at brace level 0 (the key here is that a \ does not immediately follow the opening brace -- if so, it would make it a special character) do increment the brace level as well as do nested braces within them. All text and control sequences at brace level 1 or higher is protected from case changes or other processing. It is perhaps easier to understand from an example. Consider: title = "L0 {}relax S0 {S0 {S0}}} L0 {L1 {}relax L2 {L3}} L1} \LaTeX} L0"where Lx indicates brace level \(x\) and Sx indicates a (part of a) special character at brace level \(x\). Again, nothing would change here if braces had been used to delimit the entire field instead of quotes. The three S0's are all considered to be part of the same special character because they are all within a \... } construct at brace level 0. Text at S0 may be case changed, but the \relax as well as other control sequences in S0 will not be changed. Note that the additional nested braces within the special character do not increment the brace level. Thus, there is no such thing as S1 or higher. The first L1 is at brace level 1 because it is a {.. } (and not a special character). Note that in this case, additional levels of braces do increment the brace level counter. Furthermore, the second {\relax.. is _not_ treated as a special character because it occurs at brace level 1. All characters and control sequences at L1 and higher will be protected from case changes. Note that in this example the control sequence \LaTeX _is_ subject to case changes. Thus, if the bibstyle set the title to lowercase, the resultant \latex command would likely generate an error. With all this in mind, we can look at some practical examples. Consider: title = "Secrets of {NASA}" NASA needs to be enclosed in braces because it is an acronym that must remain in uppercase. Likewise, we usually need to protect math from case changes: title = "The {$A\beta$} Protocol" Simple argumentless LaTeX commands are also easily protected: title = "The {\LaTeX} Book" However, note that in this case, \LaTeX will be treated as a special character and so the text "LaTeX" will not be considered when sorting. Thus, in cases where the name of the LaTeX command is identical to the text it represents, it may be better to use an extra set of braces so that the letters that make up the command will be taken into consideration when sorting: title = "The {\LaTeX} Book" Thanks to <NAME> for clarifying this issue [5]. Another application of brace shielding is with titles in languages (such as German) in which title capitalization must be preserved with some words (such as nouns and names): title = "{M}essung von {S}t{"o}rfeldern an {A}nlagen und {L}eitungen der {T}elekommunikation im {F}requenzbereich 9 {kHz} bis 3 {GHz}", Note that {\"o} is treated as a special character and the "o" is not protected against case changes. However, the first letter of the nouns are protected because they are at brace level 1. Things get a bit more complicated when a LaTeX command has an argument. The correct approach depends on whether the argument needs to be protected from case changes. Consider: note = "Volume^2 is listed under Knuth \cite{TEX:book}" if the bibstyle changes the note field to lowercase, we will get: volume^2 is listed under knuth \cite{TEX:book} so we will likely want to enclose first letter of Knuth's last name in braces. Furthermore, if we had an unusual bibstyle that rendered the note field in uppercase, we would get: VOLUME^2 IS LISTED UNDER KNUTH \CITE{TEX:book} which would result in an error when the nonexistent \CITE is executed. We might be tempted to try something like this: note = "Volume^2 is listed under Knuth {\cite}{TEX:book}" but this won't work because the extra braces around the \cite command will prevent it from seeing its argument:``` VOLUME^2ISLISTEDUNDERKNUTH{\cite}{TEX:book} ``` Instead, we might try something like this: ``` note="Volume^2islistedunder{K}nuth{\cite{TEX:book}}" ``` However, this is not safe either because the cite key "TEX:book" is now considered to be part of a special character and so it may be case changed (just like the second S0 in the example before)! Therefore, we need to employ an additional set of braces to get the \cite command and its argument to brace level(s) greater than zero: ``` note="Volume^2islistedunder{K}nuth{\cite{TEX:book}}" ``` so as to ensure everything will work regardless of what the bibstyle does to the note field. It is usually a good idea to let the.bst file convert/format the fields as it sees fit -- so don't force things with extra braces unless you have to. Future versions of BibTeX may be more intelligent with respect to case changing and thus may require fewer "manual interventions" with braces. Special thanks to <NAME> for contributing much material to this answer. #### Q6: Where can I get more information about the entry and formatting of names with BibTeX? There is an excellent summary of this topic in Nicolas Markey's _Tame the BeaST -- The B to X of BibTeX_[5] in the section titled "The author field". #### Q7: How do I handle the case of multiletter initials in author names (transcribed initials)? This is covered in the TeX FAQ [7, "Transcribed initials in BibTeX" entry]. However, a bit of reiteration here may be of help. The solution is to use BibTeX's special character mechanism so that the multiple letters will be treated as a single character. \relax can be employed to get the needed BibTeX special character \ sequence: ``` author="S.{\relaxYu}.EpifanovandA.A.Vigasin", ``` (this example borrows the names from the example in the TeX FAQ) and thus avoiding the need to store the multiletter initial in an external TeX macro which would have to be declared using the BibTeX's @premable mechanism. Q8: How do I handle the case of compound last names. For example, "<NAME>" where the last name is "<NAME>"? There are two approaches. The first is to use the "last, first" entry format: ``` author="Sp{\"a}rckJones,Karen", ``` The second approach is to use braces to hide the spaces between the names: ``` author="KarenSp{\"a}rck{J}ones", or ``` The braces around the "J" serve to protect it from case changes. Thanks to <NAME>, <NAME> and <NAME> for posting this solution to the newsgroup comp.text.tex on October 29, 2004 in the thread "BibTeX, accents, AND compound names [Bug?]". #### Q9: How do I handle the case of a "von" part that is capitalized? For example, "<NAME>"? You have to hide the capitals from BibTeX:author = "Maria {uppercase{d}e La} Cruz", Thus, BibTeX will see the "de La" as the "von" part, and BibTeX, via \uppercase, will restore the "D". Thanks to <NAME> for posting this solution from [19] to the newsgroup comp.text.tex on June 29, 2001 in the thread "BibTeX Author "von" token". However, <NAME> points out [5] that this may not be an entirely satisfactory solution if an "alphanumeric" style is used as the label would be "[De LaC]":2 Another approach would be to use Footnote 2: Assuming that the bibstyle uses the “von” part when constructing the label, as is usually the case. As Markey mentioned, perhaps doing so is not the correct thing to do. author = "{uppercase{d}e {uppercase{l}}<NAME>", which would result in the label "[DLC]". However, the simplest approach is author = "{D}e {L}<NAME>, Maria", which works because BibTeX looks only at characters at brace level zero when determining what part a name belongs to. **Q10: How do I handle the case of a middle or last name that has a part that looks like a "von" name? For example, "<NAME>", where "<NAME>" is his middle name (and should be abbreviated as "I. <NAME>. Pool") or "<NAME>", where "<NAME>" is the last name (as is common with Spanish names)?** You can use the special character trick to join the names: author = "Pool, Ithiel {relax de S}ola", or, if using the "first name first" entry form, you have to also hide the lowercase "d" from BibTeX: author = "Ithiel {lowercase{D}e S}<NAME>", For the latter case, simple braces will suffice to prevent the "d" from being seen as a "von" part because BibTeX looks for the "von" part only at brace level 0 -- that is, because names entirely in brace level 1 (and thus being indeterminate) default to the last rather than the "von" part: author = "Canudas {de} Wit, Carlos", However, to prevent the "de" from appearing in the labels of alphanumeric styles, you can use: author = "Canudas {}de Wit, Carlos", or: author = "{<NAME>} Wit, Carlos", The same approach can be used for multiple last name "von-like" parts: author = "Gomez {de} {la} <NAME>", However, to prevent the "de la" from appearing in the labels of alphanumeric styles, you can use: author = "Gomez{}de{} {}la <NAME>", or join them all together in brace level 1: author = "{<NAME>} <NAME>", Be aware that, if you omit the braces, the mistake may not be visible when using bibstyles that place the "von" just before the last part because, when using the "von last, first" format, BibTeX will consider everything up through the last "von" part to be the "von" part (in this case "Gomez de la"). Thanks to <NAME> for posting these solutions to the newsgroup comp.text.tex on February 22, 2002 in the thread "BibTeX "von" in middle name" and on March 26, 2002 in the thread "Strange Citation {BibTeX question}". See also the November 1, 2004 comp.text.tex thread "More about bibtex formatting of compound surnames", the November 27, 1999 comp.text.tex thread "bibTeX: first name + last name + von + last name" and "How to get lowercase letters in the Last?" in [5]. **Q11: How about names that do not have a space between the "von" and last parts (e.g., Jean d'Ormesson)?** Just insert a \relax to gobble up the space: author = "d'\relax <NAME>", Thanks to Nicolas Markey for answering this in [5]. **Q12: BibTeX is not correctly sorting names with letters such as "/E", "/Q", etc. How can I fix this?** On systems, such as MiKTeX, that have 8-bit BibTeX[20] (the executable is called bibtex8) you can use the -c or -csfile option to specify a code page and sorting order file. There is a code page for Scandinavian (88591sca.csf). Thanks to <NAME> for posting this solution to the newsgroup comp.text.tex on June 13, 2006 in the thread "BiBTeX doesn't get the alphabet right". Alternatively, you can provide a sort key, but it can be tricky to produce one that places names after (all) those that begin with "Z": key = "Zzzname", Thanks to <NAME> for posting this solution to the newsgroup comp.text.tex on January 26, 1998 in the thread "BibTeX". **Q13: Should I use words or numerals for the month, edition, etc., fields, and why?** You should always use the three letter month macros (undelimited) for the name of the month (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec) as this lets each.bst file format the month names as is required for that bibliography style. There is usually no excuse for doing things like: month = "{Sept.}", to compensate for.bst files that do not format their month names correctly, because such things are easy to manually fix within the.bst file. Just find the month macro definitions: MACRO {sep} {"Sep."} and correct them as needed. If you should need a "multiple month," you can still build one using the BibTeX concatenation operator "#" in conjunction with the month name macros: month = jun # "/" # jul, However, the edition field poses a bit of a challenge. The BibTeX standard way of specifying edition numbers is to use ordinal words with capital first letters such as "First", "Second", "Third" and so forth. The problem is that some bibliography styles use words for edition numbers while others use numerical values (e.g., "First", "1st", "1", etc.). Converting between these forms is currently non-trivial because the algorithms and lookup tables required for such conversions can become quite complex. Bibstyle files made with recent versions of makebst use an algorithm that will convert edition numbers as needed up to about the fifth. After that, they will fallback and use the form as it is given in the edition field. But, when converting between the Arabic-numeral (e.g., "17") and Arabic-ordinal (e.g., "17th") forms, which is a much easier task, they are usually smart enough to handle any number. So, with this in mind, it might be a good idea to use "First", "Second" all the way up to "Fifth" and then use the form of the bibstyle that you use most often for editions after "Fifth":edition = "{17th}", One way around this problem might be to have.bst files provide an secondary edition field so that the user can specify one or both the ordinal word and Arabic numeral forms. Then, the.bst files can choose which to work with based on the information that has been given (this pushes the tough part of the conversion into "human space" -- the database author). However, such extensions are considered to be non-standard as well as awkward. Another, superior approach, would be to have an algorithm within the.bst files that is clever enough to accept either the ordinal-word or Arabic-numeral forms, or even just the Arabic-numeral form, and then to convert as needed. Finally, numbers like the year often do not need delimiters, but it might be a good idea to use them anyway as they will be needed of the year field ever contains non-numeric characters: year = "2002/2003", **Q14: Where am I supposed to put my.bst and.bib files if I want them to be accessible system-wide?** The standard place for these is in the bst and bib subdirectories of <texmf>/bibtex, where <texmf> is the top level directory of your TeX/METAFONT installation. (The local tree, <texmf-local>, which may be called localtexmf, is perhaps an even better place because it will not get overwritten if the system is later upgraded.) Unix users will need to have root access to be able to add things here. You can also modify the BSTINPUTS and BIBINPUTS environment variables (Unix) or the "Input Dirs" path in the bibtex section of the miktex.ini configuration file (MiKTeX) to alter the BIBIFEX search paths. Note that some/most TeX systems require that the directory lookup hash tables be refreshed before files added to the <texmf> tree are recognized. (teTeX and fpTeX users should run "texhash" as root, MiKTeX users can run "initexml -u"). **Q15: When I use cross references, BIBIFEX inserts the cross referenced entry into the bibliography list. How do I control this feature? For instance, I want to use the cross reference facility to allow me to make "parent" entries so that I will not have to retype the same information all the time in the "child" entries that "inherent" from them (via crossref= fields), but I don't want to have the "parents" appear in the bibliography and I want the child entries to be formatted the same way as they are when not using crossref (i.e., no \cite or otherwise altered formatting in them).** This is controlled by the -min-crossrefs option on the BIBIFEX command line. When a number of entries equal to or greater than -min-crossrefs uses a cross reference, that cross reference is given an entry of its own and the format of the entries that reference it may (depending on the.bst file) change to refer to it (via using \cite).3 The default value of -min-crossrefs is usually 2. With current versions (0.99c) of BIBIFEX, this cannot be altered from within the.bst files. So, if you don't want the cross referenced entries to appear, set -min-crossrefs to a high value: Footnote 3: Note to.bst file designers: entries using cross references will have crossref missing$ test true if less than -min-crossref s entries that cross reference. This allows the.bst to alter the formats of the entries to cite the extra cross reference that will be present (when crossref missing$ will test false). bibtex -min-crossrefs=9000 myfile Regardless of the value of -min-crossrefs, any entry using a cross referenced entry will inherent any field values that it is missing from the cross referenced entry. Users should also be aware that the book entry definition in most.bst files use the series field of a cross referenced entry to format the title of the inclusive work, but incomlection and inbook uses booktitle field to contain the title of the inclusive work. Thanks to <NAME> for posting these clarifications to the newsgroup comp.text.tex on August 14-15, 1998 in the thread "BibTeXperts: is this a bizarre BibTeX crossref bug?". **Q16: How do I get multiple citations within a single bibliography entry as is sometimes done in **physics journals?** See the TeX FAQ [7, "Multiple citations" entry]. **Q17: What kinds of support and bibstyles are there for languages other than English?** See the TeX FAQ [7, "Non-english bibliographies" entry]. ### Citation Questions **Q18: When I put \cite commands in the captions of figures or tables (or in section headings) under a numerical style, the citation order gets corrupted resulting in the "real" first reference not being labeled as "I". Why does this happen and how can I fix it?** The problem stems from the fact that the citations get moved into the List of Figures/Tables or Table of Contents where they become numbered as the first citations. The solution is to load Donald Arseneau's notoccite.sty package [21]. **Q19: Why do I get errors when I put \cite commands in the captions of figures or tables?** You are using a version of LaTeX that is older than December 1995. You might even be still using LaTeX 2.09. Some class files can have this problem too. The best thing to do is to update your LaTeX or class file, but you can get around the problem by preceding the \cite command with \protect. **Q20: I am having trouble getting cite.sty to work with hyperref.sty. What can I do?** At present (2007), these two packages will not work perfectly together. Recent versions (4.0 and later) of cite.sty will work with hyperref.sty in that you can load both and still get sorted and compressed citation lists. However, they will not be hyperlinked. Future versions of cite.sty may fix this. **Q21: How do I reference where the citation occurred in the bibliography?** See the TeX FAQ [7, "References from the bibliography to the citation" entry]. ### Internet and Other Special Reference Questions **Q22: How do I reference internet URLs, patents and/or standards?** Some.bst files have provisions for these (such as IEEEtran.bst [22]), but standard BibTeX styles do not provide them yet. The misc type can be used for internet references with the note field containing the URL. The misc type can also be used for patents. <NAME> has an example.bib file showing how he handled his references of various standards (via @manual) [23]. See also Tip 13. **Q23: Within the url field, how should I enter %6, _, &, # and other special characters that normally need to be escaped (e.g., \))?** If you are not using a bibstyle that renders the URLs within a \url command in conjunction with a package that provides a \url that automatically escapes these special characters then you have to escape these characters (as is normally required in LaTeX) or an error will occur. However, the solution recommended by the vast majority of TeX gurus is to load url.sty [14] or hyperref.sty (version 6.72y 2002-09-12 or later) [15] in conjunction with a bibstyle that places the URL within a \url command and then _not_ to escape any special characters when entering the url field into the BibTeX database. Note that it is not safe to escape all the special characters and still use url.sty and/or hyperref.sty. For example, under the \url command from url.sty, url = "http://one\%two",will result in http://one\(\backslash\)\(\backslash\)\(\backslash\)two (complete with backslash), even though valid URLs can not contain backslashes. Similarly, under the \(\backslash\)url command of hyperref.sty, url = "http://one\(\backslash\)\(\backslash\)\(\backslash\)two", will result in http://one\(\backslash\)\(\backslash\)\(\backslash\)two. Thanks to <NAME> and <NAME> for helping the authors to better understand this issue. **Q24: My URLs don't want to "break" which results in badly formatted entries accompanied by under/overfull hbox warnings. What can I do to fix this?** Properly breaking URLs is a non-trivial matter. The url.sty package [14] will help out a lot and it may be all you need. However, even it can sometimes benefit from a little assistance/configuration. Url.sty's configuration can be altered (via the \(\backslash\)UrlBreaks, \(\backslash\)UrlBigBreaks, etc. commands) to allow for more breakpoints. See the url.sty documentation (in the url.sty source code) for details. This issue can also arise when using hyperref.sty [15] under DVI (but not PDF from pdHEIX) output. One good workaround for this is to use Vilar Camara Neto's breakurl.sty [24] package which is designed to be loaded _after_ hyperref.sty to provide a breakable hyperlinked \(\backslash\)url command under DVI output. **Q25: I am getting unwanted % signs in my URLs. Why? How do I stop this?** BibTlEX works by scanning the.aux file of your document along with the.bib databases, and then writing out the bibliography LaTeX code to the.bbl file for later importation by the.tex file during the next LaTeX run. But, writing out TeX code is not an easy thing to do -- especially when one does not interpret it (and therefore does not know what it means) as it is being written. BibTlEX has to break lines every now and then to keep the lines of the.bbl LaTeX bibliography code to a reasonable length. Normally, BibTlEX breaks at spaces. However, URLs can have long lengths of characters with no spaces. In such cases, BibTlEX will break between characters. But this poses a new danger. If BibTlEX does not shield the end-of-line break point with a %, TeX will add an unwanted space. So, BibTlEX places a % before the break point. For example, a.bbl file might contain something like: \url\(\backslash\)[http://www.bibtex.org/topfiledirectory/middlefieldirector%y/lowerfiledirectory/bottomfiledirectory](http://www.bibtex.org/topfiledirectory/middlefieldirector%y/lowerfiledirectory/bottomfiledirectory)} Now, ordinarily, TeX would ignore that %. But, % is a valid URL character, and within the \url command argument, it will be considered as being part of your URL and show up in the bibliography.4 Footnote 4: Those of you who are familiar with TeX may wonder why the % is not tokenized as a comment character when the \url command acquires its argument. The answer is that \url commands are usually implemented in an argumentless way that allows them to change catcodes as needed just prior to argument scanning. You can get around this problem by putting your URLs within LaTeX macros (such as those obtained by using url.sty's \urldef command). But, this is a pain for more than a few URLs. Manually editing the.bbl to remove the offending % characters or using scripts that do it for you are also possible options. The best and easiest approach is to use packages with \url commands that are programmed to ignore % characters that are immediately followed by a line break. Recent versions (6.70s, 2000-08-31 and later) of the hyperref packages as well as url.sty (version 1.6 and later) have a \url command that does this. Future versions of BibTlEX may allow the.bst file to better control the line breaking of their.bbl output so as to eliminate this problem altogether. ### Bibliography Modification Questions **Q26: How do I get the bibliography/references list into the table of contents?** The simple answer to this question is to insert the line if you are using book or report class, or \addcontentsline{toc}{section}{\refname} if you are using article class, or \addcontentsline{toc}{section}{whatever-you-want} immediately after the line containing \begin{thebibliography}. The problem here (if you are using BibTeX) is that this line will occur in the.bbl file (created by BibTeX) not the.tex source created by you. You can place the \addcontentsline line before \begin{thebibliography}, but you've got to watch out if the bibliography starts on a new page (causing the table of contents entry to point to the page just prior to where the bibliography actually starts). Under such circumstances, a quick hack is to add a \clearpage or \cleardoubepage just prior to the \addcontentsline. The better solution requires modifying the document class file to redefine the \thebibliography environment so as to include an \addcontentsline. Another, related, approach is to place the \addcontentsline within the \@openbib@code macro (Question 27). Last, but certainly not least, there is <NAME>'s tocbibind.sty package [25] that is designed just for this purpose. However, be forewarned that cbcbidind.sty may not work with every LaTeX class file (it will of course work with the standard article, report, book and proc classes). #### Q27: How do I alter the spacing between items in the references list? The bibliography environment depends on the \list environment for formatting. With \list, one can control the separation between the items by altering the values of \itemsep, \parsep, etc. The problem is how to insert commands like these into the bibliography environment. One possible approach is to redefine \thebibliography by making a copy of the one in the class file you are using and insert the needed commands into the second argument of the \list within it to make a "hacked" version that will do what you want. Another approach is to take advantage of the fact that, in most modern class files (including the standard ones of LaTeX\(2_{\mathbb{E}}\)), the command \@openbib@code occurs at the above mentioned point to provide an external way to switch between open and closed bibliography styles. So, you could do some commands like: \makeatletter \newcommand{adjustmybblparameters}{\setlength{\itemsep}{2\baselineskip}\setlength{\parsep}{Opt}} \let{ORIGINALlater@openbib@code=\@openbib@code \renewcommand{\@openbib@code}{\backslash\@ORIGINALlater&openbib@code\backslash\adjustmybblparameters} \backslash\makeatother where \itemsep and the other parameters are adjusted as you wish. This code should to be placed before the start of the bibliography. The above works by redefining \@openbib@code to contain code that alters list parameters in the desired way. It will not work with class files that don't use the \@openbib@code (and will generate an error if that command has not been defined). If you are using the natbib package [11], note that it provides a \bibsep length that allows for easy adjustment of the bibliography list spacing. #### Q28: How do I get numbers in the references list to appear without the square brackets around them? Before the bibliography section, insert the following: \makeatletter \renewcommand{biblabel[1]{\hfill #1.} \makeatother that "electronic" is the most likely candidate. However, some authors of potential rivals of BibTeX may disagree here. In particular, <NAME>'s biblatex [35] uses the entry name "online". Remember that, if a.bst file does not recognize an entry name, it will result in an error. So, users of your.bst file need to be warned that they might want to keep all their @electronic or @online entries in a separate.bib file to help flag the fact that they can't be used with every.bst file. (Their mere presence in the.bib file will not cause an error, but if they are ever actually referenced under a.bst that does not recognize the type, there will be an error.) Furthermore, some.bst files already use other names such as "webpage" or "www" -- so you may eventually end up having to rename database entry types and/or creating aliases in other.bst files. Sigh. **Q34: How can I modify a.bst file so that it will handle an "electronic", "online", etc., entry type that it currently does not understand?** The easiest solution is to create aliases with the desired names that refer to an existing type that is most compatible. The misc entry type is often the most appropriate. This can be done by placing commands (in the.bst file) such as: FUNCTION {online} {misc} FUNCTION {internet} {misc} FUNCTION {www} {misc} FUNCTION {webpage} {misc} FUNCTION {electronic} {misc} A good place is around the same place the.bst file defines: FUNCTION {default.type} {misc} Of course, you won't get anything other than misc type formatting, but the results might be quite usable if the.bst file supports the url field (adding this latter capability is more difficult). The same trick can be used to provide aliases for existing electronic/online entry types: FUNCTION {online} {webpage} **Q35: I need to have BibTeX format the abbreviated names with no space between the initials. However, when formatting like this, BibTeX no longer places a hyphened between the initials of the hyphenated names. How can I overcome this and have both capabilities?** This is a known problem. Briefly, when using a format.name$ string like: {f{.}.^}{vv^}{ll}{, jj} "<NAME>" will be formatted as "<NAME>" when "<NAME>" is desired. The only known workaround is to modify the.bst file so that each part of the name is formatted separately, all spaces are manually removed from the first name part, and then the parts are joined back together. The code to do this looks like: STRING {z} FUNCTION {remove.spaces} { 'z := "" { z empty$ not } { z #1 #1 substring$ z #2 global.max$ substring$ 'z := duplicate$ """ = 'pop$ { * } if$ { if$ } while$ } INTEGERS { nameptr namesleft numnames } FUNCTION {formname.format.string} { "{f.}" } FUNCTION {sumname.format.string} { "{vv"}{ll}" } FUNCTION {jnname.format.string} { "{, jj}" } FUNCTION {format.names} {'s := #1 'nameptr := s num.names$ 'numnames := numnames 'namesleft := { namesleft #0 > } { s nameptr forname.format.string format.name$ remove.spaces duplicat$ empty$'skip$ { "^" * } iff$ s nameptr surname.format.string format.name$ * s memptr jnrname.format.string format.name$ * 't :=. Obviously, this code will have to be adjusted to the specific name format desired and.bst file used. Thanks to <NAME> for posting this solution to the newsgroup comp.text.tex on June 28, 2002 in the thread "BiBTeX, bst hackers, format.name$, please help". **Q36: I want to make.bst file with a macro that contains an umlaut accent. For instance, I need a macro for March in German (Marz). MACRO{mr}{"M"arz"} will not work because BiBTeX sees the quote as a delimiter (even if shielded in braces) and I can't use the BiBTeX quote$ command within a BiBTeX macro. How do I do this?** Perhaps the best way out of this jam is to use TeX's \(\widehat{\ }\) notation for characters. So you can do: MACRO{mar}{"M\"b{a}rz"} The braces prevent TeX from seeing the "a" as a hex digit. This approach is safe -- it does not depend on font or character encoding, just TeX's fixed internal coding. Thanks to <NAME> and <NAME> for posting this answer to the newsgroup comp.text.tex on October 17, 2000 in the thread "Can a BibTeX MACRO definition include "'?". **Q37: When running BiBTeX, I get an error message like:** Sorry-you've exceeded BibTeX's single function space 100 or Sorry-you've exceeded BibTeX's wizard-defined function space 3000 or Warning-you've exceeded 100, the entry-string-size... or Warning-you've exceeded 1000, the global-string-size, for entry... or Sorry-you've exceeded BibTeX's buffer size 1000 offending function (first case) is divided into two smaller functions or removing unneeded functions (second case). The "entry-string-size" error message is caused by an entry field that is too long for BibTeX to handle. One workaround is store the long text into a LaTeX file (say longfield.tex) and then replace the field with \input{./longfield.tex} instead of the text itself. Of course, you may have to manually adjust things if BibTeX is supposed to do case changes or abbreviations within it. Note that the 100 bytes indicated by the example error message above is a very low limit -- most modern BibTeXs (especially those on Unix systems) provide a limit much larger than this. As covered in the TeX FAQ [7, "String too long in BibTeX" entry], many (most).bst files use a coding technique in their output routine that uses memory inefficiently. These output.null functions can be improved by changing the first line and deleting the last. That is, this form: FUNCTION {output.nonnull} {'s :=.... } can be changed to this: FUNCTION {output.nonnull} { swap$.. } Sometimes the increase in memory efficiency is enough to stop the problem. The "global-string-size" error is similar to the "entry-string-size" except that it applies to the length of internal string work variables within the.bst file. The "buffer size" error means that an input line or field exceeded the size of the input read buffer. This can occur in older versions of BibTeX when reading a.bib file that does not use Unix newline characters. Finally, the "pool size" error means that BibTeX ran out of total string space. This can occur with very large bibliographies. Make sure that you do not have a mistake in your database entries (especially misplaced/omitted/extra braces, semicolons or commas) as these can sometimes trigger errors like the above. ### Software Application Questions **Q38: What kinds of BibTeX-related software applications (database managers, etc.) are there?** There are too many to name here, but you can find current lists of BibTeX tools at Google [36] and The Open Directory Project [37]. **Q39: What kinds of tools are there for converting between BibTeX and other formats?** Some of the more notable ones include: **Bibutils**: by <NAME>, is a set of tools for converting between BibTeX and other formats using the Library of Congress's Metadata Object Description Schema (MODS) [38] as an intermediate [39]. **BibTeXML**: by <NAME> and <NAME>, is an XML DTD and schema for BibTeX conversion to/from XML and then from XML to other formats (HTML, DocBook, etc.) [40]. **bib2xhtml**: by <NAME> and <NAME>, is an application that converts BibTeX.bib or LaTeX bibliography.aux files to (X)HTML [41]. **bibtex2html**: by <NAME> and <NAME>, is an application, written in Objective Caml, that converts BibTeX.bib files to HTML [42]. **bibTex-XML-HTML**: by <NAME> and <NAME>, is a system of applications that converts BibTeX.bib files to HTML via XML [43]. **bib2html**: by <NAME>, is an application that converts BibTeX.bib files to HTML [44]. **Kiri's bib2html**: by <NAME>, is another application that converts BibTeX.bib files to HTML [45]. **Q40: What about.bbl (BibTeX generated bibliography) file to HTML conversion?**: Remember,.bbl files, although created by BibTeX, are really LaTeX files. So these are best handled by applications such as LaTeX2HTML [46], TeX4ht [47] and TtH [48]. **Q41: What alternatives are there to BibTeX?**: Despite its age and shortcomings with respect to use with languages other than English, BibTeX's maturity, simplicity and ease-of-use have helped it remain the primary bibliography generator of choice by most LaTeX users. Some of the more notable alternatives include: **amsrefs**: by <NAME> and <NAME>, is a BibTeX-like implementation in LaTeX which can be used with BibTeX or to replace it [49]. **biblatex**: by <NAME>, is a recent (and at the time of this writing still in beta development) and powerful reimplementation of the bibliographic facilities provided by LaTeX [35]. BibTeX is used only to sort the bibliography and generate labels. The formatting of the bibliography is controlled by LaTeX macros. **bibTeX++**: a project from ENST Bretagne (University), is a BibTeX replacement written in Java [50]. **biblioX**: by <NAME>, is an XML-based system for formatting bibliographic citations and references using XSLT [51]. **bibulus**: by <NAME>, is an XML-based BibTeX replacement which is written in Perl [52]. **cl-BibTeX**: by <NAME>, is a BibTeX replacement implemented in Common Lisp [53]. **biblioTeX**: by <NAME>, is a new implementation of BibTeX, originally written in Scheme, but now in C, with multilingual features and which uses a new bibstyle language that is close to XSLT [54]. That's all folks. Best wishes, mds. ## Acknowledgments The authors would like to thank <NAME> for his help in answering questions about the operation of BibTeX as well as taking the time to review this document and providing additional material. Robin Fairbairns' LaTeX FAQ helped with identifying which issues BibTeX users most often encountered as well as their proper solutions. Finally, D<NAME>eneau helped us to better understand the intricacies of URL handling in LaTeX. ## References * [1] <NAME> and <NAME>. (2007, Jan.) BibTeX tips and FAQ. btxFAQ.pdf. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/](http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/) * [2] <NAME>, _BTEX: A Document Preparation System_, 2nd ed. Harlow, England: Addison-Wesley, 1994. * [3] <NAME> and <NAME>, _Guide to LaTeX_, 4th ed. Harlow, England: Addison-Wesley, 2003. * [4] <NAME>. (1988, Feb.) BibTeXing. btxdoc.pdf. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/](http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/) * [5] <NAME>. (2005, Oct.) Tame the beast -- the b to x of BibTeX. [Online]. Available: [http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/](http://tug.ctan.org/tex-archive/info/bibtex/tamethebeast/) * [6] <NAME>. (2004, Apr.) A BibTeX guide via examples. bibtex_guide.pdf. [Online]. Available: [http://www.geocities.com/kijoo2000/](http://www.geocities.com/kijoo2000/) * [7] <NAME>. (2007, Jan.) The TeX FAQ. [Online]. Available: [http://www.tex.ac.uk/cgi-bin/texfaq2html/](http://www.tex.ac.uk/cgi-bin/texfaq2html/) * [8] <NAME>. (2005, Aug.) How to efficiently use BibTeX. [Online]. Available: [http://www.itp.uni-hannover.de/~kreutzm/en/doc_bibtex.html](http://www.itp.uni-hannover.de/~kreutzm/en/doc_bibtex.html) * [9] <NAME>. (2007, Jan.) The IEEEtran BibTeX style. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/bibtex/](http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/bibtex/) * [10] <NAME>. (2006, Sep.) The cite.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/cite/](http://www.ctan.org/tex-archive/macros/latex/contrib/cite/) * [11] <NAME>. (2006, Sep.) The natbib.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/natbib/](http://www.ctan.org/tex-archive/macros/latex/contrib/natbib/) * [12] <NAME>. (1995, Apr.) The harvard.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/harvard/](http://www.ctan.org/tex-archive/macros/latex/contrib/harvard/) * [13] <NAME>. (1992, Sep.) The chicago.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/contrib/chicago/](http://www.ctan.org/tex-archive/biblio/bibtex/contrib/chicago/) * [14] <NAME>. (2005, Jun.) The url.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/misc/](http://www.ctan.org/tex-archive/macros/latex/contrib/misc/) * [15] <NAME> and <NAME>. (2006, Nov.) The hyperref.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/hyperref/](http://www.ctan.org/tex-archive/macros/latex/contrib/hyperref/) * [16] <NAME>. (2005, Oct.) The custom-bib package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/custom-bib/](http://www.ctan.org/tex-archive/macros/latex/contrib/custom-bib/) * [17] <NAME>. (2003, Jul.) BibTeX yesterday, today, and tomorrow. [Online]. Available: [http://www.tug.org/tug2003/abstracts/final/Patashnik/patashnik-abstract/](http://www.tug.org/tug2003/abstracts/final/Patashnik/patashnik-abstract/) * [18] <NAME>. (2006, Aug.) TeX user group bibliography archive. [Online]. Available: [http://www.math.utah.edu:8080/pub/tex/bib/index-table.html](http://www.math.utah.edu:8080/pub/tex/bib/index-table.html) * [19] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, _The LaTeX Companion_, 2nd ed. Harlow, England: Addison-Wesley, 2004. * [20] <NAME> and <NAME>. (1996, Aug.) 8-bit BibTeX. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/8-bit/](http://www.ctan.org/tex-archive/biblio/bibtex/8-bit/) * [21] <NAME>. (2000, Jul.) The notoccite.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/misc/](http://www.ctan.org/tex-archive/macros/latex/contrib/misc/) * [22] <NAME>. (2007, Jan.) The IEEEtran.cls package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/](http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/) * [23] <NAME>. (2003, Mar.) References of standards. [Online]. Available: [http://www.math.utah.edu/pub/tex/bib/standard.html](http://www.math.utah.edu/pub/tex/bib/standard.html)* [24] <NAME>. (2006, Aug.) The breakurl.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/breakurl/](http://www.ctan.org/tex-archive/macros/latex/contrib/breakurl/) * [25] <NAME>. (2004, May) The tocbibind.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/tocbibind/](http://www.ctan.org/tex-archive/macros/latex/contrib/tocbibind/) * [26] <NAME>. (2004, Mar.) The chapterbib.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/cite/](http://www.ctan.org/tex-archive/macros/latex/contrib/cite/) * [27] <NAME>. (2004, May) The bibunits.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/bibunits/](http://www.ctan.org/tex-archive/macros/latex/contrib/bibunits/) * [28] ----. (2004, Jan.) The multibib.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/multibib/](http://www.ctan.org/tex-archive/macros/latex/contrib/multibib/) * [29] <NAME> and <NAME>. (2006, Sep.) The bibtopic.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/bibtopic/](http://www.ctan.org/tex-archive/macros/latex/contrib/bibtopic/) * [30] <NAME>. (2004, Jul.) The multibbl.sty package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/contrib/multibbl/](http://www.ctan.org/tex-archive/macros/latex/contrib/multibbl/) * [31] <NAME>. (1988, Feb.) Designing BibTeX styles. btxhak.pdf. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/](http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/) * [32] ----. (1988, Feb.) The BibTeX standard styles. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/distribs/styles/](http://www.ctan.org/tex-archive/biblio/bibtex/distribs/styles/) * [33] ----. (1993, Nov.) The BibTeX standard styles source code. btxbst.doc. This is a text file despite its.doc suffix. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/distribs/doc/](http://www.ctan.org/tex-archive/biblio/bibtex/distribs/doc/) * [34] <NAME>. (2005, Jun.) The urlbst package. [Online]. Available: [http://www.ctan.org/tex-archive/biblio/bibtex/contrib/urlbst/](http://www.ctan.org/tex-archive/biblio/bibtex/contrib/urlbst/) * [35] <NAME>. (2006, Nov.) The biblatex package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/expt/biblatex/](http://www.ctan.org/tex-archive/macros/latex/expt/biblatex/) * [36] (2006, Nov.) Directory of BibTeX related software. Google, Inc. [Online]. Available: [http://directory.google.com/Top/Computers/Software/Typesetting/TeX/BibTeX/](http://directory.google.com/Top/Computers/Software/Typesetting/TeX/BibTeX/) * [37] (2006, Nov.) Directory of BibTeX related software. The Open Directory Project. [Online]. Available: [http://dmoz.org/Computers/Software/Typesetting/TeX/BibTeX/](http://dmoz.org/Computers/Software/Typesetting/TeX/BibTeX/) * [38] (2004, Dec.) Metadata object description schema (MODS). United States Library of Congress. [Online]. Available: [http://www.loc.gov/standards/mods/](http://www.loc.gov/standards/mods/) * [39] <NAME>. (2005, Oct.) Bibutils. [Online]. Available: [http://www.scripps.edu/~cdputnam/software/bibutils/](http://www.scripps.edu/~cdputnam/software/bibutils/) * [40] <NAME> and <NAME>. (2005, May) BibTeXML. [Online]. Available: [http://bibtexml.sourceforge.net/](http://bibtexml.sourceforge.net/) * [41] <NAME> and <NAME>. (2006, Mar.) bib2xhtml. [Online]. Available: [http://www.spinellis.gr/sw/textproc/bib2xhtml/](http://www.spinellis.gr/sw/textproc/bib2xhtml/) * [42] J.-C. Filliatre and <NAME>. (2006, Nov.) bibtex2html. [Online]. Available: [http://www.lri.fr/~filliatr/bibtex2html/index.en.html](http://www.lri.fr/~filliatr/bibtex2html/index.en.html) * [43] <NAME> and <NAME>. (2006, Jun.) The BibTeX-XML-HTML bibliography project. [Online]. Available: [http://www.authopilot.com/xml/home.htm](http://www.authopilot.com/xml/home.htm) * [44] <NAME>. (2006, Oct.) bib2html. [Online]. Available: [http://www.arakhne.org/rubrique.php3?id_rubrique=19](http://www.arakhne.org/rubrique.php3?id_rubrique=19) * [45] <NAME>. (2003, Nov.) Kiri's bib2html. [Online]. Available: [http://www.litech.org/~wkiri/bib2html/](http://www.litech.org/~wkiri/bib2html/) * [46] <NAME>. (2004, Oct.) LaTeX2HTML. [Online]. Available: [http://www.latex2html.org/](http://www.latex2html.org/) * [47] <NAME>. (2006, Nov.) TeX4ht. [Online]. Available: [http://www.cse.ohio-state.edu/~gurari/TeX4ht/](http://www.cse.ohio-state.edu/~gurari/TeX4ht/)* [48] <NAME>. (2006, Aug.) TtH. [Online]. Available: [http://hutchinson.belmont.ma.us/tth/](http://hutchinson.belmont.ma.us/tth/) * [49] <NAME> and <NAME>. (2004, Jun.) The amsrefs package. [Online]. Available: [http://www.ctan.org/tex-archive/macros/latex/required/amslatex/amsrefs/](http://www.ctan.org/tex-archive/macros/latex/required/amslatex/amsrefs/) * [50] (2005, Jul.) Bibtex++. ENST Bretagne. [Online]. Available: [https://info.enstb.org/projects/bibtex/](https://info.enstb.org/projects/bibtex/) * [51] <NAME>. (2004, Apr.) Bibliox. [Online]. Available: [http://www.silmaril.ie/bibliox/](http://www.silmaril.ie/bibliox/) * [52] <NAME>. (2004, May) Bibulus. [Online]. Available: [http://www.nongnu.org/bibulus/](http://www.nongnu.org/bibulus/) * [53] <NAME>. (2005, Mar.) cl-bibtex. [Online]. Available: [http://www.nongnu.org/cl-bibtex/](http://www.nongnu.org/cl-bibtex/) * [54] <NAME>. (2004, May) Mlbibtex. [Online]. Available: [http://lifc.univ-fcomte.fr/~hufflen/texts/mlbibtex/](http://lifc.univ-fcomte.fr/~hufflen/texts/mlbibtex/)
modest_ex
hex
Erlang
Toggle Theme ModestEx v1.0.1 ModestEx === Serialization scope. Possible values are: :html html will be serialized to complete document … :head html will be reduced only to the head fragment … :body html will be reduced only to the body fragment … :body_children html will be reduced to the children of the body [Link to this section](#summary) Summary === [Types](#types) --- [error()](#t:error/0) [input()](#t:input/0) [success()](#t:success/0) [Functions](#functions) --- [append(bin, selector, new_bin)](#append/3) Append new html as a child at the end of selected node. Returns updated html string [find(bin, selector)](#find/2) Find nodes with a CSS selector. Returns the outer html of each node as a list of strings [get_attribute(bin, key)](#get_attribute/2) Get all attributes with key. Returns list of strings [get_attribute(bin, selector, key)](#get_attribute/3) [get_text(bin)](#get_text/1) Get all text. Returns list of strings [get_text(bin, selector)](#get_text/2) [insert_after(bin, selector, new_bin)](#insert_after/3) Insert new html after selected node. Returns updated html string [insert_before(bin, selector, new_bin)](#insert_before/3) Insert new html before selected node. Returns updated html string [position(bin, selector)](#position/2) Get position of selected nodes in in relation to its parent. Returns list of positions [prepend(bin, selector, new_bin)](#prepend/3) Prepend new html as a child at the beginning of selected node. Returns updated html string [pretty_print(bin)](#pretty_print/1) Pretty print html [remove(bin, selector)](#remove/2) Remove nodes with a CSS selector. Returns updated html string [replace(bin, selector, new_bin)](#replace/3) Replace selected node with new html Returns updated html string [resolve(list)](#resolve/1) [scope()](#scope/0) [serialize(bin, scope \\ :html)](#serialize/2) Serialize any string with valid or broken html. Returns valid html string [set_attribute(bin, selector, key, value)](#set_attribute/4) Set value for all attributes with key. Returns single html string or returns list of strings [set_text(bin, selector, text)](#set_text/3) Set text for all nodes. Returns single html string or returns list of strings [slice(bin, selector, start_index, end_index)](#slice/4) Slice selected set into subset. Returns single html string or returns list of strings [to_scope(flag)](#to_scope/1) [wrap(bin, selector, new_bin)](#wrap/3) Wrap an HTML structure around each element in the set of matched elements. Returns updated html string [Link to this section](#types) Types === [Link to this type](#t:error/0 "Link to this type") error() ``` error() :: {:error, [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()} ``` [Link to this type](#t:input/0 "Link to this type") input() ``` input() :: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)() | [[String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()] ``` [Link to this type](#t:success/0 "Link to this type") success() ``` success() :: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)() | [[String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()] ``` [Link to this section](#functions) Functions === [Link to this function](#append/3 "Link to this function") append(bin, selector, new_bin) ``` append([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Append new html as a child at the end of selected node. Returns updated html string Examples --- iex> ModestEx.append(“Hello ”, “div”, “World ”) “Hello World ” [Link to this function](#find/2 "Link to this function") find(bin, selector) ``` find([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Find nodes with a CSS selector. Returns the outer html of each node as a list of strings. Examples --- iex> ModestEx.find(“Hello World ”, “p a”) “Hello” iex> ModestEx.find(“Hello World ”, “span”) [“Hello”, “World”] [Link to this function](#get_attribute/2 "Link to this function") get_attribute(bin, key) ``` get_attribute([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Get all attributes with key. Returns list of strings. Examples --- iex> ModestEx.get_attribute(“[Hello](\"https://elixir-lang.org\")”, “href”) “https://elixir-lang.org” [Link to this function](#get_attribute/3 "Link to this function") get_attribute(bin, selector, key) ``` get_attribute([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` [Link to this function](#get_text/1 "Link to this function") get_text(bin) ``` get_text([input](#t:input/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Get all text. Returns list of strings. Examples --- iex> ModestEx.get_text(“Hello World”) “Hello World” [Link to this function](#get_text/2 "Link to this function") get_text(bin, selector) ``` get_text([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` [Link to this function](#insert_after/3 "Link to this function") insert_after(bin, selector, new_bin) ``` insert_after([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Insert new html after selected node. Returns updated html string Examples --- iex> ModestEx.insert_after(“Hello ”, “div p”, “World ”) “Hello World ” [Link to this function](#insert_before/3 "Link to this function") insert_before(bin, selector, new_bin) ``` insert_before([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Insert new html before selected node. Returns updated html string Examples --- iex> ModestEx.insert_before(“World ”, “div p”, “Hello ”) “Hello World ” [Link to this function](#position/2 "Link to this function") position(bin, selector) ``` position([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Get position of selected nodes in in relation to its parent. Returns list of positions. Examples --- iex> ModestEx.position(“Hello World ”, “p”) [1, 3] [Link to this function](#prepend/3 "Link to this function") prepend(bin, selector, new_bin) ``` prepend([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Prepend new html as a child at the beginning of selected node. Returns updated html string Examples --- iex> ModestEx.prepend(“World ”, “div”, “Hello ”) “Hello World ” [Link to this function](#pretty_print/1 "Link to this function") pretty_print(bin) ``` pretty_print([input](#t:input/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Pretty print html. Examples --- iex> ModestEx.pretty_print(“Hello World ”) “\n\tHello World\n \n” [Link to this function](#remove/2 "Link to this function") remove(bin, selector) ``` remove([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Remove nodes with a CSS selector. Returns updated html string Examples --- iex> ModestEx.remove(“Hello World”, “div p”) “World” [Link to this function](#replace/3 "Link to this function") replace(bin, selector, new_bin) ``` replace([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Replace selected node with new html Returns updated html string Examples --- iex> ModestEx.replace(“Hello ”, “div p”, “World ”) “World ” [Link to this function](#resolve/1 "Link to this function") resolve(list) [Link to this function](#scope/0 "Link to this function") scope() [Link to this function](#serialize/2 "Link to this function") serialize(bin, scope \\ :html) ``` serialize([input](#t:input/0)(), [Atom.t](https://hexdocs.pm/elixir/Atom.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Serialize any string with valid or broken html. Returns valid html string. Examples --- iex> ModestEx.serialize(“HelloWorld”) “HelloWorld” [Link to this function](#set_attribute/4 "Link to this function") set_attribute(bin, selector, key, value) ``` set_attribute([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [input](#t:input/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Set value for all attributes with key. Returns single html string or returns list of strings. Examples --- iex> ModestEx.set_attribute(“Hello”, “a”, “href”, “https://elixir-lang.org”) “[Hello](\"https://elixir-lang.org\")” [Link to this function](#set_text/3 "Link to this function") set_text(bin, selector, text) ``` set_text([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [input](#t:input/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Set text for all nodes. Returns single html string or returns list of strings. Examples --- iex> ModestEx.set_text(“Hello ”, “div p”, “World”) “World ” [Link to this function](#slice/4 "Link to this function") slice(bin, selector, start_index, end_index) ``` slice([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [Integer.t](https://hexdocs.pm/elixir/Integer.html#t:t/0)(), [Integer.t](https://hexdocs.pm/elixir/Integer.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Slice selected set into subset. Returns single html string or returns list of strings. Examples --- iex> ModestEx.slice(“Lorem ipsum === dolor sit amet * Coffee * Tea * Milk Sed ut perspiciatis unde omnis iste natus ”, “body > *”, 0, -1) [“Lorem ipsum === ”, “dolor sit amet ”, “* Coffee * Tea * Milk ”, “Sed ut perspiciatis ”, “unde omnis iste natus ”] [Link to this function](#to_scope/1 "Link to this function") to_scope(flag) [Link to this function](#wrap/3 "Link to this function") wrap(bin, selector, new_bin) ``` wrap([input](#t:input/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()) :: [success](#t:success/0)() | [error](#t:error/0)() ``` Wrap an HTML structure around each element in the set of matched elements. Returns updated html string. Examples --- iex> ModestEx.wrap(“Hello World ”, “p”, “”) “Hello World ”
dosearch
cran
R
Package ‘dosearch’ October 13, 2022 Type Package Version 1.0.8 Title Causal Effect Identification from Multiple Incomplete Data Sources Description Identification of causal effects from arbitrary observational and experimental probabil- ity distributions via do-calculus and standard probability manipulations using a search-based al- gorithm by Tikka et al. (2021) <doi:10.18637/jss.v099.i05>. Allows for the presence of mecha- nisms related to selection bias (Barein- boim, E. and <NAME>. (2015) <http://ftp.cs.ucla.edu/pub/stat_ser/r445.pdf>), trans- portability (Barein- bo<NAME>. and <NAME>. (2014) <http://ftp.cs.ucla.edu/pub/stat_ser/r443.pdf>), miss- ing data (<NAME>. and <NAME>. and <NAME>. (2013) <http: //ftp.cs.ucla.edu/pub/stat_ser/r410.pdf>) and arbitrary combina- tions of these. Also supports identification in the presence of context-specific indepen- dence (CSI) relations through labeled directed acyclic graphs (LDAG). For de- tails on CSIs see Corander et al. (2019) <doi:10.1016/j.apal.2019.04.004>. License GPL (>= 2) Imports Rcpp (>= 0.12.19) Suggests dagitty, DOT, igraph LinkingTo Rcpp SystemRequirements C++11 NeedsCompilation yes Author <NAME> [aut, cre] (<https://orcid.org/0000-0003-4039-4342>), <NAME> [ctb] (<https://orcid.org/0000-0002-6649-3229>), <NAME> [ctb] (<https://orcid.org/0000-0001-5530-769X>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2021-08-19 16:40:02 UTC R topics documented: dosearch-packag... 2 bivariate_missingnes... 5 dosearc... 6 get_benchmar... 13 get_derivatio... 14 get_formul... 14 is_identifiabl... 15 dosearch-package Causal Effect Identification from Multiple Incomplete Data Sources Description Solves causal effect identifiability problems from arbitrary observational and experimental data using a heuristic search. Allows for the presence of advanced data-generating mechanims. See Tikka et al. (2021) <doi:10.18637/jss.v099.i05> for further details. Author(s) <NAME>, <NAME>, <NAME> References <NAME>, <NAME>, <NAME>, and <NAME>. The computational complexity of structure-based causality. Journal of Artificial Intelligence Research, 58:431–451, 2017. <NAME>, <NAME>, and <NAME>. Identification of causal effects using instrumental variables. Journal of the American Statistical Association, 91(434):444–455, 1996. <NAME> and <NAME>. Context-specific Bayesian clustering for gene expression data. Journal of Computational Biology, 9(2):169–191, 2002. <NAME> and <NAME>. Controlling selection bias in causal inference. In Proceedings of the 15th International Conference on Artificial Intelligence and Statistics, 22:100–108, 2012a. <NAME> and <NAME>. Causal inference by surrogate experiments: z-identifiability. In Pro- ceedings of the 28th Conference on Uncertainty in Artificial Intelligence, 113–120, 2012b. <NAME> and <NAME>. A general algorithm for deciding transportability of experimental re- sults. Journal of Causal Inference, 1:107–134, 2013. <NAME> and <NAME>. Transportability from multiple environments with limited experiments: Completeness results. In Proceedings of the 27th Annual Conference on Neural Information Pro- cessing Systems, 280–288, 2014. <NAME> and <NAME>. Recovering causal effects from selection bias. In Proceedings of the 29th AAAI Conference on Artificial Intelligence, 3475–3481, 2015. <NAME>, <NAME>, and <NAME>. Recovering from selection bias in causal and statistical in- ference. In Proceedings of the 28th AAAI Conference on Neural Information Processing Systems, 2014. <NAME>, <NAME>, <NAME>, and <NAME>. Context-specific independence in Bayesian networks. In Proceedings of the 12th International Conference on Uncertainty in Artificial Intelli- gence, 115–123, 1996. <NAME>. Statistics in epidemiology: The case-control study. Journal of the American Statis- tical Association, 91(433):14–28, 1996. <NAME>, <NAME>, and <NAME>. Relevant path separation: A faster method for testing independencies in Bayesian networks. In 8th International Conference on Probabilistic Graphical Models, 74–85, 2016. <NAME>, <NAME>, and <NAME>. Identification and model testing in linear structural equa- tion models using auxiliary variables. In Proceedings of the 34th International Conference on Machine Learning, 70:757–766, 2017. <NAME>. The computational complexity of probabilistic inference using Bayesian belief net- works. Artificial Intelligence, 42(2):393–405, 1990. <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. A logical approach to context- specific independence. Annals of Pure and Applied Logic, 2019. <NAME> and <NAME>. Causal effect identification by adjustment under confounding and selection biases. In Proceedings of the 31st AAAI Conference on Artificial Intelligence, 2017. <NAME>, <NAME>, and <NAME>. Generalized adjustment under confounding and selection biases. In Proceedings of the 32nd AAAI Conference on Artificial Intelligence, 2018. <NAME>, <NAME>, and <NAME>. Integrating locally learned causal structures with over- lapping variables. In Advances in Neural Information Processing Systems, 1665–1672, 2009. <NAME>. Influence diagrams for causal modelling and inference. International Statistical Re- view, 70(2):161–189, 2002. <NAME>, <NAME>, and <NAME>. Data-driven covariate selection for nonparametric estimation of causal effects. In Proceedings of the 16th International Conference on Artificial Intelligence and Statistics, 31:256–264, 2013. <NAME> and <NAME>. Testing identifiability of causal effects. In Proceedings of the 11th Confer- ence Annual Conference on Uncertainty in Artificial Intelligence, 185–195, 1995. <NAME>, <NAME>, and <NAME>. Context-specific independence mixture modelling for protein families. In European Conference on Principles of Data Mining and Knowledge Discovery, 79–90, 2007. <NAME>, <NAME>, and <NAME>. Confounding and collapsibility in causal inference. Sta- tistical Science, 14(1):29–46, 1999. <NAME>. Axiomatizing causal reasoning. Journal of Artificial Intelligence Research, 12:317– 337, 2000. <NAME> and <NAME>. Pearl’s calculus of intervention is complete. In Proceedings of the 22nd Conference on Uncertainty in Artificial Intelligence, 217–224, 2006. <NAME>, <NAME>, and <NAME>. Causal discovery of linear cyclic models from multi- ple experimental data sets with overlapping variables. In Proceedings of the 28th Conference on Uncertainty in Artificial Intelligence, 387–396, 2012. <NAME>, <NAME>, and <NAME>. Do-calculus when the true graph is unknown. In Proceedings of the 31st Conference on Uncertainty in Artificial Intelligence, 395–404, 2015. <NAME>, <NAME>, and <NAME>. Causal identification under Markov equivalence. In Pro- ceedings of the 34th Conference on Uncertainty in Artificial Intelligence, 978–987, 2018. <NAME>. Study design in causal models. Scandinavian Journal of Statistics, 42(2):361–377, 2015. <NAME> and <NAME>. Probabilistic Graphical Models: Principles and Techniques, 2009. <NAME>. Causal inference from graphical models. In Complex Stochastic Systems, 67–107, 2000. <NAME> and <NAME>. Statistical Analysis with Missing Data, 1986. <NAME>, <NAME>, and <NAME>. Estimating high-dimensional intervention effects from observational data. The Annals of Statistics, 37(6A):3133–3164, 2009. <NAME> and <NAME>. Estimating bounds on causal effects in high-dimensional and possibly confounded systems. International Journal of Approximate Reasoning, 88:371–384, 2017. <NAME> and <NAME>. Graphical models for processing missing data. 2018. Forthcoming, https://arxiv.org/abs/1801.03583. <NAME>, <NAME>, and <NAME>. Graphical models for inference with missing data. In Advances in Neural Information Systems, 26:1277–1285, 2013. <NAME>, <NAME>, <NAME>, and <NAME>. Stratified graphical models-context-specific inde- pendence in graphical models. Bayesian Analysis, 9(4):883–908, 2014. <NAME> and <NAME>. Causal effect identification in acyclic directed mixed graphs and gated models. International Journal of Approximate Reasoning, 90:56–75, 2017. <NAME>. Causal diagrams for empirical research. Biometrika, 82(4):669–688, 1995. <NAME>. Causality: Models, Reasoning, and Inference, 2009. <NAME>, <NAME>, <NAME>, and <NAME>. Labeled directed acyclic graphs: a generaliza- tion of context-specific independence in directed graphical models. Data Mining and Knowledge Discovery, 29(2):503–533, 2015. <NAME>, <NAME>, <NAME>, and <NAME>. A complete generalized adjustment criterion. In Proceedings of the 31st Conference on Uncertainty in Artificial Intelligence, 682–691, 2015. <NAME>, <NAME>, <NAME>, and <NAME>. Causal discovery with continuous additive noise models. Journal of Machine Learning Research, 15:2009–2053, 2014. <NAME>. Explanation, irrelevance, and statistical independence. In Proceedings of the 9th National conference on Artificial intelligence - Volume 1, 482–487, 1991. <NAME> and <NAME>. Identification of joint interventional distributions in recursive semi-Markovian causal models. In Proceedings of the 21st National Conference on Artificial Intelligence – Volume 2, 1219–1226, 2006a. <NAME> and <NAME>. Identification of conditional interventional distributions. In Proceedings of the 22nd Conference on Uncertainty in Artificial Intelligence, 437–444, 2006b. <NAME> and <NAME>. Complete identification methods for the causal hierarchy. Journal of Ma- chine Learning Research, 9:1941–1979, 2008. <NAME>, <NAME>, and <NAME>. Missing data as a causal and probabilistic problem. In Proceed- ings of the 31st Conference on Uncertainty in Artificial Intelligence, 802–811, 2015. <NAME>, <NAME>, and <NAME>. Causation, Prediction, and Search, 1993. <NAME> and <NAME>. Identifying causal effects with the R package causaleffect. Journal of Statistical Software, 76(12):1–30, 2017a. <NAME> and <NAME>. Simplifying probabilistic expressions in causal inference. Journal of Machine Learning Research, 18(36):1–30, 2017b. <NAME> and <NAME>. Enhancing identification of causal effects by pruning. Journal of Machine Learning Research, 18(194):1–23, 2018. <NAME> and <NAME>. Surrogate outcomes and transportability. International Journal of Ap- proximate Reasoning, 108:21–37, 2019. <NAME>, <NAME> and <NAME>. Causal effect identification from multiple incomplete data sources: a general search-based approach. Journal of Statistical Software, 99(5):1–40, 2021. <NAME> and <NAME>. Learning equivalence classes of acyclic models with latent and selection variables from multiple datasets with overlapping variables. In Proceedings of the 14th Interna- tional Conference on Artificial Intelligence and Statistics, 3–15, 2011. <NAME> and <NAME>. Constraint-based causal discovery from multiple interventions over overlapping variable sets. Journal of Machine Learning Research, 16:2147–2205, 2015. <NAME>, <NAME>, and <NAME>. Learning causal structure from overlapping variable sets. In Proceedings of the 13th International Conference on Artificial Intelligence and Statistics, 860–867, 2010. <NAME> and <NAME>. On searching for generalized instrumental variables. In Proceedings of the 19th International Conference on Artificial Intelligence and Statistics, 2016. <NAME>, <NAME>, <NAME>, and <NAME>. Using temporal context-specific independence information in the exploratory analysis of disease processes. In Conference on Artificial Intelligence in Medicine in Europe, 87–96, 2007. bivariate_missingness Systematic Analysis of Bivariate Missing Data Problems Description This data set contains the results of a systematic analysis of all missing data problems of two vari- ables. Each problem is associated with a graph containing two vertices, X and Y , and their response indicators, RX and RY . Usage data(bivariate_missingness) Format A data frame with 6144 rows and 8 variables: graph the graph of the instance, see get_derivation for more details on the syntax nedges number of edges in the graph (directed and bidirected) arrowXtoY whether the graph contains an arrow from X to Y or not jointXY identifiability of the joint distribution of X and Y marginX identifiability of the marginal distribution of X marginY identifiability of the marginal distribution of Y YcondX identifiability of the conditional distribution of Y given X YdoX identifiability of the causal effect of X on Y Source Tikka et. al. (2019) <arXiv:1902.01073> dosearch Identify a causal effect from arbitrary experiments and observations Description Identify a causal query from available data in a causal model described by a graph that is a semi-Markovian DAG or a labeled directed acyclic graph (LDAG). For DAGs, special mechanisms related to transportability of causal effects, recoverability from selection bias and identifiability under missing data can also be included. Usage dosearch(data, query, graph, transportability, selection_bias, missing_data, control) Arguments data a character string describing the available distributions in the package syntax. Alternatively, a list of character vectors. See ‘Details’. query a character string describing the target distribution in the package syntax. Alter- natively, a character vector. See ‘Details’. graph a character string describing either a DAG or an LDAG in the package syntax. Alternatively, an "igraph" graph as used in the "causaleffect" package or a DAG constructed using the "dagitty" package. See ‘Details’. transportability a character string describing the transportability nodes of the model in the pack- age syntax (for DAGs only). See ‘Details’. selection_bias a character string describing the selection bias nodes of the model in the package syntax (for DAGs only). See ‘Details’. missing_data a character string describing the missing data mechanisms of the model in the package syntax (for DAGs only). See ‘Details’. control a list of control parameters. See ‘Details’. Details data is used to list the available input distributions. When graph is a DAG the distributions should be of the form P (Ai |do(Bi ), Ci ). Individual variables within sets should be separated by a comma. For example, three input distribu- tions P (Z|do(X)), P (W, Y |do(Z, X)), P (W, Y, X|Z), should be given as follows: > data <- " + P(Z|do(X)) + P(W,Y|do(Z,X)) + P(W,Y,X|Z) +" The use of multiple do-operators is not permitted. Furthermore, when both conditioning variables and a do-operator are present, every conditioning variable must either precede the do-operator or follow it. When graph is an LDAG, the do-operation is represented by an intervention node, i.e., P (Y |do(X), Z) = P (Y |X, Z, IX = 1) For example, in the case of the previous example in an LDAG, the three input distributions become: > data <- " + P(Z|X,I_X = 1) + P(W,Y|Z,X,I_X=1,I_Z=1) + P(W,Y,X|Z) +" The intervention nodes IX and IZ must be explicitly defined in the graph along with the relevant labels for the edges. query is the target distribution of the search. It has the same syntax as data, but only a single distribution should be given. graph is a description of a directed acyclic graph where directed edges are denoted by -> and bidirected arcs corresponding to unobserved confounders are denoted by <-> (or by --). As an example, a DAG with two directed edges and one bidirected edge is constructed as follows: > graph <- " + X -> Z + Z -> Y + X <-> Y +" Some alternative formats for DAGs are supported as well. Graphs created using the igraph pack- age in the causal.effect syntax can be used here. Similarly, DAGs created using dagitty are supported. LDAGs are constructed similarly with the addition of labels and with the omission bidirected edges (latent variables must be explicitly defined). As an example, an LDAG with two labeled edges can be constructed as follows: > graph <- " + X -> Z : A = 0 + Z -> Y : A = 1 + A -> Z + A -> Y +" Here the labels indicate that the edge from X to Z vanishes when A has the value 0 and the edge from Z to Y vanishes when A has the value 1. Multiple labels on the same edge should be separated by a semi-colon. transportability enumerates the nodes that should be understood as transportability nodes re- sponsible for discrepancies between domains. Individual variables should be separated by a comma. See e.g., Bareinboim and Pearl (2014) for details on transportability. selection_bias enumerates the nodes that should be understood as selection bias nodes respon- sible for bias in the input data sets. Individual variables should be separated by a comma. See e.g., Bareinboim and Pearl (2014) for details on selection bias recoverability. missing_data enumerates the missingness mechanisms of the model. The syntax for a single mechanism is M_X : X where MX is the mechanism for X. Individual mechanisms should be sep- arated by a comma. Note that both MX and X must be present in the graph if the corresponding mechanism is given as input. Proxy variables should not be included in the graph, since they are automatically generated based on missing_data. By default, a warning is issued if a proxy variable is present in an input distribution but its corresponding mechanism is not present in any input. See e.g., Mohan, Pearl and Tian (2013) for details on missing data as a causal inference problem. The control argument is a list that can supply any of the following components: benchmark A logical value. If TRUE, the search time is recorded and returned (in milliseconds). Defaults to FALSE. benchmark_rules A logical value. If TRUE, the time taken by each individual inference rule is also recorded in the benchmark (in milliseconds). Defaults to FALSE. draw_derivation A logical value. If TRUE, a string representing the derivation steps as a DOT graph is returned. The graph can be exported as an image for example by using the DOT package. Defaults to FALSE. draw_all A logical value. If TRUE and if draw_derivation = TRUE, the derivation will contain every step taken by the search. If FALSE, only steps that resulted in an identifiable target are returned. Defaults to FALSE. formula A logical value. If TRUE, a string representing the identifiable query is returned when the target query is identifiable. If FALSE, only a logical value is returned that takes the value TRUE for an identifiable target and FALSE otherwise. Defaults to TRUE. heuristic A logical value. If TRUE, new distributions are expanded according to a search heuristic (see Tikka et al. (2019) for details). Otherwise, distributions are expanded in the order in which they were identified. Defaults to FALSE. md_sym A single character describing the symbol to use for active missing data mechanisms. De- faults to "1". time_limit A numeric value giving a time limit for the search (in hours). Defaults to a negative value that disables the limit. verbose A logical value. If TRUE, diagnostic information is printed to the console during the search. Defaults to FALSE. warn A logical value. If TRUE, a warning is issued for possibly unintentionally misspecified but syntactically correct input distributions. Value An object of class dosearch which is a list with the following components by default. See the op- tions of control for how to obtain a graphical representation of the derivation or how to benchmark the search. identifiable A logical value that attains the value TRUE is the target quantity is identifiable and FALSE otherwise. formula A character string describing a formula for an identifiable query or an empty character vector for an unidentifiable effect. Author(s) <NAME> References <NAME>, <NAME> and <NAME>. Causal effect identification from multiple incomplete data sources: a general search-based approach. Journal of Statistical Software, 99(5):1–40, 2021. Examples ## Simple back-door formula data1 <- "P(x,y,z)" query1 <- "P(y|do(x))" graph1 <- " x -> y z -> x z -> y " dosearch(data1, query1, graph1) ## Simple front-door formula data2 <- "P(x,y,z)" query2 <- "P(y|do(x))" graph2 <- " x -> z z -> y x <-> y " dosearch(data2, query2, graph2) ## Graph input using 'igraph' in the 'causaleffect' syntax if (requireNamespace("igraph", quietly = TRUE)) { g_igraph <- igraph::graph.formula(x -+ z, z -+ y, x -+ y, y -+ x) g_igraph <- igraph::set.edge.attribute(g_igraph, "description", 3:4, "U") dosearch(data2, query2, g_igraph) } ## Graph input with 'dagitty' if (requireNamespace("dagitty", quietly = TRUE)) { g_dagitty <- dagitty::dagitty("dag{x -> z -> y; x <-> y}") dosearch(data2, query2, g_dagitty) } ## Alternative distribution input style using lists and vectors: ## Each element of the list describes a single distribution ## Each element is a character vector that describes the role ## of each variable in the distribution as follows: ## For a variable V and a distribution P(A|do(B),C) we have ## V = 0, if V is in A ## V = 1, if V is in B ## V = 2, if V is in C data_alt <- list( c(x = 0, y = 0, z = 0) # = P(x,y,z) ) query_alt <- c(x = 1, y = 0) # = P(y|do(x)) dosearch(data_alt, query_alt, graph2) ## Additional examples ## Not run: ## Multiple input distributions (both observational and interventional) data3 <- " p(z_2,x_2|do(x_1)) p(z_1|x_2,do(x_1,y)) p(x_1|w_1,do(x_2)) p(y|z_1,z_2,x_1,do(x_2)) p(w|y,x_1,do(x_2)) " query3 <- "p(y,x_1|w,do(x_2))" graph3 <- " x_1 -> z_2 x_1 -> z_1 x_2 -> z_1 x_2 -> z_2 z_1 -> y z_2 -> y x_1 -> w x_2 -> w z_1 -> w z_2 -> w " dosearch(data3, query3, graph3) ## Selection bias data4 <- " p(x,y,z_1,z_2|s) p(z_1,z_2) " query4 <- "p(y|do(x))" graph4 <- " x -> z_1 z_1 -> z_2 x -> y y -- z_2 z_2 -> s " dosearch(data4, query4, graph4, selection_bias = "s") ## Transportability data5 <- " p(x,y,z_1,z_2) p(x,y,z_1|s_1,s_2,do(z_2)) p(x,y,z_2|s_3,do(z_1)) " query5 <- "p(y|do(x))" graph5 <- " z_1 -> x x -> z_2 z_2 -> y z_1 <-> x z_1 <-> z_2 z_1 <-> y t_1 -> z_1 t_2 -> z_2 t_3 -> y " dosearch(data5, query5, graph5, transportability = "t_1, t_2, t_3") ## Missing data ## Proxy variables are denoted by an asterisk (*) data6 <- " p(x*,y*,z*,m_x,m_y,m_z) " query6 <- "p(x,y,z)" graph6 <- " z -> x x -> y x -> m_z y -> m_z y -> m_x z <-> y " dosearch(data6, query6, graph6, missing_data = "m_x : x, m_y : y, m_z : z") ## An LDAG data7 <- "P(X,Y,Z)" query7 <- "P(Y|X,I_X=1)" graph7 <- " X -> Y : Z = 1 Z -> Y Z -> X : I_X = 1 I_X -> X H -> X : I_X = 1 H -> Z Q -> Z Q -> Y : Z = 0 " dosearch(data7, query7, graph7) ## A more complicated LDAG ## with multiple assignments for the edge X -> Z data8 <- "P(X,Y,Z,A,W)" query8 <- "P(Y|X,I_X=1)" graph8 <- " I_X -> X I_Z -> Z A -> W Z -> Y A -> Z X -> Z : I_Z = 1; A = 1 X -> Y : A = 0 W -> X : I_X = 1 W -> Y : A = 0 A -> Y U -> X : I_X = 1 U -> Y : A = 1 " dosearch(data8, query8, graph8) ## Export the DOT diagram of the derivation as an SVG file ## to the working directory via the DOT package. ## By default, only the identifying part is plotted. ## PostScript format is also supported. if (requireNamespace("DOT", quietly = TRUE)) { d <- get_derivation(data1, query1, graph1, control = list(draw_derivation = TRUE)) DOT::dot(d$derivation, "derivation.svg") } ## End(Not run) get_benchmark Benchmark a specific run of the search Description Returns the benchmarking information of an object of class "dosearch". Usage get_benchmark(x, run_again = FALSE, include_rules = FALSE) Arguments x an object of class "dosearch". run_again a logical value. If TRUE, run the search again to obtain the benchmarking infor- mation if it was not requested in the function call that produced x. include_rules A logical value. If TRUE, also benchmark the time taken by each inference rule separately. Value A list with one or two elements. The first is always a numeric value of the total time taken by the search in milliseconds. The second is a numeric vector of the time taken by each inference rule (in the internal C++ implementation) of the search in milliseconds if include_rules = TRUE. Author(s) <NAME> Examples data <- "P(x,y,z)" query <- "P(y|do(x))" graph <- " x -> y z -> x z -> y " x <- dosearch(data, query, graph, control = list(benchmark = FALSE)) get_benchmark(x, run_again = TRUE) get_derivation Retrieve the derivation of a causal query Description Returns the derivation of causal query of an object of class "dosearch". Usage get_derivation(x, run_again = FALSE, draw_all = FALSE) Arguments x an object of class "dosearch". run_again a logical value. If TRUE, run the search again to obtain a derivation for the query if one was not requested in the function call that produced x. draw_all a logical value. If TRUE, the derivation will contain every step taken by the search. If FALSE, only steps that resulted in identification are returned. Author(s) <NAME> Examples data <- "P(x,y,z)" query <- "P(y|do(x))" graph <- " x -> y z -> x z -> y " x <- dosearch(data, query, graph, control = list(draw_derivation = FALSE)) get_derivation(x, run_again = TRUE) get_formula Retrieve the identifying formula of a causal query Description Returns the identifying formula describing a causal query of an object of class "dosearch". Usage get_formula(x, run_again = FALSE) Arguments x an object of class "dosearch". run_again a logical value. If TRUE, run the search again to obtain a formula for the query if one was not requested in the function call that produced x. Value A character string representing the query in terms of the input data. Author(s) <NAME> Examples data <- "P(x,y,z)" query <- "P(y|do(x))" graph <- " x -> y z -> x z -> y " x <- dosearch(data, query, graph, control = list(formula = FALSE)) get_formula(x, run_again = TRUE) is_identifiable Query whether the target distribution was identifiable or not Description Returns the a logical value describing the identifiability of a causal query of an object of class "dosearch". Usage is_identifiable(x) Arguments x an object of class "dosearch". Value A logical value. If TRUE, the target distribution is identifiable from the available inputs. Author(s) <NAME> 16 is_identifiable Examples data <- "P(x,y,z)" query <- "P(y|do(x))" graph <- " x -> y z -> x z -> y " x <- dosearch(data, query, graph) is_identifiable(x) # TRUE
github.com/hhrutter/pdfcpu/pkg/pdfcpu/fonts/metrics
go
Go
None Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package metrics provides font metrics. ### Index [¶](#pkg-index) * [func CharWidth(fontName string, c int) int](#CharWidth) * [func FontBoundingBox(fontName string) *types.Rectangle](#FontBoundingBox) * [func FontNames() []string](#FontNames) * [func FontSize(text, fontName string, width float64) int](#FontSize) * [func TextWidth(text, fontName string, fontSize int) float64](#TextWidth) * [func UserSpaceFontBBox(fontName string, fontSize int) *types.Rectangle](#UserSpaceFontBBox) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) #### func [CharWidth](https://github.com/hhrutter/pdfcpu/blob/v0.2.2/pkg/pdfcpu/fonts/metrics/metrics.go#L48) [¶](#CharWidth) ``` func CharWidth(fontName [string](/builtin#string), c [int](/builtin#int)) [int](/builtin#int) ``` CharWidth returns the character width for a char and font in glyph space units. #### func [FontBoundingBox](https://github.com/hhrutter/pdfcpu/blob/v0.2.2/pkg/pdfcpu/fonts/metrics/metrics.go#L43) [¶](#FontBoundingBox) ``` func FontBoundingBox(fontName [string](/builtin#string)) *[types](/github.com/hhrutter/[email protected]/pkg/types).[Rectangle](/github.com/hhrutter/[email protected]/pkg/types#Rectangle) ``` FontBoundingBox returns the font bounding box for a given font as specified in the corresponding AFM file. #### func [FontNames](https://github.com/hhrutter/pdfcpu/blob/v0.2.2/pkg/pdfcpu/fonts/metrics/metrics.go#L118) [¶](#FontNames) ``` func FontNames() [][string](/builtin#string) ``` FontNames returns the list of supported font names. #### func [FontSize](https://github.com/hhrutter/pdfcpu/blob/v0.2.2/pkg/pdfcpu/fonts/metrics/metrics.go#L99) [¶](#FontSize) ``` func FontSize(text, fontName [string](/builtin#string), width [float64](/builtin#float64)) [int](/builtin#int) ``` FontSize returns the needed font size (aka. font scaling factor) in points for rendering a given text string using a given font name with a given user space width. #### func [TextWidth](https://github.com/hhrutter/pdfcpu/blob/v0.2.2/pkg/pdfcpu/fonts/metrics/metrics.go#L87) [¶](#TextWidth) ``` func TextWidth(text, fontName [string](/builtin#string), fontSize [int](/builtin#int)) [float64](/builtin#float64) ``` TextWidth represents the width in user space units for a given text string, font name and font size. #### func [UserSpaceFontBBox](https://github.com/hhrutter/pdfcpu/blob/v0.2.2/pkg/pdfcpu/fonts/metrics/metrics.go#L108) [¶](#UserSpaceFontBBox) ``` func UserSpaceFontBBox(fontName [string](/builtin#string), fontSize [int](/builtin#int)) *[types](/github.com/hhrutter/[email protected]/pkg/types).[Rectangle](/github.com/hhrutter/[email protected]/pkg/types#Rectangle) ``` UserSpaceFontBBox returns the font box for given font name and font size in user space coordinates. ### Types [¶](#pkg-types) This section is empty.
federation
readthedoc
YAML
Federation 0.24.1 documentation federation[¶](#federation) === Python library to abstract social web federation protocols like ActivityPub and Diaspora. Contents: Introduction[¶](#introduction) --- The aim of `federation` is to provide and abstract multiple social web protocols like ActivityPub and Diaspora in one package, over an easy to use and understand Python API. This way applications can be built to (almost) transparently support many protocols without the app builder having to know everything about those protocols. ### Status[¶](#status) Currently three protocols are being focused on. * Diaspora is considered to be stable with most of the protocol implemented. * ActivityPub support should be considered as beta - inbound payload are handled by a jsonld processor (calamus) * Matrix support cannot be considered usable as of yet. The code base is well tested and in use in several projects. Backward incompatible changes will be clearly documented in changelog entries. ### Additional information[¶](#additional-information) #### Installation and requirements[¶](#installation-and-requirements) See [installation documentation](http://federation.readthedocs.io/en/latest/install.html). #### Usage and API documentation[¶](#usage-and-api-documentation) See [usage documentation](http://federation.readthedocs.io/en/latest/usage.html). #### Support and help[¶](#support-and-help) See [development and support documentation](http://federation.readthedocs.io/en/latest/development.html). #### License[¶](#license) [BSD 3-clause license](https://www.tldrlegal.com/l/bsd3). #### Author[¶](#author) <NAME> / [jasonrobinson.me](https://jasonrobinson.me) / [@jaywink:federator.dev](https://matrix.to/#/@jaywink:federator.dev) / [GitLab](https://gitlab.com/jaywink) / [GitHub](https://github.com/jaywink) Install[¶](#install) --- ### Dependencies[¶](#dependencies) Depending on your operating system, certain dependencies will need to be installed. #### lxml[¶](#lxml) lxml itself is installed by pip but the dependencies need to be installed [as per lxml instructions](http://lxml.de/installation.html#requirements). ### Installation[¶](#installation) Install with pip or include in your requirements file. ``` pip install federation ``` Protocols[¶](#protocols) --- Currently three protocols are being focused on. * Diaspora is considered to be stable with most of the protocol implemented. * ActivityPub support should be considered as beta - all the basic things work and we are fixing incompatibilities as they are identified. * Matrix support cannot be considered usable as of yet. For example implementations in real life projects check [Projects using federation](index.html#example-projects). ### Diaspora[¶](#diaspora) This library only supports the [current renewed version](http://diaspora.github.io/diaspora_federation/) of the protocol. Compatibility for the legacy version was dropped in version 0.18.0. The feature set supported is the following: * Webfinger, hCard and other discovery documents * NodeInfo 1.0 documents * Social-Relay documents * Magic envelopes, signatures and other transport method related necessities * Entities as follows: > + Comment > + Like > + Photo > + Profile > + Retraction > + StatusMessage > + Contact > + Reshare ### ActivityPub[¶](#activitypub) Features currently supported: * Webfinger * Objects and activities as follows: > + Actor (Person outbound, Person, Organization, Service inbound) > + Note, Article and Page (Create, Delete, Update) > * These become a `Post` or `Comment` depending on `inReplyTo`. > + Attachment images, (inbound only for audios and videos) from the above objects > + Follow, Accept Follow, Undo Follow > + Announce > + Inbound Peertube Video objects translated as `Post`. > * Inbound processing of reply collections, for platforms that implement it. * Link, Like, View, Signature, PropertyValue, IdentityProof and Emojis objects are only processed for inbound payloads currently. Outbound processing requires support by the client application. #### Namespace[¶](#namespace) All payloads over ActivityPub sent can be identified with by checking `@context` which will include the `pyfed: https://docs.jasonrobinson.me/ns/python-federation` namespace. #### Content media type[¶](#content-media-type) The following keys will be set on the entity based on the `source` property existing: * if the object has an `object.source` property: * `_media_type` will be the source media type (only text/markdown is supported). * `rendered_content` will be the object `content` * `raw_content` will be the source `content` * if the object has no `object.source` property: * `_media_type` will be `text/html` * `rendered_content` will be the object `content` * `raw_content` will be empty The `contentMap` property is processed but content language selection is not implemented yet. For outbound entities, `raw_content` is expected to be in `text/markdown`, specifically CommonMark. The client applications are expected to provide the rendered content for protocols that require it (e.g. ActivityPub). When sending payloads, `object.contentMap` will be set to `rendered_content` and `raw_content` will be added to the `object.source` property. #### Medias[¶](#medias) Any images referenced in the `raw_content` of outbound entities will be extracted into `object.attachment` object. For receivers that don’t support inline images, image attachments will have a `pyfed:inlineImage` property set to `true` to indicate the image has been extracted from the content. Receivers should ignore the inline image attachments if they support showing `<img>` HTML tags or the markdown content in `object.source`. Outbound audio and video attachments currently lack support from client applications. For inbound entities we do this automatically by not including received image attachments in the entity `_children` attribute. Audio and video are passed through the client application. #### Hashtags and mentions[¶](#hashtags-and-mentions) For outbound payloads, client applications must add/set the hashtag/mention value to the `class` attribute of rendered content linkified hashtags/mentions. These will be used to help build the corresponding `Hashtag` and `Mention` objects. For inbound payloads, if a markdown source is provided, hashtags/mentions will be extracted through the same method used for Diaspora. If only HTML content is provided, the `a` tags will be marked with a `data-[hashtag|mention]` attribute (based on the provided Hashtag/Mention objects) to facilitate the `href` attribute modifications lient applications might wish to make. This should ensure links can be replaced regardless of how the HTML is structured. ### Matrix[¶](#matrix) The aim of Matrix support in this library is not to provide instant messaging but to wrap the parts of the Matrix protocol that specifically are especially useful for social media applications. The current ongoing work on [Ceruelan](https://matrix.org/blog/2020/12/18/introducing-cerulean) provides much of what will be implemented in this library. This library doesn’t aim to be a homeserver or provide any part of the server to server API. The plan is to provide an appservice to hook onto a separate homeserver that deals with all the complex protocol related details. This library will then aim to abstract much of what the appservice gives or takes behind the same API as is provided for the other protocols. Currently support is being added, please visit back in future versions. NOTE! Current features also assume Django is configured, though this is likely to not be the case in the future. #### Appservice[¶](#appservice) To generate the appservice registration file you must ensure you’ve added the relevant configuration (see [Configuration](index.html#usage-configuration)). Then launch a Django shell inside your project and run the following: ``` from federation.protocols.matrix.appservice import print_registration_yaml print_registration_yaml() ``` This YAML needs to be registered with the linked Matrix homeserver as instructed in the relevant homeserver documentation. Usage[¶](#usage) --- ### Entities[¶](#entities) Federation has it’s own base entity classes. When incoming messages are processed, the protocol specific entity mappers transform the messages into our base entities. In reverse, when creating outgoing payloads, outgoing protocol specific messages are constructed from the base entities. Entity types are as follows below. #### Protocol entities[¶](#protocol-entities) Each protocol additionally has it’s own variants of the base entities, for example Diaspora entities in `federation.entities.diaspora.entities`. All the protocol specific entities subclass the base entities so you can safely work with for example `DiasporaPost` and use `isinstance(obj, Post)`. When creating incoming objects from messages, protocol specific entity classes are returned. This is to ensure protocol specific extra attributes or methods are passed back to the caller. For sending messages out, either base or protocol specific entities can be passed to the outbound senders. If you need the correct protocol specific entity class from the base entity, each protocol will define a `get_outbound_entity` function. #### Federation identifiers[¶](#federation-identifiers) All entities have an `id` to guarantee them a unique name in the network. The format of the `id` depends on the protocol in question. * ActivityPub: maps to the object `id` (whether wrapped in an Activity or not) * Diaspora: maps to `guid` for the entity. ##### Profiles[¶](#profiles) Profiles are uniquely identified by the `id` as above. Additionally for Diaspora they always have a `handle`. ActivityPub profiles can also have a `handle` but it is optional. A handle will always be in email like format, without the @ prefix found on some platforms. This will be added to outgoing payloads where needed. #### Creator and owner identifiers[¶](#creator-and-owner-identifiers) All entities except `Profile` have an `actor_id` which tells who created this object or activity. The format depends on the protocol in question. * ActivityPub: maps to Object `attributedTo` or Activity `actor_id`. * Diaspora: maps to entity `author` #### Activity identifiers[¶](#activity-identifiers) Entities which are an activity on something, for example creating, updating, deleting, following, etc, should have an `activity_id` given to be able to send out to the ActivityPub protocol. #### Mentions[¶](#mentions) Entities store mentions in the list `_mentions`. The list is a simple list of strings which will be either an URL format `profile.id` or handle, as per above examples. The syntax for a mention in text is URL format `@{<profile.id>}` or `@{<profile.handle>}`. The GUID format `profile.id` cannot be used for a mention. Examples: ``` # profile.handle Hello @{<EMAIL>}! # profile.id in URL format Hello @{https://domain.tld/user} ``` It is suggested `profile.handle` syntax is used always for textual mentions unless handles are not available. ##### Inbound[¶](#inbound) Mentions are added to the entity `_mentions` list when processing inbound entities. For ActivityPub they will be extracted from `Mention` tags and for Diaspora extracted from the text using the Diaspora mention format. ##### Outbound[¶](#outbound) Mentions can be given in the `_mentions` list. If not given, they will be extracted from the textual content using the above formats in the example. For ActivityPub they will be added as `Mention` tags before sending. If the mention is in handle format, a WebFinger fetch will be made to find the profile URL format ID. For Diaspora they will be added to the text in the correct format, if not found. If they are found in the text in non-Diaspora format, they will be converted before sending. ### Discovery[¶](#discovery) Federation provides many generators to allow providing discovery documents. They have been made as Pythonic as possible so that library users don’t have to meddle with the various documents and their internals. The protocols themselves are too complex to document within this library, please consult protocol documentation on what kind of discovery documents are expected to be served by the application. #### Generators[¶](#generators) ##### Helper methods[¶](#helper-methods) ##### Generator classes[¶](#generator-classes) ### Fetchers[¶](#fetchers) High level utility functions to fetch remote objects. These should be favoured instead of protocol specific utility functions. ### Inbound[¶](#id1) High level utility functions to pass incoming messages to. These should be favoured instead of protocol specific utility functions. ### Outbound[¶](#id2) High level utility functions to pass outbound entities to. These should be favoured instead of protocol specific utility functions. ### Django[¶](#django) Some ready provided views and URL configuration exist for Django. Note! Django is not part of the normal requirements for this library. It must be installed separately. #### Configuration[¶](#configuration) To use the Django views, ensure a modern version of Django is installed and add the views to your URL config for example as follows. The URL’s must be mounted on root if Diaspora protocol support is required. ``` url(r"", include("federation.hostmeta.django.urls")), ``` Some settings need to be set in Django settings. An example is below: ``` FEDERATION = { "base_url": "https://myserver.domain.tld, "federation_id": "https://example.com/u/john/", "get_object_function": "myproject.utils.get_object", "get_private_key_function": "myproject.utils.get_private_key", "get_profile_function": "myproject.utils.get_profile", "matrix_config_function": "myproject.utils.matrix_config_funct", "nodeinfo2_function": "myproject.utils.get_nodeinfo2_data", "process_payload_function": "myproject.utils.process_payload", "search_path": "/search/?q=", "tags_path": "/tags/:tag:", } ``` * `base_url` is the base URL of the server, ie protocol://domain.tld. * `federation_id` is a valid ActivityPub local profile id whose private key will be used to create the HTTP signature for GET requests to ActivityPub platforms. * `get_object_function` should be the full path to a function that will return the object matching the ActivityPub ID for the request object passed to this function. * `get_private_key_function` should be the full path to a function that will accept a federation ID (url, handle or guid) and return the private key of the user (as an RSA object). Required for example to sign outbound messages in some cases. * `get_profile_function` should be the full path to a function that should return a `Profile` entity. The function should take one or more keyword arguments: `fid`, `handle`, `guid` or `request`. It should look up a profile with one or more of the provided parameters. * `matrix_config_function` (optional) function that returns a Matrix configuration dictionary, with the following objects: ``` { # Location of the homeserver (not server name) "homeserver_base_url": "https://matrix.domain.tld", # Homeserver domain and port (not server domain) "homeserver_domain_with_port": "matrix.domain.tld:443", # Homeserver name "homeserver_name": "domain.tld", # Appservice details "appservice": { # Unique ID to register with at the homeserver. Don't change this after creating. "id": "uniqueid", # Short code (a-z only), used for various things like namespacing "shortcode": "federatedapp", # Secret token for communication "token": "secret_token", }, # (Optional) location of identity server "identity_server_base_url": "https://id.domain.tld", # (Optional) other keys to include in the client well-known (must be a dictionary) "client_wellknown_other_keys": { "org.foo.key" "barfoo", }, # (Optional) registration shared secret "registration_shared_secret": "supersecretstring", } ``` * `nodeinfo2_function` (optional) function that returns data for generating a [NodeInfo2 document](https://github.com/jaywink/nodeinfo2). Once configured the path `/.well-known/x-nodeinfo2` will automatically generate a NodeInfo2 document. The function should return a `dict` corresponding to the NodeInfo2 schema, with the following minimum items: ``` {server: baseUrl name software version } openRegistrations ``` * `process_payload_function` (optional) function that takes in a request object. It should return `True` if successful (or placed in queue for processing later) or `False` in case of any errors. * `search_path` (optional) site search path which ends in a parameter for search input, for example “/search?q=” * `tags_path` (optional) path format to view items for a particular tag. `:tag:` will be replaced with the tag (without `#`). ### Protocols[¶](#protocols) The code for opening and creating protocol messages lives under each protocol module in `federation.protocols`. Each protocol defines a `protocol.Protocol` class under it’s own module. This is expected to contain certain methods that are used by the higher level functions that are called on incoming messages and when sending outbound messages. Everything that is needed to transform an entity into a message payload and vice versa should be here. Instead of calling methods directly for a specific protocol, higher level generic functions should be normally used. ### Utils[¶](#utils) Various utils are provided for internal and external usage. #### ActivityPub[¶](#activitypub) #### Diaspora[¶](#diaspora) #### Matrix[¶](#matrix) #### Network[¶](#network) #### Protocols[¶](#id3) ### Exceptions[¶](#exceptions) Various custom exception classes might be returned. Development[¶](#development) --- Help is more than welcome to extend this library. Please see the following resources. * [Source code repo](https://gitlab.com/jaywink/federation) * [Issue tracker](https://gitlab.com/jaywink/federation/-/issues) ### Environment setup[¶](#environment-setup) Once you have your (Python 3.7+) virtualenv set up, install the development requirements: ``` pip install -r dev-requirements.txt ``` ### Running tests[¶](#running-tests) ``` py.test ``` ### Building local documentation[¶](#building-local-documentation) ``` cd docs make html ``` Built documentation is available at `docs/_build/html/index.html`. ### Contact for help[¶](#contact-for-help) Easiest via Matrix on room `#socialhome:federator.dev`. You can also ask questions or give feedback via issues. Projects using federation[¶](#projects-using-federation) --- For examples on how to integrate this library into your project, check these examples: * [Socialhome](https://socialhome.network) - a federated home page builder slash personal social network server with high emphasis on card style content visualization. * [Social-Relay](https://github.com/jaywink/social-relay) - a reference server for the public content relay system that uses the Diaspora protocol. * [The Federation info](https://the-federation.info) - statistics and node list for the federated web. Changelog[¶](#changelog) --- ### [0.25] - Unreleased[¶](#unreleased) #### Added[¶](#added) * LD signature. Relayable AP payloads signatures are checked (inbound) and signed (outbound). A missing or invalid signature on inbound payloads will trigger a fetch if the sender differs from the author (i.e., a relay). * The `signable` attribute has been added. It defaults to `False` and will enforce the fetching of relayed payloads with a bad signature when set to `True`on a given class. * The `url` property is now set to the `id` property as some platforms make use of it. #### Changed[¶](#changed) * Re-implement dynamically generated LD contexts for outbound payloads. AP extensions are defined on a per class/property basis. For classes, a `ctx` attribute is set if required. For properties, the calamus field `metadata` property is used. * For inbound payload, a cached dict of all the defined AP extensions is merged with each incoming LD context. * Better handle conflicting property defaults by having `get_base_attributes` return only attributes that are not empty (or bool). This helps distinguish between `marshmallow.missing` and empty values. * JsonLD document caching now set in `activitypub/__init__.py`. * Patch outbound payloads for platform that don’t handle arrays compacted to a single value and `as:Public`. * Always try to get profiles from the client app before fetching from remote. In support of this, the client app AP profiles must include the keyId and the followers URIs. As a significant side effect, profile retractions are now more likely to succeed. #### Fixed[¶](#fixed) * Inbound AP share retractions (undo announce) were deserialized as a `base.Retraction` class, which would throw an error when accessing the missing `signable` attribute. To fix this, a `Retraction` class was added. * Because of the additions and changes above, a number of tests needed to be fixed. * HTTP signature verification now returns the signature author fid which is used as the actual sender by `message_to_object`. * In fetch_document: if response.encoding is not set, default to utf-8. * Fix process_text_links that would crash on `a` tags with no `href` attribute. * Ignore relayed AP retractions. ### [0.24.1] - 2023-03-18[¶](#id1) #### Fixed[¶](#id2) * Fix documentation builds ### [0.24.0] - 2023-03-18[¶](#id3) #### Added[¶](#id4) * Add a validation function for the Activitypub `attributedTo` property. Ensure it starts with `http`. #### Changed[¶](#id5) * Optimize handle_send by ensuring a payload is only sent once per recipient unique endpoint. * Match the Activitypub Hashtag object `href` property value against the raw content in order to make this process platform agnostic. #### Fixed[¶](#id6) * The Activitypub `url` property can now handle nested Link objects for all defined object types. * Catch cases where an Activitypub CollectionPage `next` property points back to a Collection object. * Make the Activitypub Follow class handle both the Undo and the Accept activities. ### [0.23.1] - 2023-02-08[¶](#id7) #### Changed[¶](#id8) * Switch `python-httpsig-socialhome` dependency to PyPi packaged version. ### [0.23.0] - 2023-02-08[¶](#id9) #### Added[¶](#id10) * Activitypub payloads are now processed by calamus (https://github.com/SwissDataScienceCenter/calamus), which is a jsonld processor based on marshmallow. + A large number of inbound Activitypub objects and properties are deserialized, it’s up to the client app to implement the corresponding behavior. + Unsupported objects and properties should be easy to implement. Unsupported payloads are logged as such. + More AP platforms are now supported (friendica, pixelfed, misskey, pleroma, gotosocial, litepub, and more). The jsonld context some platforms provide sometimes needs to be patched because of missing jsonld term definitions. + Peertube Video objects are translated into Posts. * For performance, requests_cache has been added. It pulls a redis configuration from django if one exists or falls back to a sqlite backend. Special case: pyld document loader has been extended to use redis directly. * Activitypub GET requests are now signed if the django configuration includes FEDERATION_USER which is used to fetch that user’s private key. * Activitypub remote GET signature is now verified in order to authorize remote access to limited content. * Added Video and Audio objects. Inbound support only. * Process Activitypub reply collections. When supported by the client app, it allows for a more complete view of conversations, especially for shared content. * WIP: initial support for providing reponses to Activitypub collections requests. This release only responds with a count for the followers and following collections. #### Changed[¶](#id11) * outbound.py doesn’t need to set the to and cc Activitypub properties, they are now expected to be set by the client app. * Attempts are made to remove duplicate img tags some platforms send (friendica, for one). * Activitypub receivers of the followers variant are now correctly processed for all known platforms. * Accept images with application/octet-stream content type (with the help of the magic library). * user@domain is now the only format used for mentions. The client app is expected to comply. For Activitypub, this means making a webfinger request to validate the handle if the client app doesn’t already know the corresponding profile. * Because of the change above, ensure mentions in Diaspora outbound payloads are as per their protocol spec (i.e. replacing @user@domain with @{user@domain} in the text) #### Fixed[¶](#id12) * Signatures are not verified and the corresponding payload is dropped if no public key is found. * Sign forwarded AP replies and shares with the target content author’s private key. #### Internal changes[¶](#internal-changes) * Dropped python 3.6 support. * Many tests were fixed/updated. ### [0.22.0] - 2021-08-15[¶](#id13) #### Added[¶](#id14) * Work in progress Matrix support over an appservice 😻 Currently requires Django support. Tested on Dendrite and up to version v0.3.11 only. Features so far: + Register local users on the configured Matrix server. + Post local user public posts into Matrix side to their profile timeline rooms and to each hashtag room. #### Fixed[¶](#id15) * Fixed image delivery between platforms that send ActivityPub payloads with a markdown `source`, caused by overenthusiastic linkifying of markdown. * Fix a crash in `outbound.handle_send` when payload failed to be generated and `parent_user` was not given. ### [0.21.0] - 2020-12-20[¶](#id16) #### Added[¶](#id17) * Start testing on Python 3.8 which is the new recommended version to use. #### Removed[¶](#removed) * Removed the network utils `fetch_host_ip_and_country` and `fetch_country_by_ip` due to the library that was used starting to require an API key. #### Internal changes[¶](#id18) * Fix some tests for newer Python. ### [0.20.0] - 2020-12-20[¶](#id19) #### Added[¶](#id20) * Entities with a `raw_content` field now have URL syntax mentions rendered into a link. ([related issue](https://git.feneas.org/socialhome/socialhome/issues/572)) If Django is configured, a profile will be retrieved using the configured profile getter function and the profile name or username will be used for the link. * Add `process_text_links` text utility to linkify URL’s in text. * Add `find_tags` text utility to find hashtags from text. Optionally the function can also replace the tags through a given `replacer` function. This utility is used to improve the tag extraction logic from entities text fields. ([related issue](https://git.feneas.org/jaywink/federation/issues/70)) * Outbound functions `handle_send` and `handle_create_payload` now accept an optional `payload_logger` parameter. If given it should be a function that takes three parameters: + `str` or `dict` payload + `str` protocol name + `str` sender idThe function will be called for each generated payload. * Cross-protocol improvements: + Extract Diaspora guid from ActivityPub payloads implementing the Diaspora extension. + Add Diaspora extension and guid to outbound ActivityPub payloads, if available. For profiles, also add handle. + Extract ActivityPub ID from Diaspora payloads if found as the `activitypub_id` property. + Add ActivityPub ID to outbound Diaspora payloads of types comment, post and profile, if an URL given as `id`. #### Changed[¶](#id21) * The NodeInfo2 hostmeta parser now cleans the port out of the host name. * URL’s in outgoing text content are now linkified for the HTML representation of the content for ActivityPub payloads. * Don’t include OStatus for Mastodon 3.0+ protocols list. ([related issue](https://github.com/thefederationinfo/the-federation.info/issues/217)) * **Backwards incompatible**: Stop markdownifying incoming ActivityPub content. Instead copy it as is to the `raw_content` attribute on the entity, setting also the `_media_type` to `text/html`. #### Fixed[¶](#id22) * Don’t crash loudly when fetching webfinger for Diaspora that does not contain XML. * Add missing `response.raise_for_status()` call to the `fetch_document` network helper when fetching with given URL. Error status was already being raised correctly when fetching by domain and path. * Don’t crash when parsing an invalid NodeInfo document where the usage dictionary is not following specification. * Ensure Pixelfed, Kroeg and Kibou instances that emulate the Mastodon API don’t get identified as Mastodon instances. * Loosen validation of `TargetIDMixin`, it now requires one of the target attributes to be set, not just `target_id`. This fixes follows over the Diaspora protocol which broke with stricter send validation added in 0.19.0. * Fix some edge case crashes of `handle_send` when there are Diaspora protocol receivers. * Fix reading `sharedInbox` from remote ActivityPub profiles. This caused public payloads not to be deduplicated when sending public payloads to remote ActivityPub servers. Refetching profiles should now fix this. ([related issue](https://git.feneas.org/jaywink/federation/issues/124)) * Don’t always crash generating payloads if Django is installed but not configured. * Don’t try to relay AP payloads to Diaspora receivers and vice versa, for now, until cross-protocol relaying is supported. * Fix some characters stopping tags being identified ([related issue](https://git.feneas.org/socialhome/socialhome/-/issues/222)) * Fix tags separated by slashes being identified ([related issue](https://git.feneas.org/socialhome/socialhome/-/issues/198)) ### [0.19.0] - 2019-12-15[¶](#id23) #### Added[¶](#id24) * The fetcher `retrieve_remote_profile` now also supports handle based fetching for the ActivityPub protocol. #### Changed[¶](#id25) * All outgoing entities are now validated before sending. This stops the sending of invalid entities to the network, for example a Share of a Post from ActivityPub to the Diaspora protocol network. #### Fixed[¶](#id26) * Allow ActivityPub HTTP Signature verification to pass if signature is at most 24 hours old. Previously requirement was 30 seconds, which caused loss of messages where signature validation didn’t happen immediately, but in a background worker which didn’t immediately process the job. #### Internal changes[¶](#id27) * Improve performance of generating ActivityPub payloads for a large number of receivers in `handle_send`. * Fail early in outbound `handle_send` if a payload cannot be generated for a payload which doesn’t depend on recipient attributes. ### [0.18.1] - 2019-10-06[¶](#id28) #### Changed[¶](#id29) * Removed possibility to deactivate ActivityPub support. It is now always enabled by default. ### [0.18.0] - 2019-10-06[¶](#id30) #### Added[¶](#id31) * Base entities `Post`, `Comment` and `Image` now accept an `url` parameter. This will be used when serializing the entities to AS2 for ActivityPub. * RFC7033 webfinger generator now has compatibility to platforms using it with ActivityPub. It now lists `aliases` pointing to the ActivityPub entity ID and profile URL. Also there is a `rel=self` to point to the `application/activity+json` AS2 document location. * Added a Django view decorator that makes any Profile or Post view ActivityPub compatible. Right now basic AS2 serialization is supported when the view is called using the supported content types in the Accept header. If the content types are not in the header, the view will render normally. When used, a few extra settings must be given in the Django `FEDERATION` configuration dictionary. + `get_object_function` should contain the Python path to a function that takes a request object and returns an object matching the ActivityPub ID for the request or `None`. + `process_payload_function` should contain the Python path to a function that takes in a request object. It should return `True` if successful (or placed in queue for processing later) or `False` in case of any errors. * Added network utility `network.fetch_host_ip` to fetch IP by hostname. * Entities of type `Profile` now have a dictionary of `inboxes`, with two elements, `private` and `public`. These should be URL’s indicating where to send payloads for the recipient. ActivityPub profiles will parse these values from incoming profile documents. Diaspora entities will default to the inboxes in the specification. * Added support for Diaspora `Comment` entity `thread_parent_guid` attribute. * Added `root_target_id` and `root_target_guid` to `Comment` base entity. This allows referring to a parent object up the hierarchy chain for threaded comments. * The high level fetcher `retrieve_remote_content` now supports ActivityPub ID’s. * All ActivityPub payloads are added a `pyfed: https://docs.jasonrobinson.me/ns/python-federation` context to identify payloads sent by this library. * Entities with `raw_content` now also contain a `_media_type` and `rendered_content`. The default `_media_type` is `text/markdown` except for ActivityPub originating posts it defaults to `text/html`. If the ActivityPub payload contains a `source`, that mediaType will be used instead. * Host meta fetchers now support NodeInfo 2.1 #### Changed[¶](#id32) * **Backwards incompatible.** Lowest compatible Python version is now 3.6. * **Backwards incompatible.** Internal refactoring to allow adding ActivityPub support as the second supported protocol. Highlights of changes below. + Reversal of all the work previously done to use Diaspora URL format identifiers. Working with the Diaspora protocol now always requires using handles and GUID’s as before the changes introduced in v0.15.0. It ended up impossible to construct a Diaspora URL in all cases in a way that apps only need to store one identifier. + The `id` and possible `target_id` are now either URL format identifiers (ActivityPub) or a handle or GUID (Diaspora, depending on entity). Additionally a new `actor_id` has been added which for ActivityPub is an URL and for Diaspora a handle. Note, Diaspora entities always have also the `guid`, `handle`, `target_guid` and `target_handle` as before v0.15.0, depending on the entity. When creating Diaspora entities, you must pass these in for sending to work. + The high level `fetchers.retrieve_remote_content` signature has changed. It now expects an `id` for fetching from AP protocol and `handle`, `guid` and `entity_type` to fetch from Diaspora. Additionally a `sender_key_fetcher` can be passed in as before to optimize public key fetching using a callable. + The high level `fetchers.retrieve_remote_profile` signature has changed. It now expects as first parameter an `id` which for ActivityPub objects is the URL ID and for Diaspora objects is the handle. Additionally a `sender_key_fetcher` can be passed in as before to optimize public key fetching using a callable. + The generator class `RFC7033Webfinger` now expects instead of an `id` the `handle` and `guid` of the profile. + NodeInfo2 parser now returns the admin user in `handle` format instead of a Diaspora format URL. + The high level inbound and outbound functions `inbound.handle_receive`, `outbound.handle_send` parameter `user` must now receive a `UserType` compatible object. This must have the attribute `id`, and for `handle_send` also `private_key`. If Diaspora support is required then also `handle` and `guid` should exist. The type can be found as a class in `types.UserType`. + The high level inbound function `inbound.handle_receive` first parameter has been changed to `request` which must be a `RequestType` compatible object. This must have the attribute `body` which corrresponds to the old `payload` parameter. For ActivityPub inbound requests the object must also contain `headers`, `method` and `url`. + The outbound function `outbound.handle_send` parameter `recipients` structure has changed. It must now be a list of dictionaries, containing at minimum the following: `endpoint` for the recipient endpoint, `fid` for the recipient federation ID (ActivityPub only), `protocol` for the protocol to use and `public` as a boolean whether the payload should be treated as visible to anyone. For Diaspora private deliveries, also a `public_key` is required containing the receiver public key. Note that passing in handles as recipients is not any more possible - always pass in a url for `endpoint`. + The outbound function `outbound.handle_create_payload` now requires an extra third parameter for the protocol to use. This function should rarely need to be called directly - use `handle_send` instead which can handle both ActivityPub and Diaspora protocols. + The `Image` base entity has been made more generic. The following were removed: `remote_path`, `remote_name`, `linked_type`, `linked_guid`, `public`. The following were added: `url`, `name`. * **Backwards incompatible.** Generator `RFC3033Webfinger` and the related `rfc3033_webfinger_view` have been renamed to `RFC7033Webfinger` and `rfc7033_webfinger_view` to reflect the right RFC number. * Network helper utility `fetch_document` can now also take a dictionary of `headers`. They will be passed to the underlying `requests` method call as is. * `Retraction` entity can now also have an `entity_type` of `Object`. Receivers will need to find the correct object using `target_id` only. This is currently only relevant for ActivityPub where retraction messages do not refer to object type. * **Backwards incompatible.** Inbound entities now have a list of receivers. Entities processed by inbound mappers will now have a list of receivers in `_receivers`. This replaces the `_receiving_actor_id` which was previously set for Diaspora entities. * UserType now has a `receiver_variant` which is one of `ReceiverVariant` enum. `ACTOR` means this receiver is a single actor ID. `FOLLOWERS` means this is the followers of the ID in the receiver. #### Fixed[¶](#id33) * Ensure Diaspora mentions are extracted when they don’t have a display name part. #### Removed[¶](#id34) * **Backwards incompatible.** Support for Legacy Diaspora payloads have been removed to reduce the amount of code needed to maintain while refactoring for ActivityPub. ### [0.17.0] - 2018-08-11[¶](#id35) #### Fixed[¶](#id36) * Switch crypto library `pycrypto` to `pycryptodome`, which is a more up to date fork of the former. This fixes CVE-2018-6594 found in the former. **Deployment note.** When updating an application, you *must* uninstall `pycrypto` first, otherwise there will be a conflict if both the versions are installed at the same time. To uninstall, do `pip uninstall pycrypto`. ### [0.16.0] - 2018-07-23[¶](#id37) #### Added[¶](#id38) * Enable generating encrypted JSON payloads with the Diaspora protocol which adds private message support. ([related issue](https://github.com/jaywink/federation/issues/82)) JSON encrypted payload encryption and decryption is handled by the Diaspora `EncryptedPayload` class. * Add RFC7033 webfinger generator ([related issue](https://github.com/jaywink/federation/issues/108)) Also provided is a Django view and url configuration for easy addition into Django projects. Django is not a hard dependency of this library, usage of the Django view obviously requires installing Django itself. For configuration details see documentation. * Add fetchers and parsers for NodeInfo, NodeInfo2, StatisticsJSON and Mastodon server metainfo documents. * Add NodeInfo2 generator and Django view. See documentation for details. ([related issue](https://github.com/jaywink/federation/issues/32)) * Added new network utilities to fetch IP and country information from a host. The country information is fetched using the free `ipdata.co` service. NOTE! This service is rate limited to 1500 requests per day. * Extract mentions from Diaspora payloads that have text content. The mentions will be available in the entity as `_mentions` which is a set of Diaspora ID’s in URI format. #### Changed[¶](#id39) * Send outbound Diaspora payloads in new format. Remove possibility to generate legacy MagicEnvelope payloads. ([related issue](https://github.com/jaywink/federation/issues/82)) * **Backwards incompatible**. Refactor `handle_send` function Now handle_send high level outbound helper function also allows delivering private payloads using the Diaspora protocol. ([related issue](https://github.com/jaywink/federation/issues/82)) The signature has changed. Parameter `recipients` should now be a list of recipients to delivery to. Each recipient should either be an `id` or a tuple of `(id, public key)`. If public key is provided, Diaspora protocol delivery will be made as an encrypted private delivery. * **Backwards incompatible**. Change `handle_create_payload` function signature. Parameter `to_user` is now `to_user_key` and thus instead of an object containing the `key` attribute it should now be an RSA public key object instance. This simplifies things since we only need the key from the user, nothing else. * Switch Diaspora protocol to send new style entities ([related issue](https://github.com/jaywink/federation/issues/59)) We’ve already accepted these on incoming payloads for a long time and so do all the other platforms now, so now we always send out entities with the new property names. This can break federation with really old servers that don’t understand these keys yet. #### Fixed[¶](#id40) * Change unquote method used when preparing Diaspora XML payloads for verification ([related issue](https://github.com/jaywink/federation/issues/115)) Some platforms deliver payloads not using the urlsafe base64 standard which caused problems when validating the unquoted signature. Ensure maximum compatibility by allowing non-standard urlsafe quoted payloads. * Fix for empty values in Diaspora protocol entities sometimes ending up as `None` instead of empty string when processing incoming payloads. * Fix validation of `Retraction` with entity type `Share` * Allow port in Diaspora handles as per the protocol specification Previously handles were validated like emails. * Fix Diaspora `Profile` mapping regarding `last_name` property Previously only `first_name` was used when creating the `Profile.name` value. Now both `first_name` and `last_name` are used. When creating outgoing payloads, the `Profile.name` will still be placed in `first_name` to avoid trying to artificially split it. ### [0.15.0] - 2018-02-12[¶](#id41) #### Added[¶](#id42) * Added base entity `Share` which maps to a `DiasporaReshare` for the Diaspora protocol. ([related issue](https://github.com/jaywink/federation/issues/94)) The `Share` entity supports all the properties that a Diaspora reshare does. Additionally two other properties are supported: `raw_content` and `entity_type`. The former can be used for a “quoted share” case where the sharer adds their own note to the share. The latter can be used to reference the type of object that was shared, to help the receiver, if it is not sharing a `Post` entity. The value must be a base entity class name. * Entities have two new properties: `id` and `target_id`. Diaspora entity ID’s are in the form of the [Diaspora URI scheme](https://diaspora.github.io/diaspora_federation/federation/diaspora_scheme.html), where it is possible to construct an ID from the entity. In the future, ActivityPub object ID’s will be found in these properties. * New high level fetcher function `federation.fetchers.retrieve_remote_content`. ([related issue](https://github.com/jaywink/federation/issues/103)) This function takes the following parameters: + `id` - Object ID. For Diaspora, the only supported protocol at the moment, this is in the [Diaspora URI](https://diaspora.github.io/diaspora_federation/federation/diaspora_scheme.html) format. + `sender_key_fetcher` - Optional function that takes a profile `handle` and returns a public key in `str` format. If this is not given, the public key will be fetched from the remote profile over the network.The given ID will be fetched from the remote endpoint, validated to be from the correct author against their public key and then an instance of the entity class will be constructed and returned. * New Diaspora protocol helpers in `federation.utils.diaspora`: + `retrieve_and_parse_content`. See notes regarding the high level fetcher above. + `fetch_public_key`. Given a `handle` as a parameter, will fetch the remote profile and return the `public_key` from it. + `parse_diaspora_uri`. Parses a Diaspora URI scheme string, returns either `None` if parsing fails or a `tuple` of `handle`, `entity_type` and `guid`. * Support fetching new style Diaspora protocol Webfinger (RFC 3033) ([related issue](https://github.com/jaywink/federation/issues/108)) The legaxy Webfinger is still used as fallback if the new Webfinger is not found. #### Changed[¶](#id43) * Refactoring for Diaspora `MagicEnvelope` class. The class init now also allows passing in parameters to construct and verify MagicEnvelope instances. The order of init parameters has not been changed, but they are now all optional. When creating a class instance, one should always pass in the necessary parameters depnding on whether the class instance will be used for building a payload or verifying an incoming payload. See class docstring for details. * Diaspora procotol receive flow now uses the `MagicEnvelope` class to verify payloads. No functional changes regarding verification otherwise. * Diaspora protocol receive flow now fetches the sender public key over the network if a `sender_key_fetcher` function is not passed in. Previously an error would be raised. Note that fetching over the network for each payload is wasteful. Implementers should instead cache public keys when possible and pass in a function to retrieve them, as before. #### Fixed[¶](#id44) * Converting base entity `Profile` to `DiasporaProfile` for outbound sending missed two attributes, `image_urls` and `tag_list`. Those are now included so that the values transfer into the built payload. * Fix fallback to HTTP in the `fetch_document` network helper in the case of `ConnectionError` when trying HTTPS. Thanks @autogestion. * Ensure `handle` is always lower cased when fetching remote profile using `retrieve_remote_profile`. Warning will be logged if an upper case handle is passed in. ### [0.14.1] - 2017-08-06[¶](#id45) #### Fixed[¶](#id46) * Fix regression in handling Diaspora relayables due to security fix in 0.14.0. Payload and entity handle need to be allowed to be different when handling relayables. ### [0.14.0] - 2017-08-06[¶](#id47) #### Security[¶](#security) * Add proper checks to make sure Diaspora protocol payload handle and entity handle are the same. Even though we already verified the signature of the sender, we didn’t ensure that the sender isn’t trying to fake an entity authored by someone else. The Diaspora protocol functions `message_to_objects` and `element_to_objects` now require a new parameter, the payload sender handle. These functions should normally not be needed to be used directly. #### Changed[¶](#id48) * **Breaking change.** The high level `federation.outbound` functions `handle_send` and `handle_create_payload` signatures have been changed. This has been done to better represent the objects that are actually sent in and to add an optional `parent_user` object. For both functions the `from_user` parameter has been renamed to `author_user`. Optionally a `parent_user` object can also be passed in. Both the user objects must have `private_key` and `handle` attributes. In the case that `parent_user` is given, that user will be used to sign the payload and for Diaspora relayables an extra `parent_author_signature` in the payload itself. ### [0.13.0] - 2017-07-22[¶](#id49) #### Backwards incompatible changes[¶](#backwards-incompatible-changes) * When processing Diaspora payloads, entity used to get a `_source_object` stored to it. This was an `etree.Element` created from the source object. Due to serialization issues in applications (for example pushing the object to a task queue or saving to database), `_source_object` is now a byte string representation for the element done with `etree.tostring()`. #### Added[¶](#id50) * New style Diaspora private encrypted JSON payloads are now supported in the receiving side. Outbound private Diaspora payloads are still sent as legacy encrypted payloads. ([issue](https://github.com/jaywink/federation/issues/83)) + No additional changes need to be made when calling `handle_receive` from your task processing. Just pass in the full received XML or JSON payload as a string with recipient user object as before. * Add `created_at` to Diaspora `Comment` entity XML creator. This is required in renewed Diaspora protocol. ([related issue](https://github.com/jaywink/federation/issues/59)) #### Fixed[¶](#id51) * Fix getting sender from a combination of legacy Diaspora encrypted payload and new entity names (for example `author`). This combination probably only existed in this library. * Correctly extend entity `_children`. Certain Diaspora payloads caused `_children` for an entity to be written over by an empty list, causing for example status message photos to not be saved. Correctly do an extend on it. ([issue](https://github.com/jaywink/federation/issues/89)) * Fix parsing Diaspora profile `tag_string` into `Profile.tag_list` if the `tag_string` is an empty string. This caused the whole `Profile` object creation to fail. ([issue](https://github.com/jaywink/federation/issues/88)) * Fix processing Diaspora payload if it is passed to `handle_receive` as a `bytes` object. ([issue](https://github.com/jaywink/federation/issues/91)) * Fix broken Diaspora relayables after latest 0.2.0 protocol changes. Previously relayables worked only because they were reverse engineered from the legacy protocol. Now that XML order is not important and tag names can be different depending on which protocol version, the relayable forwarding broke. To fix, we don’t regenerate the entity when forwarding it but store the original received object when generating a `parent_author_signature` (which is optional in some cases, but we generate it anyway for now). This happens in the previously existing `entity.sign_with_parent()` method. In the sending part, if the original received object (now with a parent author signature) exists in the entity, we send that to the remote instead of serializing the entity to XML. + To forward a relayable you must call `entity.sign_with_parent()` before calling `handle_send` to send the entity. #### Removed[¶](#id52) * `Post.photos` entity attribute was never used by any code and has been removed. Child entities of type `Image` are stored in the `Post._children` as before. * Removed deprecated user private key lookup using `user.key` in Diaspora receive processing. Passed in `user` objects must now have a `private_key` attribute. ### [0.12.0] - 2017-05-22[¶](#id53) #### Backwards incompatible changes[¶](#id54) * Removed exception class `NoHeaderInMessageError`. New style Diaspora protocol does not have a custom header in the Salmon magic envelope and thus there is no need to raise this anywhere. #### Added[¶](#id55) * New style Diaspora public payloads are now supported (see [here](https://github.com/diaspora/diaspora_federation/issues/30)). Old style payloads are still supported. Payloads are also still sent out old style. * Add new `Follow` base entity and support for the new Diaspora “contact” payload. The simple `Follow` maps to Diaspora contact entity with following/sharing both true or false. Sharing as a separate concept is not currently supported. * Added `_receiving_guid` to all entities. This is filled with `user.guid` if `user` is passed to `federation.inbound.handle_receive` and it has a `guid`. Normally in for example Diaspora, this will always be done in private payloads. #### Fixed[¶](#id56) * Legacy Diaspora retraction of sharing/following is now supported correctly. The end result is a `DiasporaRetraction` for entity type `Profile`. Since the payload doesn’t contain the receiving user for a sharing/following retraction in legacy Diaspora protocol, we store the guid of the user in the entity as `_receiving_guid`, assuming it was passed in for processing. ### [0.11.0] - 2017-05-08[¶](#id57) #### Backwards incompatible changes[¶](#id58) Diaspora protocol support added for `comment` and `like` relayable types. On inbound payloads the signature included in the payload will be verified against the sender public key. A failed verification will raise `SignatureVerificationError`. For outbound entities, the author private key will be used to add a signature to the payload. This introduces some backwards incompatible changes to the way entities are processed. Diaspora entity mappers `get_outbound_entity` and entity utilities `get_full_xml_representation` now requires the author `private_key` as a parameter. This is required to sign outgoing `Comment` and `Reaction` (like) entities. Additionally, Diaspora entity mappers `message_to_objects` and `element_to_objects` now take an optional `sender_key_fetcher` parameter. This must be a function that when called with the sender handle will return the sender public key. This allows using locally cached public keys instead of fetching them as needed. NOTE! If the function is not given, each processed payload will fetch the public key over the network. A failed payload signature verification now raises a `SignatureVerificationError` instead of a less specific `AssertionError`. #### Added[¶](#id59) * Three new attributes added to entities. + Add protocol name to all entities to attribute `_source_protocol`. This might be useful for applications to know which protocol payload the entity was created from once multiple protocols are implemented. + Add source payload object to the entity at `_source_object` when processing it. + Add sender public key to the entity at `_sender_key`, but only if it was used for validating signatures. * Add support for the new Diaspora payload properties coming in the next protocol version. Old XML payloads are and will be still supported. * `DiasporaComment` and `DiasporaLike` will get the order of elements in the XML payload as a list in `xml_tags`. For implementers who want to recreate payloads for these relayables, this list should be saved for later use. * High level `federation.outbound.handle_send` helper function now allows sending entities to a list of recipients without having to deal with payload creation or caring about the protocol (in preparation of being a multi-protocol library). + The function takes three parameters, `entity` that will be sent, `from_user` that is sending (note, not necessarely authoring, this user will be used to sign the payload for Diaspora for example) and a list of recipients as tuples of recipient handle/domain and optionally protocol. In the future, if protocol is not given, it will be guessed from the recipient handle, and if necessary a network lookup will be made to see what protocols the receiving identity supports. + Payloads will be delivered to each receiver only once. Currently only public messages are supported through this helper, so multiple recipients on a single domain will cause only one delivery. #### Changed[¶](#id60) * Refactor processing of Diaspora payload XML into entities. Diaspora protocol is dropping the `<XML><post></post></XML>` wrapper for the payloads. Payloads with the wrapper will still be parsed as before. ### [0.10.1] - 2017-03-09[¶](#id61) #### Fixes[¶](#fixes) * Ensure tags are lower cased after collecting them from entity `raw_content`. ### [0.10.0] - 2017-01-28[¶](#id62) #### Added[¶](#id63) * Add support for new Diaspora protocol ISO 8601 timestamp format introduced in protocol version 0.1.6. * Tests are now executed also against Python 3.6. #### Fixes[¶](#id64) * Don’t crash `federation.utils.diaspora.retrieve_diaspora_webfinger` if XRD parse raises an `xml.parsers.expat.ExpatError`. ### [0.9.1] - 2016-12-10[¶](#id65) #### Fixes[¶](#id66) * Made `Profile.raw_content` optional. This fixes validating profiles parsed from Diaspora hCard’s. ### [0.9.0] - 2016-12-10[¶](#id67) #### Backwards incompatible changes[¶](#id68) * `Image` no longer has a `text` attribute. It is replaced by `raw_content`, the same attribute as `Post` and `Comment` have. Unlike the latter two, `Image.raw_content` is not mandatory. #### Added[¶](#id69) * Entities can now have a children. These can be accessed using the `_children` list. Acceptable children depends on the entity. Currently, `Post`, `Comment` and `Profile` can have children of entity type `Image`. Child types are validated in the `.validate()` entity method call. #### Fixed[¶](#id70) * Diaspora protocol `message_to_objects` method (called through inbound high level methods) now correctly parses Diaspora `<photo>` elements and creates `Image` entities from them. If they are children of status messages, they will be available through the `Post._children` list. ### [0.8.2] - 2016-10-23[¶](#id71) #### Fixed[¶](#id72) * Remove legacy splitting of payload to 60 chars when creating Diaspora payloads. Diaspora 0.6 doesn’t understand these any more. ### [0.8.1] - 2016-10-18[¶](#id73) #### Fixed[¶](#id74) * `federation.utils.network.send_document` incorrectly passed in `kwargs` to `requests.post`, causing an error when sending custom headers. * Make sure `federation.utils.network.send_document` headers are treated case insensitive before passing then onwards to `requests.post`. ### [0.8.0] - 2016-10-09[¶](#id75) #### Library is now called `federation`[¶](#library-is-now-called-federation) The name Social-Federation was really only an early project name which stuck. Since the beginning, the main module has been `federation`. It makes sense to unify these and also shorter names are generally nicer. ##### What do you need to do?[¶](#what-do-you-need-to-do) Mostly nothing since the module was already called `federation`. Some things to note below: * Update your requirements with the new library name `federation`. * If you hook to the old logger `social-federation`, update those to listen to `federation`, which is now the standard logger name used throughout. #### Other backwards incompatible changes[¶](#other-backwards-incompatible-changes) * `federation.utils.diaspora.retrieve_and_parse_profile` will now return `None` if the `Profile` retrieved doesn’t validate. This will affect also the output of `federation.fetchers.retrieve_remote_profile` which is the high level function to retrieve profiles. * Remove unnecessary `protocol` parameter from `federation.fetchers.retrieve_remote_profile`. We’re miles away from including other protocols and ideally the caller shouldn’t have to pass in the protocol anyway. #### Added[¶](#id76) * Added `Retraction` entity with `DiasporaRetraction` counterpart. ### [0.7.0] - 2016-09-15[¶](#id77) #### Backwards incompatible changes[¶](#id78) * Made `guid` mandatory for `Profile` entity. Library users should always be able to get a full validated object as we consider `guid` a core attribute of a profile. * Always validate entities created through `federation.entities.diaspora.mappers.message_to_objects`. This is the code that transforms federation messages for the Diaspora protocol to actual entity objects. Previously no validation was done and callers of `federation.inbound.handle_receive` received entities that were not always valid, for example they were missing a `guid`. Now validation is done in the conversion stage and errors are pushed to the `federation` logger in the event of invalid messages. + Note Diaspora Profile XML messages do not provide a GUID. This is handled internally by fetching the guid from the remote hCard so that a valid `Profile` entity can be created. #### Added[¶](#id79) * Raise a warning if unknown parameters are passed to entities. * Ensure entity required attributes are validated for `None` or empty string values. Required attributes must not only exist but also have a value. * Add validation to entities with the attribute `public`. Only `bool` values are accepted. #### Changed[¶](#id80) * Function `federation.utils.diaspora.parse_profile_from_hcard` now requires a second argument, `handle`. Since in the future Diaspora hCard is not guaranteed to have username and domain, we now pass handle to the parser directly. ### [0.6.1] - 2016-09-14[¶](#id81) #### Fixed[¶](#id82) * New style Diaspora Magic Envelope didn’t require or like payload data to be cut to 60 char lines, as the legacy protocol does. Fixed to not cut lines. ### [0.6.0] - 2016-09-13[¶](#id83) #### Added[¶](#id84) * New style Diaspora Magic Envelope support. The magic envelope can be created using the class `federation.protocols.diaspora.magic_envelope.MagicEnvelope`. By default this will not wrap the payload message in `<XML><post></post></XML>`. To provide that functionality the class should be initialized with `wrap_payload=True`. No changes are made to the protocol send methods yet, if you need this new magic envelope you can initialize and render it directly. #### Changed[¶](#id85) * Deprecate receiving user `key` attribute for Diaspora protocol. Instead correct attribute is now `private_key` for any user passed to `federation.inbound.handle_receive`. We already use `private_key` in the message creation code so this is just to unify the user related required attributes. + DEPRECATION: There is a fallback with `key` for user objects in the receiving payload part of the Diaspora protocol until 0.8.0. #### Fixes[¶](#id86) * Loosen up hCard selectors when parsing profile from hCard document in `federation.utils.diaspora.parse_profile_from_hcard`. The selectors now match Diaspora upcoming federation documentation. ### [0.5.0] - 2016-09-05[¶](#id87) #### Breaking changes[¶](#breaking-changes) * `federation.outbound.handle_create_payload` parameter `to_user` is now optional. Public posts don’t need a recipient. This also affects Diaspora protocol `build_send` method where the change is reflected similarly. [#43](https://github.com/jaywink/federation/pull/43) + In practise this means the signature has changed for `handle_create_payload` and `build_send` from **`from_user, to_user, entity`** to **`entity, from_user, to_user=None`**. #### Added[¶](#id88) * `Post.provider_display_name` is now supported in the entity outbound/inbound mappers. [#44](https://github.com/jaywink/federation/pull/44) * Add utility method `federation.utils.network.send_document` which is just a wrapper around `requests.post`. User agent will be added to the headers and exceptions will be silently captured and returned instead. [#45](https://github.com/jaywink/federation/pull/45) * Add Diaspora entity utility `federation.entities.diaspora.utils.get_full_xml_representation`. Renders the entity XML document and wraps it in `<XML><post>...</post></XML>`. [#46](https://github.com/jaywink/federation/pull/46) ### [0.4.1] - 2016-09-04[¶](#id89) #### Fixes[¶](#id90) * Don’t quote/encode `Protocol.build_send` payload. It was doing it wrongly in the first place and also it’s not necessary since Diaspora 0.6 protocol changes. [#41](https://github.com/jaywink/federation/pull/41) * Fix identification of Diaspora protocol messages. This was not working in the case that the attributes in the tag were in different order. [#41](https://github.com/jaywink/federation/pull/41) ### [0.4.0] - 2016-07-24[¶](#id91) #### Breaking changes[¶](#id92) * While in early stages, doing some renaming of modules to suit the longer term. `federation.controllers` has been split into two, `federation.outbound` and `federation.inbound`. The following methods have new import locations: + `federation.controllers.handle_receive` -> `federation.inbound.handle_receive` + `federation.controllers.handle_create_payload` -> `federation.outbound.handle_create_payload` * Class `federation.hostmeta.generators.DiasporaHCard` now requires `guid`, `public_key` and `username` for initialization. Leaving these out was a mistake in the initial implementation. Diaspora has these in at least 0.6 development branch. #### Added[¶](#id93) * `Relationship` base entity which represents relationships between two handles. Types can be following, sharing, ignoring and blocking. The Diaspora counterpart, `DiasporaRequest`, which represents a sharing/following request is outwards a single entity, but incoming a double entity, handled by creating both a sharing and following version of the relationship. * `Profile` base entity and Diaspora counterpart `DiasporaProfile`. Represents a user profile. * `federation.utils.network.fetch_document` utility function to fetch a remote document. Returns document, status code and possible exception. Takes either `url` or a `host` + `path` combination. With `host`, https is first tried and optionally fall back to http. * Utility methods to retrieve Diaspora user discovery related documents. These include the host-meta, webfinger and hCard documents. The utility methods are in `federation.utils.diaspora`. * Utility to fetch remote profile, `federation.fetchers.retrieve_remote_profile`. Currently always uses Diaspora protocol. Returns a `Profile` entity. #### Changed[¶](#id94) * Unlock most of the direct dependencies to a certain version range. Unlock all of test requirements to any version. * Entities passed to `federation.controllers.handle_create_payload` are now converted from the base entity types (Post, Comment, Reaction, etc) to Diaspora entity types (DiasporaPost, DiasporaComment, DiasporaLike, etc). This ensures actual payload generation has the correct methods available (for example `to_xml`) whatever entity is passed in. #### Fixes[¶](#id95) * Fix fetching sender handle from Diaspora protocol private messages. As it is not contained in the header, it needs to be read from the message content itself. * Fix various issues with `DiasporaHCard` template after comparing to some real world hCard templates from real pods. Old version was based on documentation in Diaspora project wiki. ### [0.3.2] - 2016-05-09[¶](#id96) #### Changed[¶](#id97) * Test factories and other test files are now included in the package installation. Factories can be useful when creating project tests. * Bump allowed `lxml` to 3.6.0 * Bump allowed `python-dateutil` to 2.5.3 #### Fixes[¶](#id98) * Don’t raise on Post.tags if Post.raw_content is None ### [0.3.1] - 2016-04-13[¶](#id99) #### Added[¶](#id100) * Support for generating `.well-known/nodeinfo` document, which was forgotten from the 0.3.0 release. Method `federation.hostmeta.generators.get_nodeinfo_well_known_document` does this task. It requires an `url` which should be the full base url of the host. Optionally `document_path` can be specified, but it is optional and defaults to the one in the NodeInfo spec. ### [0.3.0] - 2016-04-13[¶](#id101) #### Added[¶](#id102) * Support for generating [NodeInfo](http://nodeinfo.diaspora.software) documents using the generator `federation.hostmeta.generators.NodeInfo`. Strict validation is skipped by default, but can be enabled by passing in `raise_on_validate` to the `NodeInfo` class. By default a warning will be generated on documents that don’t conform with the strict NodeInfo values. This can be disabled by passing in `skip_validate` to the class. ### [0.2.0] - 2016-04-09[¶](#id103) #### Backwards incompatible changes[¶](#id104) * Any implementations using the Diaspora protocol and `Post` entities must now use `DiasporaPost` instead. See “Changed” below. #### Added[¶](#id105) * Support for using `validate_field()` methods for entity fields and checking missing fields against `_required`. To use this validation, `validate()` must specifically be called for the entity instance. * Base entities `Comment` and `Reaction` which subclass the new `ParticipationMixin`. * Diaspora entity `DiasporaComment`, a variant of `Comment`. * Diaspora entity `DiasporaLike`, a variant of `Reaction` with the `reaction = "like"` default. #### Changed[¶](#id106) * Refactored Diaspora XML generators into the Diaspora entities themselves. This introduces Diaspora versions of the base entities called `DiasporaPost`, `DiasporaComment` and `DiasporaLike`. **Any implementations using the Diaspora protocol and `Post` entities must now use `DiasporaPost` instead.** #### Fixes[¶](#id107) * Entities which don’t specifically get passed a `created_at` now get correct current time in `created_at` instead of always having the time part as `00:00`. ### [0.1.1] - 2016-04-03[¶](#id108) #### Initial package release[¶](#initial-package-release) Supports well Post type object receiving over Diaspora protocol. Untested support for crafting outgoing protocol messages. Indices and tables[¶](#indices-and-tables) === * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html) [Federation](index.html#document-index) === ### Navigation * [Introduction](index.html#document-introduction) * [Install](index.html#document-install) * [Protocols](index.html#document-protocols) * [Usage](index.html#document-usage) * [Development](index.html#document-development) * [Projects using federation](index.html#document-example_projects) * [Changelog](index.html#document-changelog) ### Related Topics * [Documentation overview](index.html#document-index) ### Quick search
pallet-utility
rust
Rust
Crate pallet_utility === Utility Pallet --- A stateless pallet with helpers for dispatch management which does no re-authentication. * `Config` * `Call` ### Overview This pallet contains two basic pieces of functionality: * Batch dispatch: A stateless operation, allowing any origin to execute multiple calls in a single dispatch. This can be useful to amalgamate proposals, combining `set_code` with corresponding `set_storage`s, for efficient multiple payouts with just a single signature verify, or in combination with one of the other two dispatch functionality. * Pseudonymal dispatch: A stateless operation, allowing a signed origin to execute a call from an alternative signed origin. Each account has 2 * 2**16 possible “pseudonyms” (alternative account IDs) and these can be stacked. This can be useful as a key management tool, where you need multiple distinct accounts (e.g. as controllers for many staking accounts), but where it’s perfectly fine to have each of them controlled by the same underlying keypair. Derivative accounts are, for the purposes of proxy filtering considered exactly the same as the origin and are thus hampered with the origin’s filters. Since proxy filters are respected in all dispatches of this pallet, it should never need to be filtered by any proxy. ### Interface #### Dispatchable Functions ##### For batch dispatch * `batch` - Dispatch multiple calls from the sender’s origin. ##### For pseudonymal dispatch * `as_derivative` - Dispatch a call from a derivative signed origin. Re-exports --- * `pub use weights::WeightInfo;` * `pub use pallet::*;` Modules --- * palletThe `pallet` module in each FRAME pallet hosts the most important items needed to construct this pallet. * weightsAutogenerated weights for pallet_utility Crate pallet_utility === Utility Pallet --- A stateless pallet with helpers for dispatch management which does no re-authentication. * `Config` * `Call` ### Overview This pallet contains two basic pieces of functionality: * Batch dispatch: A stateless operation, allowing any origin to execute multiple calls in a single dispatch. This can be useful to amalgamate proposals, combining `set_code` with corresponding `set_storage`s, for efficient multiple payouts with just a single signature verify, or in combination with one of the other two dispatch functionality. * Pseudonymal dispatch: A stateless operation, allowing a signed origin to execute a call from an alternative signed origin. Each account has 2 * 2**16 possible “pseudonyms” (alternative account IDs) and these can be stacked. This can be useful as a key management tool, where you need multiple distinct accounts (e.g. as controllers for many staking accounts), but where it’s perfectly fine to have each of them controlled by the same underlying keypair. Derivative accounts are, for the purposes of proxy filtering considered exactly the same as the origin and are thus hampered with the origin’s filters. Since proxy filters are respected in all dispatches of this pallet, it should never need to be filtered by any proxy. ### Interface #### Dispatchable Functions ##### For batch dispatch * `batch` - Dispatch multiple calls from the sender’s origin. ##### For pseudonymal dispatch * `as_derivative` - Dispatch a call from a derivative signed origin. Re-exports --- * `pub use weights::WeightInfo;` * `pub use pallet::*;` Modules --- * palletThe `pallet` module in each FRAME pallet hosts the most important items needed to construct this pallet. * weightsAutogenerated weights for pallet_utility Trait pallet_utility::pallet::Config === ``` pub trait Config: Config { type RuntimeEvent: From<Event> + IsType<<Self as Config>::RuntimeEvent>; type RuntimeCall: Parameter + Dispatchable<RuntimeOrigin = Self::RuntimeOrigin, PostInfo = PostDispatchInfo> + GetDispatchInfo + From<Call<Self>> + UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin> + IsSubType<Call<Self>> + IsType<<Self as Config>::RuntimeCall>; type PalletsOrigin: Parameter + Into<<Self as Config>::RuntimeOrigin> + IsType<<<Self as Config>::RuntimeOrigin as OriginTrait>::PalletsOrigin>; type WeightInfo: WeightInfo; } ``` Configuration trait of this pallet. The main purpose of this trait is to act as an interface between this pallet and the runtime in which it is embedded in. A type, function, or constant in this trait is essentially left to be configured by the runtime that includes this pallet. Consequently, a runtime that wants to include this pallet must implement this trait. Configuration trait. Required Associated Types --- #### type RuntimeEvent: From<Event> + IsType<<Self as Config>::RuntimeEventThe overarching event type. #### type RuntimeCall: Parameter + Dispatchable<RuntimeOrigin = Self::RuntimeOrigin, PostInfo = PostDispatchInfo> + GetDispatchInfo + From<Call<Self>> + UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin> + IsSubType<Call<Self>> + IsType<<Self as Config>::RuntimeCallThe overarching call type. #### type PalletsOrigin: Parameter + Into<<Self as Config>::RuntimeOrigin> + IsType<<<Self as Config>::RuntimeOrigin as OriginTrait>::PalletsOriginThe caller origin, overarching type of all pallets origins. #### type WeightInfo: WeightInfo Weight information for extrinsics in this pallet. Implementors --- Enum pallet_utility::pallet::Call === ``` pub enum Call<T: Config> { batch { calls: Vec<<T as Config>::RuntimeCall>, }, as_derivative { index: u16, call: Box<<T as Config>::RuntimeCall>, }, batch_all { calls: Vec<<T as Config>::RuntimeCall>, }, dispatch_as { as_origin: Box<T::PalletsOrigin>, call: Box<<T as Config>::RuntimeCall>, }, force_batch { calls: Vec<<T as Config>::RuntimeCall>, }, with_weight { call: Box<<T as Config>::RuntimeCall>, weight: Weight, }, // some variants omitted } ``` Contains a variant per dispatchable extrinsic that this pallet has. Variants --- ### batch #### Fields `calls: Vec<<T as Config>::RuntimeCall>`See `Pallet::batch`. ### as_derivative #### Fields `index: u16``call: Box<<T as Config>::RuntimeCall>`See `Pallet::as_derivative`. ### batch_all #### Fields `calls: Vec<<T as Config>::RuntimeCall>`See `Pallet::batch_all`. ### dispatch_as #### Fields `as_origin: Box<T::PalletsOrigin>``call: Box<<T as Config>::RuntimeCall>`See `Pallet::dispatch_as`. ### force_batch #### Fields `calls: Vec<<T as Config>::RuntimeCall>`See `Pallet::force_batch`. ### with_weight #### Fields `call: Box<<T as Config>::RuntimeCall>``weight: Weight`See `Pallet::with_weight`. Implementations --- ### impl<T: Config> Call<T#### pub fn new_call_variant_batch(calls: Vec<<T as Config>::RuntimeCall>) -> Self Create a call with the variant `batch`. #### pub fn new_call_variant_as_derivative( index: u16, call: Box<<T as Config>::RuntimeCall> ) -> Self Create a call with the variant `as_derivative`. #### pub fn new_call_variant_batch_all( calls: Vec<<T as Config>::RuntimeCall> ) -> Self Create a call with the variant `batch_all`. #### pub fn new_call_variant_dispatch_as( as_origin: Box<T::PalletsOrigin>, call: Box<<T as Config>::RuntimeCall> ) -> Self Create a call with the variant `dispatch_as`. #### pub fn new_call_variant_force_batch( calls: Vec<<T as Config>::RuntimeCall> ) -> Self Create a call with the variant `force_batch`. #### pub fn new_call_variant_with_weight( call: Box<<T as Config>::RuntimeCall>, weight: Weight ) -> Self Create a call with the variant `with_weight`. Trait Implementations --- ### impl<T: Config> Clone for Call<T#### fn clone(&self) -> Self Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. __codec_input_edqy: &mut __CodecInputEdqy ) -> Result<Self, ErrorAttempt to deserialise the value from input.#### fn decode_into<I>( input: &mut I, dst: &mut MaybeUninit<Self> ) -> Result<DecodeFinished, Error>where I: Input, Attempt to deserialize the value from input into a pre-allocated piece of memory. I: Input, Attempt to skip the encoded value from input. If possible give a hint of expected size of the encoding. &self, __codec_dest_edqy: &mut __CodecOutputEdqy ) Convert self to a slice and append it to the destination.#### fn encode(&self) -> Vec<u8, GlobalConvert self to an owned vector.#### fn using_encoded<R, F>(&self, f: F) -> Rwhere F: FnOnce(&[u8]) -> R, Convert self to a slice and then invoke the given closure with it.#### fn encoded_size(&self) -> usize Calculates the encoded size. Return the index of this Call.#### fn get_call_indices() -> &'static [u8] Return all call indices in the same order as `GetCallName`.### impl<T: Config> GetCallName for Call<T#### fn get_call_name(&self) -> &'static str Return the function name of the Call.#### fn get_call_names() -> &'static [&'static str] Return all function names in the same order as `GetCallIndex`.### impl<T: Config> GetDispatchInfo for Call<T#### fn get_dispatch_info(&self) -> DispatchInfo Return a `DispatchInfo`, containing relevant information of this dispatch. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<T> TypeInfo for Call<T>where PhantomData<(T,)>: TypeInfo + 'static, Vec<<T as Config>::RuntimeCall>: TypeInfo + 'static, Box<<T as Config>::RuntimeCall>: TypeInfo + 'static, Box<T::PalletsOrigin>: TypeInfo + 'static, T: Config + 'static, #### type Identity = Call<TThe type identifying for which type info is provided. Returns the static type identifier for `Self`.### impl<T: Config> UnfilteredDispatchable for Call<T#### type RuntimeOrigin = <T as Config>::RuntimeOrigin The origin type of the runtime, (i.e. `frame_system::Config::RuntimeOrigin`).#### fn dispatch_bypass_filter( self, origin: Self::RuntimeOrigin ) -> DispatchResultWithPostInfo Dispatch this call but do not check the filter in origin.### impl<T: Config> EncodeLike<Call<T>> for Call<T### impl<T: Config> Eq for Call<TAuto Trait Implementations --- ### impl<T> RefUnwindSafe for Call<T>where T: RefUnwindSafe, <T as Config>::PalletsOrigin: RefUnwindSafe, <T as Config>::RuntimeCall: RefUnwindSafe, ### impl<T> Send for Call<T>where T: Send, <T as Config>::PalletsOrigin: Send, <T as Config>::RuntimeCall: Send, ### impl<T> Sync for Call<T>where T: Sync, <T as Config>::PalletsOrigin: Sync, <T as Config>::RuntimeCall: Sync, ### impl<T> Unpin for Call<T>where T: Unpin, <T as Config>::RuntimeCall: Unpin, ### impl<T> UnwindSafe for Call<T>where T: UnwindSafe, <T as Config>::PalletsOrigin: UnwindSafe, <T as Config>::RuntimeCall: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn checked_from<T>(t: T) -> Option<Self>where Self: TryFrom<T>, Convert from a value of `T` into an equivalent instance of `Option<Self>`. Self: TryInto<T>, Consume self to return `Some` equivalent value of `Option<T>`. T: Decode, #### fn decode_all(input: &mut &[u8]) -> Result<T, ErrorDecode `Self` and consume all of the given input data. T: Decode, #### fn decode_all_with_depth_limit( limit: u32, input: &mut &[u8] ) -> Result<T, ErrorDecode `Self` and consume all of the given input data. I: Input, Decode `Self` with the given maximum recursion depth and advance `input` by the number of bytes consumed. T: Clone, #### fn __clone_box(&self, _: Private) -> *mut() ### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Checks if this value is equivalent to the given key. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Hashable for Twhere T: Codec, #### fn blake2_128(&self) -> [u8; 16] #### fn blake2_256(&self) -> [u8; 32] #### fn blake2_128_concat(&self) -> Vec<u8, Global#### fn twox_128(&self) -> [u8; 16] #### fn twox_256(&self) -> [u8; 32] #### fn twox_64_concat(&self) -> Vec<u8, Global#### fn identity(&self) -> Vec<u8, Global### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> IsType<T> for T #### fn from_ref(t: &T) -> &T Cast reference.#### fn into_ref(&self) -> &T Cast reference.#### fn from_mut(t: &mut T) -> &mut T Cast mutable reference.#### fn into_mut(&mut self) -> &mut T Cast mutable reference.### impl<T, Outer> IsWrappedBy<Outer> for Twhere Outer: AsRef<T> + AsMut<T> + From<T>, T: From<Outer>, #### fn from_ref(outer: &Outer) -> &T Get a reference to the inner from the outer. #### fn from_mut(outer: &mut Outer) -> &mut T Get a mutable reference to the inner from the outer. ### impl<T> KeyedVec for Twhere T: Codec, #### fn to_keyed_vec(&self, prepend_key: &[u8]) -> Vec<u8, GlobalReturn an encoding of `Self` prepended by given slice.### impl<T> Same<T> for T #### type Output = T Should always be `Self`### impl<T> SaturatedConversion for T #### fn saturated_from<T>(t: T) -> Selfwhere Self: UniqueSaturatedFrom<T>, Convert from a value of `T` into an equivalent instance of `Self`. Self: UniqueSaturatedInto<T>, Consume self to return an equivalent value of `T`. T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<S, T> UncheckedInto<T> for Swhere T: UncheckedFrom<S>, #### fn unchecked_into(self) -> T The counterpart to `unchecked_from`.### impl<T, S> UniqueSaturatedInto<T> for Swhere T: Bounded, S: TryInto<T>, #### fn unique_saturated_into(self) -> T Consume self to return an equivalent value of `T`.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. S: Decode + Encode, ### impl<T> EncodeLike<&&T> for Twhere T: Encode, ### impl<T> EncodeLike<&T> for Twhere T: Encode, ### impl<T> EncodeLike<&mut T> for Twhere T: Encode, ### impl<T> EncodeLike<Arc<T, Global>> for Twhere T: Encode, ### impl<T> EncodeLike<Box<T, Global>> for Twhere T: Encode, ### impl<'a, T> EncodeLike<Cow<'a, T>> for Twhere T: ToOwned + Encode, ### impl<T> EncodeLike<Rc<T, Global>> for Twhere T: Encode, ### impl<S> FullCodec for Swhere S: Decode + FullEncode, ### impl<S> FullEncode for Swhere S: Encode + EncodeLike<S>, ### impl<T> JsonSchemaMaybe for T ### impl<T> MaybeDebug for Twhere T: Debug, ### impl<T> MaybeRefUnwindSafe for Twhere T: RefUnwindSafe, ### impl<T> Member for Twhere T: Send + Sync + Debug + Eq + PartialEq<T> + Clone + 'static, ### impl<T> Parameter for Twhere T: Codec + EncodeLike<T> + Clone + Eq + Debug + TypeInfo, ### impl<T> StaticTypeInfo for Twhere T: TypeInfo + 'static, {"&'static [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","Vec<u8, Global>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html\" title=\"struct alloc::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/alloc/trait.Allocator.html\" title=\"trait core::alloc::Allocator\">Allocator</a>,</span></span>"} Trait pallet_utility::weights::WeightInfo === ``` pub trait WeightInfo { // Required methods fn batch(c: u32) -> Weight; fn as_derivative() -> Weight; fn batch_all(c: u32) -> Weight; fn dispatch_as() -> Weight; fn force_batch(c: u32) -> Weight; } ``` Weight functions needed for pallet_utility. Required Methods --- #### fn batch(c: u32) -> Weight #### fn as_derivative() -> Weight #### fn batch_all(c: u32) -> Weight #### fn dispatch_as() -> Weight #### fn force_batch(c: u32) -> Weight Implementations on Foreign Types --- ### impl WeightInfo for () #### fn batch(c: u32) -> Weight The range of component `c` is `[0, 1000]`. #### fn batch_all(c: u32) -> Weight The range of component `c` is `[0, 1000]`. #### fn force_batch(c: u32) -> Weight The range of component `c` is `[0, 1000]`. #### fn as_derivative() -> Weight #### fn dispatch_as() -> Weight Implementors --- ### impl<T: Config> WeightInfo for SubstrateWeight<TModule pallet_utility::pallet === The `pallet` module in each FRAME pallet hosts the most important items needed to construct this pallet. The main components of this pallet are: * `Pallet`, which implements all of the dispatchable extrinsics of the pallet, among other public functions. + The subset of the functions that are dispatchable can be identified either in the `dispatchables` module or in the `Call` enum. * `storage_types`, which contains the list of all types that are representing a storage item. Otherwise, all storage items are listed among *Type Definitions*. * `Config`, which contains the configuration trait of this pallet. * `Event` and `Error`, which are listed among the *Enums*. Re-exports --- * `pub use __tt_error_token_1 as tt_error_token;` * `pub use __tt_default_parts_7 as tt_default_parts;` * `pub use __tt_extra_parts_7 as tt_extra_parts;` Modules --- * dispatchablesAuto-generated docs-only module listing all defined dispatchables for this pallet. * storage_typesAuto-generated docs-only module listing all (public and private) defined storage types for this pallet. Structs --- * PalletThe `Pallet` struct, the main type that implements traits and standalone functions within the pallet. Enums --- * CallContains a variant per dispatchable extrinsic that this pallet has. * ErrorThe `Error` enum of this pallet. * EventThe `Event` enum of this pallet Traits --- * ConfigConfiguration trait of this pallet. Type Aliases --- * ModuleDeprecatedType alias to `Pallet`, to be used by `construct_runtime`. Module pallet_utility::weights === Autogenerated weights for pallet_utility THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev DATE: 2023-06-16, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` WORST CASE MAP SIZE: `1000000` HOSTNAME: `runner-e8ezs4ez-project-145-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some(“dev”), DB CACHE: 1024 Structs --- * SubstrateWeightWeights for pallet_utility using the Substrate node and recommended hardware. Traits --- * WeightInfoWeight functions needed for pallet_utility.
MDFS
cran
R
Package ‘MDFS’ May 10, 2023 Title MultiDimensional Feature Selection Version 1.5.3 Date 2023-05-09 URL https://www.mdfs.it/ Description Functions for MultiDimensional Feature Selection (MDFS): calculating multidimensional information gains, scoring variables, finding important variables, plotting selection results. This package includes an optional CUDA implementation that speeds up information gain calculation using NVIDIA GPGPUs. R. Piliszek et al. (2019) <doi:10.32614/RJ-2019-019>. Depends R (>= 3.4.0) License GPL-3 SystemRequirements C++17 NeedsCompilation yes Encoding UTF-8 LazyData true RoxygenNote 7.2.3 Author <NAME> [aut, cre], <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-05-09 23:40:06 UTC R topics documented: AddContrastVariable... 2 as.data.frame.MDF... 3 ComputeInterestingTuple... 3 ComputeInterestingTuplesDiscret... 5 ComputeMaxInfoGain... 7 ComputeMaxInfoGainsDiscret... 8 ComputePValu... 9 Discretiz... 11 GenContrastVariable... 12 GetRang... 12 madelo... 13 MDF... 14 mdfs_omp_set_num_thread... 15 plot.MDF... 16 RelevantVariable... 16 RelevantVariables.MDF... 17 AddContrastVariables Add contrast variables to data Description This function is deprecated. Please use GenContrastVariables instead. Usage AddContrastVariables(data, n.contrast = max(ncol(data)/10, 30)) Arguments data data organized in matrix with separate variables in columns n.contrast number of constrast variables (defaults to max of 1/10 of variables number and 30) Value A list with the following key names: • indices – vector of indices of input variables used to construct contrast variables • x – data with constrast variables appended to it • mask – vector of booleans making it easy to select just contrast variables as.data.frame.MDFS as.data.frame S3 method implementation for MDFS Description as.data.frame S3 method implementation for MDFS Usage ## S3 method for class 'MDFS' as.data.frame(x, ...) Arguments x an MDFS object ... ignored Value data.frame ComputeInterestingTuples Interesting tuples Description Interesting tuples Usage ComputeInterestingTuples( data, decision = NULL, dimensions = 2, divisions = 1, discretizations = 1, seed = NULL, range = NULL, pc.xi = 0.25, ig.thr = 0, I.lower = NULL, interesting.vars = vector(mode = "integer"), require.all.vars = FALSE, return.matrix = FALSE, stat_mode = "MI", average = FALSE ) Arguments data input data where columns are variables and rows are observations (all numeric) decision decision variable as a binary sequence of length equal to number of observations dimensions number of dimensions (a positive integer; 5 max) divisions number of divisions (from 1 to 15) discretizations number of discretizations seed seed for PRNG used during discretizations (NULL for random) range discretization range (from 0.0 to 1.0; NULL selects probable optimal number) pc.xi parameter xi used to compute pseudocounts (the default is recommended not to be changed) ig.thr IG threshold above which the tuple is interesting (0 and negative mean no filter- ing) I.lower IG values computed for lower dimension (1D for 2D, etc.) interesting.vars variables for which to check the IGs (none = all) require.all.vars boolean whether to require tuple to consist of only interesting.vars return.matrix boolean whether to return a matrix instead of a list (ignored if not using the optimised method variant) stat_mode character, one of: "MI" (mutual information, the default; becomes information gain when decision is given), "H" (entropy; becomes conditional entropy when decision is given), "VI" (variation of information; becomes target information difference when decision is given); decides on the value computed average boolean whether to average over discretisations instead of maximising (the de- fault) Details If running in 2D and no filtering is applied, this function is able to run in an optimised fashion. It is recommended to avoid filtering in 2D if only it is feasible. This function calculates what stat_mode dictates. When decision is omitted, the stat_mode is calculated on the descriptive variables. When decision is given, the stat_mode is calculated on the decision variable, conditional on the other variables. Translate "IG" to that value in the rest of this function’s description. Value A data.frame or NULL (following a warning) if no tuples are found. The following columns are present in the data.frame: • Var – interesting variable index • Tuple.1, Tuple.2, ... – corresponding tuple (up to dimensions columns) • IG – information gain achieved by var in Tuple.* Additionally attribute named run.params with run parameters is set on the result. Examples ig.1d <- ComputeMaxInfoGains(madelon$data, madelon$decision, dimensions = 1, divisions = 1, range = 0, seed = 0) ComputeInterestingTuples(madelon$data, madelon$decision, dimensions = 2, divisions = 1, range = 0, seed = 0, ig.thr = 100, I.lower = ig.1d$IG) ComputeInterestingTuplesDiscrete Interesting tuples (discrete) Description Interesting tuples (discrete) Usage ComputeInterestingTuplesDiscrete( data, decision = NULL, dimensions = 2, pc.xi = 0.25, ig.thr = 0, I.lower = NULL, interesting.vars = vector(mode = "integer"), require.all.vars = FALSE, return.matrix = FALSE, stat_mode = "MI" ) Arguments data input data where columns are variables and rows are observations (all discrete with the same number of categories) decision decision variable as a binary sequence of length equal to number of observations dimensions number of dimensions (a positive integer; 5 max) pc.xi parameter xi used to compute pseudocounts (the default is recommended not to be changed) ig.thr IG threshold above which the tuple is interesting (0 and negative mean no filter- ing) I.lower IG values computed for lower dimension (1D for 2D, etc.) interesting.vars variables for which to check the IGs (none = all) require.all.vars boolean whether to require tuple to consist of only interesting.vars return.matrix boolean whether to return a matrix instead of a list (ignored if not using the optimised method variant) stat_mode character, one of: "MI" (mutual information, the default; becomes information gain when decision is given), "H" (entropy; becomes conditional entropy when decision is given), "VI" (variation of information; becomes target information difference when decision is given); decides on the value computed Details If running in 2D and no filtering is applied, this function is able to run in an optimised fashion. It is recommended to avoid filtering in 2D if only it is feasible. This function calculates what stat_mode dictates. When decision is omitted, the stat_mode is calculated on the descriptive variables. When decision is given, the stat_mode is calculated on the decision variable, conditional on the other variables. Translate "IG" to that value in the rest of this function’s description. Value A data.frame or NULL (following a warning) if no tuples are found. The following columns are present in the data.frame: • Var – interesting variable index • Tuple.1, Tuple.2, ... – corresponding tuple (up to dimensions columns) • IG – information gain achieved by var in Tuple.* Additionally attribute named run.params with run parameters is set on the result. Examples ig.1d <- ComputeMaxInfoGainsDiscrete(madelon$data > 500, madelon$decision, dimensions = 1) ComputeInterestingTuplesDiscrete(madelon$data > 500, madelon$decision, dimensions = 2, ig.thr = 100, I.lower = ig.1d$IG) ComputeMaxInfoGains Max information gains Description Max information gains Usage ComputeMaxInfoGains( data, decision, contrast_data = NULL, dimensions = 1, divisions = 1, discretizations = 1, seed = NULL, range = NULL, pc.xi = 0.25, return.tuples = FALSE, interesting.vars = vector(mode = "integer"), require.all.vars = FALSE, use.CUDA = FALSE ) Arguments data input data where columns are variables and rows are observations (all numeric) decision decision variable as a binary sequence of length equal to number of observations contrast_data the contrast counterpart of data, has to have the same number of observations - not supported with CUDA dimensions number of dimensions (a positive integer; 5 max) divisions number of divisions (from 1 to 15; additionally limited by dimensions if using CUDA) discretizations number of discretizations seed seed for PRNG used during discretizations (NULL for random) range discretization range (from 0.0 to 1.0; NULL selects probable optimal number) pc.xi parameter xi used to compute pseudocounts (the default is recommended not to be changed) return.tuples whether to return tuples (and relevant discretization number) where max IG was observed (one tuple and relevant discretization number per variable) - not sup- ported with CUDA nor in 1D interesting.vars variables for which to check the IGs (none = all) - not supported with CUDA require.all.vars boolean whether to require tuple to consist of only interesting.vars use.CUDA whether to use CUDA acceleration (must be compiled with CUDA) Value A data.frame with the following columns: • IG – max information gain (of each variable) • Tuple.1, Tuple.2, ... – corresponding tuple (up to dimensions columns, available only when return.tuples == T) • Discretization.nr – corresponding discretization number (available only when return.tuples == T) Additionally attribute named run.params with run parameters is set on the result. Examples ComputeMaxInfoGains(madelon$data, madelon$decision, dimensions = 2, divisions = 1, range = 0, seed = 0) ComputeMaxInfoGainsDiscrete Max information gains (discrete) Description Max information gains (discrete) Usage ComputeMaxInfoGainsDiscrete( data, decision, contrast_data = NULL, dimensions = 1, pc.xi = 0.25, return.tuples = FALSE, interesting.vars = vector(mode = "integer"), require.all.vars = FALSE ) Arguments data input data where columns are variables and rows are observations (all discrete with the same number of categories) decision decision variable as a binary sequence of length equal to number of observations contrast_data the contrast counterpart of data, has to have the same number of observations dimensions number of dimensions (a positive integer; 5 max) pc.xi parameter xi used to compute pseudocounts (the default is recommended not to be changed) return.tuples whether to return tuples where max IG was observed (one tuple per variable) - not supported with CUDA nor in 1D interesting.vars variables for which to check the IGs (none = all) - not supported with CUDA require.all.vars boolean whether to require tuple to consist of only interesting.vars Value A data.frame with the following columns: • IG – max information gain (of each variable) • Tuple.1, Tuple.2, ... – corresponding tuple (up to dimensions columns, available only when return.tuples == T) • Discretization.nr – always 1 (for compatibility with the non-discrete function; available only when return.tuples == T) Additionally attribute named run.params with run parameters is set on the result. Examples ComputeMaxInfoGainsDiscrete(madelon$data > 500, madelon$decision, dimensions = 2) ComputePValue Compute p-values from information gains and return MDFS Description Compute p-values from information gains and return MDFS Usage ComputePValue( IG, dimensions, divisions, response.divisions = 1, df = NULL, contrast.mask = NULL, ig.in.bits = TRUE, ig.doubled = FALSE, one.dim.mode = "exp", irr.vars.num = NULL, ign.low.ig.vars.num = NULL, min.irr.vars.num = NULL, max.ign.low.ig.vars.num = NULL, search.points = 8, level = 0.05 ) Arguments IG max conditional information gains dimensions number of dimensions divisions number of divisions response.divisions number of response divisions (i.e. categories-1) df vector of degrees of freedom for each variable (optional) contrast.mask boolean mask on IG specifying which variables are contrast variables (or NULL if none, otherwise at least 3 variables must be marked) ig.in.bits TRUE if input is in binary log (as opposed to natural log) ig.doubled TRUE if input is doubled (to follow the chi-squared distribution) one.dim.mode 'exp' for exponential distribution, 'lin' for linear function of chi-squared or 'raw' for raw chi-squared irr.vars.num if not NULL, number of irrelevant variables, specified by the user ign.low.ig.vars.num if not NULL, number of ignored low IG variables, specified by the user min.irr.vars.num minimum number of irrelevant variables (NULL selects probable optimal num- ber) max.ign.low.ig.vars.num maximum number of ignored low IG variables (NULL selects probable optimal number) search.points number of points in search procedure for the optimal number of ignored vari- ables level acceptable error level of goodness-of-fit one-sample Kolmogorov-Smirnov test (used only for warning) Value A data.frame with class set to MDFS. Can be coerced back to data.frame using as.data.frame. The following columns are present: • IG – information gains (input copy) • chi.squared.p.value – chi-squared p-values • p.value – theoretical p-values Additionally the following attributes are set: • run.params – run parameters • sq.dev – vector of square deviations used to estimate the number of irrelevant variables • dist.param – distribution parameter • err.param – squared error of the distribution parameter • fit.p.value – p-value of fit Examples ComputePValue(madelon$IG.2D, dimensions = 2, divisions = 1) Discretize Discretize variable on demand Description Discretize variable on demand Usage Discretize(data, variable.idx, divisions, discretization.nr, seed, range) Arguments data input data where columns are variables and rows are observations (all numeric) variable.idx variable index (as it appears in data) divisions number of divisions discretization.nr discretization number (positive integer) seed seed for PRNG range discretization range Value Discretized variable. Examples Discretize(madelon$data, 3, 1, 1, 0, 0.5) GenContrastVariables Generate contrast variables from data Description Generate contrast variables from data Usage GenContrastVariables(data, n.contrast = max(ncol(data), 30)) Arguments data data organized in matrix with separate variables in columns n.contrast number of constrast variables (defaults to max of 1/10 of variables number and 30) Value A list with the following key names: • indices – vector of indices of input variables used to construct contrast variables • x – data with constrast variables appended to it • mask – vector of booleans making it easy to select just contrast variables Examples GenContrastVariables(madelon$data) GetRange Get the recommended range for multiple discretisations Description Get the recommended range for multiple discretisations Usage GetRange(k = 3, n, dimensions, divisions = 1) Arguments k the assumed minimum number of objects in a bucket (the default is the recom- mended value) n the total number of objects considered dimensions the number of dimensions of analysis divisions the number of divisions of discretisations Value The recommended range value (a floating point number). Examples GetRange(n = 250, dimensions = 2) madelon An artificial dataset called MADELON Description An artificial dataset containing data points grouped in 32 clusters placed on the vertices of a five dimensional hypercube and randomly labeled 0/1. Usage madelon Format A list of two elements: data 2000 by 500 matrix of 2000 objects with 500 features decision vector of 2000 decisions (labels 0/1) IG.2D example 2D IG computed using ComputeMaxInfoGains Details The five dimensions constitute 5 informative features. 15 linear combinations of those features are added to form a set of 20 (redundant) informative features. There are 480 distractor features called ’probes’ having no predictive power. Included is the original training set with label -1 changed to 0. Source https://archive.ics.uci.edu/ml/datasets/Madelon MDFS Run end-to-end MDFS Description Run end-to-end MDFS Usage MDFS( data, decision, n.contrast = max(ncol(data), 30), dimensions = 1, divisions = 1, discretizations = 1, range = NULL, pc.xi = 0.25, p.adjust.method = "holm", level = 0.05, seed = NULL, use.CUDA = FALSE ) Arguments data input data where columns are variables and rows are observations (all numeric) decision decision variable as a boolean vector of length equal to number of observations n.contrast number of constrast variables (defaults to max of 1/10 of variables number and 30) dimensions number of dimensions (a positive integer; on CUDA limited to 2–5 range) divisions number of divisions (from 1 to 15) discretizations number of discretizations range discretization range (from 0.0 to 1.0; NULL selects probable optimal number) pc.xi parameter xi used to compute pseudocounts (the default is recommended not to be changed) p.adjust.method method as accepted by p.adjust ("BY" is recommended for FDR, see Details) level statistical significance level seed seed for PRNG used during discretizations (NULL for random) use.CUDA whether to use CUDA acceleration (must be compiled with CUDA; NOTE: the CUDA version might provide a slightly lower sensitivity due to a lack of native support for contrast_data) Details In case of FDR control it is recommended to use Benjamini-Hochberg-Yekutieli p-value adjustment method ("BY" in p.adjust) due to unknown dependencies between tests. Value A list with the following fields: • contrast.indices – indices of variables chosen to build contrast variables • contrast.variables – built contrast variables • MIG.Result – result of ComputeMaxInfoGains • MDFS – result of ComputePValue (the MDFS object) • statistic – vector of statistic’s values (IGs) for corresponding variables • p.value – vector of p-values for corresponding variables • adjusted.p.value – vector of adjusted p-values for corresponding variables • relevant.variables – vector of relevant variables indices Examples MDFS(madelon$data, madelon$decision, dimensions = 2, divisions = 1, range = 0, seed = 0) mdfs_omp_set_num_threads Call omp_set_num_threads Description Call omp_set_num_threads Usage mdfs_omp_set_num_threads(num_threads) Arguments num_threads input data where columns are variables and rows are observations (all numeric) plot.MDFS Plot MDFS details Description Plot MDFS details Usage ## S3 method for class 'MDFS' plot(x, plots = c("ig", "c", "p"), ...) Arguments x an MDFS object plots plots to plot (ig for max IG, c for chi-squared p-values, p for p-values) ... passed on to plot RelevantVariables Find indices of relevant variables Description Find indices of relevant variables Usage RelevantVariables(fs, ...) Arguments fs feature selector ... arguments passed to methods Value indices of important variables RelevantVariables.MDFS Find indices of relevant variables from MDFS Description Find indices of relevant variables from MDFS Usage ## S3 method for class 'MDFS' RelevantVariables(fs, level = 0.05, p.adjust.method = "holm", ...) Arguments fs an MDFS object level statistical significance level p.adjust.method method as accepted by p.adjust ("BY" is recommended for FDR, see Details) ... ignored Details In case of FDR control it is recommended to use Benjamini-Hochberg-Yekutieli p-value adjustment method ("BY" in p.adjust) due to unknown dependencies between tests. Value indices of relevant variables
forestecology
cran
R
Package ‘forestecology’ October 13, 2022 Type Package Title Fitting and Assessing Neighborhood Models of the Effect of Interspecific Competition on the Growth of Trees Version 0.2.0 Maintainer <NAME> <<EMAIL>> Description Code for fitting and assessing models for the growth of trees. In particular for the Bayesian neighborhood competition linear regression model of Allen (2020): methods for model fitting and generating fitted/predicted values, evaluating the effect of competitor species identity using permutation tests, and evaluating model performance using spatial cross-validation. License MIT + file LICENSE Encoding UTF-8 LazyData true RoxygenNote 7.1.1 URL https://github.com/rudeboybert/forestecology BugReports https://github.com/rudeboybert/forestecology/issues Depends R (>= 3.2.4) Suggests testthat (>= 3.0.0), knitr, rmarkdown, covr Imports magrittr, rlang, glue, ggplot2, stringr, dplyr, tidyr, purrr, ggridges, mvnfast, sf, sfheaders, snakecase, tibble, yardstick, blockCV, forcats, patchwork Config/testthat/edition 3 VignetteBuilder knitr NeedsCompilation no Author <NAME> [aut, cre] (<https://orcid.org/0000-0001-7824-306X>), <NAME> [aut] (<https://orcid.org/0000-0002-0712-9603>), <NAME> [aut] (<https://orcid.org/0000-0001-5676-5107>) Repository CRAN Date/Publication 2021-10-02 13:30:05 UTC R topics documented: add_buffer_variabl... 2 autoplot.comp_bayes_l... 4 blocks_e... 5 census_1_e... 6 census_2008_b... 7 census_2014_b... 8 census_2_e... 10 compute_buffer_regio... 11 compute_growt... 12 comp_bayes_l... 13 comp_bayes_lm_e... 14 create_bayes_lm_dat... 15 create_focal_vs_com... 15 focal_vs_comp_distanc... 17 focal_vs_comp_e... 18 forestecolog... 20 growth_e... 20 growth_spatial_e... 21 growth_to... 23 predict.comp_bayes_l... 23 run_c... 24 species_b... 25 study_region_b... 26 study_region_e... 27 add_buffer_variable Identify trees in the buffer region Description Identify trees in the buffer region Usage add_buffer_variable(growth_df, direction = "in", size, region) Arguments growth_df sf data frame direction "in" for buffers that are contained within region (default), "out" for buffers that contain region. size Distance to determine which neighboring trees to a focal tree are competitors. The units are assumed to be the same as the geometry variables in growth_df. region An sf polygon object of region to be buffered Value The same growth_df data frame but with a new boolean variable buffer indicating if a tree is in the study region buffer area. This uses compute_buffer_region() to define the boundary of the buffer region. See Also Other spatial functions: compute_buffer_region(), focal_vs_comp_distance() Examples library(tibble) library(sfheaders) library(ggplot2) # Example square region to be buffered region <- tibble( x = c(0, 0, 1, 1), y = c(0, 1, 1, 0) ) %>% sf_polygon() # Example points study_points <- tibble( x = runif(50), y = runif(50) ) %>% sf_point() # Size of buffer size <- 0.05 # Identify whether points are within size of boundary study_points <- study_points %>% add_buffer_variable(direction = "in", size = size, region = region) # Plot study points coded by whether they are within size of boundary p <- ggplot() + geom_sf(data = region, fill = "transparent") + geom_sf(data = study_points, aes(col = buffer)) p # Additionally, show buffer boundary in red buffer_boundary <- region %>% compute_buffer_region(direction = "in", size = size) p + geom_sf(data = buffer_boundary, col = "red", fill = "transparent") autoplot.comp_bayes_lm Plot Bayesian model parameters Description Plot Bayesian model parameters Usage ## S3 method for class 'comp_bayes_lm' autoplot(object, type = "intercepts", sp_to_plot = NULL, ...) Arguments object Output of comp_bayes_lm type A single character string for plot type with possible values "intercepts", "dbh_slopes", or "competition". sp_to_plot Vector of subset of species to plot ... Currently ignored—only included for consistency with generic. Value focal_vs_comp with new column of predicted growth_hat Examples library(ggplot2) library(ggridges) # Load in posterior parameter example data(comp_bayes_lm_ex) # Plot beta_0, growth intercepts autoplot(comp_bayes_lm_ex, type = "intercepts") # Plot beta_dbh, growth-dbh slope autoplot(comp_bayes_lm_ex, type = "dbh_slopes") # Plot lambdas, competition coefficients autoplot(comp_bayes_lm_ex, type = "competition") blocks_ex Example cross validation grid Description This is an example cross validation grid. This is needed to create the focal versus comp data frame and run cross-validated models Usage blocks_ex Format A sf polygons foldID Tree identification number. This identifies an individual tree and can be used to connect trees between the two censuses. geometry Point location of the individual See Also Other example data objects: census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(ggplot2) library(sf) library(dplyr) comp_dist <- 1 ggplot(blocks_ex) + geom_sf() + geom_sf(data = growth_spatial_ex) focal_vs_comp_ex <- growth_spatial_ex %>% mutate(basal_area = 0.0001 * pi * (dbh1 / 2)^2) %>% create_focal_vs_comp(comp_dist, blocks = blocks_ex, id = "ID", comp_x_var = "basal_area") census_1_ex Example input census data for package use Description This is example forest census data to be analyzed with this package. Usage census_1_ex Format A tibble ID Tree identification number. This identifies an individual tree and can be used to connect trees between the two censuses. sp Species of the individual gx x-coordinate meters from reference point gy y-coordinate meters from reference point date Date the stem was measured codes Code for additional information on the stem: M means the main stem of the individual tree and R means the stem was lost, but the tag was moved to another stem greater than DBH cutoff, this stands for resprout. dbh Diameter at breast height of the tree in cm See Also Other example data objects: blocks_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(dplyr) library(stringr) growth_ex <- compute_growth( census_1 = census_1_ex %>% mutate(sp = to_any_case(sp) %>% factor()), census_2 = census_2_ex %>% filter(!str_detect(codes, "R")) %>% mutate(sp = to_any_case(sp) %>% factor()), id = "ID" ) census_2008_bw Michigan Big Woods research plot data Description The Big Woods data come from three censuses of a 23 ha forest research plots. All free-standing vegetation greater than 1 cm diameter at 1.3 m height (diameter at breast height; DBH) were tagged, identified, spatially mapped and had their DBH measured. The original census took place in 2003 and covered only 12 ha. A second census took place from 2008-2010 and expanded the plot to its current 23 ha. In the first and second censuses trees larger than 3.1 cm DBH were included. Finally a third census took place in 2014. In this census trees larger than 1 cm DBH were included. In the second and third censuses the original trees were found, recorded for survival, remeasured, and new individuals were tagged. This data frame has data from the second census (2008-2010). Usage census_2008_bw Format A data frame with 27193 rows and 8 variables: treeID Tree identification number. This identifies an individual tree and can be used to connect trees between the two censuses. stemID Stem number for a multi-stemmed individual. For all trees this starts at 1 and continues up from there. To uniquely identify a stem across the plot this value must be combined with treeID. dbh Diameter at breast sp Code for the species. See species_bw for scientific name. gx x-coordinate meters from reference point gy y-coordinate meters from reference point date Approximate date the stem was measured codes Code for additional information on the stem: M means the main stem of the individual tree; AL means the stem is alive but leaning or completely fallen over; B means the stem is broken and over half the canopy is assumed to be missing; and R means the stem was lost, but the tag was moved to another stem greater than DBH cutoff, this stands for resprout. Details This plot is part of the Smithsonian Institution’s Forest Global Earth Observatory (ForestGEO) global network of forest research sites. For complete details on this dataset see its Deep Blue Data repository page. See Also Other Big Woods data: census_2014_bw, species_bw, study_region_bw Other example data objects: blocks_ex, census_1_ex, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(ggplot2) library(sf) # Convert all 2008 plot stems to sf object census_2008_bw_sf <- census_2008_bw %>% st_as_sf(coords = c("gx", "gy")) # Plot stems with plot boundary ggplot() + geom_sf(data = census_2008_bw_sf, size = 0.25) census_2014_bw Michigan Big Woods research plot data Description The Big Woods data come from three censuses of a 23 ha forest research plots. All free-standing vegetation greater than 1 cm diameter at 1.3 m height (diameter at breast height; DBH) were tagged, identified, spatially mapped and had their DBH measured. The original census took place in 2003 and covered only 12 ha. A second census took place from 2008-2010 and expanded the plot to its current 23 ha. In the first and second censuses trees larger than 3.1 cm DBH were included. Finally a third census took place in 2014. In this census trees larger than 1 cm DBH were included. In the second and third censuses the original trees were found, recorded for survival, remeasured, and new individuals were tagged. This data frame has data from the third census (2014). Usage census_2014_bw Format A data frame with 48371 rows and 8 variables: treeID Tree identification number. This identifies an individual tree and can be used to connect trees between the two censuses. stemID Stem number for a multi-stemmed individual. For all trees this starts at 1 and continues up from there. To uniquely identify a stem across the plot this value must be combined with treeID. sp Code for the species. See species_bw for scientific name. dbh Diameter at breast gx x-coordinate meters from reference point gy y-coordinate meters from reference point date Approximate date the stem was measured codes Code for additional information on the stem: M means the main stem of the individual tree; AL means the stem is alive but leaning or completely fallen over; B means the stem is broken and over half the canopy is assumed to be missing; and R means the stem was lost, but the tag was moved to another stem greater than DBH cutoff, this stands for resprout. Details This plot is part of the Smithsonian Institution’s Forest Global Earth Observatory (ForestGEO) global network of forest research sites. For complete details on this dataset see its Deep Blue Data repository page. See Also Other Big Woods data: census_2008_bw, species_bw, study_region_bw Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(ggplot2) library(sf) library(dplyr) # Convert all 2008 plot stems to sf object census_2008_bw_sf <- census_2008_bw %>% st_as_sf(coords = c("gx", "gy")) # Plot stems with plot boundary ggplot() + geom_sf(data = census_2008_bw_sf, size = 0.25) # Species-specific mortality between 2008 and 2014 censuses census_2008_bw %>% left_join(census_2014_bw, by = c("treeID", "stemID"), suffix = c("_2008", "_2014")) %>% mutate(mortality = ifelse(is.na(dbh_2014), 1, 0)) %>% group_by(sp_2008) %>% summarize(mortality = mean(mortality), n = n()) %>% arrange(desc(n)) census_2_ex Example input census data for package use Description This is an example second census to be analyzed with the package. Usage census_2_ex Format A tibble ID Tree identification number. This identifies an individual tree and can be used to connect trees between the two censuses. sp Species of the individual gx x-coordinate meters from reference point gy y-coordinate meters from reference point date Date the stem was measured codes Code for additional information on the stem: M means the main stem of the individual tree and R means the stem was lost, but the tag was moved to another stem greater than DBH cutoff, this stands for resprout. dbh Diameter at breast height of the tree in cm See Also Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(dplyr) library(stringr) growth_ex <- compute_growth( census_1 = census_1_ex %>% mutate(sp = to_any_case(sp) %>% factor()), census_2 = census_2_ex %>% filter(!str_detect(codes, "R")) %>% mutate(sp = to_any_case(sp) %>% factor()), id = "ID" ) compute_buffer_region Compute buffer to a region. Description Compute buffer to a region. Usage compute_buffer_region(region, direction = "in", size) Arguments region An sf polygon object of region to be buffered direction "in" for buffers that are contained within region (default), "out" for buffers that contain region. size Distance to determine which neighboring trees to a focal tree are competitors. The units are assumed to be the same as the geometry variables in growth_df. Value An sf polygon object of buffer See Also Other spatial functions: add_buffer_variable(), focal_vs_comp_distance() Examples library(tibble) library(sfheaders) library(ggplot2) # Example square region to be buffered (as sf object) region <- tibble( x = c(0, 0, 1, 1), y = c(0, 1, 1, 0) ) %>% sf_polygon() # Size of buffer size <- 0.05 # Compute "inwards" buffer inwards_buffer_region <- region %>% compute_buffer_region(direction = "in", size = size) # Compute "outwards" buffer outwards_buffer_region <- region %>% compute_buffer_region(direction = "out", size = size) # Plot all three regions: ggplot() + geom_sf(data = outwards_buffer_region, col = "blue", fill = "transparent") + geom_sf(data = region, fill = "transparent") + geom_sf(data = inwards_buffer_region, col = "orange", fill = "transparent") + labs(title = "Regions: original (black), inwards buffer (orange), and outwards buffer (blue)") compute_growth Compute growth of trees Description Based on two tree censuses, compute the average annual growth in dbh for all trees. Usage compute_growth(census_1, census_2, id) Arguments census_1 A data frame of the first census. census_2 A data frame of the second (later) census id Name of variable that uniquely identifies each tree common to census_1 and census_2 allowing you to join/merge both data frames. Value An sf data frame with column growth giving the average annual growth in dbh. See Also Other data processing functions: create_bayes_lm_data(), create_focal_vs_comp() Examples library(dplyr) library(stringr) growth_ex <- compute_growth( census_1 = census_1_ex %>% mutate(sp = to_any_case(sp) %>% factor()), census_2 = census_2_ex %>% filter(!str_detect(codes, "R")) %>% mutate(sp = to_any_case(sp) %>% factor()), id = "ID" ) comp_bayes_lm Fit Bayesian competition model Description Fit a Bayesian linear regression model with interactions terms where y = Xβ +  µ mean hyperparameter vector for β of length p + 1 V covariance hyperparameter matrix for β of dimension (p + 1)x(p + 1) a shape hyperparameter for σ 2 > 0 b scale hyperparameter for σ 2 > 0 Usage comp_bayes_lm(focal_vs_comp, prior_param = NULL, run_shuffle = FALSE) Arguments focal_vs_comp data frame from create_focal_vs_comp() prior_param A list of {a_0, b_0, mu_0, V_0} prior hyperparameters. Defaults to a_0 = 250, b_0 = 250, mu_0 a vector of zeros of length p + 1, V_0 an identity matrix of dimension (p + 1)x(p + 1) run_shuffle boolean as to whether to run permutation test shuffle of competitor tree species within a particular focal_ID Value A list of {a_star, b_star, mu_star, V_star} posterior hyperparameters Source Closed-form solutions of Bayesian linear regression doi: 10.1371/journal.pone.0229930.s004 See Also Other modeling functions: create_bayes_lm_data(), predict.comp_bayes_lm(), run_cv() Examples library(dplyr) # Load in focal versus comp data(focal_vs_comp_ex) comp_bayes_lm_ex <- focal_vs_comp_ex %>% comp_bayes_lm(prior_param = NULL, run_shuffle = FALSE) comp_bayes_lm_ex Example bayesian competition model fit Description This object contains an example fitted Bayesian competition model outputted by comp_bayes_lm(). Usage comp_bayes_lm_ex Format A list subclass containing the following elements: prior_params Prior parameters supplied to comp_bayes_lm() post_params Posterior parameters outputted by comp_bayes_lm() terms The formula object used in model fitting See Also comp_bayes_lm() Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(dplyr) library(yardstick) # Compare model predictions to observation predictions <- focal_vs_comp_ex %>% mutate(growth_hat = predict(comp_bayes_lm_ex, focal_vs_comp_ex)) predictions %>% rmse(truth = growth, estimate = growth_hat) %>% pull(.estimate) # Plot posterior parameters comp_bayes_lm_ex %>% autoplot() create_bayes_lm_data Create input data frame for Bayesian regression Description This function "widens" focal-competitor data frames for use inside of package modeling functions, where each comp_sp inside of the comp list-column receives its own column with its associated total basal area. This function is used internally by comp_bayes_lm() and predict.comp_bayes_lm() exported as a convenience for applications extending this package’s functionality. Usage create_bayes_lm_data(focal_vs_comp, run_shuffle = FALSE) Arguments focal_vs_comp data frame from create_focal_vs_comp() run_shuffle boolean as to whether to run permutation test shuffle of competitor tree species within a particular focal_ID Value Data frame for internal package use. See Also Other modeling functions: comp_bayes_lm(), predict.comp_bayes_lm(), run_cv() Other data processing functions: compute_growth(), create_focal_vs_comp() Examples create_bayes_lm_data(focal_vs_comp_ex) create_focal_vs_comp Create focal versus competitor trees data frame Description "Focal versus competitor trees" data frames are the main data frame used for analysis. "Focal trees" are all trees that satisfy the following criteria 1. Were alive at both censuses 2. Were not part of the study region’s buffer as computed by add_buffer_variable() 3. Were not a resprout at the second census. Such trees should be coded as "R" in the codes2 variable (OK if a resprout at first census) For each focal tree, "competitor trees" are all trees that (1) were alive at the first census and (2) within comp_dist distance of the focal tree. Usage create_focal_vs_comp(growth_df, comp_dist, blocks, id, comp_x_var) Arguments growth_df A compute_growth() output converted to sf object comp_dist Distance to determine which neighboring trees to a focal tree are competitors. blocks An sf object of a blockCV block output id A character string of the variable name in growth_df uniquely identifying each tree comp_x_var A character string indicating which numerical variable to use as competitor ex- planatory variable Value focal_vs_comp data frame of all focal trees and for each focal tree all possible competitor trees. In particular, for each competitor tree we return comp_x_var. Potential examples of comp_x_var include basal area or estimate above ground biomass. Note In order to speed computation, in particular of distances between all focal/competitor tree pairs, we use the cross-validation blockCV object to divide the study region into smaller subsets. See Also Other data processing functions: compute_growth(), create_bayes_lm_data() Examples library(ggplot2) library(dplyr) library(stringr) library(sf) library(sfheaders) library(tibble) # Create fold information sf object. SpatialBlock_ex <- tibble( # Study region boundary x = c(0, 0, 5, 5), y = c(0, 5, 5, 0) ) %>% # Convert to sf object sf_polygon() %>% mutate(folds = "1") # Plot example data. Observe for comp_dist = 1.5, there are 6 focal vs comp pairs: # 1. focal 1 vs comp 2 # 2. focal 2 vs comp 1 # 3. focal 2 vs comp 3 # 4. focal 3 vs comp 2 # 5. focal 4 vs comp 5 # 6. focal 5 vs comp 4 ggplot() + geom_sf(data = SpatialBlock_ex, fill = "transparent") + geom_sf_label(data = growth_toy, aes(label = ID)) # Return corresponding data frame growth_toy %>% mutate(basal_area = 0.0001 * pi * (dbh1 / 2)^2) %>% create_focal_vs_comp(comp_dist = 1.5, blocks = SpatialBlock_ex, id = "ID", comp_x_var = "basal_area") # Load in growth_df with spatial data # See ?growth_ex for attaching spatial data to growth_df data(growth_spatial_ex) # Load in blocks data(blocks_ex) focal_vs_comp_ex <- growth_spatial_ex %>% mutate(basal_area = 0.0001 * pi * (dbh1 / 2)^2) %>% create_focal_vs_comp(comp_dist = 1, blocks = blocks_ex, id = "ID", comp_x_var = "basal_area") focal_vs_comp_distance Return all pairwise distances between two data frames of trees Description Return all pairwise distances between two data frames of trees Usage focal_vs_comp_distance(focal_trees, comp_trees) Arguments focal_trees An sf polygon object of the focal trees of interest comp_trees An sf polygon object of the competitor trees Value A data frame with three columns: focal_ID of focal tree, comp_dist of competitor tree, and dist of distance between them. See Also Other spatial functions: add_buffer_variable(), compute_buffer_region() Examples library(tibble) library(ggplot2) library(sf) # Create toy example focal and competitor trees focal_trees <- tibble( focal_ID = c(1, 2, 3), x = c(0.3, 0.6, 0.7), y = c(0.1, 0.5, 0.7) ) %>% st_as_sf(coords = c("x", "y")) comp_trees <- tibble( comp_ID = c(4, 5, 6, 7), x = c(0, 0.2, 0.4, 0.6), y = c(0.6, 0.7, 1, 0.2) ) %>% st_as_sf(coords = c("x", "y")) # Plot both sets of trees ggplot() + geom_sf_label(data = focal_trees, aes(label = focal_ID), col = "black") + geom_sf_label(data = comp_trees, aes(label = comp_ID), col = "orange") + labs(title = "Focal trees in black, competitor trees in orange") # Compute corresponding distances between the 3 focal trees and 4 competitor trees focal_vs_comp_distance(focal_trees, comp_trees) focal_vs_comp_ex Example focal versus comp data frame Description This is an example focal versus comp data frame. The rows are focal trees which are repeated for all competitor trees within a specified distance from them. In this case that distance is 1. This is the focal versus comp for growth_spatial_ex. Usage focal_vs_comp_ex Format A tibble::tbl_df: focal_ID Tree identification number for the focal tree focal_sp Species of the focal tree dbh Diameter at breast height of the focal tree at the first census foldID The CV-fold that the focal tree is in geometry The point location of the focal tree growth The average annual growth of the focal tree between censuses comp A list-column: characteristics of the relevant competitor trees The comp list-column contains tibble::tbl_dfs with columns: comp_ID Tree identification number for the competitor tree dist The distance between the focal and comp tree, this will be less than the max distance specified. comp_sp Species of the comp tree comp_x_var Numerical variable associated with comp tree See Also create_focal_vs_comp() Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples comp_bayes_lm_ex <- focal_vs_comp_ex %>% comp_bayes_lm(prior_param = NULL, run_shuffle = FALSE) forestecology forestecology package Description Methods and data for forest ecology model selection and assessment Details See the README on GitHub growth_ex Example growth data frame for small example Description This is an example growth data frame formed from two census data frames. In this case it is made by combining census_1_ex and census_2_ex. The individuals alive in both censuses were linked by their tree ID. Usage growth_ex Format A sf spatial tibble ID Tree identification number. This identifies an individual tree and can be used to connect trees between the two censuses. sp Species of the individual codes1 Code for additional information on the stem during the first census: M means the main stem of the individual tree and R means the stem was lost, but the tag was moved to another stem greater than DBH cutoff, this stands for resprout. dbh1 Diameter at breast height of the tree in cm at the first census dbh2 Diameter at breast height of the tree in cm at the second census growth Average annual growth between the two censuses in cm per year codes2 Codes at the second census geometry Point location of the individual See Also compute_growth() Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(ggplot2) library(dplyr) library(sf) library(sfheaders) library(blockCV) growth_ex %>% ggplot() + geom_sf() growth_ex %>% group_by(sp) %>% summarize(mean(growth)) # Add buffer growth_spatial_ex <- growth_ex %>% add_buffer_variable(direction = "in", size = 1, region = study_region_ex) # Add cross-validation folds fold1 <- rbind(c(0, 0), c(5, 0), c(5, 5), c(0, 5), c(0, 0)) fold2 <- rbind(c(5, 0), c(10, 0), c(10, 5), c(5, 5), c(5, 0)) blocks <- bind_rows( sf_polygon(fold1), sf_polygon(fold2) ) %>% mutate(foldID = c(1, 2)) SpatialBlock_ex <- spatialBlock( speciesData = growth_ex, verbose = FALSE, k = 2, selection = "systematic", blocks = blocks ) # Add foldID to data growth_spatial_ex <- growth_spatial_ex %>% mutate(foldID = SpatialBlock_ex$foldID %>% as.factor()) growth_spatial_ex Example growth data frame with spatial data for small example Description This is an example growth data frame formed from two census data frames which has been updated with spatial data. It starts from growth_ex. Usage growth_spatial_ex Format A sf spatial tibble ID Tree identification number. This identifies an individual tree and can be used to connect trees between the two censuses. sp Species of the individual codes1 Code for additional information on the stem during the first census: M means the main stem of the individual tree and R means the stem was lost, but the tag was moved to another stem greater than DBH cutoff, this stands for resprout. dbh1 Diameter at breast height of the tree in cm at the first census dbh2 Diameter at breast height of the tree in cm at the second census growth Average annual growth between the two censuses in cm per year codes2 Codes at the second census geometry Point location of the individual buffer A boolean variable for whether the individual is in the buffer region or not foldID Which cross-validation fold the individual is in See Also compute_growth() Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_toy, species_bw, study_region_bw, study_region_ex Examples library(ggplot2) library(dplyr) library(sf) comp_dist <- 1 ggplot() + geom_sf(data = growth_spatial_ex, aes(col = buffer), size = 2) ggplot() + geom_sf(data = growth_spatial_ex, aes(col = foldID), size = 2) # Create the focal versus comp data frame focal_vs_comp_ex <- growth_spatial_ex %>% mutate(basal_area = 0.0001 * pi * (dbh1 / 2)^2) %>% create_focal_vs_comp(comp_dist, blocks = blocks_ex, id = "ID", comp_x_var = "basal_area") growth_toy Example input data for create_focal_vs_comp() Description An example sf of type generated by compute_growth() Usage growth_toy Format A sf spatial features polygon See Also Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, species_bw, study_region_bw, study_region_ex predict.comp_bayes_lm Make predictions based on fitted Bayesian model Description Applies fitted model from comp_bayes_lm() and returns posterior predicted values. Usage ## S3 method for class 'comp_bayes_lm' predict(object, newdata, ...) Arguments object Output of comp_bayes_lm(): A list of {a_star, b_star, mu_star, V_star} posterior hyperparameters newdata A data frame of type focal_vs_comp in which to look for variables with which to predict. ... Currently ignored—only included for consistency with generic. Value A vector of predictions with length equal to the input data. Source Closed-form solutions of Bayesian linear regression doi: 10.1371/journal.pone.0229930.s004 See Also Other modeling functions: comp_bayes_lm(), create_bayes_lm_data(), run_cv() Examples library(dplyr) library(sf) library(ggplot2) # Load in posterior parameter example # and growth data to compare to data(comp_bayes_lm_ex, growth_ex) predictions <- focal_vs_comp_ex %>% mutate(growth_hat = predict(comp_bayes_lm_ex, focal_vs_comp_ex)) predictions %>% ggplot(aes(growth, growth_hat)) + geom_point() + geom_abline(slope = 1, intercept = 0) run_cv Run the bayesian model with spatial cross validation Description This function carries out the bayesian modeling process with spatial cross-validation as described in <NAME> Kim (2020). Given a focal-competitor data frame, it appends a column with predicted growth values. Usage run_cv( focal_vs_comp, comp_dist, blocks, prior_param = NULL, run_shuffle = FALSE ) Arguments focal_vs_comp data frame from create_focal_vs_comp() comp_dist Distance to determine which neighboring trees to a focal tree are competitors. blocks An sf object of a blockCV block output prior_param A list of {a_0, b_0, mu_0, V_0} prior hyperparameters. Defaults to a_0 = 250, b_0 = 250, mu_0 a vector of zeros of length p + 1, V_0 an identity matrix of dimension (p + 1)x(p + 1) run_shuffle boolean as to whether to run permutation test shuffle of competitor tree species within a particular focal_ID Value focal_vs_comp with new column of predicted growth_hat See Also Other modeling functions: comp_bayes_lm(), create_bayes_lm_data(), predict.comp_bayes_lm() Examples run_cv( focal_vs_comp_ex, comp_dist = 1, blocks = blocks_ex ) species_bw Phylogenic groupings and trait based clustering of various tree species Description A date frame mapping the species codes to their common names, scientific names, and families. This also includes a trait-based clustering of the species. Usage species_bw Format A data frame with 46 rows and 6 variables: sp The code for the species. Link to census_2008_bw and census_2014_bw with sp variable. genus Genus species Species epithet latin Scientific name family Family trait_group Clustering of species based on three traits rather than their evolutionary relationships. The traits are specific leaf area, maximum height, and wood density Source For more information on trait clustering see Allen and Kim 2020 "A permutation test and spatial cross-validation approach to assess models of interspecific competition between trees." doi: 10.1371/ journal.pone.0229930PLOS One 15: e0229930. See Also Other Big Woods data: census_2008_bw, census_2014_bw, study_region_bw Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, study_region_bw, study_region_ex Examples library(dplyr) # Original 2008 census data census_2008_bw # 2008 census data with additional species information census_2008_bw %>% left_join(species_bw, by = "sp") study_region_bw Bigwoods forest study region boundary Description Boundary region for Bigwoods defined in terms of (x,y) vertices of a polygon. Usage study_region_bw Format A sf spatial features polygon See Also Other Big Woods data: census_2008_bw, census_2014_bw, species_bw Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_ex Examples library(ggplot2) library(sf) # Convert all 2008 plot stems to sf object census_2008_bw_sf <- census_2008_bw %>% st_as_sf(coords = c("gx", "gy")) # Plot stems with plot boundary ggplot() + geom_sf(data = census_2008_bw_sf, size = 0.25) + geom_sf(data = study_region_bw, color = "red", fill = "transparent") study_region_ex Study region for example data Description Boundary region for small example data set defined in terms of (x,y) vertices of a polygon. Usage study_region_ex Format A sf spatial features polygon See Also Other example data objects: blocks_ex, census_1_ex, census_2008_bw, census_2014_bw, census_2_ex, comp_bayes_lm_ex, focal_vs_comp_ex, growth_ex, growth_spatial_ex, growth_toy, species_bw, study_region_bw Examples library(ggplot2) library(sf) # Convert stems to sf object census_1_ex_sf <- census_1_ex %>% st_as_sf(coords = c("gx", "gy")) # Plot stems with plot boundary ggplot() + geom_sf(data = study_region_ex) + geom_sf(data = study_region_bw, color = "red", fill = "transparent")
short-unique-id
npm
JavaScript
[Short Unique ID (UUID) Generating Library](#short-unique-id-uuid-generating-library) === --- Tiny (6.7kB minified) no-dependency library for generating random or sequential UUID of any length with exceptionally minuscule probabilies of duplicate IDs. ``` const uid = new ShortUniqueId({ length: 10 }); uid.rnd(); // p0ZoB1FwH6 uid.rnd(); // mSjGCTfn8w uid.rnd(); // yt4Xx5nHMB // ... // or const { randomUUID } = new ShortUniqueId({ length: 10 }); randomUUID(); // e8Civ0HoDy randomUUID(); // iPjiGoHXAK randomUUID(); // n528gSMwTN // ... ``` For example, using the default dictionary of numbers and letters (lower and upper case): ``` 0,1,2,3,4,5,6,7,8,9, a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z, A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z ``` * if you generate a unique ID of 16 characters (half of the standard UUID of 32 characters) * generating 100 unique IDs **per second** #### [It would take **~10 thousand years** to have a 1% probability of at least one collision!](#it-would-take-10-thousand-years-to-have-a-1-probability-of-at-least-one-collision) To put this into perspective: * 73 years is the (global) average life expectancy of a human being * 120 years ago no human ever had set foot on either of the Earth's poles * 480 years ago Nicolaus Copernicus was still working on his theory of the Earth revolving around the Sun * 1000 years ago there was no such thing as government-issued paper money (and wouldn't be for about a century) * 5000 years ago the global population of humans was under 50 million (right now Mexico has a population of 127 million) You can calculate duplicate/collision probabilities using the included functions: * [availableUUIDs()](https://shortunique.id/classes/default.html#availableuuids) * [approxMaxBeforeCollision()](https://shortunique.id/classes/default.html#approxmaxbeforecollision) * [collisionProbability()](https://shortunique.id/classes/default.html#collisionprobability) *NOTE: 👆 On these links you will also find explanations for the math used within the functions.* --- [Open source notice](#open-source-notice) --- This project is part of the [Open Collective](https://opencollective.com/simplyhexagonal) project [Simply Hexagonal](https://simplyhexagonal.org) and is open to updates by its users, we ensure that PRs are relevant to the community. In other words, if you find a bug or want a new feature, please help us by becoming one of the [contributors](#contributors-) ✌️ ! See the [contributing section](#contributing). [Like this module? ❤](#like-this-module-) --- Please consider: * [Buying me a coffee](https://www.buymeacoffee.com/jeanlescure) ☕ * Supporting me on [Patreon](https://www.patreon.com/jeanlescure) 🏆 * Starring this repo on [Github](https://github.com/jeanlescure/short-unique-id) 🌟 [📣 v5 Notice](#-v5-notice) --- In order to improve security compliance we have removed the ability to use a ShortUniqueId as a function, i.e. `const uid = new ShortUniqueId(); uid();` is no longer supported. If you plan to upgrade to v5 make sure to refactor `uid();` to `uid.rnd();` in your code beforehand. For more information regarding this decision you can view [issue #53](https://github.com/simplyhexagonal/short-unique-id/issues/53). ### [Features](#features) The ability to generate UUIDs that contain a timestamp which can be extracted: ``` // js/ts const uid = new ShortUniqueId(); const uidWithTimestamp = uid.stamp(32); console.log(uidWithTimestamp); // GDa608f973aRCHLXQYPTbKDbjDeVsSb3 const recoveredTimestamp = uid.parseStamp(uidWithTimestamp); console.log(recoveredTimestamp); // 2021-05-03T06:24:58.000Z ``` ``` # cli $ suid -s -l 42 lW611f30a2ky4276g3l8N7nBHI5AQ5rCiwYzU47HP2 $ suid -p lW611f30a2ky4276g3l8N7nBHI5AQ5rCiwYzU47HP2 2021-08-20T04:33:38.000Z ``` Default dictionaries (generated on the spot to reduce memory footprint and avoid dictionary injection vulnerabilities): * number * alpha * alpha_lower * alpha_upper * **alphanum** *(default when no dictionary is provided to `new ShortUniqueId()`)* * alphanum_lower * alphanum_upper * hex ``` // instantiate using one of the default dictionary strings const uid = new ShortUniqueId({ dictionary: 'hex', }); console.log(uid.dict.join()); // 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f // or change the dictionary after instantiation uid.setDictionary('alpha_upper'); console.log(uid.dict.join()); // A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z ``` Ability to use custom formatting. Where `$r` is random UUID, `$s` is sequential UUID, and `$t` is timestamp UUID: ``` const timestamp = new Date('2023-01-29T03:21:21.000Z'); const result = uid.formattedUUID('Time: $t0 ID: $s2-$r4', timestamp); // timestamp is optional console.log(result); // Time: 63d5e631 ID: 0b-aaab ``` ### [Use in CLI](#use-in-cli) ``` $ npm install --global short-unique-id $ suid -h # Usage: # node short-unique-id [OPTION] # # Options: # -l, --length=ARG character length of the uid to generate. # -s, --stamp include timestamp in uid (must be used with --length (-l) of 10 or more). # -t, --timestamp=ARG custom timestamp to parse (must be used along with -s, --stamp, -f, or --format). # -f, --format=ARG string representing custom format to generate id with. # -p, --parse=ARG extract timestamp from stamped uid (ARG). # -d, --dictionaryJson=ARG json file with dictionary array. # -h, --help display this help ``` ### [Use as module](#use-as-module) Add to your project: ``` // ES6 / TypeScript Import import ShortUniqueId from 'short-unique-id'; // Node.js require const ShortUniqueId = require('short-unique-id'); // Deno (web module) Import import ShortUniqueId from 'https://esm.sh/short-unique-id'; ``` Instantiate and use: ``` //Instantiate const uid = new ShortUniqueId(); // Random UUID console.log(uid.rnd()); // Sequential UUID console.log(uid.seq()); ``` alternatively using destructuring assignment: ``` // Instantiate and destructure (long method name recommended for code readability) const { randomUUID, sequentialUUID } = new ShortUniqueId(); // Random UUID console.log(randomUUID()); // Sequential UUID console.log(sequentialUUID()); ``` *NOTE:* we made sure to use `bind()` on all ShortUniqueId methods to ensure that any options passed when creating the instance will be respected by the destructured methods. ### [Use in browser](#use-in-browser) ``` <!-- Add source (minified 4.6kB) --> <script src="https://cdn.jsdelivr.net/npm/short-unique-id@latest/dist/short-unique-id.min.js"></script<!-- Usage --> <script> // Instantiate var uid = new ShortUniqueId(); // Random UUID document.write(uid.rnd()); // Sequential UUID document.write(uid.seq()); </script> ``` ### [Options](#options) Options can be passed when instantiating `uid`: ``` const options = { ... }; const uid = new ShortUniqueId(options); ``` For more information take a look at the [docs](https://shortunique.id/interfaces/shortuniqueidoptions.html). [Available for](#available-for) --- * [Node.js (npm)](https://www.npmjs.com/package/short-unique-id) * [Deno](https://esm.sh/short-unique-id) * [Browsers](https://www.jsdelivr.com/package/npm/short-unique-id?path=dist) [Documentation with Online Short UUID Generator](#documentation-with-online-short-uuid-generator) --- You can find the docs and online generator at: <https://shortunique.id[What is the probability of generating the same id again?](#what-is-the-probability-of-generating-the-same-id-again) --- This largely depends on the given dictionary and the selected UUID length. Out of the box this library provides a shuffled dictionary of digits from 0 to 9, as well as the alphabet from a to z both in UPPER and lower case, with a default UUID length of 6. That gives you a total of 56,800,235,584 possible UUIDs. So, given the previous values, the probability of generating a duplicate in 1,000,000 rounds is ~0.00000002, or about 1 in 50,000,000. If you change the dictionary and/or the UUID length then we have provided the function `collisionProbability()` function to calculate the probability of hitting a duplicate in a given number of rounds (a collision) and the function `uniqueness()` which provides a score (from 0 to 1) to rate the "quality" of the combination of given dictionary and UUID length (the closer to 1, higher the uniqueness and thus better the quality). To find out more about the math behind these functions please refer to the [API Reference](https://shortunique.id/classes/default.html#collisionprobability). [Acknowledgement and platform support](#acknowledgement-and-platform-support) --- This repo and npm package started as a straight up manual transpilation to ES6 of the [short-uid](https://github.com/serendipious/nodejs-short-uid) npm package by [<NAME>](https://github.com/serendipious/). Since this package is now reporting 200k+ npm weekly downloads and 16M+ weekly cdn hits, we've gone ahead and re-written the whole of it in TypeScript and made sure to package dist modules compatible with Deno, Node.js and all major Browsers. [Sponsors](#sponsors) --- * [Clever Synapse](https://cleversynapse.com) [Development](#development) --- Clone this repo: ``` # SSH git clone [email protected]:jeanlescure/short-unique-id.git # HTTPS git clone https://github.com/jeanlescure/short-unique-id.git ``` Tests run using: ``` pnpm test ``` [Build](#build) --- In order to publish the latest changes you must build the distribution files: ``` pnpm build ``` Then commit all changes and run the release script: ``` pnpm release ``` [Contributing](#contributing) --- Yes, thank you! This plugin is community-driven, most of its features are from different authors. Please update the docs and tests and add your name to the `package.json` file. [Contributors ✨](#contributors-) --- Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | --- | | [💻](https://github.com/jeanlescure/short-unique-id/commits?author=serendipious "Code") | | | | | --- | | [🚧](#maintenance-jeanlescure "Maintenance") [💻](https://github.com/jeanlescure/short-unique-id/commits?author=jeanlescure "Code") [📖](https://github.com/jeanlescure/short-unique-id/commits?author=jeanlescure "Documentation") [⚠️](https://github.com/jeanlescure/short-unique-id/commits?author=jeanlescure "Tests") | | | | | --- | | [💻](https://github.com/jeanlescure/short_uuid/commits?author=DiLescure "Code") | | | | | --- | | [💻](https://github.com/jeanlescure/short_uuid/commits?author=EmerLM "Code") | | | | | | --- | | [💻](https://github.com/jeanlescure/short_uuid/commits?author=angelnath26 "Code") [👀](https://github.com/jeanlescure/short_uuid/pulls?q=is%3Apr+reviewed-by%3Aangelnath26 "Reviewed Pull Requests") | | | | | --- | | [💻](https://github.com/jeanlescure/short-unique-id/commits?author=jeffturcotte "Code") | | | | | --- | | [💻](https://github.com/jeanlescure/short-unique-id/commits?author=neversun "Code") | | | | | --- | | [🤔](https://github.com/jeanlescure/short-unique-id/issues/19 "Ideas, Planning, & Feedback") | | | | | | --- | | [🛡️](https://github.com/jeanlescure/short-unique-id/issues/35 "Security") | | | | | --- | | [💻](https://github.com/jeanlescure/short-unique-id/pull/46 "Code") | | | | | --- | | [💻](https://github.com/jeanlescure/short-unique-id/pull/48 "Code") | | | | | --- | | [📖](https://github.com/jeanlescure/short-unique-id/issues/47 "Documentation") | | [License](#license) --- Copyright (c) 2018-2023 [Short Unique ID Contributors](https://github.com/jeanlescure/short-unique-id/#contributors-). Licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). Readme --- ### Keywords * short * random * uid * uuid * guid * node * unique id * generator * tiny
geostat-framework
readthedoc
Unknown
GeoStat Framework Release 1.0 Jul 04, 2021 Contents 1.1 GSTool... 3 1.2 PyKrig... 3 1.3 ogs5p... 4 1.4 WellTestP... 4 1.5 AnaFlo... 5 1.6 pentap... 5 i ii GeoStat Framework, Release 1.0 Create your geo-statistical model with Python! GeoStat Framework, Release 1.0 2 Contents CHAPTER 1 Included Packages The following Python-Packages are part of the GeoStat Framework. 1.1 GSTools GeoStatTools is a library providing geostatistical tools like kriging, random field generation, variogram estimation, covariance models and much more. Version Installation pip install gstools or conda install gstools Source https://github.com/GeoStat-Framework/GSTools Documentation https://gstools.readthedocs.io 1.2 PyKrige PyKrige provides 2D and 3D ordinary and universal kriging. GeoStat Framework, Release 1.0 Version Installation pip install PyKrige or conda install pykrige Source https://github.com/GeoStat-Framework/PyKrige Documentation https://pykrige.readthedocs.io 1.3 ogs5py ogs5py is a Python-API for the OpenGeoSys 5 scientific modeling package. Version Installation pip install ogs5py or conda install ogs5py Source https://github.com/GeoStat-Framework/ogs5py Documentation https://ogs5py.readthedocs.io 1.4 WellTestPy WellTestPy is a python-package for handling well based field campaigns. GeoStat Framework, Release 1.0 Version Installation pip install welltestpy Source https://github.com/GeoStat-Framework/welltestpy Documentation https://welltestpy.readthedocs.io 1.5 AnaFlow Anaflow provides several analytical and semi-analytical solutions for the groundwater-flow-equation. Version Installation pip install anaflow Source https://github.com/GeoStat-Framework/AnaFlow Documentation https://anaflow.readthedocs.io 1.6 pentapy pentapy is a toolbox to deal with pentadiagonal matrices in Python. GeoStat Framework, Release 1.0 Version Installation pip install pentapy Source https://github.com/GeoStat-Framework/pentapy Documentation https://pentapy.readthedocs.io
git-object
rust
Rust
Crate git_object === This crate provides types for read-only git objects backed by bytes provided in git’s serialization format as well as mutable versions of these. Both types of objects can be encoded. ### Feature Flags * **`serde1`** — Data structures implement `serde::Serialize` and `serde::Deserialize`. * **`verbose-object-parsing-errors`** — When parsing objects by default errors will only be available on the granularity of success or failure, and with the above flag enabled details information about the error location will be collected. Use it in applications which expect broken or invalid objects or for debugging purposes. Incorrectly formatted objects aren’t at all common otherwise. Re-exports --- `pub use bstr;`Modules --- commitdataContains a borrowed Object bound to a buffer holding its decompressed data.decodeencodeEncoding utilitieskindtagtreeStructs --- BlobA mutable chunk of any `data`.BlobRefA chunk of any `data`.CommitA mutable git commit, representing an annotated state of a working tree along with a reference to its historical commits.CommitRefA git commit parsed using `from_bytes()`.CommitRefIterLike `CommitRef`, but as `Iterator` to support (up to) entirely allocation free parsing. It’s particularly useful to traverse the commit graph without ever allocating arrays for parents.DataA borrowed object using a slice as backing buffer, or in other words a bytes buffer that knows the kind of object it represents.TagA mutable git tag.TagRefRepresents a git tag, commonly indicating a software release.TagRefIterLike `TagRef`, but as `Iterator` to support entirely allocation free parsing. It’s particularly useful to dereference only the target chain.TreeA mutable Tree, containing other trees, blobs or commits.TreeRefA directory snapshot containing files (blobs), directories (trees) and submodules (commits).TreeRefIterA directory snapshot containing files (blobs), directories (trees) and submodules (commits), lazily evaluated.Enums --- KindThe four types of objects that git differentiates. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]ObjectMutable objects with each field being separately allocated and changeable.ObjectRefImmutable objects are read-only structures referencing most data from a byte slice.Traits --- WriteToWriting of objects to a `Write` implementation Crate git_object === This crate provides types for read-only git objects backed by bytes provided in git’s serialization format as well as mutable versions of these. Both types of objects can be encoded. ### Feature Flags * **`serde1`** — Data structures implement `serde::Serialize` and `serde::Deserialize`. * **`verbose-object-parsing-errors`** — When parsing objects by default errors will only be available on the granularity of success or failure, and with the above flag enabled details information about the error location will be collected. Use it in applications which expect broken or invalid objects or for debugging purposes. Incorrectly formatted objects aren’t at all common otherwise. Re-exports --- `pub use bstr;`Modules --- commitdataContains a borrowed Object bound to a buffer holding its decompressed data.decodeencodeEncoding utilitieskindtagtreeStructs --- BlobA mutable chunk of any `data`.BlobRefA chunk of any `data`.CommitA mutable git commit, representing an annotated state of a working tree along with a reference to its historical commits.CommitRefA git commit parsed using `from_bytes()`.CommitRefIterLike `CommitRef`, but as `Iterator` to support (up to) entirely allocation free parsing. It’s particularly useful to traverse the commit graph without ever allocating arrays for parents.DataA borrowed object using a slice as backing buffer, or in other words a bytes buffer that knows the kind of object it represents.TagA mutable git tag.TagRefRepresents a git tag, commonly indicating a software release.TagRefIterLike `TagRef`, but as `Iterator` to support entirely allocation free parsing. It’s particularly useful to dereference only the target chain.TreeA mutable Tree, containing other trees, blobs or commits.TreeRefA directory snapshot containing files (blobs), directories (trees) and submodules (commits).TreeRefIterA directory snapshot containing files (blobs), directories (trees) and submodules (commits), lazily evaluated.Enums --- KindThe four types of objects that git differentiates. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]ObjectMutable objects with each field being separately allocated and changeable.ObjectRefImmutable objects are read-only structures referencing most data from a byte slice.Traits --- WriteToWriting of objects to a `Write` implementation Enum git_object::ObjectRef === ``` pub enum ObjectRef<'a> { Tree(TreeRef<'a>), Blob(BlobRef<'a>), Commit(CommitRef<'a>), Tag(TagRef<'a>), } ``` Immutable objects are read-only structures referencing most data from a byte slice. Immutable objects are expected to be deserialized from bytes that acts as backing store, and they cannot be mutated or serialized. Instead, one will convert them into their `mutable` counterparts which support mutation and serialization. An `ObjectRef` is representing `Trees`, `Blobs`, `Commits`, or `Tags`. Variants --- ### Tree(TreeRef<'a>) ### Blob(BlobRef<'a>) ### Commit(CommitRef<'a>) ### Tag(TagRef<'a>) Implementations --- ### impl<'a> ObjectRef<'a#### pub fn from_loose(data: &'a [u8]) -> Result<ObjectRef<'a>, LooseDecodeErrorDeserialize an object from a loose serialisation #### pub fn from_bytes(kind: Kind, data: &'a [u8]) -> Result<ObjectRef<'a>, ErrorDeserialize an object of `kind` from the given `data`. #### pub fn into_owned(self) -> Object Convert the immutable object into a mutable version, consuming the source in the process. Note that this is an expensive operation. #### pub fn to_owned(&self) -> Object Convert this immutable object into its mutable counterpart. Note that this is an expensive operation. ### impl<'a> ObjectRef<'aConvenient access to contained objects. #### pub fn as_blob(&self) -> Option<&BlobRef<'a>Interpret this object as blob. #### pub fn into_blob(self) -> Option<BlobRef<'a>Interpret this object as blob, chainable. #### pub fn as_commit(&self) -> Option<&CommitRef<'a>Interpret this object as commit. #### pub fn into_commit(self) -> Option<CommitRef<'a>Interpret this object as commit, chainable. #### pub fn as_tree(&self) -> Option<&TreeRef<'a>Interpret this object as tree. #### pub fn into_tree(self) -> Option<TreeRef<'a>Interpret this object as tree, chainable #### pub fn as_tag(&self) -> Option<&TagRef<'a>Interpret this object as tag. #### pub fn into_tag(self) -> Option<TagRef<'a>Interpret this object as tag, chainable. #### pub fn kind(&self) -> Kind Return the kind of object. Trait Implementations --- ### impl<'a> Clone for ObjectRef<'a#### fn clone(&self) -> ObjectRef<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. Converts to this type from the input type.### impl<'a> From<CommitRef<'a>> for ObjectRef<'a#### fn from(v: CommitRef<'a>) -> Self Converts to this type from the input type.### impl<'a> From<ObjectRef<'a>> for Object #### fn from(v: ObjectRef<'_>) -> Self Converts to this type from the input type.### impl<'a> From<TagRef<'a>> for ObjectRef<'a#### fn from(v: TagRef<'a>) -> Self Converts to this type from the input type.### impl<'a> From<TreeRef<'a>> for ObjectRef<'a#### fn from(v: TreeRef<'a>) -> Self Converts to this type from the input type.### impl<'a> Hash for ObjectRef<'a#### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> PartialOrd<ObjectRef<'a>> for ObjectRef<'a#### fn partial_cmp(&self, other: &ObjectRef<'a>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. __S: Serializer, Serialize this value into the given Serde serializer. #### fn write_to(&self, out: impl Write) -> Result<()Write the contained object to `out` in the git serialization format. #### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). Returns the type of this object.#### fn loose_header(&self) -> SmallVec<[u8; 28]Returns a loose object header based on the object’s data### impl<'a> Eq for ObjectRef<'a### impl<'a> StructuralEq for ObjectRef<'a### impl<'a> StructuralPartialEq for ObjectRef<'aAuto Trait Implementations --- ### impl<'a> RefUnwindSafe for ObjectRef<'a### impl<'a> Send for ObjectRef<'a### impl<'a> Sync for ObjectRef<'a### impl<'a> Unpin for ObjectRef<'a### impl<'a> UnwindSafe for ObjectRef<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Enum git_object::Object === ``` pub enum Object { Tree(Tree), Blob(Blob), Commit(Commit), Tag(Tag), } ``` Mutable objects with each field being separately allocated and changeable. Mutable objects are Commits, Trees, Blobs and Tags that can be changed and serialized. They either created using object construction or by deserializing existing objects and converting these into mutable copies for adjustments. An `Object` is representing `Trees`, `Blobs`, `Commits` or `Tags`. Variants --- ### Tree(Tree) ### Blob(Blob) ### Commit(Commit) ### Tag(Tag) Implementations --- ### impl Object Convenient extraction of typed object. #### pub fn into_blob(self) -> Blob Turns this instance into a `Blob`, panic otherwise. #### pub fn into_commit(self) -> Commit Turns this instance into a `Commit` panic otherwise. #### pub fn into_tree(self) -> Tree Turns this instance into a `Tree` panic otherwise. #### pub fn into_tag(self) -> Tag Turns this instance into a `Tag` panic otherwise. #### pub fn try_into_blob(self) -> Result<Blob, SelfTurns this instance into a `Blob` if it is one. #### pub fn try_into_blob_ref(&self) -> Option<BlobRef<'_>Turns this instance into a `BlobRef` if it is a blob. #### pub fn try_into_commit(self) -> Result<Commit, SelfTurns this instance into a `Commit` if it is one. #### pub fn try_into_tree(self) -> Result<Tree, SelfTurns this instance into a `Tree` if it is one. #### pub fn try_into_tag(self) -> Result<Tag, SelfTurns this instance into a `Tag` if it is one. #### pub fn as_blob(&self) -> Option<&BlobReturns a `Blob` if it is one. #### pub fn as_commit(&self) -> Option<&CommitReturns a `Commit` if it is one. #### pub fn as_tree(&self) -> Option<&TreeReturns a `Tree` if it is one. #### pub fn as_tag(&self) -> Option<&TagReturns a `Tag` if it is one. #### pub fn kind(&self) -> Kind Returns the kind of object stored in this instance. Trait Implementations --- ### impl Clone for Object #### fn clone(&self) -> Object Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(v: Blob) -> Self Converts to this type from the input type.### impl From<Commit> for Object #### fn from(v: Commit) -> Self Converts to this type from the input type.### impl<'a> From<ObjectRef<'a>> for Object #### fn from(v: ObjectRef<'_>) -> Self Converts to this type from the input type.### impl From<Tag> for Object #### fn from(v: Tag) -> Self Converts to this type from the input type.### impl From<Tree> for Object #### fn from(v: Tree) -> Self Converts to this type from the input type.### impl Hash for Object #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Object) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Object) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Object> for Object #### fn partial_cmp(&self, other: &Object) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl TryFrom<Object> for Commit #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl TryFrom<Object> for Tag #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl TryFrom<Object> for Tree #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl WriteTo for Object Serialization #### fn write_to(&self, out: impl Write) -> Result<()Write the contained object to `out` in the git serialization format. #### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). Returns the type of this object.#### fn loose_header(&self) -> SmallVec<[u8; 28]Returns a loose object header based on the object’s data### impl Eq for Object ### impl StructuralEq for Object ### impl StructuralPartialEq for Object Auto Trait Implementations --- ### impl RefUnwindSafe for Object ### impl Send for Object ### impl Sync for Object ### impl Unpin for Object ### impl UnwindSafe for Object Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Module git_object::commit === Modules --- messageref_iterStructs --- ExtraHeadersAn iterator over extra headers in owned and borrowed commits.MessageRefA parsed commit message that assumes a title separated from the body by two consecutive newlines. Module git_object::data === Contains a borrowed Object bound to a buffer holding its decompressed data. Modules --- verifyTypes supporting object hash verification Module git_object::decode === Structs --- Error`verbose-object-parsing-errors`A type to indicate errors during parsing and to abstract away details related to `nom`.Enums --- LooseHeaderDecodeErrorReturned by `loose_header()`Functions --- loose_headerDecode a loose object header, being `<kind> <size>\0`, returns (`kind`, `size`, `consumed bytes`).Type Definitions --- ParseError`verbose-object-parsing-errors`The type to be used for parse errors.ParseErrorOwned`verbose-object-parsing-errors`The owned type to be used for parse errors. Module git_object::encode === Encoding utilities Enums --- ErrorAn error returned when object encoding fails.Functions --- loose_headerGenerates a loose header buffer Module git_object::kind === Enums --- ErrorThe Error used in `Kind::from_bytes()`. Module git_object::tag === Modules --- ref_iterwrite Module git_object::tree === Modules --- writeStructs --- EntryAn entry in a `Tree`, similar to an entry in a directory.EntryRefAn element of a `TreeRef`.Enums --- EntryModeThe mode of items storable in a tree, similar to the file mode on a unix file system. Struct git_object::Blob === ``` pub struct Blob { pub data: Vec<u8>, } ``` A mutable chunk of any `data`. Fields --- `data: Vec<u8>`The data itself. Implementations --- ### impl Blob #### pub fn to_ref(&self) -> BlobRef<'_Provide a `BlobRef` to this owned blob Trait Implementations --- ### impl Clone for Blob #### fn clone(&self) -> Blob Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(v: Blob) -> Self Converts to this type from the input type.### impl<'a> From<BlobRef<'a>> for Blob #### fn from(v: BlobRef<'a>) -> Self Converts to this type from the input type.### impl Hash for Blob #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Blob) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Blob) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Blob> for Blob #### fn partial_cmp(&self, other: &Blob) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl WriteTo for Blob #### fn write_to(&self, out: impl Write) -> Result<()Write the blobs data to `out` verbatim. #### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). Returns the type of this object.#### fn loose_header(&self) -> SmallVec<[u8; 28]Returns a loose object header based on the object’s data### impl Eq for Blob ### impl StructuralEq for Blob ### impl StructuralPartialEq for Blob Auto Trait Implementations --- ### impl RefUnwindSafe for Blob ### impl Send for Blob ### impl Sync for Blob ### impl Unpin for Blob ### impl UnwindSafe for Blob Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_object::BlobRef === ``` pub struct BlobRef<'a> { pub data: &'a [u8], } ``` A chunk of any `data`. Fields --- `data: &'a [u8]`The bytes themselves. Implementations --- ### impl<'a> BlobRef<'a#### pub fn from_bytes(data: &[u8]) -> Result<BlobRef<'_>, InfallibleInstantiate a `Blob` from the given `data`, which is used as-is. Trait Implementations --- ### impl<'a> Clone for BlobRef<'a#### fn clone(&self) -> BlobRef<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(v: BlobRef<'a>) -> Self Converts to this type from the input type.### impl<'a> From<BlobRef<'a>> for ObjectRef<'a#### fn from(v: BlobRef<'a>) -> Self Converts to this type from the input type.### impl<'a> Hash for BlobRef<'a#### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> PartialOrd<BlobRef<'a>> for BlobRef<'a#### fn partial_cmp(&self, other: &BlobRef<'a>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. __S: Serializer, Serialize this value into the given Serde serializer. #### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). Returns the type of this object.#### fn loose_header(&self) -> SmallVec<[u8; 28]Returns a loose object header based on the object’s data### impl<'a> Eq for BlobRef<'a### impl<'a> StructuralEq for BlobRef<'a### impl<'a> StructuralPartialEq for BlobRef<'aAuto Trait Implementations --- ### impl<'a> RefUnwindSafe for BlobRef<'a### impl<'a> Send for BlobRef<'a### impl<'a> Sync for BlobRef<'a### impl<'a> Unpin for BlobRef<'a### impl<'a> UnwindSafe for BlobRef<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_object::Commit === ``` pub struct Commit { pub tree: ObjectId, pub parents: SmallVec<[ObjectId; 1]>, pub author: Signature, pub committer: Signature, pub encoding: Option<BString>, pub message: BString, pub extra_headers: Vec<(BString, BString)>, } ``` A mutable git commit, representing an annotated state of a working tree along with a reference to its historical commits. Fields --- `tree: ObjectId`The hash of recorded working tree state. `parents: SmallVec<[ObjectId; 1]>`Hash of each parent commit. Empty for the first commit in repository. `author: Signature`Who wrote this commit. `committer: Signature`Who committed this commit. This may be different from the `author` in case the author couldn’t write to the repository themselves and is commonly encountered with contributed commits. `encoding: Option<BString>`The name of the message encoding, otherwise UTF-8 should be assumed. `message: BString`The commit message documenting the change. `extra_headers: Vec<(BString, BString)>`Extra header fields, in order of them being encountered, made accessible with the iterator returned by `extra_headers()`. Implementations --- ### impl Commit #### pub fn extra_headers( &self ) -> ExtraHeaders<impl Iterator<Item = (&BStr, &BStr)>Returns a convenient iterator over all extra headers. Trait Implementations --- ### impl Clone for Commit #### fn clone(&self) -> Commit Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(v: Commit) -> Self Converts to this type from the input type.### impl From<CommitRef<'_>> for Commit #### fn from(other: CommitRef<'_>) -> Commit Converts to this type from the input type.### impl Hash for Commit #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Commit) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Commit) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Commit> for Commit #### fn partial_cmp(&self, other: &Commit) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl WriteTo for Commit #### fn write_to(&self, out: impl Write) -> Result<()Serializes this instance to `out` in the git serialization format. #### fn kind(&self) -> Kind Returns the type of this object.#### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). ### impl StructuralEq for Commit ### impl StructuralPartialEq for Commit Auto Trait Implementations --- ### impl RefUnwindSafe for Commit ### impl Send for Commit ### impl Sync for Commit ### impl Unpin for Commit ### impl UnwindSafe for Commit Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_object::CommitRef === ``` pub struct CommitRef<'a> { pub tree: &'a BStr, pub parents: SmallVec<[&'a BStr; 1]>, pub author: SignatureRef<'a>, pub committer: SignatureRef<'a>, pub encoding: Option<&'a BStr>, pub message: &'a BStr, pub extra_headers: Vec<(&'a BStr, Cow<'a, BStr>)>, } ``` A git commit parsed using `from_bytes()`. A commit encapsulates information about a point in time at which the state of the repository is recorded, usually after a change which is documented in the commit `message`. Fields --- `tree: &'a BStr`HEX hash of tree object we point to. Usually 40 bytes long. Use `tree()` to obtain a decoded version of it. `parents: SmallVec<[&'a BStr; 1]>`HEX hash of each parent commit. Empty for first commit in repository. `author: SignatureRef<'a>`Who wrote this commit. Name and email might contain whitespace and are not trimmed to ensure round-tripping. Use the `author()` method to received a trimmed version of it. `committer: SignatureRef<'a>`Who committed this commit. Name and email might contain whitespace and are not trimmed to ensure round-tripping. Use the `committer()` method to received a trimmed version of it. This may be different from the `author` in case the author couldn’t write to the repository themselves and is commonly encountered with contributed commits. `encoding: Option<&'a BStr>`The name of the message encoding, otherwise UTF-8 should be assumed. `message: &'a BStr`The commit message documenting the change. `extra_headers: Vec<(&'a BStr, Cow<'a, BStr>)>`Extra header fields, in order of them being encountered, made accessible with the iterator returned by `extra_headers()`. Implementations --- ### impl<'a> CommitRef<'a#### pub fn message_summary(&self) -> Cow<'a, BStrReturn exactly the same message as `MessageRef::summary()`. #### pub fn message_trailers(&self) -> Trailers<'aReturn an iterator over message trailers as obtained from the last paragraph of the commit message. May be empty. ### impl<'a> CommitRef<'a#### pub fn from_bytes(data: &'a [u8]) -> Result<CommitRef<'a>, ErrorDeserialize a commit from the given `data` bytes while avoiding most allocations. #### pub fn tree(&self) -> ObjectId Return the `tree` fields hash digest. #### pub fn parents(&self) -> impl Iterator<Item = ObjectId> + '_ Returns an iterator of parent object ids #### pub fn extra_headers( &self ) -> ExtraHeaders<impl Iterator<Item = (&BStr, &BStr)>Returns a convenient iterator over all extra headers. #### pub fn author(&self) -> SignatureRef<'aReturn the author, with whitespace trimmed. This is different from the `author` field which may contain whitespace. #### pub fn committer(&self) -> SignatureRef<'aReturn the committer, with whitespace trimmed. This is different from the `committer` field which may contain whitespace. #### pub fn message(&self) -> MessageRef<'aReturns a partially parsed message from which more information can be derived. #### pub fn time(&self) -> Time Returns the time at which this commit was created. Trait Implementations --- ### impl<'a> Clone for CommitRef<'a#### fn clone(&self) -> CommitRef<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(other: CommitRef<'_>) -> Commit Converts to this type from the input type.### impl<'a> From<CommitRef<'a>> for ObjectRef<'a#### fn from(v: CommitRef<'a>) -> Self Converts to this type from the input type.### impl<'a> Hash for CommitRef<'a#### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> PartialOrd<CommitRef<'a>> for CommitRef<'a#### fn partial_cmp(&self, other: &CommitRef<'a>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. __S: Serializer, Serialize this value into the given Serde serializer. #### fn kind(&self) -> Kind Returns the type of this object.#### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). --- ### impl<'a> RefUnwindSafe for CommitRef<'a### impl<'a> Send for CommitRef<'a### impl<'a> Sync for CommitRef<'a### impl<'a> Unpin for CommitRef<'a### impl<'a> UnwindSafe for CommitRef<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, {"Trailers<'a>":"<h3>Notable traits for <code><a class=\"struct\" href=\"commit/message/body/struct.Trailers.html\" title=\"struct git_object::commit::message::body::Trailers\">Trailers</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"commit/message/body/struct.Trailers.html\" title=\"struct git_object::commit::message::body::Trailers\">Trailers</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"struct\" href=\"commit/message/body/struct.TrailerRef.html\" title=\"struct git_object::commit::message::body::TrailerRef\">TrailerRef</a>&lt;'a&gt;;</span>"} Struct git_object::CommitRefIter === ``` pub struct CommitRefIter<'a> { /* private fields */ } ``` Like `CommitRef`, but as `Iterator` to support (up to) entirely allocation free parsing. It’s particularly useful to traverse the commit graph without ever allocating arrays for parents. Implementations --- ### impl<'a> CommitRefIter<'a#### pub fn from_bytes(data: &'a [u8]) -> CommitRefIter<'aCreate a commit iterator from data. #### pub fn tree_id(&mut self) -> Result<ObjectId, ErrorReturns the object id of this commits tree if it is the first function called and if there is no error in decoding the data. Note that this method must only be called once or else will always return None while consuming a single token. Errors are coerced into options, hiding whether there was an error or not. The caller should assume an error if they call the method as intended. Such a squelched error cannot be recovered unless the objects data is retrieved and parsed again. `next()`. #### pub fn parent_ids(self) -> impl Iterator<Item = ObjectId> + 'a Return all parent_ids as iterator. Parsing errors are ignored quietly. #### pub fn signatures(self) -> impl Iterator<Item = SignatureRef<'a>> + 'a Returns all signatures, first the author, then the committer, if there is no decoding error. Errors are coerced into options, hiding whether there was an error or not. The caller knows if there was an error or not if not exactly two signatures were iterable. Errors are not the common case - if an error needs to be detectable, use this instance as iterator. #### pub fn committer(self) -> Result<SignatureRef<'a>, ErrorReturns the committer signature if there is no decoding error. #### pub fn author(self) -> Result<SignatureRef<'a>, ErrorReturns the author signature if there is no decoding error. It may contain white space surrounding it, and is exactly as parsed. #### pub fn message(self) -> Result<&'a BStr, ErrorReturns the message if there is no decoding error. It may contain white space surrounding it, and is exactly as Trait Implementations --- ### impl<'a> Clone for CommitRefIter<'a#### fn clone(&self) -> CommitRefIter<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. &mut self ) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where Self: Sized, 🔬This is a nightly-only experimental API. (`iter_next_chunk`)Advances the iterator and returns an array containing the next `N` values. Read more1.0.0 · source#### fn size_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. Read more1.0.0 · source#### fn count(self) -> usizewhere Self: Sized, Consumes the iterator, counting the number of iterations and returning it. Read more1.0.0 · source#### fn last(self) -> Option<Self::Item>where Self: Sized, Consumes the iterator, returning the last element. Self: Sized, Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more1.0.0 · source#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where Self: Sized, U: IntoIterator<Item = Self::Item>, Takes two iterators and creates a new iterator over both in sequence. Read more1.0.0 · source#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where Self: Sized, U: IntoIterator, ‘Zips up’ two iterators into a single iterator of pairs. Self: Sized, G: FnMut() -> Self::Item, 🔬This is a nightly-only experimental API. (`iter_intersperse`)Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. Read more1.0.0 · source#### fn map<B, F>(self, f: F) -> Map<Self, F>where Self: Sized, F: FnMut(Self::Item) -> B, Takes a closure and creates an iterator which calls that closure on each element. Read more1.21.0 · source#### fn for_each<F>(self, f: F)where Self: Sized, F: FnMut(Self::Item), Calls a closure on each element of an iterator. Read more1.0.0 · source#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator which uses a closure to determine if an element should be yielded. Read more1.0.0 · source#### fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Creates an iterator that both filters and maps. Read more1.0.0 · source#### fn enumerate(self) -> Enumerate<Self>where Self: Sized, Creates an iterator which gives the current iteration count as well as the next value. Read more1.0.0 · source#### fn peekable(self) -> Peekable<Self>where Self: Sized, Creates an iterator which can use the `peek` and `peek_mut` methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more1.0.0 · source#### fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that `skip`s elements based on a predicate. Read more1.0.0 · source#### fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that yields elements based on a predicate. Read more1.57.0 · source#### fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where Self: Sized, P: FnMut(Self::Item) -> Option<B>, Creates an iterator that both yields elements based on a predicate and maps. Read more1.0.0 · source#### fn skip(self, n: usize) -> Skip<Self>where Self: Sized, Creates an iterator that skips the first `n` elements. Read more1.0.0 · source#### fn take(self, n: usize) -> Take<Self>where Self: Sized, Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. Read more1.0.0 · source#### fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>, An iterator adapter which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. Read more1.0.0 · source#### fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, Creates an iterator that works like map, but flattens nested structure. Read more1.0.0 · source#### fn fuse(self) -> Fuse<Self>where Self: Sized, Creates an iterator which ends after the first `None`. Read more1.0.0 · source#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where Self: Sized, F: FnMut(&Self::Item), Does something with each element of an iterator, passing the value on. Read more1.0.0 · source#### fn by_ref(&mut self) -> &mut Selfwhere Self: Sized, Borrows an iterator, rather than consuming it. Read more1.0.0 · source#### fn collect<B>(self) -> Bwhere B: FromIterator<Self::Item>, Self: Sized, Transforms an iterator into a collection. E: Extend<Self::Item>, Self: Sized, 🔬This is a nightly-only experimental API. (`iter_collect_into`)Collects all the items from an iterator into a collection. Read more1.0.0 · source#### fn partition<B, F>(self, f: F) -> (B, B)where Self: Sized, B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool, Consumes an iterator, creating two collections from it. Self: Sized, P: FnMut(Self::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_is_partitioned`)Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. Read more1.27.0 · source#### fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more1.27.0 · source#### fn try_for_each<F, R>(&mut self, f: F) -> Rwhere Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Output = ()>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more1.0.0 · source#### fn fold<B, F>(self, init: B, f: F) -> Bwhere Self: Sized, F: FnMut(B, Self::Item) -> B, Folds every element into an accumulator by applying an operation, returning the final result. Read more1.51.0 · source#### fn reduce<F>(self, f: F) -> Option<Self::Item>where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item, Reduces the elements to a single one, by repeatedly applying a reducing operation. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere Self: Sized, F: FnMut(Self::Item, Self::Item) -> R, R: Try<Output = Self::Item>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce`)Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more1.0.0 · source#### fn all<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if every element of the iterator matches a predicate. Read more1.0.0 · source#### fn any<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if any element of the iterator matches a predicate. Read more1.0.0 · source#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where Self: Sized, P: FnMut(&Self::Item) -> bool, Searches for an element of an iterator that satisfies a predicate. Read more1.30.0 · source#### fn find_map<B, F>(&mut self, f: F) -> Option<B>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Applies function to the elements of iterator and returns the first non-none result. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere Self: Sized, F: FnMut(&Self::Item) -> R, R: Try<Output = bool>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`try_find`)Applies function to the elements of iterator and returns the first true result or the first error. Read more1.0.0 · source#### fn position<P>(&mut self, predicate: P) -> Option<usize>where Self: Sized, P: FnMut(Self::Item) -> bool, Searches for an element in an iterator, returning its index. Read more1.6.0 · source#### fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the maximum value from the specified function. Read more1.15.0 · source#### fn max_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the maximum value with respect to the specified comparison function. Read more1.6.0 · source#### fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the minimum value from the specified function. Read more1.15.0 · source#### fn min_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the minimum value with respect to the specified comparison function. Read more1.0.0 · source#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Iterator<Item = (A, B)>, Converts an iterator of pairs into a pair of containers. Read more1.36.0 · source#### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + Copy, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which copies all of its elements. Read more1.0.0 · source#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + Clone, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which `clone`s all of its elements. Read more1.0.0 · source#### fn cycle(self) -> Cycle<Self>where Self: Sized + Clone, Repeats an iterator endlessly. Self: Sized, 🔬This is a nightly-only experimental API. (`iter_array_chunks`)Returns an iterator over `N` elements of the iterator at a time. Read more1.11.0 · source#### fn sum<S>(self) -> Swhere Self: Sized, S: Sum<Self::Item>, Sums the elements of an iterator. Read more1.11.0 · source#### fn product<P>(self) -> Pwhere Self: Sized, P: Product<Self::Item>, Iterates over the entire iterator, multiplying all the elements Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn partial_cmp<I>(self, other: I) -> Option<Ordering>where I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Lexicographically compares the elements of this `Iterator` with those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn eq<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are equal to those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_order_by`)Determines if the elements of this `Iterator` are equal to those of another with respect to the specified equality function. Read more1.5.0 · source#### fn ne<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are unequal to those of another. Read more1.5.0 · source#### fn lt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less than those of another. Read more1.5.0 · source#### fn le<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less or equal to those of another. Read more1.5.0 · source#### fn gt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than those of another. Read more1.5.0 · source#### fn ge<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than or equal to those of another. Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given comparator function. Self: Sized, F: FnMut(Self::Item) -> K, K: PartialOrd<K>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given key extraction function. --- ### impl<'a> RefUnwindSafe for CommitRefIter<'a### impl<'a> Send for CommitRefIter<'a### impl<'a> Sync for CommitRefIter<'a### impl<'a> Unpin for CommitRefIter<'a### impl<'a> UnwindSafe for CommitRefIter<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<I> IntoIterator for Iwhere I: Iterator, #### type Item = <I as Iterator>::Item The type of the elements being iterated over.#### type IntoIter = I Which kind of iterator are we turning this into?const: unstable · source#### fn into_iter(self) -> I Creates an iterator from a value. T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"CommitRefIter<'a>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.CommitRefIter.html\" title=\"struct git_object::CommitRefIter\">CommitRefIter</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"struct.CommitRefIter.html\" title=\"struct git_object::CommitRefIter\">CommitRefIter</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/result/enum.Result.html\" title=\"enum core::result::Result\">Result</a>&lt;<a class=\"enum\" href=\"commit/ref_iter/enum.Token.html\" title=\"enum git_object::commit::ref_iter::Token\">Token</a>&lt;'a&gt;, <a class=\"struct\" href=\"decode/struct.Error.html\" title=\"struct git_object::decode::Error\">Error</a>&gt;;</span>"} Struct git_object::Data === ``` pub struct Data<'a> { pub kind: Kind, pub data: &'a [u8], } ``` A borrowed object using a slice as backing buffer, or in other words a bytes buffer that knows the kind of object it represents. Fields --- `kind: Kind`kind of object `data: &'a [u8]`decoded, decompressed data, owned by a backing store. Implementations --- ### impl Data<'_#### pub fn verify_checksum(&self, desired: impl AsRef<oid>) -> Result<(), ErrorCompute the checksum of `self` and compare it with the `desired` hash. If the hashes do not match, an `Error` is returned, containing the actual hash of `self`. ### impl<'a> Data<'a#### pub fn new(kind: Kind, data: &'a [u8]) -> Data<'aConstructs a new data object from `kind` and `data`. #### pub fn decode(&self) -> Result<ObjectRef<'a>, ErrorDecodes the data in the backing slice into a `ObjectRef`, allowing to access all of its data conveniently. The cost of parsing an object is negligible. **Note** that mutable, decoded objects can be created from `Data` using `crate::ObjectRef::into_owned()`. #### pub fn try_into_tree_iter(self) -> Option<TreeRefIter<'a>Returns this object as tree iterator to parse entries one at a time to avoid allocations, or `None` if this is not a tree object. #### pub fn try_into_commit_iter(self) -> Option<CommitRefIter<'a>Returns this object as commit iterator to parse tokens one at a time to avoid allocations, or `None` if this is not a commit object. #### pub fn try_into_tag_iter(self) -> Option<TagRefIter<'a>Returns this object as tag iterator to parse tokens one at a time to avoid allocations, or `None` if this is not a tag object. Trait Implementations --- ### impl<'a> Clone for Data<'a#### fn clone(&self) -> Data<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> PartialOrd<Data<'a>> for Data<'a#### fn partial_cmp(&self, other: &Data<'a>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. --- ### impl<'a> RefUnwindSafe for Data<'a### impl<'a> Send for Data<'a### impl<'a> Sync for Data<'a### impl<'a> Unpin for Data<'a### impl<'a> UnwindSafe for Data<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct git_object::Tag === ``` pub struct Tag { pub target: ObjectId, pub target_kind: Kind, pub name: BString, pub tagger: Option<Signature>, pub message: BString, pub pgp_signature: Option<BString>, } ``` A mutable git tag. Fields --- `target: ObjectId`The hash this tag is pointing to. `target_kind: Kind`The kind of object this tag is pointing to. `name: BString`The name of the tag, e.g. “v1.0”. `tagger: Option<Signature>`The tags author. `message: BString`The message describing the tag. `pgp_signature: Option<BString>`A pgp signature over all bytes of the encoded tag, excluding the pgp signature itself. Trait Implementations --- ### impl Clone for Tag #### fn clone(&self) -> Tag Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(v: Tag) -> Self Converts to this type from the input type.### impl From<TagRef<'_>> for Tag #### fn from(other: TagRef<'_>) -> Tag Converts to this type from the input type.### impl Hash for Tag #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Tag) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Tag) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Tag> for Tag #### fn partial_cmp(&self, other: &Tag) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl WriteTo for Tag #### fn write_to(&self, out: impl Write) -> Result<()Write a representation of this instance to `out`.#### fn kind(&self) -> Kind Returns the type of this object.#### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). ### impl StructuralEq for Tag ### impl StructuralPartialEq for Tag Auto Trait Implementations --- ### impl RefUnwindSafe for Tag ### impl Send for Tag ### impl Sync for Tag ### impl Unpin for Tag ### impl UnwindSafe for Tag Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_object::TagRef === ``` pub struct TagRef<'a> { pub target: &'a BStr, pub target_kind: Kind, pub name: &'a BStr, pub tagger: Option<SignatureRef<'a>>, pub message: &'a BStr, pub pgp_signature: Option<&'a BStr>, } ``` Represents a git tag, commonly indicating a software release. Fields --- `target: &'a BStr`The hash in hexadecimal being the object this tag points to. Use `target()` to obtain a byte representation. `target_kind: Kind`The kind of object that `target` points to. `name: &'a BStr`The name of the tag, e.g. “v1.0”. `tagger: Option<SignatureRef<'a>>`The author of the tag. `message: &'a BStr`The message describing this release. `pgp_signature: Option<&'a BStr>`A cryptographic signature over the entire content of the serialized tag object thus far. Implementations --- ### impl<'a> TagRef<'a#### pub fn from_bytes(data: &'a [u8]) -> Result<TagRef<'a>, ErrorDeserialize a tag from `data`. #### pub fn target(&self) -> ObjectId The object this tag points to as `Id`. Trait Implementations --- ### impl<'a> Clone for TagRef<'a#### fn clone(&self) -> TagRef<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(other: TagRef<'_>) -> Tag Converts to this type from the input type.### impl<'a> From<TagRef<'a>> for ObjectRef<'a#### fn from(v: TagRef<'a>) -> Self Converts to this type from the input type.### impl<'a> Hash for TagRef<'a#### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> PartialOrd<TagRef<'a>> for TagRef<'a#### fn partial_cmp(&self, other: &TagRef<'a>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. __S: Serializer, Serialize this value into the given Serde serializer. Returns the type of this object.#### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). --- ### impl<'a> RefUnwindSafe for TagRef<'a### impl<'a> Send for TagRef<'a### impl<'a> Sync for TagRef<'a### impl<'a> Unpin for TagRef<'a### impl<'a> UnwindSafe for TagRef<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_object::TagRefIter === ``` pub struct TagRefIter<'a> { /* private fields */ } ``` Like `TagRef`, but as `Iterator` to support entirely allocation free parsing. It’s particularly useful to dereference only the target chain. Implementations --- ### impl<'a> TagRefIter<'a#### pub fn from_bytes(data: &'a [u8]) -> TagRefIter<'aCreate a tag iterator from data. #### pub fn target_id(self) -> Result<ObjectId, ErrorReturns the target id of this tag if it is the first function called and if there is no error in decoding the data. Note that this method must only be called once or else will always return None while consuming a single token. Errors are coerced into options, hiding whether there was an error or not. The caller should assume an error if they call the method as intended. Such a squelched error cannot be recovered unless the objects data is retrieved and parsed again. `next()`. #### pub fn tagger(self) -> Result<Option<SignatureRef<'a>>, ErrorReturns the taggers signature if there is no decoding error, and if this field exists. Errors are coerced into options, hiding whether there was an error or not. The caller knows if there was an error or not. Trait Implementations --- ### impl<'a> Clone for TagRefIter<'a#### fn clone(&self) -> TagRefIter<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. &mut self ) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where Self: Sized, 🔬This is a nightly-only experimental API. (`iter_next_chunk`)Advances the iterator and returns an array containing the next `N` values. Read more1.0.0 · source#### fn size_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. Read more1.0.0 · source#### fn count(self) -> usizewhere Self: Sized, Consumes the iterator, counting the number of iterations and returning it. Read more1.0.0 · source#### fn last(self) -> Option<Self::Item>where Self: Sized, Consumes the iterator, returning the last element. Self: Sized, Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more1.0.0 · source#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where Self: Sized, U: IntoIterator<Item = Self::Item>, Takes two iterators and creates a new iterator over both in sequence. Read more1.0.0 · source#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where Self: Sized, U: IntoIterator, ‘Zips up’ two iterators into a single iterator of pairs. Self: Sized, G: FnMut() -> Self::Item, 🔬This is a nightly-only experimental API. (`iter_intersperse`)Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. Read more1.0.0 · source#### fn map<B, F>(self, f: F) -> Map<Self, F>where Self: Sized, F: FnMut(Self::Item) -> B, Takes a closure and creates an iterator which calls that closure on each element. Read more1.21.0 · source#### fn for_each<F>(self, f: F)where Self: Sized, F: FnMut(Self::Item), Calls a closure on each element of an iterator. Read more1.0.0 · source#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator which uses a closure to determine if an element should be yielded. Read more1.0.0 · source#### fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Creates an iterator that both filters and maps. Read more1.0.0 · source#### fn enumerate(self) -> Enumerate<Self>where Self: Sized, Creates an iterator which gives the current iteration count as well as the next value. Read more1.0.0 · source#### fn peekable(self) -> Peekable<Self>where Self: Sized, Creates an iterator which can use the `peek` and `peek_mut` methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more1.0.0 · source#### fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that `skip`s elements based on a predicate. Read more1.0.0 · source#### fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that yields elements based on a predicate. Read more1.57.0 · source#### fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where Self: Sized, P: FnMut(Self::Item) -> Option<B>, Creates an iterator that both yields elements based on a predicate and maps. Read more1.0.0 · source#### fn skip(self, n: usize) -> Skip<Self>where Self: Sized, Creates an iterator that skips the first `n` elements. Read more1.0.0 · source#### fn take(self, n: usize) -> Take<Self>where Self: Sized, Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. Read more1.0.0 · source#### fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>, An iterator adapter which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. Read more1.0.0 · source#### fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, Creates an iterator that works like map, but flattens nested structure. Read more1.0.0 · source#### fn fuse(self) -> Fuse<Self>where Self: Sized, Creates an iterator which ends after the first `None`. Read more1.0.0 · source#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where Self: Sized, F: FnMut(&Self::Item), Does something with each element of an iterator, passing the value on. Read more1.0.0 · source#### fn by_ref(&mut self) -> &mut Selfwhere Self: Sized, Borrows an iterator, rather than consuming it. Read more1.0.0 · source#### fn collect<B>(self) -> Bwhere B: FromIterator<Self::Item>, Self: Sized, Transforms an iterator into a collection. E: Extend<Self::Item>, Self: Sized, 🔬This is a nightly-only experimental API. (`iter_collect_into`)Collects all the items from an iterator into a collection. Read more1.0.0 · source#### fn partition<B, F>(self, f: F) -> (B, B)where Self: Sized, B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool, Consumes an iterator, creating two collections from it. Self: Sized, P: FnMut(Self::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_is_partitioned`)Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. Read more1.27.0 · source#### fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more1.27.0 · source#### fn try_for_each<F, R>(&mut self, f: F) -> Rwhere Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Output = ()>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more1.0.0 · source#### fn fold<B, F>(self, init: B, f: F) -> Bwhere Self: Sized, F: FnMut(B, Self::Item) -> B, Folds every element into an accumulator by applying an operation, returning the final result. Read more1.51.0 · source#### fn reduce<F>(self, f: F) -> Option<Self::Item>where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item, Reduces the elements to a single one, by repeatedly applying a reducing operation. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere Self: Sized, F: FnMut(Self::Item, Self::Item) -> R, R: Try<Output = Self::Item>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce`)Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more1.0.0 · source#### fn all<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if every element of the iterator matches a predicate. Read more1.0.0 · source#### fn any<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if any element of the iterator matches a predicate. Read more1.0.0 · source#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where Self: Sized, P: FnMut(&Self::Item) -> bool, Searches for an element of an iterator that satisfies a predicate. Read more1.30.0 · source#### fn find_map<B, F>(&mut self, f: F) -> Option<B>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Applies function to the elements of iterator and returns the first non-none result. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere Self: Sized, F: FnMut(&Self::Item) -> R, R: Try<Output = bool>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`try_find`)Applies function to the elements of iterator and returns the first true result or the first error. Read more1.0.0 · source#### fn position<P>(&mut self, predicate: P) -> Option<usize>where Self: Sized, P: FnMut(Self::Item) -> bool, Searches for an element in an iterator, returning its index. Read more1.6.0 · source#### fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the maximum value from the specified function. Read more1.15.0 · source#### fn max_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the maximum value with respect to the specified comparison function. Read more1.6.0 · source#### fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the minimum value from the specified function. Read more1.15.0 · source#### fn min_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the minimum value with respect to the specified comparison function. Read more1.0.0 · source#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Iterator<Item = (A, B)>, Converts an iterator of pairs into a pair of containers. Read more1.36.0 · source#### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + Copy, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which copies all of its elements. Read more1.0.0 · source#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + Clone, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which `clone`s all of its elements. Read more1.0.0 · source#### fn cycle(self) -> Cycle<Self>where Self: Sized + Clone, Repeats an iterator endlessly. Self: Sized, 🔬This is a nightly-only experimental API. (`iter_array_chunks`)Returns an iterator over `N` elements of the iterator at a time. Read more1.11.0 · source#### fn sum<S>(self) -> Swhere Self: Sized, S: Sum<Self::Item>, Sums the elements of an iterator. Read more1.11.0 · source#### fn product<P>(self) -> Pwhere Self: Sized, P: Product<Self::Item>, Iterates over the entire iterator, multiplying all the elements Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn partial_cmp<I>(self, other: I) -> Option<Ordering>where I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Lexicographically compares the elements of this `Iterator` with those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn eq<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are equal to those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_order_by`)Determines if the elements of this `Iterator` are equal to those of another with respect to the specified equality function. Read more1.5.0 · source#### fn ne<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are unequal to those of another. Read more1.5.0 · source#### fn lt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less than those of another. Read more1.5.0 · source#### fn le<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less or equal to those of another. Read more1.5.0 · source#### fn gt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than those of another. Read more1.5.0 · source#### fn ge<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than or equal to those of another. Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given comparator function. Self: Sized, F: FnMut(Self::Item) -> K, K: PartialOrd<K>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given key extraction function. --- ### impl<'a> RefUnwindSafe for TagRefIter<'a### impl<'a> Send for TagRefIter<'a### impl<'a> Sync for TagRefIter<'a### impl<'a> Unpin for TagRefIter<'a### impl<'a> UnwindSafe for TagRefIter<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<I> IntoIterator for Iwhere I: Iterator, #### type Item = <I as Iterator>::Item The type of the elements being iterated over.#### type IntoIter = I Which kind of iterator are we turning this into?const: unstable · source#### fn into_iter(self) -> I Creates an iterator from a value. T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"TagRefIter<'a>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.TagRefIter.html\" title=\"struct git_object::TagRefIter\">TagRefIter</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"struct.TagRefIter.html\" title=\"struct git_object::TagRefIter\">TagRefIter</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/result/enum.Result.html\" title=\"enum core::result::Result\">Result</a>&lt;<a class=\"enum\" href=\"tag/ref_iter/enum.Token.html\" title=\"enum git_object::tag::ref_iter::Token\">Token</a>&lt;'a&gt;, <a class=\"struct\" href=\"decode/struct.Error.html\" title=\"struct git_object::decode::Error\">Error</a>&gt;;</span>"} Struct git_object::Tree === ``` pub struct Tree { pub entries: Vec<Entry>, } ``` A mutable Tree, containing other trees, blobs or commits. Fields --- `entries: Vec<Entry>`The directories and files contained in this tree. They must be and remain sorted by `filename`. Implementations --- ### impl Tree #### pub fn empty() -> Self Return an empty tree which serializes to a well-known hash Trait Implementations --- ### impl Clone for Tree #### fn clone(&self) -> Tree Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(v: Tree) -> Self Converts to this type from the input type.### impl From<TreeRef<'_>> for Tree #### fn from(other: TreeRef<'_>) -> Tree Converts to this type from the input type.### impl Hash for Tree #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Tree) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Tree) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Tree> for Tree #### fn partial_cmp(&self, other: &Tree) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. #### type Error = Object The type returned in the event of a conversion error.#### fn try_from(value: Object) -> Result<Self, Self::ErrorPerforms the conversion.### impl WriteTo for Tree Serialization #### fn write_to(&self, out: impl Write) -> Result<()Serialize this tree to `out` in the git internal format. #### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). Returns the type of this object.#### fn loose_header(&self) -> SmallVec<[u8; 28]Returns a loose object header based on the object’s data### impl Eq for Tree ### impl StructuralEq for Tree ### impl StructuralPartialEq for Tree Auto Trait Implementations --- ### impl RefUnwindSafe for Tree ### impl Send for Tree ### impl Sync for Tree ### impl Unpin for Tree ### impl UnwindSafe for Tree Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_object::TreeRef === ``` pub struct TreeRef<'a> { pub entries: Vec<EntryRef<'a>>, } ``` A directory snapshot containing files (blobs), directories (trees) and submodules (commits). Fields --- `entries: Vec<EntryRef<'a>>`The directories and files contained in this tree. Implementations --- ### impl<'a> TreeRef<'a#### pub fn from_bytes(data: &'a [u8]) -> Result<TreeRef<'a>, ErrorDeserialize a Tree from `data`. #### pub const fn empty() -> TreeRef<'staticCreate an instance of the empty tree. It’s particularly useful as static part of a program. Trait Implementations --- ### impl<'a> Clone for TreeRef<'a#### fn clone(&self) -> TreeRef<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(other: TreeRef<'_>) -> Tree Converts to this type from the input type.### impl<'a> From<TreeRef<'a>> for ObjectRef<'a#### fn from(v: TreeRef<'a>) -> Self Converts to this type from the input type.### impl<'a> Hash for TreeRef<'a#### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> PartialOrd<TreeRef<'a>> for TreeRef<'a#### fn partial_cmp(&self, other: &TreeRef<'a>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. __S: Serializer, Serialize this value into the given Serde serializer. #### fn write_to(&self, out: impl Write) -> Result<()Serialize this tree to `out` in the git internal format. #### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). Returns the type of this object.#### fn loose_header(&self) -> SmallVec<[u8; 28]Returns a loose object header based on the object’s data### impl<'a> Eq for TreeRef<'a### impl<'a> StructuralEq for TreeRef<'a### impl<'a> StructuralPartialEq for TreeRef<'aAuto Trait Implementations --- ### impl<'a> RefUnwindSafe for TreeRef<'a### impl<'a> Send for TreeRef<'a### impl<'a> Sync for TreeRef<'a### impl<'a> Unpin for TreeRef<'a### impl<'a> UnwindSafe for TreeRef<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_object::TreeRefIter === ``` pub struct TreeRefIter<'a> { /* private fields */ } ``` A directory snapshot containing files (blobs), directories (trees) and submodules (commits), lazily evaluated. Implementations --- ### impl<'a> TreeRefIter<'a#### pub fn from_bytes(data: &'a [u8]) -> TreeRefIter<'aInstantiate an iterator from the given tree data. ### impl<'a> TreeRefIter<'a#### pub fn entries(self) -> Result<Vec<EntryRef<'a>>, ErrorConsume self and return all parsed entries. Trait Implementations --- ### impl<'a> Clone for TreeRefIter<'a#### fn clone(&self) -> TreeRefIter<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. &mut self ) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where Self: Sized, 🔬This is a nightly-only experimental API. (`iter_next_chunk`)Advances the iterator and returns an array containing the next `N` values. Read more1.0.0 · source#### fn size_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. Read more1.0.0 · source#### fn count(self) -> usizewhere Self: Sized, Consumes the iterator, counting the number of iterations and returning it. Read more1.0.0 · source#### fn last(self) -> Option<Self::Item>where Self: Sized, Consumes the iterator, returning the last element. Self: Sized, Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more1.0.0 · source#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>where Self: Sized, U: IntoIterator<Item = Self::Item>, Takes two iterators and creates a new iterator over both in sequence. Read more1.0.0 · source#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where Self: Sized, U: IntoIterator, ‘Zips up’ two iterators into a single iterator of pairs. Self: Sized, G: FnMut() -> Self::Item, 🔬This is a nightly-only experimental API. (`iter_intersperse`)Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. Read more1.0.0 · source#### fn map<B, F>(self, f: F) -> Map<Self, F>where Self: Sized, F: FnMut(Self::Item) -> B, Takes a closure and creates an iterator which calls that closure on each element. Read more1.21.0 · source#### fn for_each<F>(self, f: F)where Self: Sized, F: FnMut(Self::Item), Calls a closure on each element of an iterator. Read more1.0.0 · source#### fn filter<P>(self, predicate: P) -> Filter<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator which uses a closure to determine if an element should be yielded. Read more1.0.0 · source#### fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Creates an iterator that both filters and maps. Read more1.0.0 · source#### fn enumerate(self) -> Enumerate<Self>where Self: Sized, Creates an iterator which gives the current iteration count as well as the next value. Read more1.0.0 · source#### fn peekable(self) -> Peekable<Self>where Self: Sized, Creates an iterator which can use the `peek` and `peek_mut` methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more1.0.0 · source#### fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that `skip`s elements based on a predicate. Read more1.0.0 · source#### fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that yields elements based on a predicate. Read more1.57.0 · source#### fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>where Self: Sized, P: FnMut(Self::Item) -> Option<B>, Creates an iterator that both yields elements based on a predicate and maps. Read more1.0.0 · source#### fn skip(self, n: usize) -> Skip<Self>where Self: Sized, Creates an iterator that skips the first `n` elements. Read more1.0.0 · source#### fn take(self, n: usize) -> Take<Self>where Self: Sized, Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. Read more1.0.0 · source#### fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>, An iterator adapter which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. Read more1.0.0 · source#### fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, Creates an iterator that works like map, but flattens nested structure. Read more1.0.0 · source#### fn fuse(self) -> Fuse<Self>where Self: Sized, Creates an iterator which ends after the first `None`. Read more1.0.0 · source#### fn inspect<F>(self, f: F) -> Inspect<Self, F>where Self: Sized, F: FnMut(&Self::Item), Does something with each element of an iterator, passing the value on. Read more1.0.0 · source#### fn by_ref(&mut self) -> &mut Selfwhere Self: Sized, Borrows an iterator, rather than consuming it. Read more1.0.0 · source#### fn collect<B>(self) -> Bwhere B: FromIterator<Self::Item>, Self: Sized, Transforms an iterator into a collection. E: Extend<Self::Item>, Self: Sized, 🔬This is a nightly-only experimental API. (`iter_collect_into`)Collects all the items from an iterator into a collection. Read more1.0.0 · source#### fn partition<B, F>(self, f: F) -> (B, B)where Self: Sized, B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool, Consumes an iterator, creating two collections from it. Self: Sized, P: FnMut(Self::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_is_partitioned`)Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. Read more1.27.0 · source#### fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more1.27.0 · source#### fn try_for_each<F, R>(&mut self, f: F) -> Rwhere Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Output = ()>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more1.0.0 · source#### fn fold<B, F>(self, init: B, f: F) -> Bwhere Self: Sized, F: FnMut(B, Self::Item) -> B, Folds every element into an accumulator by applying an operation, returning the final result. Read more1.51.0 · source#### fn reduce<F>(self, f: F) -> Option<Self::Item>where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item, Reduces the elements to a single one, by repeatedly applying a reducing operation. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere Self: Sized, F: FnMut(Self::Item, Self::Item) -> R, R: Try<Output = Self::Item>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce`)Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more1.0.0 · source#### fn all<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if every element of the iterator matches a predicate. Read more1.0.0 · source#### fn any<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if any element of the iterator matches a predicate. Read more1.0.0 · source#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where Self: Sized, P: FnMut(&Self::Item) -> bool, Searches for an element of an iterator that satisfies a predicate. Read more1.30.0 · source#### fn find_map<B, F>(&mut self, f: F) -> Option<B>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Applies function to the elements of iterator and returns the first non-none result. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere Self: Sized, F: FnMut(&Self::Item) -> R, R: Try<Output = bool>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`try_find`)Applies function to the elements of iterator and returns the first true result or the first error. Read more1.0.0 · source#### fn position<P>(&mut self, predicate: P) -> Option<usize>where Self: Sized, P: FnMut(Self::Item) -> bool, Searches for an element in an iterator, returning its index. Read more1.6.0 · source#### fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the maximum value from the specified function. Read more1.15.0 · source#### fn max_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the maximum value with respect to the specified comparison function. Read more1.6.0 · source#### fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the minimum value from the specified function. Read more1.15.0 · source#### fn min_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the minimum value with respect to the specified comparison function. Read more1.0.0 · source#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Iterator<Item = (A, B)>, Converts an iterator of pairs into a pair of containers. Read more1.36.0 · source#### fn copied<'a, T>(self) -> Copied<Self>where T: 'a + Copy, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which copies all of its elements. Read more1.0.0 · source#### fn cloned<'a, T>(self) -> Cloned<Self>where T: 'a + Clone, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which `clone`s all of its elements. Read more1.0.0 · source#### fn cycle(self) -> Cycle<Self>where Self: Sized + Clone, Repeats an iterator endlessly. Self: Sized, 🔬This is a nightly-only experimental API. (`iter_array_chunks`)Returns an iterator over `N` elements of the iterator at a time. Read more1.11.0 · source#### fn sum<S>(self) -> Swhere Self: Sized, S: Sum<Self::Item>, Sums the elements of an iterator. Read more1.11.0 · source#### fn product<P>(self) -> Pwhere Self: Sized, P: Product<Self::Item>, Iterates over the entire iterator, multiplying all the elements Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn partial_cmp<I>(self, other: I) -> Option<Ordering>where I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Lexicographically compares the elements of this `Iterator` with those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn eq<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are equal to those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_order_by`)Determines if the elements of this `Iterator` are equal to those of another with respect to the specified equality function. Read more1.5.0 · source#### fn ne<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are unequal to those of another. Read more1.5.0 · source#### fn lt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less than those of another. Read more1.5.0 · source#### fn le<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less or equal to those of another. Read more1.5.0 · source#### fn gt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than those of another. Read more1.5.0 · source#### fn ge<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than or equal to those of another. Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given comparator function. Self: Sized, F: FnMut(Self::Item) -> K, K: PartialOrd<K>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given key extraction function. This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> PartialOrd<TreeRefIter<'a>> for TreeRefIter<'a#### fn partial_cmp(&self, other: &TreeRefIter<'a>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. --- ### impl<'a> RefUnwindSafe for TreeRefIter<'a### impl<'a> Send for TreeRefIter<'a### impl<'a> Sync for TreeRefIter<'a### impl<'a> Unpin for TreeRefIter<'a### impl<'a> UnwindSafe for TreeRefIter<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<I> IntoIterator for Iwhere I: Iterator, #### type Item = <I as Iterator>::Item The type of the elements being iterated over.#### type IntoIter = I Which kind of iterator are we turning this into?const: unstable · source#### fn into_iter(self) -> I Creates an iterator from a value. T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"TreeRefIter<'a>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.TreeRefIter.html\" title=\"struct git_object::TreeRefIter\">TreeRefIter</a>&lt;'a&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html\" title=\"trait core::iter::traits::iterator::Iterator\">Iterator</a> for <a class=\"struct\" href=\"struct.TreeRefIter.html\" title=\"struct git_object::TreeRefIter\">TreeRefIter</a>&lt;'a&gt;</span><span class=\"where fmt-newline\"> type <a href=\"https://doc.rust-lang.org/nightly/core/iter/traits/iterator/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/result/enum.Result.html\" title=\"enum core::result::Result\">Result</a>&lt;<a class=\"struct\" href=\"tree/struct.EntryRef.html\" title=\"struct git_object::tree::EntryRef\">EntryRef</a>&lt;'a&gt;, <a class=\"struct\" href=\"decode/struct.Error.html\" title=\"struct git_object::decode::Error\">Error</a>&gt;;</span>"} Enum git_object::Kind === ``` pub enum Kind { Tree, Blob, Commit, Tag, } ``` The four types of objects that git differentiates. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)] Variants --- ### Tree ### Blob ### Commit ### Tag Implementations --- ### impl Kind #### pub fn from_bytes(s: &[u8]) -> Result<Kind, ErrorParse a `Kind` from its serialized loose git objects. #### pub fn as_bytes(&self) -> &[u8] Return the name of `self` for use in serialized loose git objects. Trait Implementations --- ### impl Clone for Kind #### fn clone(&self) -> Kind Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Kind) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Kind) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Kind> for Kind #### fn partial_cmp(&self, other: &Kind) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. ### impl Eq for Kind ### impl StructuralEq for Kind ### impl StructuralPartialEq for Kind Auto Trait Implementations --- ### impl RefUnwindSafe for Kind ### impl Send for Kind ### impl Sync for Kind ### impl Unpin for Kind ### impl UnwindSafe for Kind Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Trait git_object::WriteTo === ``` pub trait WriteTo { // Required methods fn write_to(&self, out: impl Write) -> Result<()>; fn kind(&self) -> Kind; fn size(&self) -> usize; // Provided method fn loose_header(&self) -> SmallVec<[u8; 28]> { ... } } ``` Writing of objects to a `Write` implementation Required Methods --- #### fn write_to(&self, out: impl Write) -> Result<()Write a representation of this instance to `out`. #### fn kind(&self) -> Kind Returns the type of this object. #### fn size(&self) -> usize Returns the size of this object’s representation (the amount of data which would be written by `write_to`). `size`’s value has no bearing on the validity of the object, as such it’s possible for `size` to return a sensible value but `write_to` to fail because the object was not actually valid in some way. Provided Methods --- #### fn loose_header(&self) -> SmallVec<[u8; 28]Returns a loose object header based on the object’s data Implementations on Foreign Types --- ### impl<T> WriteTo for &Twhere T: WriteTo, #### fn write_to(&self, out: impl Write) -> Result<()#### fn size(&self) -> usize #### fn kind(&self) -> Kind Implementors --- ### impl WriteTo for Object Serialization ### impl WriteTo for Blob ### impl WriteTo for Commit ### impl WriteTo for Tag ### impl WriteTo for Tree Serialization ### impl<'a> WriteTo for ObjectRef<'aSerialization ### impl<'a> WriteTo for BlobRef<'a### impl<'a> WriteTo for CommitRef<'a### impl<'a> WriteTo for TagRef<'a### impl<'a> WriteTo for TreeRef<'aSerialization
esparta_github_io_gitimmersion-spanish
free_programming_book
Unknown
* Configurar git para tenerlo listo para trabajar. ## Configurar Nombre y Correo Electrónico01 Si no ha usado git antes, necesita configurarlo primero. Ejecute los siguientes comandos para que git conozca su nombre y correo electrónico. Si ya tenía configurado git, puede saltarse esta sección. > git config --global user.name "<NAME>" > git config --global user.email "<EMAIL>" ## Configure las preferencias de fin de línea 02 Para usuarios de Unix/Mac: Para usuarios de Windows: * Obtener el material de configuración y estar listos para iniciar. ## Obtener el paquete del Tutorial. 01 Obtenga los paquetes del tutorial desde: * La memorias provistas en este tutorial. * La URL del tutorial original http://gitimmersion.com/git_tutorial.zip * Clone este tutorial desde https://github.com/esparta/gitimmersion-spanish ## Contenido del tutorial 02 El paquete contiene un directorio principal “git_tutorial” con tres subdirectorios: * html — Estos archivos en formato HTML. Apunte su navegador a html/index.html para comenzar a leer offline. * work — Un directorio vacío. Cree sus repos aquí. * repos — Repositorios Git pre-empacados con los que puede llevar el tutorial en cualquier punto. De llegar a bloquearse, sólo copie el laboratorio deseado en su directorio de trabajo. * Aprender a crear un repositorio git desde cero. ## Crear un programa “Hola, Mundo” 01 Haga un directorio vacío llamado “hello”, después cree un archivo llamado `hello.rb` con el siguiente contenido. > mkdir hello > cd hello > puts "Hello, World" ## Crear el Repositorio 02 Ya tiene un directorio con un archivo. Para crear el repositorio git a partir de este directorio, ejecute el comando git init. > git init > $ git init Initialized empty Git repository in /Users/jerrynummi/Projects/edgecase/git_immersion/auto/hello/.git/ ## Agregue el programa al repositorio 03 Ahora vamos a agregar el programa “Hola, Mundo” al repositorio. > git add hello.rb > git commit -m "First Commit" > $ git add hello.rb $ git commit -m "First Commit" [master (root-commit) 3cbf83b] First Commit 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 hello.rb * Aprender a revisar el estatus del repositorio. ## Revisar el estatus de el repositorio 01 Use el comando `git status` para revisar el estatus actual del repositorio. Debería ver El comando de status reporta que no hay nada por hacer commit. Esto significa que el repositorio tiene el mismo estado actual que el directorio de trabajo. No hay cambios pendientes de grabar. Usaremos el comando `git status` para continuar monitoreando el estado entre el repositorio y el directorio de trabajo. * Aprender a monitorear el estado del directorio de trabajo. ## Cambie el programa “Hola, Mundo”. 01 Es tiempo de cambiar nuestro programa hello para tomar un argumento desde la línea de comando. Cambie el archivo para que sea: > puts "Hello, #{ARGV.first}!" > $ git status # On branch master # Changes not staged for commit: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: hello.rb # no changes added to commit (use "git add" and/or "git commit -a") La primera cosa a notar es que git sabe que el archivo `hello.rb` ha sido modificado, pero git no ha sido notificado de esos cambios. También note que el mensaje de estatus le proporciona algunos consejos sobre lo que debería hacer a continuación. Si desea agregar estos cambios al repositorio, entonces use el comando `git add` . Mientras tanto, el comando `git checkout` puede ser usado para descartar los cambios. Poner en Stage el cambio. * Aprender cómo poner en Stage cambios para un posterior Commit. ## Agregar cambios 01 Decirle a git que ponga en Stage los cambios. Revisar el estatus. > git add hello.rb > git status > $ git add hello.rb $ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: hello.rb # El cambio al archivo `hello.rb` se ha puesto en Stage. Esto significa que git ahora tiene conocimiento del cambio, pero todavía no ha sido guardado permanentemente en el repositorio. La siguiente operación de Commit incluirá los cambios en Stage. Si al final decide que no quiere realizar el Commit de los cambios, el comando de estatus le recordará que el commando `git reset` puede ser usado para quitarlo de Stage. Un paso separado del concepto de Staging está alineado con la filosofía de "salirse del camino" hasta que se necesite hacer frente al control de código fuente. Puede continuar haciendo cambios en su directorio de trabajo, y entonces, en el punto en que quiera interactuar con el control de código fuente, git le permitirá grabar los cambios en pequeños Commits que reproducirán exactamente lo que hizo. Por ejemplo, suponga que quiere editar tres archivos: `a.rb` , `b.rb` , and `c.rb` . Ahora desea hacer Commit de todos los cambios, pero desea que los cambios en `a.rb` y `b.rb` estén en un Commit, mientras que los cambios de `c.rb` no están relacionados lógicamente con los primeros dos archivos y debería estar en un Commit separado. Puede realizar lo siguiente: > git add a.rb > git add b.rb > git commit -m "Changes for a and b" > git add c.rb > git commit -m "Unrelated change to c" Separando los Staging y Commits le dará la habilidad de afinar con precisión qué pasó en cada Commit. * Aprender a hacer Commit a los cambios en el repositorio. ## Haga Commit a los cambios 01 Ok, suficiente de Staging. Hagamos Commit a lo que hemos tenido en Stage al repositorio. Cuando usa el comando `git commit` previamente para confirmar la versión inicial del archivo `hello.rb` en el repositorio, puede incluir la opción `-m` que establece un comentario desde la línea de comando. El comando Commit permitirá comentar interactivamente la edición del comentario del Commit. Intentaremos esto ahora mismo. Si omite la opción `-m` en la línea de comando, git lanzará el editor de su preferencia. El editor es escogido de la siguiente lista (en orden de prioridad): * La variable de ambiente GIT_EDITOR * El ajuste en la configuración de core.editor * La variable de ambiente VISUAL * La variable de ambiente EDITOR Yo tengo la variable EDITOR establecida a `emacsclient` . Haga un Commit y revise el estatus. > git commit Deberá ver lo siguiente en su editor: > | # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: hello.rb # En la primera línea, escriba el comentario: “Using ARGV”. Guarde el archivo y salga del editor. Deberá ver … > git commit Waiting for Emacs... [master 569aa96] Using ARGV 1 files changed, 1 insertions(+), 1 deletions(-) La línea “Waiting for Emacs…” es del programa `emacsclient` quien envía el archivo a un programa de emacs y espera que el se cierre el archivo. El resto de la salida es el mensaje estándar del Commit. ## Revise el estatus 02 Finalmente vamos a revisar de nuevo el estatus. El directorio de trabajo está limpio y listo para continuar. * Aprender que git trabaja con cambios, no con archivos. Muchos sistemas de control de versiones trabajan con archivos. Se agrega un archivo al control de versiones y el sistema rastreará los cambios al archivo al que apunta. Git se enfoca en los cambios al archivo en vez del archivo mismo. Cuando escribe `git add file` , no le está diciendo a git que agregue el archivo al repositorio. En vez de eso, se le dice a git que debería notar el estado actual de ese archivo al que se le hará un Commit después. Intentaremos explorar esta diferencia en este laboratorio. ## Primer cambio: Permitir un nombre por defecto 01 Cambie el programa “<NAME>” para tener un valor por defecto si no se proporciona el argumento en la línea de comando. > name = ARGV.first || "World" puts "Hello, #{name}!" ## Agregue este cambio 02 Ahora agregue este cambio al área de Staging de git. ## Segundo cambio: Agregue un comentario 03 Ahora agregue un comentario al programa “<NAME>”. ## Revise el estatus actual 04 > $ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: hello.rb # # Changes not staged for commit: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: hello.rb # Observe cómo se lista `hello.rb` dos veces en el estatus. El primer cambio (agregando un valor por defecto) está en Stage y listo para el Commit. El segundo cambio (agregando un comentario) no está en Stage. Si realizara el Commit ahora mismo, el comentario no será almacenado en el repositorio. Intentemos eso. ## Realizando Committ 05 Confirme el cambio en el área de Stage (el valor por defecto),y revise de nuevo es estatus. > git commit -m "Added a default value" > git status > $ git commit -m "Added a default value" [master 1b754e9] Added a default value 1 files changed, 3 insertions(+), 1 deletions(-) $ git status # On branch master # Changes not staged for commit: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: hello.rb # no changes added to commit (use "git add" and/or "git commit -a") El comando estatus nos dice que `hello.rb` tiene cambios no guardados, pero ya no está en el área de Staging. ## Agregue el segundo cambio 06 Ahora agregue el segundo cambio al área de Staging, después ejecute git status. > git add . > git status Nota: Usamos el directorio actual (‘.’) como el archivo a agregar. Esto es un atajo realmente conveniente para agregar todos los cambios en los archivos en el directorio actual. Pero como esto agrega todo, es una realmente buena idea revisar el estatus antes de realizar un "add .", sólo para asegurarse de no agregar archivos que no tenía intenciones de agregar. Deseaba repasar el truco de “add .” , pero continuaré agregando archivos explícitamente en el resto del tutorial sólo para estar seguros. Ahora el segundo cambio está en el Stage y listo para el Commit. ## Commit del segundo cambio 07 > git commit -m "Added a comment" * Aprender a ver el historial de un proyecto. La función del comando `git log` es obtener el listado de qué cambios se han realizado. > $ git log commit 40543214b69016a1f079a0d95ff88cc7421e9b54 Author: <NAME> <jim (at) edgecase.com> Date: Tue Mar 6 16:12:08 2012 -0500 Added a comment commit 1b754e9e5d528ed7a7d82c3b380fa2b2faa3ce00 Author: <NAME> <jim (at) edgecase.com> Date: Tue Mar 6 16:12:08 2012 -0500 Added a default value commit 30534911b25d1fab76d13d269ff6215b4c4acddd Author: <NAME> <jim (at) edgecase.com> Date: Tue Mar 6 16:12:08 2012 -0500 Using ARGV commit 3cbf83b6899697985d2b4fcfae9b254ab6d0ddf7 Author: <NAME> <jim (at) edgecase.com> Date: Tue Mar 6 16:12:07 2012 -0500 First Commit Ésta es la lista de los cuatro cambios que hemos hecho en el repositorio hasta ahora. ## Historias en una línea 01 Se tiene un gran reto de controlar exactamente qué despliega el comando `log` . En lo personal, me gusta en formato de una sola línea: > $ git log --pretty=oneline 40543214b69016a1f079a0d95ff88cc7421e9b54 Added a comment 1b754e9e5d528ed7a7d82c3b380fa2b2faa3ce00 Added a default value 30534911b25d1fab76d13d269ff6215b4c4acddd Using ARGV 3cbf83b6899697985d2b4fcfae9b254ab6d0ddf7 First Commit ## Controlando cuáles entradas se muestran 02 Existen muchas opciones para seleccionar cuántas entradas se muestran en el log. Juegue con alguna de las siguientes opciones: > git log --pretty=oneline --max-count=2 > git log --pretty=oneline --since='5 minutes ago' > git log --pretty=oneline --until='5 minutes ago' > git log --pretty=oneline --author=<your name> > git log --pretty=oneline --all Vea man git-log para todos los detalles. ## Embelleciéndolo 03 Aquí está lo que uso para revisar los cambios hechos en la última semana. Agregaría `--author=jim` si sólo quisiera ver los cambios que yo he hecho.. > git log --all --pretty=format:"%h %cd %s (%an)" --since='7 days ago' ## Lo último en formatos de Log 04 Conforme pase el tiempo, he decidido que me gusta el siguiente formato para el log en la mayoría de mis trabajos. > git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short Se vería así: > $ git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short * 4054321 2012-03-06 | Added a comment (HEAD, master) [Jim Weirich] * 1b754e9 2012-03-06 | Added a default value [Jim Weirich] * 3053491 2012-03-06 | Using ARGV [Jim Weirich] * 3cbf83b 2012-03-06 | First Commit [Jim Weirich] Mirémoslo a detalle: * `--pretty="..."` define el formato de la salida. * `%h` es el hash abreviado del Commit * `%d` son algunos decorados en el Commit (por ejemplo, la cabecera del branch heads o los tags) * `%ad` es la fecha en que se realizó * `%s` el comentario * `%an` el nombre del autor * `--graph` informa a git que despliegue el arbol de Commit en un layout gráfico en código ASCII * `--date=short` mantiene la fecha en formato bonito y corto Esto es mucho como para escribir en cada ocasión que desee ver el log. Afortunadamente aprenderemos sobre los alias en git en el próximo laboratorio. ## Otra herramientas 05 Tanto `gitx` (para Macs) y `gitk` (cualquier plataforma) son útiles para explorar el historial. ### Goals * Aprender a configurar alias y atajos para los comandos de git. ## Alias Comunes 01 , , , y son algunos comandos comunes a los cuales es útil tenerle abreviaciones. Agregue los siguientes al archivo .gitconfig localizado en su directorio $HOME . # Archivo: $HOME/.gitconfig > [alias] co = checkout ci = commit st = status br = branch hist = log --pretty=format:\"%h %ad | %s%d [%an]\" --graph --date=short type = cat-file -t dump = cat-file -p Ya hemos revisado con anterioridad checkout, commit y status. En el laboratorio previo acabamos de cubrir el comando `log` . Una vez modificado el archivo .gitconfig podrá escribir `git co` donde solía escribir `git checkout` . Lo mismo sucede con `git st` para `git status` y `git ci` para `git commit` . El mejor de ellos es `git hist` , que permitirá evitar el realmente largo comando `log` visto con anterioridad. Continúe e intente estos nuevos comandos. ## Definir el alias `hist` en su archivo `.gitconfig` 02 Para la mayor parte de este tutorial, continuaré escribiendo los comandos completos en las instrucciones. La única excepción será el uso del alias `hist` definido anteriormente, en cualquier momento en que necesitemos ver la salida del comando. Asegurese de tener el alias `hist` configurado en su archivo `.gitconfig` antes de continuar. ## `Escribir` y `Volcar` 03 Hemos agregado unos cuantos alias para comandos que aún no hemos revisamos. El coamdndo `git branch` será visto pronto. Por su parte, el comando `git cat-file` será util explorando git, como veremos dentro de poco. ## Alias de Shell (Opcional) 04 Nota: Esta sección es para los que están ejecutando un shell parecido a posix. Lo usuarios de Windows y otros usuarios con shell no-posix pueden sentirse libres de omitir el siguiente laboratorio. Si su shell soporta alias y atajos, entonces puede agregar alias en este nivel también. Aquí están los que yo uso: # Archivo: .profile > alias gs='git status ' alias ga='git add ' alias gb='git branch ' alias gc='git commit' alias gd='git diff' alias go='git checkout ' alias gk='gitk --all&' alias gx='gitx --all' alias got='git ' alias get='git ' La abreviatura `go` para `git checkout` es particularmente buena, ya que permite escribir: > go <branchpara hacer checkout de un branch en particular. Y sí, suelo escribir (mal) `git` poniendo `get` o `got` tan frecuentemente como para tener alias de él. * Aprender a hacer checkout de cualquier snapshot previo en el directorio de trabajo. Regresar en la historia es muy fácil. El comando checkout copiará cualquier snapshot de el repositorio al directorio de trabajo actual. ## Obtener el hash de versiones previas 01 > git hist Nota: ¿No olvidó definir el alias `hist` en su archivo `.gitconfig` , verdad? De lo contrario, revise el laboratorio de Alias. > $ git hist * 4054321 2012-03-06 | Added a comment (HEAD, master) [Jim Weirich] * 1b754e9 2012-03-06 | Added a default value [Jim Weirich] * 3053491 2012-03-06 | Using ARGV [Jim Weirich] * 3cbf83b 2012-03-06 | First Commit [Jim Weirich] Examine la salida del log output y busque el hash de el primer Commit. Debe ser la última línea de la salida de `git hist` . Use el último código hash (con los primeros 7 caracteres será suficiente) en el comando a continuación. Después revise el contenido del archivo hello.rb . > git checkout <hash> > cat hello.rb Nota: Los comandos dados son comandos Unix y sirven de igual forma tanto en equipos Mac y Linux. Desafortunadamente, los usuarios de Windows tendrán que trasladarlo a sus comandos nativos. Nota: Muchos comandos dependen del valor del hash en el repositorio. Debido a que los valores hash serán diferentes a los míos, donde sea que vea algo como <hash> o <treehash> en la línea de comandos, sustituyalo por el hash correspondiente en su repositorio. > $ git checkout 3cbf83b Note: checking out '3cbf83b'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b new_branch_name HEAD is now at 3cbf83b... First Commit $ cat hello.rb puts "Hello, World" La salida del comando `checkout` explica la situación bastante bien. Las versiones antiguas de git se quejarán de no estar en el branch local. En cualquier caso, no se preocupe sobre eso por ahora. Observe que el contenido del archivo hello.rb es el contenido original. ## Regrese a la última versión en el branch master 02 > git checkout master > cat hello.rb > $ git checkout master Previous HEAD position was 3cbf83b... First Commit Switched to branch 'master' $ cat hello.rb # Default is "World" name = ARGV.first || "World" puts "Hello, #{name}!" ‘master’ es el nombre del branch actual. Al hacer checking out por nombre, se toma la última versión del branch. ### metas * Aprender a etiquetar Commits con nombres para futuras referencias. Llamemos a la versión actual de el programa "version 1 (v1)". ## Etiquetar version 1 01 Ahora puede referirse a la versión actual del programa como v1. ## Etiquetar versiones previas 02 Etiquetemos la versión anterior a la actual como version v1-beta. Primero necesitamos hacer un checkout en la versión anterior. En vez de buscar el hash, usaremos la notación `^` para indicar “el padre de v1”. Nota: Si la notación `v1` ^ le da algún problema, puede tambien intentar con `v1~1` , lo cuál referencia a la misma versión. Esta notación significa “el primer antecesor de v1”. > git checkout v1^ > cat hello.rb > $ git checkout v1^ Note: checking out 'v1^'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b new_branch_name HEAD is now at 1b754e9... Added a default value $ cat hello.rb name = ARGV.first || "World" puts "Hello, #{name}!" Como puede observar, esta es la versión con el valor por defecto antes de que agregaramos el comentario. Hagamos esta versión v1-beta. > git tag v1-beta ## Checking Out usando etiquetas 03 Ahora intente ir hacia tras y hacia adelante entre las dos versiones etiquetadas. > git checkout v1 > git checkout v1-beta > $ git checkout v1 Previous HEAD position was 1b754e9... Added a default value HEAD is now at 4054321... Added a comment $ git checkout v1-beta Previous HEAD position was 4054321... Added a comment HEAD is now at 1b754e9... Added a default value ## Viendo las etiquetas usando el comando `tag` 04 Puede ver qué etiquetas están disponibles usando el comando `git tag` command. > $ git tag v1 v1-beta ## Viendo etiquetas en los Logs 05 También puede revisar las etiquetas en el log. > git hist master --all > $ git hist master --all * 4054321 2012-03-06 | Added a comment (v1, master) [Jim Weirich] * 1b754e9 2012-03-06 | Added a default value (HEAD, v1-beta) [Jim Weirich] * 3053491 2012-03-06 | Using ARGV [Jim Weirich] * 3cbf83b 2012-03-06 | First Commit [Jim Weirich] Podrá observar ambas etiquetas ( `v1` y `v1-beta` ) enlistadas en la salida del comando log output, a un lado del nombre del branch ( `master` ). También observe que `HEAD` denota la versión actual en el check out (la cual es `v1-beta` al momento). # lab 14 Deshacer Cambios Locales (antes de staging) # lab 14 Deshacer Cambios Locales (antes de staging) * Aprender a revertir cambios en el directorio de trabajo. ## Hacer Checkout en Master 01 Asegúrese que está en el último Commit en la rama Master antes de proceder. ## Cambie hello.rb 02 Algunas veces tiene que modificar un archivo en su directorio local y desea revertir lo que ya se le ha hecho Commit. El comando checkout se encargará de eso. Cambie hello.rb para tener un mal comentario. > # This is a bad comment. We want to revert it. name = ARGV.first || "World" puts "Hello, #{name}!" ## Revise el estatus 03 > $ git status # On branch master # Changes not staged for commit: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: hello.rb # no changes added to commit (use "git add" and/or "git commit -a") Vemos que el archivo `hello.rb` ha sido modificado, pero no está en el Stage aún. ## Revierta los cambios en el directorio de trabajo 04 Use el comando `checkout` para realizar un checkout de la versión del repositorio del archivo `hello.rb` . > git checkout hello.rb > git status > cat hello.rb > $ git checkout hello.rb $ git status # On branch master nothing to commit (working directory clean) $ cat hello.rb # Default is "World" name = ARGV.first || "World" puts "Hello, #{name}!" El comando status nos muestra que no hay otros cambios en el directorio de trabajo, y el “mal comentario” ya no forma parte del contenido del archivo. # lab 15 Deshacer Cambios en Stage (antes de commit) # lab 15 Deshacer Cambios en Stage (antes de commit) * Aprender cómo revertir los cambios que están en área de Stage. ## Cambiar el archivo y poner en Stage el cambio 01 Modificar el archivo `hello.rb` para tener un mal comentario. > # This is an unwanted but staged comment name = ARGV.first || "World" puts "Hello, #{name}!" Y entonces, lo ponemos en Stage. Revisar el estatus de los cambios no deseados. La salida de status muestra que el cambio se ha enviado a Stage y está listo para realizar Commit. ## Restablecer el área de Staging 03 Afortunadamente la salida del comando status nos dice exactamente lo que necesitamos hacer para sacar de Staging el cambio. > git reset HEAD hello.rb > $ git reset HEAD hello.rb Unstaged changes after reset: M hello.rb El comando `reset` revierte el área de Staging para establecerlo en lo que esté en HEAD. Esto limpia el área de Staging del cambio que habíamos hecho. El comando `reset` (por defecto) no cambia el directorio de trabajo. Así que el directorio de trabajo aún tiene el comentario no deseado en él. Podemos usar el comando `checkout` visto en el laboratorio previo para quitar el cambio del directorio de trabajo. ## Realizar Checkout 04 > git checkout hello.rb > git status Con esto, nuestro directorio de trabajo está limpio una vez más. * Aprender a revertir los cambios que se enviaron a Commit en un repositorio local. ## Deshacer Commits 01 Algunas veces se da cuenta que el cambio que ya está confirmado era incorrecto y desea deshacer ese Commit. Hay varias formas de manejar este asunto, y la manera en que vamos a usar en este laboratorio siempre es segura. Esencialmente desharemos el Commit al crear un nuevo Commit que retorne el cambio no deseado. ## Cambie el archivo y haga el Commit. 02 Cambie el archivo `hello.rb` con lo siguiente. > # This is an unwanted but committed change name = ARGV.first || "World" puts "Hello, #{name}!" > git add hello.rb > git commit -m "Oops, we didn't want this commit" ## Crear y Revertir Commit 03 Para deshacer el cambio confirmado, necesitamos generar un commit que quite los cambios introducidos en nuestro Commit no deseado. > git revert HEAD Esto hará aparecer el editor. Puede editar el mensaje por defecto del Commit o dejarlo como está. Guarde y cierre el archivo. Debería ver … > $ git revert HEAD --no-edit [master 9ad227a] Revert "Oops, we didn't want this commit" 1 files changed, 1 insertions(+), 1 deletions(-) Debido a que estamos deshaciendo el último Commit que hicimos, podemos usar `HEAD` como el argumento a revertir. Podemos revertir arbitrariamente cualquier Commit en el historial simplemente al especificar su hash. Nota: El parámetro `--no-edit` en la salida puede ser ignorado. Esto es necesario para generar la salida sin abrir el editor. ## Revise el log 04 Al revisar el log nos muestra ambos Commit, el no deseado y el Commit paa revertir los cambios en nuestro repositorio. Esta técnica funcionará con cualquier commit (aunque puede que tenga que resolver conflictos). Es seguro de usar aún en ramas que están públicamente compartirdas en repositorios remotos. ## A Continuación 05 Como siguiente paso, veremos una técnica que puede ser usada para quitar los Commits más recientes del repositorio público. * Aprender a quitar los Commits más recientes de una ramificación. El comando `revert` de la sección previa es un poderoso comando que nos permite deshacer los efectos de cualquier Commit en el repositorio. Sin embrgo, ambos, el Commit original y el Commit “deshecho” están invisibles en el historial de la ramificación (usando el commando `git log` . Frecuentemente hacemos un Commit e inmediatamente nos damos cuenta que fue un error. Sería bueno tener un comando “recuperador” que nos permitiera hacer de cuenta que ese commit nunca sucedió. El comando “recuperador” incluso prevendría que el Commit defectuoso se mostrara en el historial que arroja `git log` . Sería como el Commit defectuoso nunca hubera sucedido. ## El comando `reset` 01 Ya hemos visto el comando `reset` y lo hemos usado para establecer el área de Staging para que fuera consistente con un Commit en especial (usamos el Commit HEAD en nuestro anterior lab). Cuando se realiza un Commit referenciado (por ejemplo, un hash, una ramificación o nombre de etiqueta), el comando `reset` realizará lo siguiente … * Reescribir la ramificación actual y apuntarlo a un Commit en específico * Opcionalmente reestablecer el área de Staging para coincidir con el Commit especificado * Opcionalmente reestablecer el directorio de trabajo para coincidir con el Commit especificado ## Revisar nuestro historial 02 Hagamos una revisión rápida de nuestro historial de Commits. Vemos que tenemos un Commit “Oops” y “Revert Oops” en los últimos dos Commits hechos en esta ramificación. Vamos a quitarlos usando reset. ## Primero, marquemos esta Ramificación 03 Pero antes de quitar los Commits, marquemos el último Commit con una etiqueta, así podremos buscarlo de nuevo. > git tag oops ## Reestablecer el repositorio a como se encontraba antes de Oops 04 Al ver el historial (arriba), podemos ver que el Commit etiquetado como ‘v1’ es el que se encuentra justo antes del mal comentario. Reestablezcamos el branch a ese punto. Debido a que el Branch está etiquetado , podemos usar el nombre de la etiqueta en el comando reset (si no fue etiquetado, podemos usar su hash). > git reset --hard v1 > git hist > $ git reset --hard v1 HEAD is now at 4054321 Added a comment $ git hist * 4054321 2012-03-06 | Added a comment (HEAD, v1, master) [Jim Weirich] * 1b754e9 2012-03-06 | Added a default value (v1-beta) [Jim Weirich] * 3053491 2012-03-06 | Using ARGV [Jim Weirich] * 3cbf83b 2012-03-06 | First Commit [Jim Weirich] Nuestro branch principal ahora apunta al Commit v1 y el commit "Oops" y "Revert Oops commit" no están más en la rama. El parámetro `--hard` indica que el directorio de trabajo debe ser actualizado para ser consistente con la nueva cabeza del branch. ## Nada se Pierde 05 Pero ¿qué les pasó a los malos Commits? Resulta que esos Commits están aún en el repositorio. De hecho, aún podemos referenciarlos. Recuerda que al inicio de este lab etiquetamos el Commit con “oops”. Veamos en todos los Commits. Aquí vemos que los malos Commits no han desaparecido, aún están en el repository. Lo que sucede es que sólo no están listados en el branch principal. Si no los hemos etiquetado, seguirían aún en el repositorio, pero no habría forma de referenciarlos más que usando los valores de hash. Los Commits que no tienen referencia quedan en el repositorio hasta que el sistema ejecuta el software de recolección de basura. ## Peligros del Reset 06 Los Resets en ramificaciones locales son generalmente seguros. Cualquier accidente puede ser recuperado con sólo reestablecerlo al Commit deseado. Sin embargo, si la ramificación está compartido en repositorios remotos, puede confundir a otros usuarios que comparten el branch. * Quitar la etiqueta "oops" (limpeza interna) ## Quitando etiqueta "oops" 01 La etiqueta "oops" ha servido para el propósito. Vamos a quitarla y permitir que los Commits a los que hace referencia sean manejados por el recolector de basura. > git tag -d oops > git hist --all > $ git tag -d oops Deleted tag 'oops' (was 9ad227a) $ git hist --all * 4054321 2012-03-06 | Added a comment (HEAD, v1, master) [<NAME>] * 1b754e9 2012-03-06 | Added a default value (v1-beta) [Jim Weirich] * 3053491 2012-03-06 | Using ARGV [Jim Weirich] * 3cbf83b 2012-03-06 | First Commit [Jim Weirich] La etiqueta "oops" ya no se encuentra listada en el repositorio. * Aprender a enmendar un Commit existente ## Cambie el programa, luego haga Commit 01 Agregue un comentario con el nombre del autor. > git add hello.rb > git commit -m "Add an author comment" ## Oops, debimos poner también el Email 02 Después de hacer el Commit, se dió cuenta que debió incluir el correo electrónico. Actualice el programa hello para incluirlo ## Enmiende el anterior Commit 03 Realmente no queremos un Commit por separado sólo para el email. Vamos a enmendar el anterior Commit para incluir el cambio con la introducción del correo electrónico. > git add hello.rb > git commit --amend -m "Add an author/email comment" > $ git add hello.rb $ git commit --amend -m "Add an author/email comment" [master 9c78ad8] Add an author/email comment 1 files changed, 2 insertions(+), 1 deletions(-) ## Revise el Historial 04 Podemos ver que Commit original con sólo el autor ha desaparecido, y es remplazado con el Commit de “autor/email”. Puede alcanzar el mismo efecto reestableciendo el branch al Commit anterior y reenviando el Commit con los nuevos cambios. * Aprender a mover archivos en el repositorio. ## Mover el archivo hello.rb al directorio lib. 01 Vamos a construir la estructura de nuestro repositorio, empezaremos moviendo el programa hello al directorio lib. > mkdir lib > git mv hello.rb lib > git status > $ mkdir lib $ git mv hello.rb lib $ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # renamed: hello.rb -> lib/hello.rb # Al usar git para hacer el movimiento, informamos a git de dos cosas: * Que el archivo `hello.rb` ha sido borrado. * Que el archivo `lib/hello.rb` ha sido creado. Estos bits de información son inmediatamente enviados al área de Stage y están listos para hacer Commit. El comando git status reporta que el archivo ha sido movido. ## Otra manera de mover archivos 02 Una de las cosas bonitas de git es que puede olvidarse del control de versiones hasta el punto en que esté listo de realizar confirmaciones vía Commit. ¿Qué hubiera pasado si usamos los comandos del sistemas operativos para mover el archivo en vez del comando de git? Resulta que el siguiente conjunto de comandos es idéntico a lo que acabamos de hacer. Es un poco de más trabajo, pero el resultado es el mismo. Pudimos haber hecho: > mkdir lib > mv hello.rb lib > git add lib/hello.rb > git rm hello.rb ## Realizar Commit del nuevo directorio 03 Vamos a hacer el Commit de lo anterior. > git commit -m "Moved hello.rb to lib" * Agregar otro archivo a nuestro repositorio. ## Ahora agregaremos un Rakefile 01 Vamos a agregar un Rakefile a nuestro repositorio. El siguiente archivo lo hará correctamente. > #!/usr/bin/ruby -wKU task :default => :run task :run do require './lib/hello' end Agregar y realizar Commit de los cambios. > git add Rakefile > git commit -m "Added a Rakefile." Ahora debería poder usar el Rake para ejecutar su programa hello. > rake > $ rake Hello, World! # lab 22 Al Interior de Git: El directorio .git/h1# lab 22 Al Interior de Git: El directorio .git/h1* Aprender sobre la estructura de el directorio `.git` . ## El Directorio `.git` 01 Es tiempo de explorar un poco. Primero, iniciando desde la raíz del directorio de su proyecto … > ls -C .git > $ ls -C .git COMMIT_EDITMSG config index objects HEAD description info refs ORIG_HEAD hooks logs Éste es el directorio mágico donde son almacenadas todas las “cosas” de git. Echemos un vistazo en el directorio de objetos ## El Almacenamiento de Objetos 02 > ls -C .git/objects > $ ls -C .git/objects 09 24 30 43 69 78 9c b8 e4 pack 11 27 3c 49 6b 97 af c4 e7 1b 28 40 59 76 9a b5 d2 info Debería ver un monton de directorios con nombres de dos letras. Los nombres de los directorios son las dos primeras letras del hash sha1 del objeto almacenado en git. ## A Profundidad en el Almacenamiento de Objetos 03 > ls -C .git/objects/<dir > $ ls -C .git/objects/09 6b74c56bfc6b40e754fc0725b8c70b2038b91e 9fb6f9d3a104feb32fcac22354c4d0e8a182c1 Mire en alguno de los directorios de dos letras. Verá algunos archivos con nombres de 38 caracteres. Estos son los archivos que contienen los objetos almacenados en git. Estos archivos están compresos y codificados, así que no será de mucha ayuda el mirar directamente en el contenido, pero daremos un vistazo más a detalle. ## Archivo de Configuración 04 > cat .git/config > $ cat .git/config [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true [user] name = <NAME> email = jim (at) edgecase.com Este es el archivo de configuración específico del proyecto. Las entradas en la configuración serán sobrepuestas con las configuraciones que se encuentran en el archivo `.gitconfig` en su directorio raíz, al menos para este proyecto. ## Ramas y Etiquetas 05 > ls .git/refs > ls .git/refs/heads > ls .git/refs/tags > cat .git/refs/tags/v1 > $ ls .git/refs heads tags $ ls .git/refs/heads master $ ls .git/refs/tags v1 v1-beta $ cat .git/refs/tags/v1 40543214b69016a1f079a0d95ff88cc7421e9b54 Podría reconocer los archivos en el subdirectorio "tags". Cada archivo corresponde a una etiqueta que se creó anteriormente con el comando `git tag` . Su contenido es sólo el hash del Commit atado a la etiqueta. Algo similar sucede con los directorios "heads", pero ellos son usado con las ramificaciones en vez de las etiquetas. En este momento sólo tenemos una rama, así que veremos "master" en este directorio. ## El Archivo HEAD 06 > cat .git/HEAD > $ cat .git/HEAD ref: refs/heads/master El archivo HEAD contiene una referencia a la ramificación actual. Esto debería ser una referencia a "master" en este punto. # lab 23 Al Interior de Git: Directorio de trabajo con Objetos de Git # lab 23 Al Interior de Git: Directorio de trabajo con Objetos de Git * Explorar la estructura del almacenamiento de objetos. * Aprender a usar los hash SHA1 para encontrar contenido en el repositorio. Ahora vamos a usar algunas herramientas para probar los objetos de git directamente. ## Encontrando el último Commit 01 > git hist --max-count=1 Esto debería mostrar el último Commit hecho en el repositorio. El hash SHA1 en su sistema es seguramente diferente al mío, pero verá algo como esto: > $ git hist --max-count=1 * 76ba0a7 2012-03-06 | Added a Rakefile. (HEAD, master) [Jim Weirich] ## Extrayendo el último Commit 02 Usando el hash SHA1 del listado anterior … > git cat-file -t <hash> > git cat-file -p <hashPodrá ver el siguiente resultado... > $ git cat-file -t 76ba0a7 commit $ git cat-file -p 76ba0a7 tree 096b74c56bfc6b40e754fc0725b8c70b2038b91e parent b8f15c35ac4e42485773fec06e7155203a16c986 author <NAME> <jim (at) edgecase.com> 1331068328 -0500 committer <NAME> <jim (at) edgecase.com> 1331068328 -0500 Added a Rakefile. NOTA: Si definió los alias ‘type’ y ‘dump’ en el laboratorio de alias, entonces podrá escribir `git type` y `git dump` en vez de el comando más largo cat-file (el cuál nunca puedo recordar). Este es el vaciado de el objeto Commit que está en el encabezado de la rama "master". Se parece mucho al objeto Commit de la presentación anterior. ## Buscando el Árbol 03 Podemos vaciar el árbol referenciado en el Commit. Debería ser una descripción de los archivos de más alto nivel en nuestro proyecto (para ese Commit). Use el valor del hash SHA1 de la propiedad “tree” listado arriba. > git cat-file -p <treehashAquí está cómo se ve mi árbol > $ git cat-file -p 096b74c 100644 blob 28e0e9d6ea7e25f35ec64a43f569b550e8386f90 Rakefile 040000 tree e46f374f5b36c6f02fb3e9e922b79044f754d795 lib Sí, veo el Rakefile y el directorio lib. ## Volcando el directorio lib 04 > git cat-file -p <libhash > $ git cat-file -p e46f374 100644 blob c45f26b6fdc7db6ba779fc4c385d9d24fc12cf72 hello.rb Aquí está el archivo `hello.rb` . ## Volcando el archivo `hello.rb` 05 > git cat-file -p <rbhash > $ git cat-file -p c45f26b # Default is World # Author: <NAME> (<EMAIL>) name = ARGV.first || "World" puts "Hello, #{name}!" Aquí lo tiene. Hemos volcado los objetos Commit, tree y blob directamente desde el repositorio git. Es todo lo que hay: blobs, árboles y commits. ## Explore usted mismo 06 Explore por su cuenta el repositorio git manualmente. Vea si puede encontrar el archivo origina hello.rb desde el primer Commit siguiendo manualmente las referencias de los hash SHA1 iniciando desde el último Commit. * Aprender a crear una ramificación local en un repositorio. Es tiempo de hacer una reescritura mayor de la funcionalidad del programa hello world. Debido a que esto tomara un poco de tiempo, queremos poner estos cambios en una ramificación separada para aislarlo de los cambios en "master". ## Crear una Ramificación 01 Llamemos a nuestra nueva rama ‘greet’. > git checkout -b greet > git status NOTA: ``` git checkout -b <branchname> ``` es un atajo para ``` git branch <branchname> ``` seguido de ``` git checkout <branchname> ``` . Observe que el comando git status reporta que está en la rama ‘greet’. ## Cambios para Greet: Agregar una clase Greeter. 02 # Archivo: lib/greeter.rb > class Greeter def initialize(who) @who = who end def greet "Hello, #{@who}" end end > git add lib/greeter.rb > git commit -m "Added greeter class" ## Cambios para Greet: Modificar el archivo principal 03 Actualice el archivo hello.rb para hacer uso de greeter. > require 'greeter' # Default is World name = ARGV.first || "World" greeter = Greeter.new(name) puts greeter.greet > git add lib/hello.rb > git commit -m "Hello uses Greeter" ## Cambios para Greet: Actualizar el Rakefile 04 Actualice el Rakefile para hacer uso de un proceso externo de ruby. > #!/usr/bin/ruby -wKU task :default => :run task :run do ruby '-Ilib', 'lib/hello.rb' end > git add Rakefile > git commit -m "Updated Rakefile" ## A continuación 05 Ahora tenemos una ramificación llamada greet con tres Commits en él. A continuación aprenderemos a navegar y cambiarnos entre ramas. * Aprender a navegar entre las distintas ramificaciones de un repositorio. Ahora tenemos dos ramificaciones en nuestro proyecto: ## Cambie a la Ramificación "Master" 01 Just use the `git checkout` command to switch between branches. > git checkout master > cat lib/hello.rb > $ git checkout master Switched to branch 'master' $ cat lib/hello.rb # Default is World # Author: <NAME> (<EMAIL>) name = ARGV.first || "World" puts "Hello, #{name}!" Ahora se encuentra en la ramificación principal. Puede saberlo porque el archivo hello.rb no usa la clase `Greeter` . ## Cambiar a la Ramificación "Greet". 02 > git checkout greet > cat lib/hello.rb > $ git checkout greet Switched to branch 'greet' $ cat lib/hello.rb require 'greeter' # Default is World name = ARGV.first || "World" greeter = Greeter.new(name) puts greeter.greet El contenido de `lib/hello.rb` confirma que estamos de regreso a la ramificación greet. * Aprender a trabajar con múltiples Ramificaciones con diferentes (y posiblemente conflictivos) cambios. Mientras estaba cambiando la rama "greet", alguien más decidió actualizar la ramificación "master". Agregó un archivo README. ## Cambiar a la ramificación "master". 01 ## Cree el archivo README. 02 ## Haga Commit del archivo README en master. 03 > git add README > git commit -m "Added README" * Aprender a ver las ramificaciones divergentes en el repositorio. ## Ver la Ramificación Actual 01 Ahora tenemos dos ramificaciones divergentes en el repositorio. Use el siguiente comando de log para ver las ramas y cómo divergen. > $ git hist --all * e2257cb 2012-03-06 | Updated Rakefile (greet) [Jim Weirich] * a93f079 2012-03-06 | Hello uses Greeter [Jim Weirich] * 4b9457a 2012-03-06 | Added greeter class [Jim Weirich] | * 3ce0095 2012-03-06 | Added README (HEAD, master) [Jim Weirich] |/ * 76ba0a7 2012-03-06 | Added a Rakefile. [Jim Weirich] * b8f15c3 2012-03-06 | Moved hello.rb to lib [Jim Weirich] * 9c78ad8 2012-03-06 | Add an author/email comment [Jim Weirich] * 4054321 2012-03-06 | Added a comment (v1) [Jim Weirich] * 1b754e9 2012-03-06 | Added a default value (v1-beta) [Jim Weirich] * 3053491 2012-03-06 | Using ARGV [Jim Weirich] * 3cbf83b 2012-03-06 | First Commit [Jim Weirich] Aquí está nuestro primera oportunidad para ver en acción la opción `--graph` del `git hist` , esto causa que se dibuje en pantalla el arbol de Commit usando unos sencillos caracteres ASCII. Ahora podemos ver que tenemos dos ramificaciones (greet y master), y que la ramificación principal es el actual HEAD (encabezamiento). El antecesor común de ambas ramas es el “Added a Rakefile”. La bandera `--all` nos asegura que veremos todas las ramificaciones. El valor por defecto es mostrar sólo la gráfica de la rama actual. * Aprender a fusionar dos ramificaciones divergentes para llevar los cambios de nuevo a una sola rama ## Fusionar las ramificaciones 01 La fusión junta los cambios de dos ramificaciones. Regresemos a la rama "greet" y fusionemosla con la rama "master". > git checkout greet > git merge master > git hist --all Al fusionar "master" con "greet" periódicamente puede hacer que los cambios en greet sean más compatibles con la línea principal de desarrollo ("master"). Sin embargo, esto produce unas feas gráficas de Commits. Más adelante veremos la opción de rebasar en vez de fusionar. ## A continuación 02 Pero antes, ¿Qué tal si los cambios en master tienen conflicto con los cambios en greet? * Crear un cambio conflictivo en la ramificación principal. ## Cambie a la ramificación principal y cree un conflicto 01 Cambiese a la ramificación principal y haga este cambio: > puts "What's your name" my_name = gets.strip puts "Hello, #{my_name}!" > git add lib/hello.rb > git commit -m "Made interactive" ## Vea la ramificación 02 La ramificación principal en su Commit “Added README” ha sido fusionado con la rama "greet", pero hay un Commit adicional en Master que no ha sido fusionado con "greet". ## A Continuación 03 El último cambio en Master se conflictúa con algunos cambios existentes en "greet". A continuación resolveremos este problema. * Aprender a manejar conflictos en una fusión ## Fusionar "master" a "greet" 01 Regrese a la rama "greet" e intente fusionar el nuevo "master". > $ git checkout greet Switched to branch 'greet' $ git merge master Auto-merging lib/hello.rb CONFLICT (content): Merge conflict in lib/hello.rb Automatic merge failed; fix conflicts and then commit the result. Si abre lib/hello.rb, podrá ver: > <<<<<<< HEAD require 'greeter' # Default is World name = ARGV.first || "World" greeter = Greeter.new(name) puts greeter.greet ======= # Default is World puts "What's your name" my_name = gets.strip puts "Hello, #{my_name}!" >>>>>>> master La primera sección es la versión en el encabezamiento de la ramificación actual (greet). La segunda sección es la versión en la rama "master". ## Corija el Conflicto 02 Necesita resolver el conflicto manualmente. Modifique `lib/hello.rb` para tener lo siguiente: > require 'greeter' puts "What's your name" my_name = gets.strip greeter = Greeter.new(my_name) puts greeter.greet ## Commit the Conflict Resolution 03 > git add lib/hello.rb > git commit -m "Merged master fixed conflict." > $ git add lib/hello.rb $ git commit -m "Merged master fixed conflict." [greet 3165f66] Merged master fixed conflict. ## Fusión Avanzada 04 git no provee una herramienta gráfica para fusionar, pero funcionará correctamente con cualquier herramienta de terceros que desee utilizar. Vea http://onestepback.org/index.cgi/Tech/Git/UsingP4MergeWithGit.red para una descripción de cómo utilizar "Perforce", una herramienta para fusión con git. * Aprender la diferencia entre Cambio de Base (Rebasing) y Fusión (Merging). Exploremos la diferencia entre Cambio de Base y Fusión. Para lograrlo necesitamos regresar el repositorio al momento antes de la primera fusión, después de eso rehacer los mismos pasos, pero usando el Cambio de Base en vez de la Fusión. Haremos uso de el comando `reset` para cambiar la ramificación en el historial. * Reestablecer la ramificación "greet" al punto anterior de la primera fusión. Vamos a regresar en el tiempo a la ramificación "greet" en el punto antes de que lo fusionaramos. Podemos reestablecer una ramificación en el Commit que deseemos. Esto es, esencialmente, modificiar el apuntador de la ramificación a cualquier punto dentro del arbol de Commits. En este caso deseamos regresar la ramificación "greet" en el punto antes de la fusión con "master". Necesitamos encontrar el último Commit antes de la fusión. > git checkout greet > git hist Esto es un poco difícil de leer, pero observando los datos podemos ver que el Commit “Updated Rakefile” fue el último antes de fusionaramos la ramificación "greet". Vamos a reestablecer la ramificación "greet" a ese Commit. > git reset --hard <hash > $ git reset --hard e2257cb HEAD is now at e2257cb Updated Rakefile ## Revise la ramificación. 02 Busque en el log la ramificación "greet". Ya no tenemos los Commits de la fusión en el historial. * Reestablecer la ramificación principal al punto antes del Commit conflictivo. Cuando añadimos el modo interactivo a la ramificación principal, hicimos un cambio que tenía conflictos con los cambios en la ramificación greet. Vamos a regresar la ramificación principal al punto antes del cambio conflictivo. Esto nos permite demostrar el Cambio de Base sin preocuparnos sobre los conflictos. > git checkout master > git hist El Commit ‘Added README’ está justo antes del modo interactivo con conflicto. Reestableceremos la ramificación principal a ese Commit. > git reset --hard <hash> > git hist --all Revise el log. Se debe mostrar justo como estaba el repositorio antes de que hicieramos la fusión. * Usar el comando rebase en vez del comando merge. Regresamos en el tiempo antes de la primera fusión y deseamos tener los cambios de la ramificación principal en greet. Esta vez usaremos el comando rebase en vez del comando merge para traer los cambios desde la ramificación principal. > git checkout greet > git rebase master > git hist > $ go greet Switched to branch 'greet' $ $ git rebase master First, rewinding head to replay your work on top of it... Applying: added Greeter class Applying: hello uses Greeter Applying: updated Rakefile $ $ git hist * e1399d1 2012-03-06 | Updated Rakefile (HEAD, greet) [Jim Weirich] * 183c6ad 2012-03-06 | Hello uses Greeter [Jim Weirich] * 297678c 2012-03-06 | Added greeter class [Jim Weirich] * 3ce0095 2012-03-06 | Added README (master) [Jim Weirich] * 76ba0a7 2012-03-06 | Added a Rakefile. [Jim Weirich] * b8f15c3 2012-03-06 | Moved hello.rb to lib [Jim Weirich] * 9c78ad8 2012-03-06 | Add an author/email comment [Jim Weirich] * 4054321 2012-03-06 | Added a comment (v1) [Jim Weirich] * 1b754e9 2012-03-06 | Added a default value (v1-beta) [Jim Weirich] * 3053491 2012-03-06 | Using ARGV [<NAME>] * 3cbf83b 2012-03-06 | First Commit [<NAME>] ## Merge VS Rebase 01 El resultado final del Cambio de Base es muy similar a la Fusión. La ramificación "greet" ahora contiene todos sus cambios, así como los cambios en la ramificación principal. Sin embargo, el árbol de Commits es un poco diferente. El árbol de Commits para la ramificación "greet" ha sido reescrito para la ramificación principal forme parte del historial de Commit. Esto deja la cadena de commits lineal y mucho má fácil de leer. ## ¿Cuándo usar el comando Rebase, cuándo Merge? 02 No use Rebase * Si la ramificación es pública y compartida con otros. Reescribir ramificaciones públicas tiende a hacer enojar a otros miembros del equipo. * Cuando la exactitud del historial es importante (debido a que rebase reescribe el historial de Commits). Dada las directrices anteriores, yo tiendo a usar el coamdno rebase para ramificaciones locales de corta vida, y el comando merge para ramificaciones en repositorios públicos. * Hemos mantenido nuestra ramificación "greet" al día con la principal (vía rebase), ahora vamos a fusionar los cambios en "greet" con la ramificación principal. ## Fusionar greet en la ramificación principal 01 > $ git checkout master Switched to branch 'master' $ $ git merge greet Updating 3ce0095..e1399d1 Fast-forward Rakefile | 2 +- lib/greeter.rb | 8 ++++++++ lib/hello.rb | 6 ++++-- 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 lib/greeter.rb Debido a que el encabezado de la ramificación principal es el antecesor director del encabezado en "greet", git puede hacer una fusión "hacia adelante". Cuando adelantamos (fast-forwarding), el apuntador de la ramificación simplemente se mueve hacia adelante para apuntar al mismo commit que la ramificación "greet". Nunca habrá conflictos cuando se realiza una fusión "hacia adelante". ## Revisar los logs 02 Ahora las ramificaciones "greet" y "master" son idénticas. Hasta este punto hemos trabajado con un único repositorio git. Sin embargo, git es excelente para trabajar con múltiples repositorios. Estos repositorios extra pueden ser almacenados localmente, o quizás ser accedidos a través de una conexión de red. En la siguiente sección crearemos un nuevo repositorio llamado “cloned_hello”. Mostraremos cómo mover los cambios desde un repositorio a otro, y también a manejar conflictos cuando surjan problemas entre los dos repositorios. Por ahora, estaremos trabajando con repositorios locales (por ejemplo, repositorios almacenados en su disco duro local), sin embargo, muchas de las cosas aprendidas en esta sección aplicarán tanto para trabajo local como a remoto a través de la red. NOTA: Vamos a hacer cambios en ambas copias de nuestros repositorios. Asegúrese de poner atención en cuál repositorio está en cada paso de los siguientes laboratorios. * Aprender a hacer copias de repositorios. ## Vaya al directorio de trabajo 01 Vaya al directorio de trabajo y haga un clon de nuestro repositorio hello. > cd .. > pwd > ls NOTA: En nuestro directorio de trabajo. > $ cd .. $ pwd /Users/jerrynummi/Projects/edgecase/git_immersion/auto $ ls hello En este punto debe estar en su directorio de trabajo. Debe haber un único repositorio llamado “hello”. ## Crear un clon del repositorio hello 02 Vamos a clonar el repositorio. > git clone hello cloned_hello > ls > $ git clone hello cloned_hello Cloning into 'cloned_hello'... done. $ ls cloned_hello hello Ahora debe haber dos repositorios en el directorio de trabajo: el repositorio “hello” original y el nuevo repositorio clonado “cloned_hello”. * Aprender sobre ramificaciones en repositorios remotos. ## Vea el repositorio clonado 01 Vamos a observar el repositorio clonado. > cd cloned_hello > ls > $ cd cloned_hello $ ls README Rakefile lib Debe ver una lista de todos los archivos en el directorio nivel superior del repositorio original ( `README` , `Rakefile` y `lib` ). ## Revise el Historial del Repositorio 02 Ahora debe ver un listado de todos los Commits en el nuevo repositorio, y este debería coincidir (más o menos) con el historial de Commits en el repositorio original. La única diferencia debería ser los nombre de las ramificaciones. ## Ramificaciones Remotas 03 Debe ver una ramificación master (junto con HEAD) en el listado del historial. Pero tambien tendrá una cantidad de ramificaciones con nombre extraño (origin/master, origin/greet y origin/HEAD). Hablaremos de esto en un momento más. * Aprender sobre los nombres de repositorios remotos. > git remote > $ git remote origin Vemos que el repositorio clonado sabe sobre un repositorio llamado "origin". Veremos si podemos obtener más información sobre origin: > git remote show origin > $ git remote show origin * remote origin Fetch URL: /Users/jerrynummi/Projects/edgecase/git_immersion/auto/hello Push URL: /Users/jerrynummi/Projects/edgecase/git_immersion/auto/hello HEAD branch (remote HEAD is ambiguous, may be one of the following): greet master Remote branches: greet tracked master tracked Local branch configured for 'git pull': master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) Ahora vemos que el repositorio remoto “origin” es simplemente el repositorio original hello. Los repositorios remotos viven típicamente en una máquina separada, posiblemente en un servidor centralizado. Como podemos ver aquí, sin embargo, también pueden apuntar a repositorios en la misma máquina. No hay nada particularmente especial sobre el nombre “origin”, pero la convención generalizada es usar el nombre “origin” para el repositorio principal centralizado. * Aprender sobre ramificaciones locales VS remotas Veamos las ramificaciones disponibles en el repositorio clonado. > git branch > $ git branch * master Esto es, sólo la ramificación principal está en el listado. ¿Dónde está la ramificación "greet"? El comando git branch sólo lista la ramificación local por defecto. ## Listar Ramificaciones Remotas 01 Intente esto para ver todas las ramificaciones: > git branch -a > $ git branch -a * master remotes/origin/HEAD -> origin/master remotes/origin/greet remotes/origin/master Git tiene todos los Commits desde el repositorio original, pero las ramificaciones en el repositorio remoto no son tratadas como locales aquí. Si deseamos nuestra ramificación greet, tenemos que crearla por nosotros mismos. Veremos cómo hacerlo en unos minutos. * Realizar algunos cambios en el repositorio original así podemos tratar de enviar los cambios remotamente. ## Haga un cambio en el repositorio original hello 01 > cd ../hello > # (Debería estar en el repositorio hello original) NOTA: En el repositorio hello Haga el siguiente cambio a README: Ahora agregue y realice Commit de esto cambios > git add README > git commit -m "Changed README in original repo" ## Continuando 02 El repositorio original ahora tiene cambios posteriores que no están en la versión clonada. A continuación enviaremos esos cambios hacia el repositorio clonado. * Aprender como recibir cambios de un repositorio remoto. > cd ../cloned_hello > git fetch > git hist --all NOTA: En el repositorio cloned_hello En este punto el repositorio tiene todos los Commits del repositorio original, pero no están integrados en las ramificaciones locales del repositorio clonado. Encuentre el Commit “Changed README in original repo” en el repositorio arriba mostrado. Note que el Commit incluye “origin/master” y “origin/HEAD”. Ahora mire en el Commit “Updated Rakefile”. Verá que la ramificación principal apuna a éste Commit, no al nuevo commit que acabamos de recibir. El resultado de ésto es que el comando “git fetch” traerá los nuevos commits desde el repositorio remoto, pero no los fusionará en las ramificaciones locales. ## Revise el archivo README 01 Podemos demostrar que el README está sin cambios. ¿Puede verlo?, no hay cambios. * Aprender a obtener los cambios (vía comando pull) en la ramificación y directorio de trabajo actual. ## Fusionar los cambios recibidos en el repositorio principal (master) 01 > git merge origin/master > $ git merge origin/master Updating e1399d1..e18658c Fast-forward README | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) ## Revise el archivo README una vez más 02 Debería pode ver los cambio. Existen cambios. Incluso aunque “git fetch” no fusione los cambios, aún podemos fusionar manualmente los cambios del repositorio remoto. Veremos una combinación del proceso de fetch y merge en un sólo comando. * Aprender que `git pull` es equivalente a `git fetch` seguido de `git merge` . No vamos a ir por el proceso completo de crear otro cambio y recibirlo remotamente de nuevo, pero sí saber que haciendo lo siguiente: > git pull Es equivalente a los dos pasos vistos anteriormente: > git fetch > git merge origin/master * Aprender a agregar una ramificación local que rastree una ramificación remota. Las ramificaciones que inician con remotes/origin son ramificaciones de un repositorio original. Note que no tiene una ramificación llamada "greet", pero es conocido que el repositorio original sí la tiene. ## Agregue una ramificación loal que haga rastreo a una ramificación remota. 01 > git branch --track greet origin/greet > git branch -a > git hist --max-count=2 > $ git branch --track greet origin/greet Branch greet set up to track remote branch greet from origin. $ git branch -a greet * master remotes/origin/HEAD -> origin/master remotes/origin/greet remotes/origin/master $ git hist --max-count=2 * e18658c 2012-03-06 | Changed README in original repo (HEAD, origin/master, origin/HEAD, master) [Jim Weirich] * e1399d1 2012-03-06 | Updated Rakefile (origin/greet, greet) [Jim Weirich] Ahora podemos ver la ramificación "greet" en la lista de ramificaciones del comando log. * Aprender cómo crear un repositorio escueto. Los repositorios escuetos (sin directorio de trabajo) son generalmente usados para compartir ). ## Crear un repositorio escueto. 01 > cd .. > git clone --bare hello hello.git > ls hello.git NOTA: En el directorio de trabajo > $ git clone --bare hello hello.git Cloning into bare repository 'hello.git'... done. $ ls hello.git HEAD config description hooks info objects packed-refs refs La convención generalmente aceptada es que los repositorios terminados en ‘.git’ son repositorios escuetos. Podemos ver que no hay un directorio de trabajo en el repositorio hello.git. * Agregar el repositorio escueto como uno remoto en nuestro repositorio original. Agreguemos el repositorio hello.git a nuestro repositorio original. > cd hello > git remote add shared ../hello.git NOTA: En el repositorio . * Aprender a enviar cambios a un repositorio remoto. Debido a que los repositorios escuetos son usualmente compartidos en algún tipo de servidor de red, es usualmente difícil hacer un cambio de directorio en el repositorio y recibir cambios, así que necesitamos enviar nuestros cambios desde otro repositorio. Iniciemos creando un cambio a ser enviado remotamente. Edite el archivo README y realice un Commit con él. > This is the Hello World example from the git tutorial. (Changed in the original and pushed to shared) > git checkout master > git add README > git commit -m "Added shared comment to readme" Ahora envíe el cambio al repositorio remoto. > git push shared master shared es el nombre del repositorio que está recibiendo los cambios que estamos enviados. (Recuerde, lo agregamos como repositorio remoto en laboratorio previo.) > $ git push shared master To ../hello.git e18658c..e4b00d1 master -> master NOTA: Tenemos que nombrar explícitamente la ramificación principal que está recibiendo el cambio remoto. Es posible configurarlo automáticamente, pero en mi caso nunca recuerdo el comando para hacerlo. Revise la documentación de “Git Remote Branch” para una fácil administración de ramificaciones remotas. * Aprender a recibir cambios desde un repositorio compartido. Pase por el repositorio clonado y reciba los cambios que acabamos de enviar al repositorio compartido. > cd ../cloned_hello NOTA: En el repositorio cloned_hello. Continúe con … > git remote add shared ../hello.git > git branch --track shared master > git pull shared master > cat README * Aprender a configurar un servidor git para compartir repositorios. THay muchas formas para compartir un repositorio git en la red. Aquí está la manera rápida y sucia. ## Iniciar el servidor git 01 > # (Desde el directorio de trabajo) > git daemon --verbose --export-all --base-path=. Ahora, desde una ventana de terminal por separado, vaya al directorio de trabajo. > # (Desde el directorio de trabajo) > git clone git://localhost/hello.git network_hello > cd network_hello > ls Deberá ver una copia del proyecto hello. ## Enviando cambios al Demonio Git 02 Si desea enviar los cambios al repositorio git, agregue el parámetro ``` --enable=receive-pack ``` al comando del demonio git. Tenga cuidado porque aún no hay autentificación en este servidor, cualquiera podría envíar cambios a su repositorio. * Aprender a compartir repositorio a través del WIFI. Vea si su vecino está ejecutando un demonio git. Intercambie direcciones IP y vea si puede enviar cambios entre sus repositorios. NOTA: El paquete gitjour es realmente útil al estar compartiendo repositorios. Aquí están algunos tópicos que podría desar investigar por su cuenta: * Revertir cambios realizados * Final de Línea en diversos sistemas operativos * Servidores Remotos * Protocolos * Configuración SSH * Administración de Ramificaciones Remotas * Encontrando Commits con Bugs (git bisect) * Flujos de trabajo * Herramientas gráficas (gitx, gitk, magit) * Trabajando con GitHub
djangogrpcframework
readthedoc
Python
django-grpc-framework 0.2 documentation Django gRPC Framework[¶](#django-grpc-framework) === Django gRPC framework is a toolkit for building gRPC services with Django. Officially we only support proto3. User’s Guide[¶](#user-s-guide) --- This part of the documentation begins with installation, followed by more instructions for building services. ### Installation[¶](#installation) #### Requirements[¶](#requirements) We requires the following: * Python (3.6, 3.7, 3.8) * Django (2.2, 3.0) * Django REST Framework (3.10.x, 3.11.x) * gRPC * gRPC tools * proto3 #### virtualenv[¶](#virtualenv) Virtualenv might be something you want to use for development! let’s create one working environment: ``` $ mkdir myproject $ cd myproject $ python3 -m venv env $ source env/bin/activate ``` It is time to get the django grpc framework: ``` $ pip install djangogrpcframework $ pip install django $ pip install djangorestframework $ pip install grpcio $ pip install grpcio-tools ``` #### System Wide[¶](#system-wide) Install it for all users on the system: ``` $ sudo pip install djangogrpcframework ``` #### Development Version[¶](#development-version) Try the latest version: ``` $ source env/bin/activate $ git clone https://github.com/fengsp/django-grpc-framework.git $ cd django-grpc-framework $ python setup.py develop ``` ### Quickstart[¶](#quickstart) We’re going to create a simple service to allow clients to retrieve and edit the users in the system. #### Project setup[¶](#project-setup) Create a new Django project named `quickstart`, then start a new app called `account`: ``` # Create a virtual environment python3 -m venv env source env/bin/activate # Install Django and Django gRPC framework pip install django pip install djangorestframework pip install djangogrpcframework pip install grpcio pip install grpcio-tools # Create a new project and a new application django-admin startproject quickstart cd quickstart django-admin startapp account ``` Now sync the database: ``` python manage.py migrate ``` #### Update settings[¶](#update-settings) Add `django_grpc_framework` to `INSTALLED_APPS`, settings module is in `quickstart/settings.py`: ``` INSTALLED_APPS = [ ... 'django_grpc_framework', ] ``` #### Defining protos[¶](#defining-protos) Our first step is to define the gRPC service and messages, create a file `quickstart/account.proto` next to `quickstart/manage.py`: ``` syntax = "proto3"; package account; import "google/protobuf/empty.proto"; service UserController { rpc List(UserListRequest) returns (stream User) {} rpc Create(User) returns (User) {} rpc Retrieve(UserRetrieveRequest) returns (User) {} rpc Update(User) returns (User) {} rpc Destroy(User) returns (google.protobuf.Empty) {} } message User { int32 id = 1; string username = 2; string email = 3; repeated int32 groups = 4; } message UserListRequest { } message UserRetrieveRequest { int32 id = 1; } ``` Or you can generate it automatically based on `User` model: ``` python manage.py generateproto --model django.contrib.auth.models.User --fields id,username,email,groups --file account.proto ``` Next we need to generate gRPC code, from the `quickstart` directory, run: ``` python -m grpc_tools.protoc --proto_path=./ --python_out=./ --grpc_python_out=./ ./account.proto ``` #### Writing serializers[¶](#writing-serializers) Then we’re going to define a serializer, let’s create a new module named `account/serializers.py`: ``` from django.contrib.auth.models import User from django_grpc_framework import proto_serializers import account_pb2 class UserProtoSerializer(proto_serializers.ModelProtoSerializer): class Meta: model = User proto_class = account_pb2.User fields = ['id', 'username', 'email', 'groups'] ``` #### Writing services[¶](#writing-services) Now we’d write some a service, create `account/services.py`: ``` from django.contrib.auth.models import User from django_grpc_framework import generics from account.serializers import UserProtoSerializer class UserService(generics.ModelService): """ gRPC service that allows users to be retrieved or updated. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserProtoSerializer ``` #### Register handlers[¶](#register-handlers) Ok, let’s wire up the gRPC handlers, edit `quickstart/urls.py`: ``` import account_pb2_grpc from account.services import UserService urlpatterns = [] def grpc_handlers(server): account_pb2_grpc.add_UserControllerServicer_to_server(UserService.as_servicer(), server) ``` We’re done, the project layout should look like: ``` . ./quickstart ./quickstart/asgi.py ./quickstart/__init__.py ./quickstart/settings.py ./quickstart/urls.py ./quickstart/wsgi.py ./manage.py ./account ./account/migrations ./account/migrations/__init__.py ./account/services.py ./account/models.py ./account/serializers.py ./account/__init__.py ./account/apps.py ./account/admin.py ./account/tests.py ./account.proto ./account_pb2_grpc.py ./account_pb2.py ``` #### Calling our service[¶](#calling-our-service) Fire up the server with development mode: ``` python manage.py grpcrunserver --dev ``` We can now access our service from the gRPC client: ``` import grpc import account_pb2 import account_pb2_grpc with grpc.insecure_channel('localhost:50051') as channel: stub = account_pb2_grpc.UserControllerStub(channel) for user in stub.List(account_pb2.UserListRequest()): print(user, end='') ``` ### Tutorial[¶](#tutorial) This part provides a basic introduction to work with Django gRPC framework. In this tutorial, we will create a simple blog rpc server. You can get the source code in [tutorial example](https://github.com/fengsp/django-grpc-framework/tree/master/examples/tutorial). #### Building Services[¶](#building-services) This tutorial will create a simple blog gRPC Service. ##### Environment setup[¶](#environment-setup) Create a new virtual environment for our project: ``` python3 -m venv env source env/bin/activate ``` Install our packages: ``` pip install django pip install djangorestframework # we need the serialization pip install djangogrpcframework pip install grpcio pip install grpcio-tools ``` ##### Project setup[¶](#project-setup) Let’s create a new project to work with: ``` django-admin startproject tutorial cd tutorial ``` Now we can create an app that we’ll use to create a simple gRPC Service: ``` python manage.py startapp blog ``` We’ll need to add our new `blog` app and the `django_grpc_framework` app to `INSTALLED_APPS`. Let’s edit the `tutorial/settings.py` file: ``` INSTALLED_APPS = [ ... 'django_grpc_framework', 'blog', ] ``` ##### Create a model[¶](#create-a-model) Now we’re going to create a simple `Post` model that is used to store blog posts. Edit the `blog/models.py` file: ``` from django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] ``` We also need to create a migration for our post model, and sync the database: ``` python manage.py makemigrations blog python manage.py migrate ``` ##### Defining a service[¶](#defining-a-service) Our first step is to define the gRPC service and messages, create a directory `tutorial/protos` that sits next to `tutorial/manage.py`, create another directory `protos/blog_proto` and create the `protos/blog_proto/post.proto` file: ``` syntax = "proto3"; package blog_proto; import "google/protobuf/empty.proto"; service PostController { rpc List(PostListRequest) returns (stream Post) {} rpc Create(Post) returns (Post) {} rpc Retrieve(PostRetrieveRequest) returns (Post) {} rpc Update(Post) returns (Post) {} rpc Destroy(Post) returns (google.protobuf.Empty) {} } message Post { int32 id = 1; string title = 2; string content = 3; } message PostListRequest { } message PostRetrieveRequest { int32 id = 1; } ``` For a model-backed service, you could also just run the model proto generator: ``` python manage.py generateproto --model blog.models.Post --fields=id,title,content --file protos/blog_proto/post.proto ``` Then edit it as needed, here the package name can’t be automatically inferred by the proto generator, change `package post` to `package blog_proto`. Next we need to generate gRPC code, from the `tutorial` directory, run: ``` python -m grpc_tools.protoc --proto_path=./protos --python_out=./ --grpc_python_out=./ ./protos/blog_proto/post.proto ``` ##### Create a Serializer class[¶](#create-a-serializer-class) Before we implement our gRPC service, we need to provide a way of serializing and deserializing the post instances into protocol buffer messages. We can do this by declaring serializers, create a file in the `blog` directory named `serializers.py` and add the following: ``` from django_grpc_framework import proto_serializerss from blog.models import Post from blog_proto import post_pb2 class PostProtoSerializer(proto_serializers.ModelProtoSerializer): class Meta: model = Post proto_class = post_pb2.Post fields = ['id', 'title', 'content'] ``` ##### Write a service[¶](#write-a-service) With our serializer class, we’ll write a regular grpc service, create a file in the `blog` directory named `services.py` and add the following: ``` import grpc from google.protobuf import empty_pb2 from django_grpc_framework.services import Service from blog.models import Post from blog.serializers import PostProtoSerializer class PostService(Service): def List(self, request, context): posts = Post.objects.all() serializer = PostProtoSerializer(posts, many=True) for msg in serializer.message: yield msg def Create(self, request, context): serializer = PostProtoSerializer(message=request) serializer.is_valid(raise_exception=True) serializer.save() return serializer.message def get_object(self, pk): try: return Post.objects.get(pk=pk) except Post.DoesNotExist: self.context.abort(grpc.StatusCode.NOT_FOUND, 'Post:%s not found!' % pk) def Retrieve(self, request, context): post = self.get_object(request.id) serializer = PostProtoSerializer(post) return serializer.message def Update(self, request, context): post = self.get_object(request.id) serializer = PostProtoSerializer(post, message=request) serializer.is_valid(raise_exception=True) serializer.save() return serializer.message def Destroy(self, request, context): post = self.get_object(request.id) post.delete() return empty_pb2.Empty() ``` Finally we need to wire there services up, create `blog/handlers.py` file: ``` from blog._services import PostService from blog_proto import post_pb2_grpc def grpc_handlers(server): post_pb2_grpc.add_PostControllerServicer_to_server(PostService.as_servicer(), server) ``` Also we need to wire up the root handlers conf, in `tutorial/urls.py` file, include our blog app’s grpc handlers: ``` from blog.handlers import grpc_handlers as blog_grpc_handlers urlpatterns = [] def grpc_handlers(server): blog_grpc_handlers(server) ``` ##### Calling our service[¶](#calling-our-service) Now we can start up a gRPC server so that clients can actually use our service: ``` python manage.py grpcrunserver --dev ``` In another terminal window, we can test the server: ``` import grpc from blog_proto import post_pb2, post_pb2_grpc with grpc.insecure_channel('localhost:50051') as channel: stub = post_pb2_grpc.PostControllerStub(channel) print('--- Create ---') response = stub.Create(post_pb2.Post(title='t1', content='c1')) print(response, end='') print('--- List ---') for post in stub.List(post_pb2.PostListRequest()): print(post, end='') print('--- Retrieve ---') response = stub.Retrieve(post_pb2.PostRetrieveRequest(id=response.id)) print(response, end='') print('--- Update ---') response = stub.Update(post_pb2.Post(id=response.id, title='t2', content='c2')) print(response, end='') print('--- Delete ---') stub.Destroy(post_pb2.Post(id=response.id)) ``` #### Using Generic Services[¶](#using-generic-services) We provide a number of pre-built services as a shortcut for common usage patterns. The generic services allow you to quickly build services that map closely to database models. ##### Using mixins[¶](#using-mixins) The create/list/retrieve/update/destroy operations that we’ve been using so far are going to be similar for any model-backend services. Those operations are implemented in gRPC framework’s mixin classes. Let’s take a look at how we can compose the services by using the mixin classes, here is our `blog/services` file again: ``` from blog.models import Post from blog.serializers import PostProtoSerializer from django_grpc_framework import mixins from django_grpc_framework import generics class PostService(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericService): queryset = Post.objects.all() serializer_class = PostProtoSerializer ``` We are building our service with `GenericService`, and adding in `ListModelMixin`,``CreateModelMixin``, etc. The base class provides the core functionality, and the mixin classes provice the `.List()` and `.Create()` handlers. ##### Using model service[¶](#using-model-service) If you want all operations of create/list/retrieve/update/destroy, we provide one already mixed-in generic services: ``` class PostService(generics.ModelService): queryset = Post.objects.all() serializer_class = PostProtoSerializer ``` #### Writing and running tests[¶](#writing-and-running-tests) Let’s write some tests for our service and run them. ##### Writing tests[¶](#id1) Let’s edit the `blog/tests.py` file: ``` import grpc from django_grpc_framework.test import RPCTestCase from blog_proto import post_pb2, post_pb2_grpc from blog.models import Post class PostServiceTest(RPCTestCase): def test_create_post(self): stub = post_pb2_grpc.PostControllerStub(self.channel) response = stub.Create(post_pb2.Post(title='title', content='content')) self.assertEqual(response.title, 'title') self.assertEqual(response.content, 'content') self.assertEqual(Post.objects.count(), 1) def test_list_posts(self): Post.objects.create(title='title1', content='content1') Post.objects.create(title='title2', content='content2') stub = post_pb2_grpc.PostControllerStub(self.channel) post_list = list(stub.List(post_pb2.PostListRequest())) self.assertEqual(len(post_list), 2) ``` ##### Running tests[¶](#running-tests) Once you’ve written tests, run them: ``` python manage.py test ``` ### Services[¶](#services) Django gRPC framework provides an `Service` class, which is pretty much the same as using a regular gRPC generated servicer interface. For example: ``` import grpc from django_grpc_framework.services import Service from blog.models import Post from blog.serializers import PostProtoSerializer class PostService(Service): def get_object(self, pk): try: return Post.objects.get(pk=pk) except Post.DoesNotExist: self.context.abort(grpc.StatusCode.NOT_FOUND, 'Post:%s not found!' % pk) def Retrieve(self, request, context): post = self.get_object(request.id) serializer = PostProtoSerializer(post) return serializer.message ``` #### Service instance attributes[¶](#service-instance-attributes) The following attributes are available in a service instance. * `.request` - the gRPC request object * `.context` - the `grpc.ServicerContext` object * `.action` - the name of the current service method #### As servicer method[¶](#as-servicer-method) *classmethod* `Service.``as_servicer`(***initkwargs*)[¶](#django_grpc_framework.services.Service.as_servicer) Returns a gRPC servicer instance: ``` servicer = PostService.as_servicer() add_PostControllerServicer_to_server(servicer, server) ``` #### Root handlers hook[¶](#root-handlers-hook) We need a hanlders hook function to add all servicers to the server, for example: ``` def grpc_handlers(server): demo_pb2_grpc.add_UserControllerServicer_to_server(UserService.as_servicer(), server) ``` You can set the root handlers hook using the `ROOT_HANDLERS_HOOK` setting key, for example set the following in your `settings.py` file: ``` GRPC_FRAMEWORK = { ... 'ROOT_HANDLERS_HOOK': 'path.to.your.curtom_grpc_handlers', } ``` The default setting is `'{settings.ROOT_URLCONF}.grpc_handlers'`. ### Generic services[¶](#generic-services) The generic services provided by gRPC framework allow you to quickly build gRPC services that map closely to your database models. If the generic services don’t suit your needs, use the regular `Service` class, or reuse the mixins and base classes used by the generic services to compose your own set of ressable generic services. For example: ``` from blog.models import Post from blog.serializers import PostProtoSerializer from django_grpc_framework import generics class PostService(generics.ModelService): queryset = Post.objects.all() serializer_class = PostProtoSerializer ``` #### GenericService[¶](#genericservice) This class extends `Service` class, adding commonly required behavior for standard list and detail services. All concrete generic services is built by composing `GenericService`, with one or more mixin classes. ##### Attributes[¶](#attributes) **Basic settings:** The following attributes control the basic service behavior: * `queryset` - The queryset that should be used for returning objects from this service. You must set this or override the `get_queryset` method, you should call `get_queryset` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests. * `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. You must either set this attribute, or override the `get_serializer_class()` method. * `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to primary key field name. * `lookup_request_field` - The request field that should be used for object lookup. If unset this defaults to using the same value as `lookup_field`. ##### Methods[¶](#methods) *class* `django_grpc_framework.generics.``GenericService`(***kwargs*)[¶](#django_grpc_framework.generics.GenericService) Base class for all other generic services. `filter_queryset`(*queryset*)[¶](#django_grpc_framework.generics.GenericService.filter_queryset) Given a queryset, filter it, returning a new queryset. `get_object`()[¶](#django_grpc_framework.generics.GenericService.get_object) Returns an object instance that should be used for detail services. Defaults to using the lookup_field parameter to filter the base queryset. `get_queryset`()[¶](#django_grpc_framework.generics.GenericService.get_queryset) Get the list of items for this service. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. If you are overriding a handler method, it is important that you call `get_queryset()` instead of accessing the `queryset` attribute as `queryset` will get evaluated only once. Override this to provide dynamic behavior, for example: ``` def get_queryset(self): if self.action == 'ListSpecialUser': return SpecialUser.objects.all() return super().get_queryset() ``` `get_serializer`(**args*, ***kwargs*)[¶](#django_grpc_framework.generics.GenericService.get_serializer) Return the serializer instance that should be used for validating and deserializing input, and for serializing output. `get_serializer_class`()[¶](#django_grpc_framework.generics.GenericService.get_serializer_class) Return the class to use for the serializer. Defaults to using self.serializer_class. `get_serializer_context`()[¶](#django_grpc_framework.generics.GenericService.get_serializer_context) Extra context provided to the serializer class. Defaults to including `grpc_request`, `grpc_context`, and `service` keys. #### Mixins[¶](#mixins) The mixin classes provide the actions that are used to privide the basic service behavior. The mixin classes can be imported from `django_grpc_framework.mixins`. *class* `django_grpc_framework.mixins.``ListModelMixin`[¶](#django_grpc_framework.mixins.ListModelMixin) `List`(*request*, *context*)[¶](#django_grpc_framework.mixins.ListModelMixin.List) List a queryset. This sends a sequence of messages of `serializer.Meta.proto_class` to the client. Note This is a server streaming RPC. *class* `django_grpc_framework.mixins.``CreateModelMixin`[¶](#django_grpc_framework.mixins.CreateModelMixin) `Create`(*request*, *context*)[¶](#django_grpc_framework.mixins.CreateModelMixin.Create) Create a model instance. The request shoule be a proto message of `serializer.Meta.proto_class`. If an object is created this returns a proto message of `serializer.Meta.proto_class`. `perform_create`(*serializer*)[¶](#django_grpc_framework.mixins.CreateModelMixin.perform_create) Save a new object instance. *class* `django_grpc_framework.mixins.``RetrieveModelMixin`[¶](#django_grpc_framework.mixins.RetrieveModelMixin) `Retrieve`(*request*, *context*)[¶](#django_grpc_framework.mixins.RetrieveModelMixin.Retrieve) Retrieve a model instance. The request have to include a field corresponding to `lookup_request_field`. If an object can be retrieved this returns a proto message of `serializer.Meta.proto_class`. *class* `django_grpc_framework.mixins.``UpdateModelMixin`[¶](#django_grpc_framework.mixins.UpdateModelMixin) `Update`(*request*, *context*)[¶](#django_grpc_framework.mixins.UpdateModelMixin.Update) Update a model instance. The request shoule be a proto message of `serializer.Meta.proto_class`. If an object is updated this returns a proto message of `serializer.Meta.proto_class`. `perform_update`(*serializer*)[¶](#django_grpc_framework.mixins.UpdateModelMixin.perform_update) Save an existing object instance. *class* `django_grpc_framework.mixins.``DestroyModelMixin`[¶](#django_grpc_framework.mixins.DestroyModelMixin) `Destroy`(*request*, *context*)[¶](#django_grpc_framework.mixins.DestroyModelMixin.Destroy) Destroy a model instance. The request have to include a field corresponding to `lookup_request_field`. If an object is deleted this returns a proto message of `google.protobuf.empty_pb2.Empty`. `perform_destroy`(*instance*)[¶](#django_grpc_framework.mixins.DestroyModelMixin.perform_destroy) Delete an object instance. #### Concrete service classes[¶](#concrete-service-classes) The following classes are the concrete generic services. They can be imported from `django_grpc_framework.generics`. *class* `django_grpc_framework.generics.``CreateService`(***kwargs*)[¶](#django_grpc_framework.generics.CreateService) Concrete service for creating a model instance that provides a `Create()` handler. *class* `django_grpc_framework.generics.``ListService`(***kwargs*)[¶](#django_grpc_framework.generics.ListService) Concrete service for listing a queryset that provides a `List()` handler. *class* `django_grpc_framework.generics.``RetrieveService`(***kwargs*)[¶](#django_grpc_framework.generics.RetrieveService) Concrete service for retrieving a model instance that provides a `Retrieve()` handler. *class* `django_grpc_framework.generics.``DestroyService`(***kwargs*)[¶](#django_grpc_framework.generics.DestroyService) Concrete service for deleting a model instance that provides a `Destroy()` handler. *class* `django_grpc_framework.generics.``UpdateService`(***kwargs*)[¶](#django_grpc_framework.generics.UpdateService) Concrete service for updating a model instance that provides a `Update()` handler. *class* `django_grpc_framework.generics.``ReadOnlyModelService`(***kwargs*)[¶](#django_grpc_framework.generics.ReadOnlyModelService) Concrete service that provides default `List()` and `Retrieve()` handlers. *class* `django_grpc_framework.generics.``ModelService`(***kwargs*)[¶](#django_grpc_framework.generics.ModelService) Concrete service that provides default `Create()`, `Retrieve()`, `Update()`, `Destroy()` and `List()` handlers. You may need to provide custom classes that have certain actions, to create a base class that provides `List()` and `Create()` handlers, inherit from `GenericService` and mixin the required handlers: ``` from django_grpc_framework import mixins from django_grpc_framework import generics class ListCreateService(mixins.CreateModelMixin, mixins.ListModelMixin, GenericService): """ Concrete service that provides ``Create()`` and ``List()`` handlers. """ pass ``` ### Proto Serializers[¶](#proto-serializers) The serializers work almost exactly the same with REST framework’s `Serializer` class and `ModelSerializer`, but use `message` instead of `data` as input and output. #### Declaring serializers[¶](#declaring-serializers) Declaring a serializer looks very similar to declaring a rest framework serializer: ``` from rest_framework import serializers from django_grpc_framework import proto_serializers class PersonProtoSerializer(proto_serializers.ProtoSerializer): name = serializers.CharField(max_length=100) email = serializers.EmailField(max_length=100) class Meta: proto_class = hrm_pb2.Person ``` #### Overriding serialization and deserialization behavior[¶](#overriding-serialization-and-deserialization-behavior) A proto serializer is the same as one rest framework serializer, but we are adding the following logic: * Protobuf message -> Dict of python primitive datatypes. * Protobuf message <- Dict of python primitive datatypes. If you need to alter the convert behavior of a serializer class, you can do so by overriding the `.message_to_data()` or `.data_to_message` methods. Here is the default implementation: ``` from google.protobuf.json_format import MessageToDict, ParseDict class ProtoSerializer(BaseProtoSerializer, Serializer): def message_to_data(self, message): """Protobuf message -> Dict of python primitive datatypes. """ return MessageToDict( message, including_default_value_fields=True, preserving_proto_field_name=True ) def data_to_message(self, data): """Protobuf message <- Dict of python primitive datatypes.""" return ParseDict( data, self.Meta.proto_class(), ignore_unknown_fields=True ) ``` The default behavior requires you to provide `ProtoSerializer.Meta.proto_class`, it is the protobuf class that should be used for create output proto message object. You must either set this attribute, or override the `data_to_message()` method. #### Serializing objects[¶](#serializing-objects) We can now use `PersonProtoSerializer` to serialize a person object: ``` >>> serializer = PersonProtoSerializer(person) >>> serializer.message name: "amy" email: "<EMAIL>" >>> type(serializer.message) <class 'hrm_pb2.Person'> ``` #### Deserializing objects[¶](#deserializing-objects) Deserialization is similar: ``` >>> serializer = PersonProtoSerializer(message=message) >>> serializer.is_valid() True >>> serializer.validated_data OrderedDict([('name', 'amy'), ('email', '<EMAIL>')]) ``` #### ModelProtoSerializer[¶](#modelprotoserializer) This is the same as a rest framework `ModelSerializer`: ``` from django_grpc_framework import proto_serializers from hrm.models import Person import hrm_pb2 class PersonProtoSerializer(proto_serializers.ModelProtoSerializer): class Meta: model = Person proto_class = hrm_pb2.Person fields = '__all__' ``` ### Proto[¶](#proto) Django gRPC framework provides support for automatic generation of [proto](https://developers.google.com/protocol-buffers/docs/proto3). #### Generate proto for model[¶](#generate-proto-for-model) If you want to automatically generate proto definition based on a model, you can use the `generateproto` management command: ``` python manage.py generateproto --model django.contrib.auth.models.User ``` To specify fields and save it to a file, use: ``` python manage.py generateproto --model django.contrib.auth.models.User --fields id,username,email --file demo.proto ``` Once you’ve generated a proto file in this way, you can edit it as you wish. ### Server[¶](#server) #### grpcrunserver[¶](#grpcrunserver) Run a grpc server: ``` $ python manage.py grpcrunserver ``` Run a grpc development server, this tells Django to use the auto-reloader and run checks: ``` $ python manage.py grpcrunserver --dev ``` Run the server with a certain address: ``` $ python manage.py grpcrunserver 127.0.0.1:8000 --max-workers 5 ``` #### Configuration[¶](#configuration) ##### Setting the server interceptors[¶](#setting-the-server-interceptors) If you need to add server interceptors, you can do so by setting the `SERVER_INTERCEPTORS` setting. For example, have something like this in your `settings.py` file: ``` GRPC_FRAMEWORK = { ... 'SERVER_INTERCEPTORS': [ 'path.to.DoSomethingInterceptor', 'path.to.DoAnotherThingInterceptor', ] } ``` ### Testing[¶](#testing) Django gRPC framework includes a few helper classes that come in handy when writing tests for services. #### The test channel[¶](#the-test-channel) The test channel is a Python class that acts as a dummy gRPC channel, allowing you to test you services. You can simulate gRPC requests on a service method and get the response. Here is a quick example, let’s open Django shell `python manage.py shell`: ``` >>> from django_grpc_framework.test import Channel >>> channel = Channel() >>> stub = post_pb2_grpc.PostControllerStub(channel) >>> response = stub.Retrieve(post_pb2.PostRetrieveRequest(id=post_id)) >>> response.title 'This is a title' ``` #### RPC test cases[¶](#rpc-test-cases) Django gRPC framework includes the following test case classes, that mirror the existing Django test case classes, but provide a test `Channel` instead of `Client`. * `RPCSimpleTestCase` * `RPCTransactionTestCase` * `RPCTestCase` You can use these test case classes as you would for the regular Django test case classes, the `self.channel` attribute will be an `Channel` instance: ``` from django_grpc_framework.test import RPCTestCase from django.contrib.auth.models import User import account_pb2 import account_pb2_grpc class UserServiceTest(RPCTestCase): def test_create_user(self): stub = account_pb2_grpc.UserControllerStub(self.channel) response = stub.Create(account_pb2.User(username='tom', email='<EMAIL>')) self.assertEqual(response.username, 'tom') self.assertEqual(response.email, '<EMAIL>') self.assertEqual(User.objects.count(), 1) ``` ### Settings[¶](#settings) Configuration for gRPC framework is all namespaced inside a single Django setting, named `GRPC_FRAMEWORK`, for example your project’s `settings.py` file might look like this: ``` GRPC_FRAMEWORK = { 'ROOT_HANDLERS_HOOK': 'project.urls.grpc_handlers', } ``` #### Accessing settings[¶](#accessing-settings) If you need to access the values of gRPC framework’s settings in your project, you should use the `grpc_settings` object. For example: ``` from django_grpc_framework.settings import grpc_settings print(grpc_settings.ROOT_HANDLERS_HOOK) ``` The `grpc_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal. #### Configuration values[¶](#configuration-values) `ROOT_HANDLERS_HOOK`[¶](#ROOT_HANDLERS_HOOK) A hook function that takes gRPC server object as a single parameter and add all servicers to the server. Default: `'{settings.ROOT_URLCONF}.grpc_handlers'` One example for the hook function: ``` def grpc_handlers(server): demo_pb2_grpc.add_UserControllerServicer_to_server(UserService.as_servicer(), server) ``` `SERVER_INTERCEPTORS`[¶](#SERVER_INTERCEPTORS) An optional list of ServerInterceptor objects that observe and optionally manipulate the incoming RPCs before handing them over to handlers. Default: `None` ### Patterns for gRPC[¶](#patterns-for-grpc) This part contains some snippets and patterns for Django gRPC framework. #### Handling Partial Update[¶](#handling-partial-update) In proto3: 1. All fields are optional 2. Singular primitive fields, repeated fields, and map fields are initialized with default values (0, empty list, etc). There’s no way of telling whether a field was explicitly set to the default value (for example whether a boolean was set to false) or just not set at all. If we want to do a partial update on resources, we need to know whether a field was set or not set at all. There are different strategies that can be used to represent `unset`, we’ll use a pattern called `"Has Pattern"` here. ##### Singular field absence[¶](#singular-field-absence) In proto3, for singular field types, you can use the parent message’s `HasField()` method to check if a message type field value has been set, but you can’t do it with non-message singular types. For primitive types if you need `HasField` to you could use `"google/protobuf/wrappers.proto"`. Wrappers are useful for places where you need to distinguish between the absence of a primitive typed field and its default value: ``` import "google/protobuf/wrappers.proto"; service PersonController { rpc PartialUpdate(PersonPartialUpdateRequest) returns (Person) {} } message Person { int32 id = 1; string name = 2; string email = 3; } message PersonPartialUpdateRequest { int32 id = 1; google.protobuf.StringValue name = 2; google.protobuf.StringValue email = 3; } ``` Here is the client usage: ``` from google.protobuf.wrappers_pb2 import StringValue with grpc.insecure_channel('localhost:50051') as channel: stub = hrm_pb2_grpc.PersonControllerStub(channel) request = hrm_pb2.PersonPartialUpdateRequest(id=1, name=StringValue(value="amy")) response = stub.PartialUpdate(request) print(response, end='') ``` The service implementation: ``` class PersonService(generics.GenericService): queryset = Person.objects.all() serializer_class = PersonProtoSerializer def PartialUpdate(self, request, context): instance = self.get_object() serializer = self.get_serializer(instance, message=request, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return serializer.message ``` Or you can just use `PartialUpdateModelMixin` to get the same behavior: ``` class PersonService(mixins.PartialUpdateModelMixin, generics.GenericService): queryset = Person.objects.all() serializer_class = PersonProtoSerializer ``` ##### Repeated and map field absence[¶](#repeated-and-map-field-absence) If you need to check whether repeated fields and map fields are set or not, you need to do it manually: ``` message PersonPartialUpdateRequest { int32 id = 1; google.protobuf.StringValue name = 2; google.protobuf.StringValue email = 3; repeated int32 groups = 4; bool is_groups_set = 5; } ``` #### Null Support[¶](#null-support) In proto3, all fields are never null. However, we can use `Oneof` to define a nullable type, for example: ``` syntax = "proto3"; package snippets; import "google/protobuf/struct.proto"; service SnippetController { rpc Update(Snippet) returns (Snippet) {} } message NullableString { oneof kind { string value = 1; google.protobuf.NullValue null = 2; } } message Snippet { int32 id = 1; string title = 2; NullableString language = 3; } ``` The client example: ``` import grpc import snippets_pb2 import snippets_pb2_grpc from google.protobuf.struct_pb2 import NullValue with grpc.insecure_channel('localhost:50051') as channel: stub = snippets_pb2_grpc.SnippetControllerStub(channel) request = snippets_pb2.Snippet(id=1, title='snippet title') # send non-null value # request.language.value = "python" # send null value request.language.null = NullValue.NULL_VALUE response = stub.Update(request) print(response, end='') ``` The service implementation: ``` from django_grpc_framework import generics, mixins from django_grpc_framework import proto_serializers from snippets.models import Snippet import snippets_pb2 from google.protobuf.struct_pb2 import NullValue class SnippetProtoSerializer(proto_serializers.ModelProtoSerializer): class Meta: model = Snippet fields = '__all__' def message_to_data(self, message): data = { 'title': message.title, } if message.language.HasField('value'): data['language'] = message.language.value elif message.language.HasField('null'): data['language'] = None return data def data_to_message(self, data): message = snippets_pb2.Snippet( id=data['id'], title=data['title'], ) if data['language'] is None: message.language.null = NullValue.NULL_VALUE else: message.language.value = data['language'] return message class SnippetService(mixins.UpdateModelMixin, generics.GenericService): queryset = Snippet.objects.all() serializer_class = SnippetProtoSerializer ``` Additional Stuff[¶](#additional-stuff) --- Changelog and license here if you are interested. ### Changelog[¶](#changelog) #### Version 0.2[¶](#version-0-2) * Added test module * Added proto serializers * Added proto generators #### Version 0.1[¶](#version-0-1) First public release. ### License[¶](#license) This library is licensed under Apache License. > > > > > > > > > > > > > Apache License > > > > > > > Version 2.0, January 2004 > > > > > > > > > > <http://www.apache.org/licenses/> > > > > TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION > 1. Definitions. > “License” shall mean the terms and conditions for use, reproduction, > and distribution as defined by Sections 1 through 9 of this document. > “Licensor” shall mean the copyright owner or entity authorized by > the copyright owner that is granting the License. > “Legal Entity” shall mean the union of the acting entity and all > other entities that control, are controlled by, or are under common > control with that entity. For the purposes of this definition, > “control” means (i) the power, direct or indirect, to cause the > direction or management of such entity, whether by contract or > otherwise, or (ii) ownership of fifty percent (50%) or more of the > outstanding shares, or (iii) beneficial ownership of such entity. > “You” (or “Your”) shall mean an individual or Legal Entity > exercising permissions granted by this License. > “Source” form shall mean the preferred form for making modifications, > including but not limited to software source code, documentation > source, and configuration files. > “Object” form shall mean any form resulting from mechanical > transformation or translation of a Source form, including but > not limited to compiled object code, generated documentation, > and conversions to other media types. > “Work” shall mean the work of authorship, whether in Source or > Object form, made available under the License, as indicated by a > copyright notice that is included in or attached to the work > (an example is provided in the Appendix below). > “Derivative Works” shall mean any work, whether in Source or Object > form, that is based on (or derived from) the Work and for which the > editorial revisions, annotations, elaborations, or other modifications > represent, as a whole, an original work of authorship. For the purposes > of this License, Derivative Works shall not include works that remain > separable from, or merely link (or bind by name) to the interfaces of, > the Work and Derivative Works thereof. > “Contribution” shall mean any work of authorship, including > the original version of the Work and any modifications or additions > to that Work or Derivative Works thereof, that is intentionally > submitted to Licensor for inclusion in the Work by the copyright owner > or by an individual or Legal Entity authorized to submit on behalf of > the copyright owner. For the purposes of this definition, “submitted” > means any form of electronic, verbal, or written communication sent > to the Licensor or its representatives, including but not limited to > communication on electronic mailing lists, source code control systems, > and issue tracking systems that are managed by, or on behalf of, the > Licensor for the purpose of discussing and improving the Work, but > excluding communication that is conspicuously marked or otherwise > designated in writing by the copyright owner as “Not a Contribution.” > “Contributor” shall mean Licensor and any individual or Legal Entity > on behalf of whom a Contribution has been received by Licensor and > subsequently incorporated within the Work. > 2. Grant of Copyright License. Subject to the terms and conditions of > this License, each Contributor hereby grants to You a perpetual, > worldwide, non-exclusive, no-charge, royalty-free, irrevocable > copyright license to reproduce, prepare Derivative Works of, > publicly display, publicly perform, sublicense, and distribute the > Work and such Derivative Works in Source or Object form. > 3. Grant of Patent License. Subject to the terms and conditions of > this License, each Contributor hereby grants to You a perpetual, > worldwide, non-exclusive, no-charge, royalty-free, irrevocable > (except as stated in this section) patent license to make, have made, > use, offer to sell, sell, import, and otherwise transfer the Work, > where such license applies only to those patent claims licensable > by such Contributor that are necessarily infringed by their > Contribution(s) alone or by combination of their Contribution(s) > with the Work to which such Contribution(s) was submitted. If You > institute patent litigation against any entity (including a > cross-claim or counterclaim in a lawsuit) alleging that the Work > or a Contribution incorporated within the Work constitutes direct > or contributory patent infringement, then any patent licenses > granted to You under this License for that Work shall terminate > as of the date such litigation is filed. > 4. Redistribution. You may reproduce and distribute copies of the > Work or Derivative Works thereof in any medium, with or without > modifications, and in Source or Object form, provided that You > meet the following conditions: > 1. You must give any other recipients of the Work or > Derivative Works a copy of this License; and > 2. You must cause any modified files to carry prominent notices > stating that You changed the files; and > 3. You must retain, in the Source form of any Derivative Works > that You distribute, all copyright, patent, trademark, and > attribution notices from the Source form of the Work, > excluding those notices that do not pertain to any part of > the Derivative Works; and > 4. If the Work includes a “NOTICE” text file as part of its > distribution, then any Derivative Works that You distribute must > include a readable copy of the attribution notices contained > within such NOTICE file, excluding those notices that do not > pertain to any part of the Derivative Works, in at least one > of the following places: within a NOTICE text file distributed > as part of the Derivative Works; within the Source form or > documentation, if provided along with the Derivative Works; or, > within a display generated by the Derivative Works, if and > wherever such third-party notices normally appear. The contents > of the NOTICE file are for informational purposes only and > do not modify the License. You may add Your own attribution > notices within Derivative Works that You distribute, alongside > or as an addendum to the NOTICE text from the Work, provided > that such additional attribution notices cannot be construed > as modifying the License.You may add Your own copyright statement to Your modifications and > may provide additional or different license terms and conditions > for use, reproduction, or distribution of Your modifications, or > for any such Derivative Works as a whole, provided Your use, > reproduction, and distribution of the Work otherwise complies with > the conditions stated in this License. > 5. Submission of Contributions. Unless You explicitly state otherwise, > any Contribution intentionally submitted for inclusion in the Work > by You to the Licensor shall be under the terms and conditions of > this License, without any additional terms or conditions. > Notwithstanding the above, nothing herein shall supersede or modify > the terms of any separate license agreement you may have executed > with Licensor regarding such Contributions. > 6. Trademarks. This License does not grant permission to use the trade > names, trademarks, service marks, or product names of the Licensor, > except as required for reasonable and customary use in describing the > origin of the Work and reproducing the content of the NOTICE file. > 7. Disclaimer of Warranty. Unless required by applicable law or > agreed to in writing, Licensor provides the Work (and each > Contributor provides its Contributions) on an “AS IS” BASIS, > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or > implied, including, without limitation, any warranties or conditions > of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A > PARTICULAR PURPOSE. You are solely responsible for determining the > appropriateness of using or redistributing the Work and assume any > risks associated with Your exercise of permissions under this License. > 8. Limitation of Liability. In no event and under no legal theory, > whether in tort (including negligence), contract, or otherwise, > unless required by applicable law (such as deliberate and grossly > negligent acts) or agreed to in writing, shall any Contributor be > liable to You for damages, including any direct, indirect, special, > incidental, or consequential damages of any character arising as a > result of this License or out of the use or inability to use the > Work (including but not limited to damages for loss of goodwill, > work stoppage, computer failure or malfunction, or any and all > other commercial damages or losses), even if such Contributor > has been advised of the possibility of such damages. > 9. Accepting Warranty or Additional Liability. While redistributing > the Work or Derivative Works thereof, You may choose to offer, > and charge a fee for, acceptance of support, warranty, indemnity, > or other liability obligations and/or rights consistent with this > License. However, in accepting such obligations, You may act only > on Your own behalf and on Your sole responsibility, not on behalf > of any other Contributor, and only if You agree to indemnify, > defend, and hold each Contributor harmless for any liability > incurred by, or claims asserted against, such Contributor by reason > of your accepting any such warranty or additional liability. > END OF TERMS AND CONDITIONS > APPENDIX: How to apply the Apache License to your work. > > > To apply the Apache License to your work, attach the following > > boilerplate notice, with the fields enclosed by brackets “[]” > > replaced with your own identifying information. (Don’t include > > the brackets!) The text should be enclosed in the appropriate > > comment syntax for the file format. We also recommend that a > > file or class name and description of purpose be included on the > > same “printed page” as the copyright notice for easier > > identification within third-party archives. > Copyright [yyyy] [name of copyright owner] > Licensed under the Apache License, Version 2.0 (the “License”); > you may not use this file except in compliance with the License. > You may obtain a copy of the License at > > > <http://www.apache.org/licenses/LICENSE-2.0> > Unless required by applicable law or agreed to in writing, software > distributed under the License is distributed on an “AS IS” BASIS, > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. > See the License for the specific language governing permissions and > limitations under the License. [django-grpc-framework](index.html#document-index) === ### Navigation * [Installation](index.html#document-installation) * [Quickstart](index.html#document-quickstart) * [Tutorial](index.html#document-tutorial/index) * [Services](index.html#document-services) * [Generic services](index.html#document-generics) * [Proto Serializers](index.html#document-proto_serializers) * [Proto](index.html#document-protos) * [Server](index.html#document-server) * [Testing](index.html#document-testing) * [Settings](index.html#document-settings) * [Patterns for gRPC](index.html#document-patterns/index) * [Changelog](index.html#document-changelog) * [License](index.html#document-license) ### Related Topics * [Documentation overview](index.html#document-index) ### Quick search
github.com/go-mangos/mangos
go
Go
README [¶](#section-readme) --- ### mangos [![Linux Status](https://img.shields.io/travis/go-mangos/mangos.svg?label=linux)](https://travis-ci.org/go-mangos/mangos) [![Windows Status](https://img.shields.io/appveyor/ci/gdamore/mangos.svg?label=windows)](https://ci.appveyor.com/project/gdamore/mangos) [![Apache License](https://img.shields.io/badge/license-APACHE2-blue.svg)](https://github.com/nanomsg/mangos/raw/master/LICENSE) [![Gitter](https://img.shields.io/badge/gitter-join-brightgreen.svg)](https://gitter.im/go-mangos/mangos) [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://godoc.org/nanomsg.org/go-mangos) [![Go Report Card](https://goreportcard.com/badge/nanomsg.org/go-mangos)](https://goreportcard.com/report/nanomsg.org/go-mangos) Package mangos is an implementation in pure Go of the SP ("Scalability Protocols") messaging system. This makes heavy use of go channels, internally, but it can operate on systems that lack support for cgo. NOTE: The repository has moved from github.com/go-mangos/mangos. Please import using nanomsg.org/go-mangos. Also, be advised that the master branch of this repository may contain breaking changes. Therefore, consider using a tag, such as v1, to ensure that you have the latest stable version. The reference implementation of the SP protocols is available as [nanomsg™](http://www.nanomsg.org); there is also an effort to implement an improved and more capable version of nanomsg called [NNG™](https://github.com/nanomsg/nng). The design is intended to make it easy to add new transports with almost trivial effort, as well as new topologies ("protocols" in SP terminology.) At present, all of the Req/Rep, Pub/Sub, Pair, Bus, Push/Pull, and Surveyor/Respondent patterns are supported. Additionally, there is an experimental new pattern called STAR available. This pattern is like Bus, except that the messages are delivered not just to immediate peers, but to all members of the topology. Developers must be careful not to create cycles in their network when using this pattern, otherwise infinite loops can occur. Supported transports include TCP, inproc, IPC, Websocket, Websocket/TLS and TLS. Use addresses of the form "tls+tcp://:" to access TLS. Note that ipc:// is not supported on Windows (by either this or the reference implementation.) Forcing the local TCP port in Dial is not supported yet (this is rarely useful). Basic interoperability with nanomsg and NNG has been verified (you can do so yourself with nanocat and macat) for all protocols and transports that NNG and nanomsg support. Additionally there are a number of projects that use the two products together. There is a third party experimental QUIC transport available at [quic-mangos](https://github.com/lthibault/quic-mangos). (An RFE to make this transport official exists.) If you find this useful, I would appreciate knowing about it. I can be reached via my email address, garrett -at- damore -dot- org ### Installing #### Using *go get* ``` $ go get -u github.com/nanomsg/go-mangos ``` After this command *mangos* is ready to use. Its source will be in: ``` $GOPATH/src/pkg/github.com/nanomsg.org/go-mangos ``` You can use `go get -u -a` to update all installed packages. ### Documentation For docs, see <http://godoc.org/nanomsg.org/go-mangos> or run: ``` $ godoc nanomsg.org/go-mangos ``` ### Testing This package supports internal self tests, which can be run in the idiomatic Go way. (Note that most of the tests are in a test subdirectory.) ``` $ go test nanomsg.org/go-mangos/... ``` There are also internal benchmarks available: ``` $ go test -bench=. nanomsg.org/go-mangos/test ``` ### Commercial Support [Staysail Systems, Inc.](mailto:<EMAIL>) offers [commercial support](http://staysail.tech/support/mangos) for mangos. ### Examples Some examples are posted in the directories under examples/ in this project. These examples are rewrites (in Go) of <NAME>'s [Getting Started with Nanomsg](http://nanomsg.org/gettingstarted/index.html). godoc in the example directories will yield information about how to run each example program. Enjoy! Copyright 2018 The Mangos Authors mangos™, Nanomsg™ and NNG™ are [trademarks](http://nanomsg.org/trademarks.html) of <NAME>. Documentation [¶](#section-documentation) --- [Rendered for](https://go.dev/about#build-context) linux/amd64 windows/amd64 darwin/amd64 js/wasm ### Overview [¶](#pkg-overview) Package mangos provides a pure Go implementation of the Scalability Protocols. These are more familiarily known as "nanomsg" which is the C-based software package that is also their reference implementation. These protocols facilitate the rapid creation of applications which rely on multiple participants in sometimes complex communications topologies, including Request/Reply, Publish/Subscribe, Push/Pull, Surveyor/Respondant, etc. For more information, see www.nanomsg.org. ### Index [¶](#pkg-index) * [Constants](#pkg-constants) * [Variables](#pkg-variables) * [func Device(s1 Socket, s2 Socket) error](#Device) * [func DrainChannel(ch chan<- *Message, expire time.Time) bool](#DrainChannel) * [func NullRecv(ep Endpoint)](#NullRecv) * [func ProtocolName(number uint16) string](#ProtocolName) * [func ResolveTCPAddr(addr string) (*net.TCPAddr, error)](#ResolveTCPAddr) * [func StripScheme(t Transport, addr string) (string, error)](#StripScheme) * [func ValidPeers(p1, p2 Protocol) bool](#ValidPeers) * [type CondTimed](#CondTimed) * + [func (cv *CondTimed) WaitAbsTimeout(when time.Time) bool](#CondTimed.WaitAbsTimeout) + [func (cv *CondTimed) WaitRelTimeout(when time.Duration) bool](#CondTimed.WaitRelTimeout) * [type Dialer](#Dialer) * [type Endpoint](#Endpoint) * [type Listener](#Listener) * [type Message](#Message) * + [func NewMessage(sz int) *Message](#NewMessage) * + [func (m *Message) Dup() *Message](#Message.Dup) + [func (m *Message) Expired() bool](#Message.Expired) + [func (m *Message) Free()](#Message.Free) * [type Pipe](#Pipe) * + [func NewConnPipe(c net.Conn, sock Socket, props ...interface{}) (Pipe, error)](#NewConnPipe) + [func NewConnPipeIPC(c net.Conn, sock Socket, props ...interface{}) (Pipe, error)](#NewConnPipeIPC) * [type PipeDialer](#PipeDialer) * [type PipeListener](#PipeListener) * [type Port](#Port) * [type PortAction](#PortAction) * [type PortHook](#PortHook) * [type Protocol](#Protocol) * [type ProtocolRecvHook](#ProtocolRecvHook) * [type ProtocolSendHook](#ProtocolSendHook) * [type ProtocolSocket](#ProtocolSocket) * [type Socket](#Socket) * + [func MakeSocket(proto Protocol) Socket](#MakeSocket) * [type Transport](#Transport) * [type Waiter](#Waiter) * + [func (w *Waiter) Add()](#Waiter.Add) + [func (w *Waiter) Done()](#Waiter.Done) + [func (w *Waiter) Init()](#Waiter.Init) + [func (w *Waiter) Wait()](#Waiter.Wait) + [func (w *Waiter) WaitAbsTimeout(t time.Time) bool](#Waiter.WaitAbsTimeout) + [func (w *Waiter) WaitRelTimeout(d time.Duration) bool](#Waiter.WaitRelTimeout) ### Constants [¶](#pkg-constants) ``` const ( // OptionRaw is used to enable RAW mode processing. The details of // how this varies from normal mode vary from protocol to protocol. // RAW mode corresponds to AF_SP_RAW in the C variant, and must be // used with Devices. In particular, RAW mode sockets are completely // stateless -- any state between recv/send messages is included in // the message headers. Protocol names starting with "X" default // to the RAW mode of the same protocol without the leading "X". // The value passed is a bool. OptionRaw = "RAW" // OptionRecvDeadline is the time until the next Recv times out. The // value is a time.Duration. Zero value may be passed to indicate that // no timeout should be applied. A negative value indicates a // non-blocking operation. By default there is no timeout. OptionRecvDeadline = "RECV-DEADLINE" // OptionSendDeadline is the time until the next Send times out. The // value is a time.Duration. Zero value may be passed to indicate that // no timeout should be applied. A negative value indicates a // non-blocking operation. By default there is no timeout. OptionSendDeadline = "SEND-DEADLINE" // OptionRetryTime is used by REQ. The argument is a time.Duration. // When a request has not been replied to within the given duration, // the request will automatically be resent to an available peer. // This value should be longer than the maximum possible processing // and transport time. The value zero indicates that no automatic // retries should be sent. The default value is one minute. // // Note that changing this option is only guaranteed to affect requests // sent after the option is set. Changing the value while a request // is outstanding may not have the desired effect. OptionRetryTime = "RETRY-TIME" // OptionSubscribe is used by SUB/XSUB. The argument is a []byte. // The application will receive messages that start with this prefix. // Multiple subscriptions may be in effect on a given socket. The // application will not receive messages that do not match any current // subscriptions. (If there are no subscriptions for a SUB/XSUB // socket, then the application will not receive any messages. An // empty prefix can be used to subscribe to all messages.) OptionSubscribe = "SUBSCRIBE" // OptionUnsubscribe is used by SUB/XSUB. The argument is a []byte, // representing a previously established subscription, which will be // removed from the socket. OptionUnsubscribe = "UNSUBSCRIBE" // OptionSurveyTime is used to indicate the deadline for survey // responses, when used with a SURVEYOR socket. Messages arriving // after this will be discarded. Additionally, this will set the // OptionRecvDeadline when starting the survey, so that attempts to // receive messages fail with ErrRecvTimeout when the survey is // concluded. The value is a time.Duration. Zero can be passed to // indicate an infinite time. Default is 1 second. OptionSurveyTime = "SURVEY-TIME" // OptionTLSConfig is used to supply TLS configuration details. It // can be set using the ListenOptions or DialOptions. // The parameter is a tls.Config pointer. OptionTLSConfig = "TLS-CONFIG" // OptionWriteQLen is used to set the size, in messages, of the write // queue channel. By default, it's 128. This option cannot be set if // Dial or Listen has been called on the socket. OptionWriteQLen = "WRITEQ-LEN" // OptionReadQLen is used to set the size, in messages, of the read // queue channel. By default, it's 128. This option cannot be set if // Dial or Listen has been called on the socket. OptionReadQLen = "READQ-LEN" // OptionKeepAlive is used to set TCP KeepAlive. Value is a boolean. // Default is true. OptionKeepAlive = "KEEPALIVE" // OptionNoDelay is used to configure Nagle -- when true messages are // sent as soon as possible, otherwise some buffering may occur. // Value is a boolean. Default is true. OptionNoDelay = "NO-DELAY" // OptionLinger is used to set the linger property. This is the amount // of time to wait for send queues to drain when Close() is called. // Close() may block for up to this long if there is unsent data, but // will return as soon as all data is delivered to the transport. // Value is a time.Duration. Default is one second. OptionLinger = "LINGER" // OptionTTL is used to set the maximum time-to-live for messages. // Note that not all protocols can honor this at this time, but for // those that do, if a message traverses more than this many devices, // it will be dropped. This is used to provide protection against // loops in the topology. The default is protocol specific. OptionTTL = "TTL" // OptionMaxRecvSize supplies the maximum receive size for inbound // messages. This option exists because the wire protocol allows // the sender to specify the size of the incoming message, and // if the size were overly large, a bad remote actor could perform a // remote Denial-Of-Service by requesting ridiculously large message // sizes and then stalling on send. The default value is 1MB. // // A value of 0 removes the limit, but should not be used unless // absolutely sure that the peer is trustworthy. // // Not all transports honor this lmit. For example, this limit // makes no sense when used with inproc. // // Note that the size includes any Protocol specific header. It is // better to pick a value that is a little too big, than too small. // // This option is only intended to prevent gross abuse of the system, // and not a substitute for proper application message verification. OptionMaxRecvSize = "MAX-RCV-SIZE" // OptionReconnectTime is the initial interval used for connection // attempts. If a connection attempt does not succeed, then ths socket // will wait this long before trying again. An optional exponential // backoff may cause this value to grow. See OptionMaxReconnectTime // for more details. This is a time.Duration whose default value is // 100msec. This option must be set before starting any dialers. OptionReconnectTime = "RECONNECT-TIME" // OptionMaxReconnectTime is the maximum value of the time between // connection attempts, when an exponential backoff is used. If this // value is zero, then exponential backoff is disabled, otherwise // the value to wait between attempts is doubled until it hits this // limit. This value is a time.Duration, with initial value 0. // This option must be set before starting any dialers. OptionMaxReconnectTime = "MAX-RECONNECT-TIME" // OptionBestEffort enables non-blocking send operations on the // socket. Normally (for some socket types), a socket will block if // there are no receivers, or the receivers are unable to keep up // with the sender. (Multicast sockets types like Bus or Star do not // behave this way.) If this option is set, instead of blocking, the // message will be silently discarded. The value is a boolean, and // defaults to False. OptionBestEffort = "BEST-EFFORT" ) ``` ``` const ( PortActionAdd = [iota](/builtin#iota) PortActionRemove ) ``` PortAction values. ``` const ( // PropLocalAddr expresses a local address. For dialers, this is // the (often random) address that was locally bound. For listeners, // it is usually the service address. The value is a net.Addr. PropLocalAddr = "LOCAL-ADDR" // PropRemoteAddr expresses a remote address. For dialers, this is // the service address. For listeners, its the address of the far // end dialer. The value is a net.Addr. PropRemoteAddr = "REMOTE-ADDR" // PropTLSConnState is used to supply TLS connection details. The // value is a tls.ConnectionState. It is only valid when TLS is used. PropTLSConnState = "TLS-STATE" // PropHTTPRequest conveys an *http.Request. This property only exists // for websocket connections. PropHTTPRequest = "HTTP-REQUEST" ) ``` ``` const ( ProtoPair = (1 * 16) ProtoPub = (2 * 16) ProtoSub = (2 * 16) + 1 ProtoReq = (3 * 16) ProtoRep = (3 * 16) + 1 ProtoPush = (5 * 16) ProtoPull = (5 * 16) + 1 ProtoSurveyor = (6 * 16) + 2 ProtoRespondent = (6 * 16) + 3 ProtoBus = (7 * 16) ProtoStar = (100 * 16) ) ``` Useful constants for protocol numbers. Note that the major protocol number is stored in the upper 12 bits, and the minor (subprotocol) is located in the bottom 4 bits. ### Variables [¶](#pkg-variables) ``` var ( ErrBadAddr = [errors](/errors).[New](/errors#New)("invalid address") ErrBadHeader = [errors](/errors).[New](/errors#New)("invalid header received") ErrBadVersion = [errors](/errors).[New](/errors#New)("invalid protocol version") ErrTooShort = [errors](/errors).[New](/errors#New)("message is too short") ErrTooLong = [errors](/errors).[New](/errors#New)("message is too long") ErrClosed = [errors](/errors).[New](/errors#New)("connection closed") ErrConnRefused = [errors](/errors).[New](/errors#New)("connection refused") ErrSendTimeout = [errors](/errors).[New](/errors#New)("send time out") ErrRecvTimeout = [errors](/errors).[New](/errors#New)("receive time out") ErrProtoState = [errors](/errors).[New](/errors#New)("incorrect protocol state") ErrProtoOp = [errors](/errors).[New](/errors#New)("invalid operation for protocol") ErrBadTran = [errors](/errors).[New](/errors#New)("invalid or unsupported transport") ErrBadProto = [errors](/errors).[New](/errors#New)("invalid or unsupported protocol") ErrPipeFull = [errors](/errors).[New](/errors#New)("pipe full") ErrPipeEmpty = [errors](/errors).[New](/errors#New)("pipe empty") ErrBadOption = [errors](/errors).[New](/errors#New)("invalid or unsupported option") ErrBadValue = [errors](/errors).[New](/errors#New)("invalid option value") ErrGarbled = [errors](/errors).[New](/errors#New)("message garbled") ErrAddrInUse = [errors](/errors).[New](/errors#New)("address in use") ErrBadProperty = [errors](/errors).[New](/errors#New)("invalid property name") ErrTLSNoConfig = [errors](/errors).[New](/errors#New)("missing TLS configuration") ErrTLSNoCert = [errors](/errors).[New](/errors#New)("missing TLS certificates") ) ``` Various error codes. ### Functions [¶](#pkg-functions) #### func [Device](https://github.com/go-mangos/mangos/blob/v1.4.0/device.go#L30) [¶](#Device) ``` func Device(s1 [Socket](#Socket), s2 [Socket](#Socket)) [error](/builtin#error) ``` Device is used to create a forwarding loop between two sockets. If the same socket is listed (or either socket is nil), then a loopback device is established instead. Note that the single socket case is only valid for protocols where the underlying protocol can peer for itself (e.g. PAIR, or BUS, but not REQ/REP or PUB/SUB!) Both sockets will be placed into RAW mode. If the plumbing is successful, nil will be returned. Two threads will be established to forward messages in each direction. If either socket returns error on receive or send, the goroutine doing the forwarding will exit. This means that closing either socket will generally cause the goroutines to exit. Apart from closing the socket(s), no further operations should be performed against the socket. #### func [DrainChannel](https://github.com/go-mangos/mangos/blob/v1.4.0/util.go#L58) [¶](#DrainChannel) added in v1.2.0 ``` func DrainChannel(ch chan<- *[Message](#Message), expire [time](/time).[Time](/time#Time)) [bool](/builtin#bool) ``` DrainChannel waits for the channel of Messages to finish emptying (draining) for up to the expiration. It returns true if the drain completed (the channel is empty), false otherwise. #### func [NullRecv](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L213) [¶](#NullRecv) added in v1.2.0 ``` func NullRecv(ep [Endpoint](#Endpoint)) ``` NullRecv simply loops, receiving and discarding messages, until the Endpoint returns back a nil message. This allows the Endpoint to notice a dropped connection. It is intended for use by Protocols that are write only -- it lets them become aware of a loss of connectivity even when they have no data to send. #### func [ProtocolName](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L180) [¶](#ProtocolName) ``` func ProtocolName(number [uint16](/builtin#uint16)) [string](/builtin#string) ``` ProtocolName returns the name corresponding to a given protocol number. This is useful for transports like WebSocket, which use a text name rather than the number in the handshake. #### func [ResolveTCPAddr](https://github.com/go-mangos/mangos/blob/v1.4.0/transport.go#L157) [¶](#ResolveTCPAddr) added in v1.2.0 ``` func ResolveTCPAddr(addr [string](/builtin#string)) (*[net](/net).[TCPAddr](/net#TCPAddr), [error](/builtin#error)) ``` ResolveTCPAddr is like net.ResolveTCPAddr, but it handles the wildcard used in nanomsg URLs, replacing it with an empty string to indicate that all local interfaces be used. #### func [StripScheme](https://github.com/go-mangos/mangos/blob/v1.4.0/transport.go#L147) [¶](#StripScheme) ``` func StripScheme(t [Transport](#Transport), addr [string](/builtin#string)) ([string](/builtin#string), [error](/builtin#error)) ``` StripScheme removes the leading scheme (such as "http://") from an address string. This is mostly a utility for benefit of transport providers. #### func [ValidPeers](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L198) [¶](#ValidPeers) ``` func ValidPeers(p1, p2 [Protocol](#Protocol)) [bool](/builtin#bool) ``` ValidPeers returns true if the two sockets are capable of peering to one another. For example, REQ can peer with REP, but not with BUS. ### Types [¶](#pkg-types) #### type [CondTimed](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L23) [¶](#CondTimed) ``` type CondTimed struct { [sync](/sync).[Cond](/sync#Cond) } ``` CondTimed is a condition variable (ala sync.Cond) but inclues a timeout. #### func (*CondTimed) [WaitAbsTimeout](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L43) [¶](#CondTimed.WaitAbsTimeout) ``` func (cv *[CondTimed](#CondTimed)) WaitAbsTimeout(when [time](/time).[Time](/time#Time)) [bool](/builtin#bool) ``` WaitAbsTimeout is like WaitRelTimeout, but expires on an absolute time instead of a relative one. #### func (*CondTimed) [WaitRelTimeout](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L31) [¶](#CondTimed.WaitRelTimeout) ``` func (cv *[CondTimed](#CondTimed)) WaitRelTimeout(when [time](/time).[Duration](/time#Duration)) [bool](/builtin#bool) ``` WaitRelTimeout is like Wait, but it times out. The fact that it timed out can be determined by checking the return value. True indicates that it woke up without a timeout (signaled another way), whereas false indicates a timeout occurred. #### type [Dialer](https://github.com/go-mangos/mangos/blob/v1.4.0/dialer.go#L19) [¶](#Dialer) ``` type Dialer interface { // Close closes the dialer, and removes it from any active socket. // Further operations on the Dialer will return ErrClosed. Close() [error](/builtin#error) // Dial starts connecting on the address. If a connection fails, // it will restart. Dial() [error](/builtin#error) // Address returns the string (full URL) of the Listener. Address() [string](/builtin#string) // SetOption sets an option the Listener. Setting options // can only be done before Listen() has been called. SetOption(name [string](/builtin#string), value interface{}) [error](/builtin#error) // GetOption gets an option value from the Listener. GetOption(name [string](/builtin#string)) (interface{}, [error](/builtin#error)) } ``` Dialer is an interface to the underlying dialer for a transport and address. #### type [Endpoint](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L24) [¶](#Endpoint) ``` type Endpoint interface { // GetID returns a unique 31-bit value associated with the Endpoint. // The value is unique for a given socket, at a given time. GetID() [uint32](/builtin#uint32) // Close does what you think. Close() [error](/builtin#error) // SendMsg sends a message. On success it returns nil. This is a // blocking call. SendMsg(*[Message](#Message)) [error](/builtin#error) // RecvMsg receives a message. It blocks until the message is // received. On error, the pipe is closed and nil is returned. RecvMsg() *[Message](#Message) } ``` Endpoint represents the handle that a Protocol implementation has to the underlying stream transport. It can be thought of as one side of a TCP, IPC, or other type of connection. #### type [Listener](https://github.com/go-mangos/mangos/blob/v1.4.0/listener.go#L19) [¶](#Listener) ``` type Listener interface { // Close closes the listener, and removes it from any active socket. // Further operations on the Listener will return ErrClosed. Close() [error](/builtin#error) // Listen starts listening for new connectons on the address. Listen() [error](/builtin#error) // Address returns the string (full URL) of the Listener. Address() [string](/builtin#string) // SetOption sets an option the Listener. Setting options // can only be done before Listen() has been called. SetOption(name [string](/builtin#string), value interface{}) [error](/builtin#error) // GetOption gets an option value from the Listener. GetOption(name [string](/builtin#string)) (interface{}, [error](/builtin#error)) } ``` Listener is an interface to the underlying listener for a transport and address. #### type [Message](https://github.com/go-mangos/mangos/blob/v1.4.0/message.go#L28) [¶](#Message) ``` type Message struct { // Header carries any protocol (SP) specific header. Applications // should not modify or use this unless they are using Raw mode. // No user data may be placed here. Header [][byte](/builtin#byte) // Body carries the body of the message. This can also be thought // of as the message "payload". Body [][byte](/builtin#byte) // Port may be set on message receipt, to indicate the Port from // which the Message was received. There are no guarantees that the // Port is still active, and applications should only use this for // informational purposes. Port [Port](#Port) // contains filtered or unexported fields } ``` Message encapsulates the messages that we exchange back and forth. The meaning of the Header and Body fields, and where the splits occur, will vary depending on the protocol. Note however that any headers applied by transport layers (including TCP/ethernet headers, and SP protocol independent length headers), are *not* included in the Header. #### func [NewMessage](https://github.com/go-mangos/mangos/blob/v1.4.0/message.go#L156) [¶](#NewMessage) ``` func NewMessage(sz [int](/builtin#int)) *[Message](#Message) ``` NewMessage is the supported way to obtain a new Message. This makes use of a "cache" which greatly reduces the load on the garbage collector. #### func (*Message) [Dup](https://github.com/go-mangos/mangos/blob/v1.4.0/message.go#L134) [¶](#Message.Dup) ``` func (m *[Message](#Message)) Dup() *[Message](#Message) ``` Dup creates a "duplicate" message. What it really does is simply increment the reference count on the message. Note that since the underlying message is actually shared, consumers must take care not to modify the message. (We might revise this API in the future to add a copy-on-write facility, but for now modification is neither needed nor supported.) Applications should *NOT* make use of this function -- it is intended for Protocol, Transport and internal use only. #### func (*Message) [Expired](https://github.com/go-mangos/mangos/blob/v1.4.0/message.go#L144) [¶](#Message.Expired) added in v1.2.0 ``` func (m *[Message](#Message)) Expired() [bool](/builtin#bool) ``` Expired returns true if the message has "expired". This is used by transport implementations to discard messages that have been stuck in the write queue for too long, and should be discarded rather than delivered across the transport. This is only used on the TX path, there is no sense of "expiration" on the RX path. #### func (*Message) [Free](https://github.com/go-mangos/mangos/blob/v1.4.0/message.go#L115) [¶](#Message.Free) ``` func (m *[Message](#Message)) Free() ``` Free decrements the reference count on a message, and releases its resources if no further references remain. While this is not strictly necessary thanks to GC, doing so allows for the resources to be recycled without engaging GC. This can have rather substantial benefits for performance. #### type [Pipe](https://github.com/go-mangos/mangos/blob/v1.4.0/transport.go#L29) [¶](#Pipe) ``` type Pipe interface { // Send sends a complete message. In the event of a partial send, // the Pipe will be closed, and an error is returned. For reasons // of efficiency, we allow the message to be sent in a scatter/gather // list. Send(*[Message](#Message)) [error](/builtin#error) // Recv receives a complete message. In the event that either a // complete message could not be received, an error is returned // to the caller and the Pipe is closed. // // To mitigate Denial-of-Service attacks, we limit the max message // size to 1M. Recv() (*[Message](#Message), [error](/builtin#error)) // Close closes the underlying transport. Further operations on // the Pipe will result in errors. Note that messages that are // queued in transport buffers may still be received by the remote // peer. Close() [error](/builtin#error) // LocalProtocol returns the 16-bit SP protocol number used by the // local side. This will normally be sent to the peer during // connection establishment. LocalProtocol() [uint16](/builtin#uint16) // RemoteProtocol returns the 16-bit SP protocol number used by the // remote side. This will normally be received from the peer during // connection establishment. RemoteProtocol() [uint16](/builtin#uint16) // IsOpen returns true if the underlying connection is open. IsOpen() [bool](/builtin#bool) // GetProp returns an arbitrary transport specific property. // These are like options, but are read-only and specific to a single // connection. If the property doesn't exist, then ErrBadProperty // should be returned. GetProp([string](/builtin#string)) (interface{}, [error](/builtin#error)) } ``` Pipe behaves like a full-duplex message-oriented connection between two peers. Callers may call operations on a Pipe simultaneously from different goroutines. (These are different from net.Conn because they provide message oriented semantics.) Pipe is only intended for use by transport implementors, and should not be directly used in applications. #### func [NewConnPipe](https://github.com/go-mangos/mangos/blob/v1.4.0/conn.go#L138) [¶](#NewConnPipe) ``` func NewConnPipe(c [net](/net).[Conn](/net#Conn), sock [Socket](#Socket), props ...interface{}) ([Pipe](#Pipe), [error](/builtin#error)) ``` NewConnPipe allocates a new Pipe using the supplied net.Conn, and initializes it. It performs the handshake required at the SP layer, only returning the Pipe once the SP layer negotiation is complete. Stream oriented transports can utilize this to implement a Transport. The implementation will also need to implement PipeDialer, PipeAccepter, and the Transport enclosing structure. Using this layered interface, the implementation needn't bother concerning itself with passing actual SP messages once the lower layer connection is established. #### func [NewConnPipeIPC](https://github.com/go-mangos/mangos/blob/v1.4.0/connipc_posix.go#L26) [¶](#NewConnPipeIPC) ``` func NewConnPipeIPC(c [net](/net).[Conn](/net#Conn), sock [Socket](#Socket), props ...interface{}) ([Pipe](#Pipe), [error](/builtin#error)) ``` NewConnPipeIPC allocates a new Pipe using the IPC exchange protocol. #### type [PipeDialer](https://github.com/go-mangos/mangos/blob/v1.4.0/transport.go#L76) [¶](#PipeDialer) ``` type PipeDialer interface { // Dial is used to initiate a connection to a remote peer. Dial() ([Pipe](#Pipe), [error](/builtin#error)) // SetOption sets a local option on the dialer. // ErrBadOption can be returned for unrecognized options. // ErrBadValue can be returned for incorrect value types. SetOption(name [string](/builtin#string), value interface{}) [error](/builtin#error) // GetOption gets a local option from the dialer. // ErrBadOption can be returned for unrecognized options. GetOption(name [string](/builtin#string)) (value interface{}, err [error](/builtin#error)) } ``` PipeDialer represents the client side of a connection. Clients initiate the connection. PipeDialer is only intended for use by transport implementors, and should not be directly used in applications. #### type [PipeListener](https://github.com/go-mangos/mangos/blob/v1.4.0/transport.go#L95) [¶](#PipeListener) ``` type PipeListener interface { // Listen actually begins listening on the interface. It is // called just prior to the Accept() routine normally. It is // the socket equivalent of bind()+listen(). Listen() [error](/builtin#error) // Accept completes the server side of a connection. Once the // connection is established and initial handshaking is complete, // the resulting connection is returned to the client. Accept() ([Pipe](#Pipe), [error](/builtin#error)) // Close ceases any listening activity, and will specifically close // any underlying file descriptor. Once this is done, the only way // to resume listening is to create a new Server instance. Presumably // this function is only called when the last reference to the server // is about to go away. Established connections are unaffected. Close() [error](/builtin#error) // SetOption sets a local option on the listener. // ErrBadOption can be returned for unrecognized options. // ErrBadValue can be returned for incorrect value types. SetOption(name [string](/builtin#string), value interface{}) [error](/builtin#error) // GetOption gets a local option from the listener. // ErrBadOption can be returned for unrecognized options. GetOption(name [string](/builtin#string)) (value interface{}, err [error](/builtin#error)) // Address gets the local address. The value may not be meaningful // until Listen() has been called. Address() [string](/builtin#string) } ``` PipeListener represents the server side of a connection. Servers respond to a connection request from clients. PipeListener is only intended for use by transport implementors, and should not be directly used in applications. #### type [Port](https://github.com/go-mangos/mangos/blob/v1.4.0/port.go#L22) [¶](#Port) ``` type Port interface { // Address returns the address (URL form) associated with the port. // This matches the string passed to Dial() or Listen(). Address() [string](/builtin#string) // GetProp returns an arbitrary property. The details will vary // for different transport types. GetProp(name [string](/builtin#string)) (interface{}, [error](/builtin#error)) // IsOpen determines whether this is open or not. IsOpen() [bool](/builtin#bool) // Close closes the Conn. This does a disconnect, or something similar. // Note that if a dialer is present and active, it will redial. Close() [error](/builtin#error) // IsServer returns true if the connection is from a server (Listen). IsServer() [bool](/builtin#bool) // IsClient returns true if the connection is from a client (Dial). IsClient() [bool](/builtin#bool) // LocalProtocol returns the local protocol number. LocalProtocol() [uint16](/builtin#uint16) // RemoteProtocol returns the remote protocol number. RemoteProtocol() [uint16](/builtin#uint16) // Dialer returns the dialer for this Port, or nil if a server. Dialer() [Dialer](#Dialer) // Listener returns the listener for this Port, or nil if a client. Listener() [Listener](#Listener) } ``` Port represents the high level interface to a low level communications channel. There is one of these associated with a given TCP connection, for example. This interface is intended for application use. Note that applicatons cannot send or receive data on a Port directly. #### type [PortAction](https://github.com/go-mangos/mangos/blob/v1.4.0/port.go#L59) [¶](#PortAction) ``` type PortAction [int](/builtin#int) ``` PortAction determines whether the action on a Port is addition or removal. #### type [PortHook](https://github.com/go-mangos/mangos/blob/v1.4.0/port.go#L70) [¶](#PortHook) ``` type PortHook func([PortAction](#PortAction), [Port](#Port)) [bool](/builtin#bool) ``` PortHook is a function that is called when a port is added or removed to or from a Socket. In the case of PortActionAdd, the function may return false to indicate that the port should not be added. #### type [Protocol](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L44) [¶](#Protocol) ``` type Protocol interface { // Init is called by the core to allow the protocol to perform // any initialization steps it needs. It should save the handle // for future use, as well. Init([ProtocolSocket](#ProtocolSocket)) // Shutdown is used to drain the send side. It is only ever called // when the socket is being shutdown cleanly. Protocols should use // the linger time, and wait up to that time for sockets to drain. Shutdown([time](/time).[Time](/time#Time)) // AddEndpoint is called when a new Endpoint is added to the socket. // Typically this is as a result of connect or accept completing. AddEndpoint([Endpoint](#Endpoint)) // RemoveEndpoint is called when an Endpoint is removed from the socket. // Typically this indicates a disconnected or closed connection. RemoveEndpoint([Endpoint](#Endpoint)) // ProtocolNumber returns a 16-bit value for the protocol number, // as assigned by the SP governing body. (IANA?) Number() [uint16](/builtin#uint16) // Name returns our name. Name() [string](/builtin#string) // PeerNumber() returns a 16-bit number for our peer protocol. PeerNumber() [uint16](/builtin#uint16) // PeerName() returns the name of our peer protocol. PeerName() [string](/builtin#string) // GetOption is used to retrieve the current value of an option. // If the protocol doesn't recognize the option, EBadOption should // be returned. GetOption([string](/builtin#string)) (interface{}, [error](/builtin#error)) // SetOption is used to set an option. EBadOption is returned if // the option name is not recognized, EBadValue if the value is // invalid. SetOption([string](/builtin#string), interface{}) [error](/builtin#error) } ``` Protocol implementations handle the "meat" of protocol processing. Each protocol type will implement one of these. For protocol pairs (REP/REQ), there will be one for each half of the protocol. #### type [ProtocolRecvHook](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L92) [¶](#ProtocolRecvHook) ``` type ProtocolRecvHook interface { // RecvHook is called just before the message is handed to the // application. The message may be modified. If false is returned, // then the message is dropped. RecvHook(*[Message](#Message)) [bool](/builtin#bool) } ``` ProtocolRecvHook is intended to be an additional extension to the Protocol interface. #### type [ProtocolSendHook](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L101) [¶](#ProtocolSendHook) ``` type ProtocolSendHook interface { // SendHook is called when the application calls Send. // If false is returned, the message will be silently dropped. // Note that the message may be dropped for other reasons, // such as if backpressure is applied. SendHook(*[Message](#Message)) [bool](/builtin#bool) } ``` ProtocolSendHook is intended to be an additional extension to the Protocol interface. #### type [ProtocolSocket](https://github.com/go-mangos/mangos/blob/v1.4.0/protocol.go#L113) [¶](#ProtocolSocket) ``` type ProtocolSocket interface { // SendChannel represents the channel used to send messages. The // application injects messages to it, and the protocol consumes // messages from it. The channel may be closed when the core needs to // create a new channel, typically after an option is set that requires // the channel to be reconfigured. (OptionWriteQLen) When the protocol // implementation notices this, it should call this function again to obtain // the value of the new channel. SendChannel() <-chan *[Message](#Message) // RecvChannel is the channel used to receive messages. The protocol // should inject messages to it, and the application will consume them // later. RecvChannel() chan<- *[Message](#Message) // The protocol can wait on this channel to close. When it is closed, // it indicates that the application has closed the upper read socket, // and the protocol should stop any further read operations on this // instance. CloseChannel() <-chan struct{} // GetOption may be used by the protocol to retrieve an option from // the socket. This can ultimately wind up calling into the socket's // own GetOption handler, so care should be used! GetOption([string](/builtin#string)) (interface{}, [error](/builtin#error)) // SetOption is used by the Protocol to set an option on the socket. // Note that this may set transport options, or even call back down // into the protocol's own SetOption interface! SetOption([string](/builtin#string), interface{}) [error](/builtin#error) // SetRecvError is used to cause socket RX callers to report an // error. This can be used to force an error return rather than // waiting for a message that will never arrive (e.g. due to state). // If set to nil, then RX works normally. SetRecvError([error](/builtin#error)) // SetSendError is used to cause socket TX callers to report an // error. This can be used to force an error return rather than // waiting to send a message that will never be delivered (e.g. due // to incorrect state.) If set to nil, then TX works normally. SetSendError([error](/builtin#error)) } ``` ProtocolSocket is the "handle" given to protocols to interface with the socket. The Protocol implementation should not access any sockets or pipes except by using functions made available on the ProtocolSocket. Note that all functions listed here are non-blocking. #### type [Socket](https://github.com/go-mangos/mangos/blob/v1.4.0/socket.go#L21) [¶](#Socket) ``` type Socket interface { // Close closes the open Socket. Further operations on the socket // will return ErrClosed. Close() [error](/builtin#error) // Send puts the message on the outbound send queue. It blocks // until the message can be queued, or the send deadline expires. // If a queued message is later dropped for any reason, // there will be no notification back to the application. Send([][byte](/builtin#byte)) [error](/builtin#error) // Recv receives a complete message. The entire message is received. Recv() ([][byte](/builtin#byte), [error](/builtin#error)) // SendMsg puts the message on the outbound send. It works like Send, // but allows the caller to supply message headers. AGAIN, the Socket // ASSUMES OWNERSHIP OF THE MESSAGE. SendMsg(*[Message](#Message)) [error](/builtin#error) // RecvMsg receives a complete message, including the message header, // which is useful for protocols in raw mode. RecvMsg() (*[Message](#Message), [error](/builtin#error)) // Dial connects a remote endpoint to the Socket. The function // returns immediately, and an asynchronous goroutine is started to // establish and maintain the connection, reconnecting as needed. // If the address is invalid, then an error is returned. Dial(addr [string](/builtin#string)) [error](/builtin#error) DialOptions(addr [string](/builtin#string), options map[[string](/builtin#string)]interface{}) [error](/builtin#error) // NewDialer returns a Dialer object which can be used to get // access to the underlying configuration for dialing. NewDialer(addr [string](/builtin#string), options map[[string](/builtin#string)]interface{}) ([Dialer](#Dialer), [error](/builtin#error)) // Listen connects a local endpoint to the Socket. Remote peers // may connect (e.g. with Dial) and will each be "connected" to // the Socket. The accepter logic is run in a separate goroutine. // The only error possible is if the address is invalid. Listen(addr [string](/builtin#string)) [error](/builtin#error) ListenOptions(addr [string](/builtin#string), options map[[string](/builtin#string)]interface{}) [error](/builtin#error) NewListener(addr [string](/builtin#string), options map[[string](/builtin#string)]interface{}) ([Listener](#Listener), [error](/builtin#error)) // GetOption is used to retrieve an option for a socket. GetOption(name [string](/builtin#string)) (interface{}, [error](/builtin#error)) // SetOption is used to set an option for a socket. SetOption(name [string](/builtin#string), value interface{}) [error](/builtin#error) // Protocol is used to get the underlying Protocol. GetProtocol() [Protocol](#Protocol) // AddTransport adds a new Transport to the socket. Transport specific // options may have been configured on the Transport prior to this. AddTransport([Transport](#Transport)) // SetPortHook sets a PortHook function to be called when a Port is // added or removed from this socket (connect/disconnect). The previous // hook is returned (nil if none.) SetPortHook([PortHook](#PortHook)) [PortHook](#PortHook) } ``` Socket is the main access handle applications use to access the SP system. It is an abstraction of an application's "connection" to a messaging topology. Applications can have more than one Socket open at a time. #### func [MakeSocket](https://github.com/go-mangos/mangos/blob/v1.4.0/core.go#L142) [¶](#MakeSocket) ``` func MakeSocket(proto [Protocol](#Protocol)) [Socket](#Socket) ``` MakeSocket is intended for use by Protocol implementations. The intention is that they can wrap this to provide a "proto.NewSocket()" implementation. #### type [Transport](https://github.com/go-mangos/mangos/blob/v1.4.0/transport.go#L129) [¶](#Transport) ``` type Transport interface { // Scheme returns a string used as the prefix for SP "addresses". // This is similar to a URI scheme. For example, schemes can be // "tcp" (for "tcp://xxx..."), "ipc", "inproc", etc. Scheme() [string](/builtin#string) // NewDialer creates a new Dialer for this Transport. NewDialer(url [string](/builtin#string), sock [Socket](#Socket)) ([PipeDialer](#PipeDialer), [error](/builtin#error)) // NewListener creates a new PipeListener for this Transport. // This generally also arranges for an OS-level file descriptor to be // opened, and bound to the the given address, as well as establishing // any "listen" backlog. NewListener(url [string](/builtin#string), sock [Socket](#Socket)) ([PipeListener](#PipeListener), [error](/builtin#error)) } ``` Transport is the interface for transport suppliers to implement. #### type [Waiter](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L53) [¶](#Waiter) ``` type Waiter struct { [sync](/sync).[Mutex](/sync#Mutex) // contains filtered or unexported fields } ``` Waiter is a way to wait for completion, but it includes a timeout. It is similar in some respects to sync.WaitGroup. #### func (*Waiter) [Add](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L67) [¶](#Waiter.Add) ``` func (w *[Waiter](#Waiter)) Add() ``` Add adds a new go routine/item to wait for. This should be called before starting go routines you want to wait for, for example. #### func (*Waiter) [Done](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L77) [¶](#Waiter.Done) ``` func (w *[Waiter](#Waiter)) Done() ``` Done is called when the item to wait for is done. There should be a one to one correspondance between Add and Done. When the count drops to zero, any callers blocked in Wait() are woken. If the count drops below zero, it panics. #### func (*Waiter) [Init](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L60) [¶](#Waiter.Init) ``` func (w *[Waiter](#Waiter)) Init() ``` Init must be called to initialize the Waiter. #### func (*Waiter) [Wait](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L91) [¶](#Waiter.Wait) ``` func (w *[Waiter](#Waiter)) Wait() ``` Wait waits without a timeout. It only completes when the count drops to zero. #### func (*Waiter) [WaitAbsTimeout](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L114) [¶](#Waiter.WaitAbsTimeout) ``` func (w *[Waiter](#Waiter)) WaitAbsTimeout(t [time](/time).[Time](/time#Time)) [bool](/builtin#bool) ``` WaitAbsTimeout is like WaitRelTimeout, but waits until an absolute time. #### func (*Waiter) [WaitRelTimeout](https://github.com/go-mangos/mangos/blob/v1.4.0/waiter.go#L101) [¶](#Waiter.WaitRelTimeout) ``` func (w *[Waiter](#Waiter)) WaitRelTimeout(d [time](/time).[Duration](/time#Duration)) [bool](/builtin#bool) ``` WaitRelTimeout waits until either the count drops to zero, or the timeout expires. It returns true if the count is zero, false otherwise.
SIT
cran
R
Package ‘SIT’ December 20, 2022 Title Association Measurement Through Sliced Independence Test (SIT) Version 0.1.0 Description Computes the sit coefficient between two vectors x and y, possibly all paired coefficients for a matrix. The reference for the methods implemented here is Zhang, Yilin, <NAME>, and <NAME>. 2022. ``Sliced Independence Test.'' Statis- tica Sinica. <doi:10.5705/ss.202021.0203>. This package incorporates the Galton peas example. License MIT + file LICENSE Encoding UTF-8 RoxygenNote 7.2.1 LinkingTo Rcpp, RcppArmadillo Imports Rcpp, stats Date 2022-12-19 Suggests ggplot2, psychTools NeedsCompilation yes Author <NAME> [aut, cre] (<https://orcid.org/0000-0002-0673-5812>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2022-12-20 11:00:05 UTC R topics documented: blocksu... 2 calculateSI... 2 sitco... 3 blocksum Compute the block-wise sum of a vector. Description Compute the block-wise sum of a vector. Usage blocksum(r, c) Arguments r An integer vector c The number of observations in each block Value The function returns the block sum of the vector. calculateSIT Compute the cross rank coefficient sit on two vectors. Description This function computes the sit coefficient between two vectors x and y. Usage calculateSIT(x, y, c = 2) Arguments x Vector of numeric values in the first coordinate. y Vector of numeric values in the second coordinate. c The number of observations in each slice. Value The function returns the value of the sit coefficient. Note Auxiliary function with no checks for NA, etc. Author(s) <NAME>, <NAME> & <NAME> References <NAME>., <NAME>., & <NAME>. (2021). Sliced Independence Test. Statistica Sinica. https://doi.org/10.5705/ss.202021.0203. See Also sitcor Examples # Compute one of the coefficients library("psychTools") data(peas) calculateSIT(peas$parent,peas$child) calculateSIT(peas$child,peas$parent) sitcor Conduct the sliced independence test. Description This function computes the sit coefficient between two vectors x and y, possibly all paired coeffi- cients for a matrix. Usage sitcor( x, y = NULL, c = 2, pvalue = FALSE, ties = FALSE, method = "asymptotic", nperm = 199, factor = FALSE ) Arguments x Vector of numeric values in the first coordinate. y Vector of numeric values in the second coordinate. c The number of observations in each slice. pvalue Whether or not to return the p-value of rejecting independence, if TRUE the function also returns the standard deviation of sit. ties Do we need to handle ties? If ties=TRUE the algorithm assumes that the data has ties and employs the more elaborated theory for calculating s.d. and P-value. Otherwise, it uses the simpler theory. There is no harm in putting ties = TRUE even if there are no ties. method If method = "asymptotic" the function returns P-values computed by the asymp- totic theory (not available in the presence of ties). If method = "permutation", a permutation test with nperm permutations is employed to estimate the P-value. Usually, there is no need for the permutation test. The asymptotic theory is good enough. nperm In the case of a permutation test, nperm is the number of permutations to do. factor Whether to transform integers into factors, the default is to leave them alone. Value In the case pvalue=FALSE, function returns the value of the sit coefficient, if the input is a matrix, a matrix of coefficients is returned. In the case pvalue=TRUE is chosen, the function returns a list: sitcor The value of the sit coefficient. sd The standard deviation. pval The test p-value. Author(s) <NAME>, <NAME> & <NAME> References <NAME>., <NAME>., & <NAME>. (2022). Sliced Independence Test. Statistica Sinica. https://doi.org/10.5705/ss.202021.0203. Examples ##---- Should be DIRECTLY executable !! ---- library("psychTools") data(peas) # Visualize the peas data library(ggplot2) ggplot(peas,aes(parent,child)) + geom_count() + scale_radius(range=c(0,5)) + xlim(c(13.5,24))+ylim(c(13.5,24))+ coord_fixed() + theme(legend.position="bottom") # Compute one of the coefficients sitcor(peas$parent,peas$child, c = 4, pvalue=TRUE) sitcor(peas$child,peas$parent, c = 4) # Compute all the coefficients sitcor(peas, c = 4)
phylopath
cran
R
Package ‘phylopath’ October 10, 2023 Type Package Title Perform Phylogenetic Path Analysis Version 1.2.0 Maintainer <NAME> <<EMAIL>> Description A comprehensive and easy to use R implementation of confirmatory phylogenetic path analysis as described by <NAME> and Gonzalez-Voyer (2012) <doi:10.1111/j.1558-5646.2012.01790.x>. URL https://Ax3man.github.io/phylopath/ BugReports https://github.com/Ax3man/phylopath/issues License GPL-3 LazyData TRUE Depends R (>= 2.10) Imports ape (>= 4.1), future.apply, ggm (>= 2.3), ggplot2 (>= 3.0.0), ggraph (>= 1.0.0), igraph (>= 1.0.1), MuMIn (>= 1.15.6), phylolm (>= 2.5), purrr (>= 0.2.3), tibble RoxygenNote 7.2.3 Suggests knitr, rmarkdown, testthat VignetteBuilder knitr Encoding UTF-8 NeedsCompilation no Author <NAME> [aut, cre] Repository CRAN Date/Publication 2023-10-09 23:10:03 UTC R topics documented: averag... 2 average_DAG... 3 bes... 4 choic... 5 cichlid... 6 cichlids_tre... 7 coef_plo... 7 DA... 8 define_model_se... 9 est_DA... 10 phylo_pat... 11 plot.DA... 13 plot.fitted_DA... 15 plot_model_se... 16 red_lis... 18 red_list_tre... 19 rhin... 19 rhino_tre... 20 show_warning... 20 average Extract and average the best supported models from a phylogenetic path analysis. Description Extract and average the best supported models from a phylogenetic path analysis. Usage average(phylopath, cut_off = 2, avg_method = "conditional", ...) Arguments phylopath An object of class phylopath. cut_off The CICc cut-off used to select the best models. Use Inf to average over all models. Use the best() function to only use the top model, or choice() to select any single model. avg_method Either "full" or "conditional". The methods differ in how they deal with averaging a path coefficient where the path is absent in some of the models. The full method sets the coefficient (and the variance) for the missing paths to zero, meaning paths that are missing in some models will shrink towards zero. The conditional method only averages over models where the path ap- pears, making it more sensitive to small effects. Following von Hardenberg & Gonzalez-Voyer 2013, conditional averaging is set as the default. Also see MuMIn::model.avg(). ... Arguments to pass to phylolm::phylolm and phylolm::phyloglm. Provide boot = K parameter to enable bootstrapping, where K is the number of bootstrap repli- cates. If you specified other options in the original phylo_path call you don’t need to specify them again. Value An object of class fitted_DAG. Examples candidates <- define_model_set( A = NL ~ RS, B = RS ~ NL + BM, .common = c(LS ~ BM, DD ~ NL, NL ~ BM) ) p <- phylo_path(candidates, rhino, rhino_tree) summary(p) # Models A and B have similar support, so we may decide to take # their average. avg_model <- average(p) # Print the average model to see coefficients, se and ci: avg_model ## Not run: # Plot to show the weighted graph: plot(avg_model) # One can see that an averaged model is not necessarily a DAG itself. # This model actually has a path in two directions. # Note that coefficients that only occur in one of the models become much # smaller when we use full averaging: coef_plot(avg_model) coef_plot(average(p, method = 'full')) ## End(Not run) average_DAGs Perform model averaging on a list of DAGs. Description Perform model averaging on a list of DAGs. Usage average_DAGs( fitted_DAGs, weights = rep(1, length(coef)), avg_method = "conditional", ... ) Arguments fitted_DAGs A list of fitted_DAG objects containing coefficients and standard errors, usually obtained by using est_DAG() on several DAGs. weights A vector of associated model weights. avg_method Either "full" or "conditional". The methods differ in how they deal with averaging a path coefficient where the path is absent in some of the models. The full method sets the coefficient (and the variance) for the missing paths to zero, meaning paths that are missing in some models will shrink towards zero. The conditional method only averages over models where the path ap- pears, making it more sensitive to small effects. Following <NAME> & Gonzalez-Voyer 2013, conditional averaging is set as the default. Also see MuMIn::model.avg(). ... Additional arguments passed to MuMIn::par.avg(). For details on the error calculations, see MuMIn::par.avg(). Value An object of class fitted_DAG, including standard errors and confidence intervals. Examples # Normally, I would advocate the use of the phylo_path and average # functions, but this code shows how to average any set of models. Note # that not many checks are implemented, so you may want to be careful and # make sure the DAGs make sense and contain the same variables! candidates <- define_model_set( A = NL ~ BM, B = NL ~ LS, .common = c(LS ~ BM, DD ~ NL) ) fit_cand <- lapply(candidates, est_DAG, rhino, rhino_tree, model = 'lambda', method = 'logistic_MPLE') ave_cand <- average_DAGs(fit_cand) coef_plot(ave_cand) best Extract and estimate the best supported model from a phylogenetic path analysis. Description Extract and estimate the best supported model from a phylogenetic path analysis. Usage best(phylopath, ...) Arguments phylopath An object of class phylopath. ... Arguments to pass to phylolm::phylolm and phylolm::phyloglm. Provide boot = K parameter to enable bootstrapping, where K is the number of bootstrap repli- cates. If you specified other options in the original phylo_path call you don’t need to specify them again. Value An object of class fitted_DAG. Examples candidates <- define_model_set( A = NL ~ BM, B = NL ~ LS, .common = c(LS ~ BM, DD ~ NL) ) p <- phylo_path(candidates, rhino, rhino_tree) best_model <- best(p) # Print the best model to see coefficients, se and ci: best_model # Plot to show the weighted graph: plot(best_model) choice Extract and estimate an arbitrary model from a phylogenetic path analysis. Description Extract and estimate an arbitrary model from a phylogenetic path analysis. Usage choice(phylopath, choice, ...) Arguments phylopath An object of class phylopath. choice A character string of the name of the model to be chosen, or the index in model_set. ... Arguments to pass to phylolm::phylolm and phylolm::phyloglm. Provide boot = K parameter to enable bootstrapping, where K is the number of bootstrap repli- cates. If you specified other options in the original phylo_path call you don’t need to specify them again. Value An object of class fitted_DAG. Examples candidates <- define_model_set( A = NL ~ BM, B = NL ~ LS, .common = c(LS ~ BM, DD ~ NL) ) p <- phylo_path(candidates, rhino, rhino_tree) my_model <- choice(p, "B") # Print the best model to see coefficients, se and ci: my_model # Plot to show the weighted graph: plot(my_model) cichlids Cichlid traits and the evolution of cooperative breeding. Description A data set with binary traits, used in an analysis on the evolution of cooperative breeding by Dey et al 2017. Variable names are shortened for easy of use and consist of cooperative breeding (C), mating system (M), parental care (P), social grouping (G) and diet (D). All traits are coded as two level factors. Usage cichlids Format An object of class data.frame with 69 rows and 5 columns. Source <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. 2017. Direct benefits and evolutionary transitions to complex societies. Nat Ecol Evol 1: 137. cichlids_tree Cichlid phylogeny. Description The phylogenetic tree of cichlid species that accompanies the cichlids dataset. The phylogeny is based on five nuclear genes and three mitochondrial genes. Usage cichlids_tree Format An object of class phylo of length 4. Source <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. & <NAME>. 2017. Direct benefits and evolutionary transitions to complex societies. Nat Ecol Evol 1: 137. coef_plot Plot path coefficients and their confidence intervals or standard errors. Description Plot path coefficients and their confidence intervals or standard errors. Usage coef_plot( fitted_DAG, error_bar = "ci", order_by = "default", from = NULL, to = NULL, reverse_order = FALSE ) Arguments fitted_DAG A fitted DAG, usually obtained by best(), average() or est_DAG(). error_bar Whether to use confidence intervals ("ci") or standard errors ("se") as error bars. Will force standard errors with a message if confidence intervals are not available. order_by By "default", the paths are ordered as in the the model that is supplied. Usually this is in the order that was established by [phylo_path()] for all combined graphs. This can be change to "causal" to do a reordering based on the model at hand, or to "strength" to order them by the standardized regression coefficient. from Only show path coefficients from these nodes. Supply as a character vector. to Only show path coefficients to these nodes. Supply as a character vector. reverse_order If TRUE, the paths are plotted in reverse order. Particularly useful in combination with ggplot2::coord_flip() to create horizontal versions of the plot. Value A ggplot object. Examples d <- DAG(LS ~ BM, NL ~ BM, DD ~ NL + LS) plot(d) d_fitted <- est_DAG(d, rhino, rhino_tree, 'lambda') plot(d_fitted) coef_plot(d_fitted, error_bar = "se") # to create a horizontal version, use this: coef_plot(d_fitted, error_bar = "se", reverse_order = TRUE) + ggplot2::coord_flip() DAG Directed acyclic graphs (DAGs) Description This function is a simple wrapper around the function from the ggm package with the same name. The only differences are that the order argument defaults to TRUE and that it adds a DAG class for easy plotting. Typically, one would use define_model_set() to create models for use with the phylopath package. Usage DAG(..., order = TRUE) Arguments ... a sequence of model formulae order logical, defaulting to TRUE. If TRUE the nodes of the DAG are permuted accord- ing to the topological order. If FALSE the nodes are in the order they first appear in the model formulae (from left to right). For use in the phylopath package, this should always be kept to TRUE, but the argument is available to avoid poten- tial problems with masking the function from other packages. Details Supply a formulas for the model as arguments. Formulas should be of the form child ~ parent`` and describe each path ~ parent1 + parent2. Finally, an isolate (unconnected variable) can be included as being connected to itsel late ~ isolate‘. Value An object of classes matrix and DAG Examples # Use formula notation to create DAGs: plot(DAG(A~B, B~C)) # Use + to easily add multiple parents to a node: plot(DAG(A~B+C)) # Add a node as it's own parent to create an isolate: plot(DAG(A~B+C, D~D)) define_model_set Define a model set. Description This is a convenience function to quickly and clearly define a set of causal models. Supply a list of formulas for each model, using either c(). Formulas should be of the form child ~ parent and describe each path in your model. Multiple children of a single parent can be combined into a single formula: child ~ parent1 + parent2. Usage define_model_set(..., .common = NULL) Arguments ... Named arguments, which each are a lists of formulas defining the paths of a causal model. .common A list of formulas that contain causal paths that are common to each model. Details This function uses ggm::DAG(). Value A list of models, each of class matrix and DAG. Examples (m <- define_model_set( A = c(a~b, b~c), B = c(b~a, c~b), .common = c(d~a))) plot_model_set(m) est_DAG Add standardized path coefficients to a DAG. Description Add standardized path coefficients to a DAG. Usage est_DAG(DAG, data, tree, model, method, boot = 0, ...) Arguments DAG A directed acyclic graph, typically created with DAG. data A data.frame with data. If you have binary variables, make sure they are either character values or factors! tree A phylogenetic tree of class phylo. model The evolutionary model used for the regressions on continuous variables. See phylolm::phylolm for options and details. Defaults to Pagel’s lambda model method The estimation method for the binary models. See phylolm::phyloglm for op- tions and details. Defaults to logistic MPLE. boot The number of bootstrap replicates used to estimate confidence intervals. ... Arguments passed on to phylolm: lower.bound: optional lower bound for the optimization of the phylogenetic model parameter. upper.bound: optional upper bound for the optimization of the phylogenetic model parameter. starting.value: optional starting value for the optimization of the phyloge- netic model parameter. measurement_error: a logical value indicating whether there is measurement error sigma2_error (see Details). Arguments passed on to phyloglm: btol: bound on the linear predictor to bound the searching space. log.alpha.bound: bound for the log of the parameter alpha. start.beta: starting values for beta coefficients. start.alpha: starting values for alpha (phylogenetic correlation). Value An object of class fitted_DAG. Examples d <- DAG(LS ~ BM, NL ~ BM, DD ~ NL + LS) plot(d) d_fitted <- est_DAG(d, rhino, rhino_tree, 'lambda') plot(d_fitted) phylo_path Compare causal models in a phylogenetic context. Description Continuous variables are modeled using phylolm::phylolm, while binary traits are modeled using phylolm::phyloglm. Usage phylo_path( model_set, data, tree, model = "lambda", method = "logistic_MPLE", order = NULL, parallel = NULL, na.rm = TRUE, ... ) Arguments model_set A list of directed acyclic graphs. These are matrices, typically created with define_model_set. data A data.frame with data. If you have binary variables, make sure they are either character values or factors! tree A phylogenetic tree of class phylo. model The evolutionary model used for the regressions on continuous variables. See phylolm::phylolm for options and details. Defaults to Pagel’s lambda model method The estimation method for the binary models. See phylolm::phyloglm for op- tions and details. Defaults to logistic MPLE. order Causal order of the included variable, given as a character vector. This is used to determine which variable should be the dependent in the dsep regression equa- tions. If left unspecified, the order will be automatically determined. If the combination of all included models is itself a DAG, then the ordering of that full model is used. Otherwise, the most common ordering between each pair of variables is used to create a general ordering. parallel Superseded From v1.2 phylopath uses the future package for all parallel pro- cessing, see details. na.rm Should rows that contain missing values be dropped from the data as necessary (with a message)? ... Arguments passed on to phylolm: lower.bound: optional lower bound for the optimization of the phylogenetic model parameter. upper.bound: optional upper bound for the optimization of the phylogenetic model parameter. starting.value: optional starting value for the optimization of the phyloge- netic model parameter. measurement_error: a logical value indicating whether there is measurement error sigma2_error (see Details). Arguments passed on to phyloglm: btol: bound on the linear predictor to bound the searching space. log.alpha.bound: bound for the log of the parameter alpha. start.beta: starting values for beta coefficients. start.alpha: starting values for alpha (phylogenetic correlation). Details Parallel processing: From v1.2, phylopath uses the future framework for parallel processing. This is compatible with the parallel computation within the underlying phylolm, making it easy to enable parallel processing of multiple models, and of bootstrap replicates. To enable, simply set a parallel plan() using the future package. Typically, you’ll want to run future::plan("multisession", workers = n), where n is the number of cores. Now parallel processing is enabled. Return to se- quantial processing using future::plan("sequential") Value A phylopath object, with the following components: d_sep for each model a table with separation statements and statistics. model_set the DAGs data the supplied data tree the supplied tree model the employed model of evolution in phylolm method the employed method in phyloglm dots any additional arguments given, these are passed on to downstream functions warnings any warnings generated by the models Examples #see vignette('intro_to_phylopath') for more details candidates <- define_model_set( A = NL ~ BM, B = NL ~ LS, .common = c(LS ~ BM, DD ~ NL) ) p <- phylo_path(candidates, rhino, rhino_tree) # Printing p gives some general information: p # And the summary gives statistics to compare the models: summary(p) plot.DAG Plot a directed acyclic graph. Description Plot a directed acyclic graph. Usage ## S3 method for class 'DAG' plot( x, labels = NULL, algorithm = "sugiyama", manual_layout = NULL, text_size = 6, box_x = 12, box_y = 8, edge_width = 1.5, curvature = 0.02, rotation = 0, flip_x = FALSE, flip_y = FALSE, arrow = grid::arrow(type = "closed", 18, grid::unit(15, "points")), ... ) Arguments x A ‘DAG“ object, usually created with the define_model_set() or DAG() func- tion. labels An optional set of labels to use for the nodes. This should be a named vec- tor, of the form c(var1 = "label1", var2 = "label2"). If left at ‘NULL“, the variable names of the DAGs are used. algorithm A layout algorithm from igraph, see ggraph::create_layout(). By default, uses the Sugiyama layout algorithm, which is designed to minimize edge cross- ing in DAGs. manual_layout Alternatively, precisely define the layout yourself, by providing a data.frame that at least has a column name with all variable names, and columns x and y with positions to be plotted. Setting this parameter overrides algorithm but other changes, such as rotation and flips will still be applied. text_size Size of the node label text. box_x To avoid the arrows colliding with the nodes, specify the rectangular dimensions of an invisible box around each node. If you have long labels, you need to increase this. box_y To avoid the arrows colliding with the nodes, specify the rectangular dimensions of an invisible box around each node. If you have multi-line labels, you need to increase this. edge_width Width of the edges. curvature Curvature of the edges. A slight curvature can look pretty. rotation Supply the degrees you want to rotate the layout by. This is useful in order to put rotate your upstream nodes towards the top if needed. flip_x Whether to flip the node positions horizontally. flip_y Whether to flip the node positions vertically. arrow A grid::arrow object, specifying the shape and size of the arrowheads. The order of facets is taken from the ordering of the list, with the facet labels coming from the names of the list. If the list is unnamed, sequential lettering is used. ... Not used. Examples d <- DAG(a ~ b + c + d) plot(d) # Plot with manually defined positions: ml <- data.frame( name = c('a', 'b', 'c', 'd'), x = c(1, 1, 2, 2), y = c(1, 2, 1, 2) ) plot(d, manual_layout = ml) plot.fitted_DAG Plot a directed acyclic graph with path coefficients. Description Plot a directed acyclic graph with path coefficients. Usage ## S3 method for class 'fitted_DAG' plot( x, type = "width", labels = NULL, algorithm = "sugiyama", manual_layout = NULL, text_size = 6, box_x = 12, box_y = 8, edge_width = 1.25, curvature = 0.02, rotation = 0, flip_x = FALSE, flip_y = FALSE, arrow = grid::arrow(type = "closed", 18, grid::unit(15, "points")), colors = c("firebrick", "navy"), show.legend = TRUE, width_const = NULL, ... ) Arguments x An object of class fitted_DAG. type How to express the weight of the path. Either "width", or "color". labels An optional set of labels to use for the nodes. This should be a named vec- tor, of the form c(var1 = "label1", var2 = "label2"). If left at ‘NULL“, the variable names of the DAGs are used. algorithm A layout algorithm from igraph, see ggraph::create_layout(). By default, uses the Sugiyama layout algorithm, which is designed to minimize edge cross- ing in DAGs. manual_layout Alternatively, precisely define the layout yourself, by providing a data.frame that at least has a column name with all variable names, and columns x and y with positions to be plotted. Setting this parameter overrides algorithm but other changes, such as rotation and flips will still be applied. text_size Size of the node label text. box_x To avoid the arrows colliding with the nodes, specify the rectangular dimensions of an invisible box around each node. If you have long labels, you need to increase this. box_y To avoid the arrows colliding with the nodes, specify the rectangular dimensions of an invisible box around each node. If you have multi-line labels, you need to increase this. edge_width Width of the edges. curvature Curvature of the edges. A slight curvature can look pretty. rotation Supply the degrees you want to rotate the layout by. This is useful in order to put rotate your upstream nodes towards the top if needed. flip_x Whether to flip the node positions horizontally. flip_y Whether to flip the node positions vertically. arrow A grid::arrow object, specifying the shape and size of the arrowheads. The order of facets is taken from the ordering of the list, with the facet labels coming from the names of the list. If the list is unnamed, sequential lettering is used. colors The end points of the continuous color scale. Keep in mind that red and green are obvious colors to use, but are better to be avoided because of color blind users. show.legend Whether a legend for the color scale should be shown. width_const Deprecated. ... Not used. Examples d <- DAG(LS ~ BM, NL ~ BM, DD ~ NL + LS) d_fitted <- est_DAG(d, rhino, rhino_tree, 'lambda') plot(d_fitted) plot_model_set Plot several causal hypothesis at once. Description Plot several causal hypothesis at once. Usage plot_model_set( model_set, labels = NULL, algorithm = "kk", manual_layout = NULL, text_size = 5, box_x = 12, box_y = 10, edge_width = 1, curvature = 0.05, rotation = 0, flip_x = FALSE, flip_y = FALSE, nrow = NULL, arrow = grid::arrow(type = "closed", 15, grid::unit(10, "points")) ) Arguments model_set A list of DAG objects, usually created with define_model_set(). labels An optional set of labels to use for the nodes. This should be a named vec- tor, of the form c(var1 = "label1", var2 = "label2"). If left at ‘NULL“, the variable names of the DAGs are used. algorithm A layout algorithm from igraph, see ggraph::create_layout(). By default, uses the Kamada-Kawai layout algorithm. Another good option is "sugiyama", which is designed to minimize edge crossing in DAGs. However, it can often plot nodes too close together. manual_layout Alternatively, precisely define the layout yourself, by providing a data.frame that at least has a column name with all variable names, and columns x and y with positions to be plotted. Setting this parameter overrides algorithm but other changes, such as rotation and flips will still be applied. text_size Size of the node label text. box_x To avoid the arrows colliding with the nodes, specify the rectangular dimensions of an invisible box around each node. If you have long labels, you need to increase this. box_y To avoid the arrows colliding with the nodes, specify the rectangular dimensions of an invisible box around each node. If you have multi-line labels, you need to increase this. edge_width Width of the edges. curvature Curvature of the edges. A slight curvature can look pretty. rotation Supply the degrees you want to rotate the layout by. This is useful in order to put rotate your upstream nodes towards the top if needed. flip_x Whether to flip the node positions horizontally. flip_y Whether to flip the node positions vertically. nrow Number of rows to display the models on. arrow A grid::arrow object, specifying the shape and size of the arrowheads. The order of facets is taken from the ordering of the list, with the facet labels coming from the names of the list. If the list is unnamed, sequential lettering is used. Value A ggplot object. Examples m <- list(one = DAG(a ~ b + c + d), two = DAG(a ~ b, b ~ c, d ~ d)) plot_model_set(m) plot_model_set(m, algorithm = "sugiyama") red_list Data on brain size, life history and vulnerability to extinction Description A dataset with continuous variables affecting the conservation Status of mammalian species (the IUCN red list of threatened species). Usage red_list Format An object of class data.frame with 474 rows and 7 columns. Details It includes the following variables: brain size (Br), body size (B), gestation period (G), litter size (L), weening age (W), population density (P) and vulnerability to extinction (Status). Source <NAME>, <NAME>, <NAME>, Revilla E (2016) Larger brain size indirectly in- creases vulnerability to extinction in mammals. Evolution 70:1364-1375. doi: 10.1111/evo.12943 red_list_tree Mammalian phylogeny Description This is the accompanying phylogeny for the red_list data set. It is based on the updated mammalian supertree by Bininda-Emonds et al. 2007 & Fritz et al. 2009. Usage red_list_tree Format An object of class phylo of length 4. Source Gonzalez-Voyer, <NAME>. <NAME>. and <NAME>. 2016. Larger brain size indirectly increases vulnerability to extinction in mammals. Evolution 70:1364-1375. doi: 10.1111/evo.12943. Bininda-Emonds, <NAME>., <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. 2007. The delayed rise of present-day mammals. Nature 446:507-512. <NAME>., <NAME>. Bininda-Emonds, and <NAME>. 2009. Geographical variation in predictors of mammalian extinction risk: big is bad, but only in the tropics. Ecol. Lett. 12:538-549. rhino Rhinogrades traits. Description A simulated dataset, as used by Gonzalez-Voyer and <NAME> as an example, containing variables on body mass (BM), litter size (LS), nose length (NL), dispersal distance (DD) and range size (RS). Usage rhino Format An object of class data.frame with 100 rows and 6 columns. Source <NAME> & <NAME>. 2014. An Introduction to Phylogenetic Path Analysis. Chapter 8. In: Garamszegi LZ (ed.), Modern Phylogenetic Comparative Methods and Their Appli- cation in Evolutionary Biology. pp. 201-229. Springer-Verlag Berlin Heidelberg. doi:10.1111/j.1558- 5646.2012.01790.x rhino_tree Rhinogrades phylogeny. Description A phylogenetic tree for the 100 species of the rhino dataset. Usage rhino_tree Format An object of class phylo of length 4. Source <NAME> & <NAME>. 2014. An Introduction to Phylogenetic Path Analysis. Chapter 8. In: Garamszegi LZ (ed.), Modern Phylogenetic Comparative Methods and Their Appli- cation in Evolutionary Biology. pp. 201-229. Springer-Verlag Berlin Heidelberg. doi:10.1111/j.1558- 5646.2012.01790.x show_warnings Print out warnings from a phylopath analysis. Description Use this function after running phylo_path() to conveniently print any generated warnings to the screen. You can either provide no arguments, which will only work if you run it directly after the analysis, or you have to provide the phylopath object manually. Usage show_warnings(phylopath = NULL) Arguments phylopath A phylopath object of which the warnings should be printed.
r_enum
hex
Erlang
README === [![hex.pm version](https://img.shields.io/hexpm/v/r_enum.svg)](https://hex.pm/packages/r_enum) [![CI](https://github.com/tashirosota/ex-r_enum/actions/workflows/ci.yml/badge.svg)](https://github.com/tashirosota/ex-r_enum/actions/workflows/ci.yml) ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/tashirosota/ex-r_enum) REnum === REnum is Enum extended with convenient functions inspired by Ruby and Rails ActiveSupport. It also provides full support for native functions through metaprogramming. In addition to REnum, modules such as RList, RMap, RRange can also be used. * [REnum](#renum) + [Installation](#installation) + [About REnum](#about-renum) - [compact/1](#compact-1) - [each_slice/2](#each_slice-2) - [grep/2](#grep-2) - [reverse_each/2](#reverse_each-2) - [pluck/2](#pluck-2) - [exclude?/2](#exclude-2) - [without/2](#without-2) - [many?/2](#many-2) - [list_and_not_keyword?/1](#list_and_not_keyword-1) - [map_and_not_range?/1](#map_and_not_range-1) + [About RList](#about-rlist) - [push/2](#push-2) - [combination/2](#combination-2) - [fill/3](#fill-3) - [dig/3](#dig-3) - [intersection/2](#intersection-2) - [sample/2](#sample-2) - [values_at/1](#values_at-1) - [second/1](#second-1) - [from/2](#from-2) - [to_sentence/2](#to_sentence-2) - [new/2](#new-2) + [About RMap](#about-rmap) - [dig/2](#dig-2) - [each_key/2](#each_key-2) - [except/2](#except-2) - [invert/1](#invert-1) - [values_at/2](#values_at-2) - [deep_atomize_keys/1](#deep_atomize_keys-1) - [deep_transform_keys/2](#deep_transform_keys-2) + [About RRange](#about-rrange) - [begin/1](#begin-1) - [step/2](#step-2) - [overlaps?/2](#overlaps-2) + [About RUtils](#about-rutils) - [blank?/1](#blank-1) - [present?/1](#present-1) - [define_all_functions!/2](#define_all_functions-2) + [Progress](#progress) Installation --- ``` def deps do [ {:r_enum, "~> 0.6"} ] end ``` For the full list of available functions, see [API Reference](https://hexdocs.pm/r_enum/api-reference.html). About [REnum](https://hexdocs.pm/r_enum/REnum.html) --- **All the functions are available defined in** * [Enum](https://hexdocs.pm/r_enum/REnum.Native.html) * [REnum.Ruby](https://hexdocs.pm/r_enum/REnum.Ruby.html) * [REnum.ActiveSupport](https://hexdocs.pm/r_enum/REnum.ActiveSupport.html) * [REnum.Support](https://hexdocs.pm/r_enum/REnum.Support.html) ### compact/1 Returns an list of all non-nil elements. ``` iex> REnum.compact([1, nil, 2, 3]) [1, 2, 3] # See also REnum.ActiveSupport.compact_blank ``` ### each_slice/2 Returns Stream given enumerable sliced by each amount. ``` iex> ["a", "b", "c", "d", "e"] iex> |> REnum.each_slice(2) iex> |> Enum.to_list() [["a", "b"], ["c", "d"], ["e"]] ``` ### grep/2 Returns elements selected by a given pattern or function. ``` iex> ["foo", "bar", "car", "moo"] iex> |> REnum.grep(~r/ar/) ["bar", "car"] iex> 1..10 iex> |> REnum.grep(3..8) [3, 4, 5, 6, 7, 8] ``` ### reverse_each/2 Calls the function with each element, but in reverse order; returns given enumerable. ``` iex> REnum.reverse_each([1, 2, 3], &IO.inspect(&1)) # 3 # 2 # 1 [1, 2, 3] ``` ### pluck/2 Extract the given key from each element in the enumerable. ``` iex> payments = [ ...> %Payment{dollars: 5, cents: 99}, ...> %Payment{dollars: 10, cents: 0}, ...> %Payment{dollars: 0, cents: 5} ...> ] iex> REnum.pluck(payments, [:dollars, :cents]) [[5, 99], [10, 0], [0, 5]] iex> REnum.pluck(payments, :dollars) [5, 10, 0] iex> REnum.pluck([], :dollars) [] ``` ### exclude?/2 The negative of the `Enum.member?`.Returns true+if the collection does not include the object. ``` iex> REnum.exclude?([2], 1) true iex> REnum.exclude?([2], 2) false # See also REnum.ActiveSupport.include? ``` ### without/2 Returns enumerable excluded the specified elements. ``` iex> REnum.without(1..5, [1, 5]) [2, 3, 4] iex> REnum.without(%{foo: 1, bar: 2, baz: 3}, [:bar]) %{foo: 1, baz: 3} # See also REnum.ActiveSupport.including ``` ### many?/2 Returns true if the enumerable has more than 1 element. ``` iex> REnum.many?([]) false iex> REnum.many?([1]) false iex> REnum.many?([1, 2]) true iex> REnum.many?(%{}) false iex> REnum.many?(%{a: 1}) false iex> REnum.many?(%{a: 1, b: 2}) true ``` ### list_and_not_keyword?/1 Returns true if argument is list and not keyword list. ``` iex> REnum.list_and_not_keyword?([1, 2, 3]) true iex> REnum.list_and_not_keyword?([a: 1, b: 2]) false ``` ### map_and_not_range?/1 Returns true if argument is map and not range. ``` iex> REnum.map_and_not_range?(%{}) true iex> REnum.map_and_not_range?(1..3) false ``` About [RList](https://hexdocs.pm/r_enum/RList.html) --- RList is List extended with convenient functions inspired by Ruby and Rails ActiveSupport. **All the functions are available defined in** * [List](https://hexdocs.pm/r_enum/RList.Native.html) * [REnum](https://hexdocs.pm/r_enum/REnum.html) * [RList.Ruby](https://hexdocs.pm/r_enum/RList.Ruby.html) * [RList.ActiveSupport](https://hexdocs.pm/r_enum/RList.ActiveSupport.html) * [RList.Support](https://hexdocs.pm/r_enum/RList.Support.html) ### push/2 Appends trailing elements. ``` iex> [:foo, 'bar', 2] iex> |> RList.push([:baz, :bat]) [:foo, 'bar', 2, :baz, :bat] iex> [:foo, 'bar', 2] iex> |> RList.push(:baz) [:foo, 'bar', 2, :baz] # See also REnum.Ruby.shift, REnum.Ruby.pop, REnum.Ruby.unshift ``` ### combination/2 Returns Stream that is each repeated combinations of elements of given list. The order of combinations is indeterminate. ``` iex> RList.combination([1, 2, 3, 4], 1) iex> |> Enum.to_list() [[1],[2],[3],[4]] iex> RList.combination([1, 2, 3, 4], 3) iex> |> Enum.to_list() [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] iex> RList.combination([1, 2, 3, 4], 0) iex> |> Enum.to_list() [[]] iex> RList.combination([1, 2, 3, 4], 5) iex> |> Enum.to_list() [] # See also RList.Ruby.repeated_combination, RList.Ruby.permutation, RList.Ruby.repeated_permutation ``` ### fill/3 Fills the list with the provided value. The filler can be either a function or a fixed value. ``` iex> RList.fill(~w[a b c d], "x") ["x", "x", "x", "x"] iex> RList.fill(~w[a b c d], "x", 0..1) ["x", "x", "c", "d"] iex> RList.fill(~w[a b c d], fn _, i -> i * i end) [0, 1, 4, 9] iex> RList.fill(~w[a b c d], fn _, i -> i * 2 end, 0..1) [0, 2, "c", "d"] ``` ### dig/3 Finds and returns the element in nested elements that is specified by index and identifiers. ``` iex> [:foo, [:bar, :baz, [:bat, :bam]]] iex> |> RList.dig(1) [:bar, :baz, [:bat, :bam]] iex> [:foo, [:bar, :baz, [:bat, :bam]]] iex> |> RList.dig(1, [2]) [:bat, :bam] iex> [:foo, [:bar, :baz, [:bat, :bam]]] iex> |> RList.dig(1, [2, 0]) :bat iex> [:foo, [:bar, :baz, [:bat, :bam]]] iex> |> RList.dig(1, [2, 3]) nil ``` ### intersection/2 Returns a new list containing each element found both in list1 and in all of the given list2; duplicates are omitted. ``` iex> [1, 2, 3] iex> |> RList.intersection([3, 4, 5]) [3] iex> [1, 2, 3] iex> |> RList.intersection([5, 6, 7]) [] iex> [1, 2, 3] iex> |> RList.intersection([1, 2, 3]) [1, 2, 3] """ ``` ### sample/2 Returns one or more random elements. ### values_at/1 Returns a list containing the elements in list corresponding to the given selector(s).The selectors may be either integer indices or ranges. ``` iex> RList.values_at(~w[a b c d e f], [1, 3, 5]) ["b", "d", "f"] iex> RList.values_at(~w[a b c d e f], [1, 3, 5, 7]) ["b", "d", "f", nil] iex> RList.values_at(~w[a b c d e f], [-1, -2, -2, -7]) ["f", "e", "e", nil] iex> RList.values_at(~w[a b c d e f], [4..6, 3..5]) ["e", "f", nil, "d", "e", "f"] iex> RList.values_at(~w[a b c d e f], 4..6) ["e", "f", nil] ``` ### second/1 Equal to `Enum.at(list, 1)`. ``` iex> ~w[a b c d] iex> |> RList.second() "b" # See also RList.ActiveSupport.third, RList.ActiveSupport.fourth, RList.ActiveSupport.fifth and RList.ActiveSupport.forty_two ``` ### from/2 Returns the tail of the list from position. ``` iex> ~w[a b c d] iex> |> RList.from(0) ["a", "b", "c", "d"] iex> ~w[a b c d] iex> |> RList.from(2) ["c", "d"] iex> ~w[a b c d] iex> |> RList.from(10) [] iex> ~w[] iex> |> RList.from(0) [] iex> ~w[a b c d] iex> |> RList.from(-2) ["c", "d"] iex> ~w[a b c d] iex> |> RList.from(-10) [] # See also RList.ActiveSupport.to ``` ### to_sentence/2 Converts the list to a comma-separated sentence where the last element is joined by the connector word. You can pass the following options to change the default behavior. If you pass an option key that doesn't exist in the list below, it will raise an **Options** * `:words_connector` - The sign or word used to join all but the last element in lists with three or more elements (default: ", "). * `:last_word_connector` - The sign or word used to join the last element in lists with three or more elements (default: ", and "). * `:two_words_connector` - The sign or word used to join the elements in lists with two elements (default: " and "). ``` iex> ["one", "two"] iex> |> RList.to_sentence() "one and two" iex> ["one", "two", "three"] iex> |> RList.to_sentence() "one, two, and three" iex> ["one", "two"] iex> |> RList.to_sentence(two_words_connector: "-") "one-two" iex> ["one", "two", "three"] iex> |> RList.to_sentence(words_connector: " or ", last_word_connector: " or at least ") "one or two or at least three" iex> ["one", "two", "three"] iex> |> RList.to_sentence() "one, two, and three" ``` ### new/2 Make a list of size amount. ``` iex> 1 iex> |> RList.new(3) [1, 1, 1] ``` About [RMap](https://hexdocs.pm/r_enum/RMap.html) --- RMap is Map extended with convenient functions inspired by Ruby and Rails ActiveSupport. **All the functions are available defined in** * [Map](https://hexdocs.pm/r_enum/RMap.Native.html) * [REnum](https://hexdocs.pm/r_enum/REnum.html) * [RMap.Ruby](https://hexdocs.pm/r_enum/RMap.Ruby.html) * [RMap.ActiveSupport](https://hexdocs.pm/r_enum/RMap.ActiveSupport.html) * [RMap.Support](https://hexdocs.pm/r_enum/RMap.Support.html) ### dig/2 Returns the object in nested map that is specified by a given key and additional arguments. ``` iex> RMap.dig(%{a: %{b: %{c: 1}}}, [:a, :b, :c]) 1 iex> RMap.dig(%{a: %{b: %{c: 1}}}, [:a, :c, :b]) nil ``` ### each_key/2 Calls the function with each key; returns :ok. ``` iex> RMap.each_key(%{a: 1, b: 2, c: 3}, &IO.inspect(&1)) # :a # :b # :c :ok # See also RMap.Ruby.each_value, RMap.Ruby.each_pair ``` ### except/2 Returns a map excluding entries for the given keys. ``` iex> RMap.except(%{a: 1, b: 2, c: 3}, [:a, :b]) %{c: 3} ``` ### invert/1 Returns a map object with the each key-value pair inverted. ``` iex> RMap.invert(%{"a" => 0, "b" => 100, "c" => 200, "d" => 300, "e" => 300}) %{0 => "a", 100 => "b", 200 => "c", 300 => "e"} iex> RMap.invert(%{a: 1, b: 1, c: %{d: 2}}) %{1 => :b, %{d: 2} => :c} ``` ### values_at/2 Returns a list containing values for the given keys. ``` iex> RMap.values_at(%{a: 1, b: 2, c: 3}, [:a, :b, :d]) [1, 2, nil] ``` ### deep_atomize_keys/1 Returns a list with all keys converted to atom. This includes the keys from the root map and from all nested maps and arrays. ``` iex> RMap.deep_atomize_keys(%{"name" => "Rob", "years" => "28", "nested" => %{ "a" => 1 }}) %{name: "Rob", nested: %{a: 1}, years: "28"} iex> RMap.deep_atomize_keys(%{"a" => %{"b" => %{"c" => 1}, "d" => [%{"a" => 1, "b" => %{"c" => 2}}]}}) %{a: %{b: %{c: 1}, d: [%{a: 1, b: %{c: 2}}]}} # See also RList.ActiveSupport.deep_symbolize_keys, RList.ActiveSupport.symbolize_keys, RList.ActiveSupport.deep_stringify_keys, RList.ActiveSupport.stringify_keys, ``` ### deep_transform_keys/2 Returns a list with all keys converted to atom. This includes the keys from the root map and from all nested maps and arrays. ``` iex> RMap.deep_transform_keys(%{a: %{b: %{c: 1}}}, &to_string(&1)) %{"a" => %{"b" => %{"c" => 1}}} iex> RMap.deep_transform_keys(%{a: %{b: %{c: 1}, d: [%{a: 1, b: %{c: 2}}]}}, &inspect(&1)) %{":a" => %{":b" => %{":c" => 1}, ":d" => [%{":a" => 1, ":b" => %{":c" => 2}}]}} # See also RList.ActiveSupport.deep_transform_values ``` About [RRange](https://hexdocs.pm/r_enum/RRange.html) --- **All the functions are available defined in** * [Range](https://hexdocs.pm/r_enum/RRange.Native.html) * [RRange.Ruby](https://hexdocs.pm/r_enum/RRange.Ruby.html) * [RRange.ActiveSupport](https://hexdocs.pm/r_enum/RRange.ActiveSupport.html) * [REnum](https://hexdocs.pm/r_enum/REnum.html) ### begin/1 Returns the first element of range. ``` iex> RList.begin(1..3) 1 # See also RRange.Ruby.end ``` ### step/2 Returns Stream that from given range split into by given step. ``` iex> RList.step(1..10, 2) iex> |> Enum.to_list() [1, 3, 5, 7, 9] """ ``` ### overlaps?/2 Compare two ranges and see if they overlap each other. ``` iex> RList.overlaps?(1..5, 4..6) true iex> RList.overlaps?(1..5, 7..9) false ``` About [RUtils](https://hexdocs.pm/r_enum/RUtils.html) --- Some useful functions. ### blank?/1 Return true if object is blank, false, empty, or a whitespace string. For example, +nil+, '', ' ', [], {}, and +false+ are all blank. ``` iex> RUtils.blank?(%{}) true iex> RUtils.blank?([1]) false iex> RUtils.blank?(" ") true ``` ### present?/1 Returns true if not `RUtils.blank?` ``` iex> RUtils.present?(%{}) false iex> RUtils.present?([1]) true iex> RUtils.present?(" ") false ``` ### define_all_functions!/2 Defines in the module that called all the functions of the argument module. ``` iex> defmodule A do ...> defmacro __using__(_opts) do ...> RUtils.define_all_functions!(__MODULE__) ...> end ...> ...> def test do ...> :test ...> end ...> end iex> defmodule B do ...> use A ...> end iex> B.test :test ``` Progress --- | REnum | Elixir Module | Ruby Class | Elixir | Ruby | ActiveSupport | | --- | --- | --- | --- | --- | --- | | REnum | Enum | Enumerable | ✅ | ✅ | ✅ | | RList | List | Array | ✅ | ✅ | ✅ | | RMap | Map | Hash | ✅ | ✅ | ✅ | | RRange | Range | Range | ✅ | ✅ | ✅ | | RStream | Stream | Enumerator::Lazy | ✅ | TODO | TODO | [API Reference](api-reference.html) MapKeyError exception === REnum === Entry point of Enum extensions, and can use all of REnum.* functions. See also * [REnum.Native](https://hexdocs.pm/r_enum/REnum.Native.html#content) * [REnum.Ruby](https://hexdocs.pm/r_enum/REnum.Ruby.html#content) * [REnum.ActiveSupport](https://hexdocs.pm/r_enum/REnum.ActiveSupport.html#content) * [REnum.Support](https://hexdocs.pm/r_enum/REnum.Support.html#content) [Link to this section](#summary) Summary === [Functions](#functions) --- [all?(arg1)](#all?/1) See [`Enum.all?/1`](https://hexdocs.pm/elixir/Enum.html#all?/1). [all?(arg1, arg2)](#all?/2) See [`Enum.all?/2`](https://hexdocs.pm/elixir/Enum.html#all?/2). [any?(arg1)](#any?/1) See [`Enum.any?/1`](https://hexdocs.pm/elixir/Enum.html#any?/1). [any?(arg1, arg2)](#any?/2) See [`Enum.any?/2`](https://hexdocs.pm/elixir/Enum.html#any?/2). [at(arg1, arg2)](#at/2) See [`Enum.at/2`](https://hexdocs.pm/elixir/Enum.html#at/2). [at(arg1, arg2, arg3)](#at/3) See [`Enum.at/3`](https://hexdocs.pm/elixir/Enum.html#at/3). [chain(arg1)](#chain/1) See [`REnum.Ruby.chain/1`](REnum.Ruby.html#chain/1). [chain(arg1, arg2)](#chain/2) See [`REnum.Ruby.chain/2`](REnum.Ruby.html#chain/2). [chunk_by(arg1, arg2)](#chunk_by/2) See [`Enum.chunk_by/2`](https://hexdocs.pm/elixir/Enum.html#chunk_by/2). [chunk_every(arg1, arg2)](#chunk_every/2) See [`Enum.chunk_every/2`](https://hexdocs.pm/elixir/Enum.html#chunk_every/2). [chunk_every(arg1, arg2, arg3)](#chunk_every/3) See [`Enum.chunk_every/3`](https://hexdocs.pm/elixir/Enum.html#chunk_every/3). [chunk_every(arg1, arg2, arg3, arg4)](#chunk_every/4) See [`Enum.chunk_every/4`](https://hexdocs.pm/elixir/Enum.html#chunk_every/4). [chunk_while(arg1, arg2, arg3, arg4)](#chunk_while/4) See [`Enum.chunk_while/4`](https://hexdocs.pm/elixir/Enum.html#chunk_while/4). [collect(arg1, arg2)](#collect/2) See [`REnum.Ruby.collect/2`](REnum.Ruby.html#collect/2). [collect_concat(arg1, arg2)](#collect_concat/2) See [`REnum.Ruby.collect_concat/2`](REnum.Ruby.html#collect_concat/2). [compact(arg1)](#compact/1) See [`REnum.Ruby.compact/1`](REnum.Ruby.html#compact/1). [compact_blank(arg1)](#compact_blank/1) See [`REnum.ActiveSupport.compact_blank/1`](REnum.ActiveSupport.html#compact_blank/1). [concat(arg1)](#concat/1) See [`Enum.concat/1`](https://hexdocs.pm/elixir/Enum.html#concat/1). [concat(arg1, arg2)](#concat/2) See [`Enum.concat/2`](https://hexdocs.pm/elixir/Enum.html#concat/2). [count(arg1)](#count/1) See [`Enum.count/1`](https://hexdocs.pm/elixir/Enum.html#count/1). [count(arg1, arg2)](#count/2) See [`Enum.count/2`](https://hexdocs.pm/elixir/Enum.html#count/2). [count_until(arg1, arg2)](#count_until/2) See [`Enum.count_until/2`](https://hexdocs.pm/elixir/Enum.html#count_until/2). [count_until(arg1, arg2, arg3)](#count_until/3) See [`Enum.count_until/3`](https://hexdocs.pm/elixir/Enum.html#count_until/3). [cycle(arg1, arg2, arg3)](#cycle/3) See [`REnum.Ruby.cycle/3`](REnum.Ruby.html#cycle/3). [dedup(arg1)](#dedup/1) See [`Enum.dedup/1`](https://hexdocs.pm/elixir/Enum.html#dedup/1). [dedup_by(arg1, arg2)](#dedup_by/2) See [`Enum.dedup_by/2`](https://hexdocs.pm/elixir/Enum.html#dedup_by/2). [detect(arg1, arg2)](#detect/2) See [`REnum.Ruby.detect/2`](REnum.Ruby.html#detect/2). [detect(arg1, arg2, arg3)](#detect/3) See [`REnum.Ruby.detect/3`](REnum.Ruby.html#detect/3). [drop(arg1, arg2)](#drop/2) See [`Enum.drop/2`](https://hexdocs.pm/elixir/Enum.html#drop/2). [drop_every(arg1, arg2)](#drop_every/2) See [`Enum.drop_every/2`](https://hexdocs.pm/elixir/Enum.html#drop_every/2). [drop_while(arg1, arg2)](#drop_while/2) See [`Enum.drop_while/2`](https://hexdocs.pm/elixir/Enum.html#drop_while/2). [each(arg1, arg2)](#each/2) See [`Enum.each/2`](https://hexdocs.pm/elixir/Enum.html#each/2). [each_cons(arg1, arg2, arg3)](#each_cons/3) See [`REnum.Ruby.each_cons/3`](REnum.Ruby.html#each_cons/3). [each_entry(arg1, arg2)](#each_entry/2) See [`REnum.Ruby.each_entry/2`](REnum.Ruby.html#each_entry/2). [each_slice(arg1, arg2)](#each_slice/2) See [`REnum.Ruby.each_slice/2`](REnum.Ruby.html#each_slice/2). [each_slice(arg1, arg2, arg3)](#each_slice/3) See [`REnum.Ruby.each_slice/3`](REnum.Ruby.html#each_slice/3). [each_with_index(arg1)](#each_with_index/1) See [`REnum.Ruby.each_with_index/1`](REnum.Ruby.html#each_with_index/1). [each_with_index(arg1, arg2)](#each_with_index/2) See [`REnum.Ruby.each_with_index/2`](REnum.Ruby.html#each_with_index/2). [each_with_object(arg1, arg2, arg3)](#each_with_object/3) See [`REnum.Ruby.each_with_object/3`](REnum.Ruby.html#each_with_object/3). [empty?(arg1)](#empty?/1) See [`Enum.empty?/1`](https://hexdocs.pm/elixir/Enum.html#empty?/1). [entries(arg1)](#entries/1) See [`REnum.Ruby.entries/1`](REnum.Ruby.html#entries/1). [exclude?(arg1, arg2)](#exclude?/2) See [`REnum.ActiveSupport.exclude?/2`](REnum.ActiveSupport.html#exclude?/2). [excluding(arg1, arg2)](#excluding/2) See [`REnum.ActiveSupport.excluding/2`](REnum.ActiveSupport.html#excluding/2). [fetch(arg1, arg2)](#fetch/2) See [`Enum.fetch/2`](https://hexdocs.pm/elixir/Enum.html#fetch/2). [fetch!(arg1, arg2)](#fetch!/2) See [`Enum.fetch!/2`](https://hexdocs.pm/elixir/Enum.html#fetch!/2). [filter(arg1, arg2)](#filter/2) See [`Enum.filter/2`](https://hexdocs.pm/elixir/Enum.html#filter/2). [find(arg1, arg2)](#find/2) See [`Enum.find/2`](https://hexdocs.pm/elixir/Enum.html#find/2). [find(arg1, arg2, arg3)](#find/3) See [`Enum.find/3`](https://hexdocs.pm/elixir/Enum.html#find/3). [find_all(arg1, arg2)](#find_all/2) See [`REnum.Ruby.find_all/2`](REnum.Ruby.html#find_all/2). [find_index(arg1, arg2)](#find_index/2) See [`Enum.find_index/2`](https://hexdocs.pm/elixir/Enum.html#find_index/2). [find_index_with_index(arg1, arg2)](#find_index_with_index/2) See [`REnum.Support.find_index_with_index/2`](REnum.Support.html#find_index_with_index/2). [find_value(arg1, arg2)](#find_value/2) See [`Enum.find_value/2`](https://hexdocs.pm/elixir/Enum.html#find_value/2). [find_value(arg1, arg2, arg3)](#find_value/3) See [`Enum.find_value/3`](https://hexdocs.pm/elixir/Enum.html#find_value/3). [first(arg1)](#first/1) See [`REnum.Ruby.first/1`](REnum.Ruby.html#first/1). [first(arg1, arg2)](#first/2) See [`REnum.Ruby.first/2`](REnum.Ruby.html#first/2). [flat_map(arg1, arg2)](#flat_map/2) See [`Enum.flat_map/2`](https://hexdocs.pm/elixir/Enum.html#flat_map/2). [flat_map_reduce(arg1, arg2, arg3)](#flat_map_reduce/3) See [`Enum.flat_map_reduce/3`](https://hexdocs.pm/elixir/Enum.html#flat_map_reduce/3). [frequencies(arg1)](#frequencies/1) See [`Enum.frequencies/1`](https://hexdocs.pm/elixir/Enum.html#frequencies/1). [frequencies_by(arg1, arg2)](#frequencies_by/2) See [`Enum.frequencies_by/2`](https://hexdocs.pm/elixir/Enum.html#frequencies_by/2). [grep(arg1, arg2)](#grep/2) See [`REnum.Ruby.grep/2`](REnum.Ruby.html#grep/2). [grep(arg1, arg2, arg3)](#grep/3) See [`REnum.Ruby.grep/3`](REnum.Ruby.html#grep/3). [grep_v(arg1, arg2)](#grep_v/2) See [`REnum.Ruby.grep_v/2`](REnum.Ruby.html#grep_v/2). [grep_v(arg1, arg2, arg3)](#grep_v/3) See [`REnum.Ruby.grep_v/3`](REnum.Ruby.html#grep_v/3). [group_by(arg1, arg2)](#group_by/2) See [`Enum.group_by/2`](https://hexdocs.pm/elixir/Enum.html#group_by/2). [group_by(arg1, arg2, arg3)](#group_by/3) See [`Enum.group_by/3`](https://hexdocs.pm/elixir/Enum.html#group_by/3). [in_order_of(arg1, arg2, arg3)](#in_order_of/3) See [`REnum.ActiveSupport.in_order_of/3`](REnum.ActiveSupport.html#in_order_of/3). [include?(arg1, arg2)](#include?/2) See [`REnum.Ruby.include?/2`](REnum.Ruby.html#include?/2). [including(arg1, arg2)](#including/2) See [`REnum.ActiveSupport.including/2`](REnum.ActiveSupport.html#including/2). [index_by(arg1, arg2)](#index_by/2) See [`REnum.ActiveSupport.index_by/2`](REnum.ActiveSupport.html#index_by/2). [index_with(arg1, arg2)](#index_with/2) See [`REnum.ActiveSupport.index_with/2`](REnum.ActiveSupport.html#index_with/2). [inject(arg1, arg2)](#inject/2) See [`REnum.Ruby.inject/2`](REnum.Ruby.html#inject/2). [inject(arg1, arg2, arg3)](#inject/3) See [`REnum.Ruby.inject/3`](REnum.Ruby.html#inject/3). [intersperse(arg1, arg2)](#intersperse/2) See [`Enum.intersperse/2`](https://hexdocs.pm/elixir/Enum.html#intersperse/2). [into(arg1, arg2)](#into/2) See [`Enum.into/2`](https://hexdocs.pm/elixir/Enum.html#into/2). [into(arg1, arg2, arg3)](#into/3) See [`Enum.into/3`](https://hexdocs.pm/elixir/Enum.html#into/3). [join(arg1)](#join/1) See [`Enum.join/1`](https://hexdocs.pm/elixir/Enum.html#join/1). [join(arg1, arg2)](#join/2) See [`Enum.join/2`](https://hexdocs.pm/elixir/Enum.html#join/2). [lazy(arg1)](#lazy/1) See [`REnum.Ruby.lazy/1`](REnum.Ruby.html#lazy/1). [list_and_not_keyword?(arg1)](#list_and_not_keyword?/1) See [`REnum.Support.list_and_not_keyword?/1`](REnum.Support.html#list_and_not_keyword?/1). [many?(arg1)](#many?/1) See [`REnum.ActiveSupport.many?/1`](REnum.ActiveSupport.html#many?/1). [many?(arg1, arg2)](#many?/2) See [`REnum.ActiveSupport.many?/2`](REnum.ActiveSupport.html#many?/2). [map(arg1, arg2)](#map/2) See [`Enum.map/2`](https://hexdocs.pm/elixir/Enum.html#map/2). [map_and_not_range?(arg1)](#map_and_not_range?/1) See [`REnum.Support.map_and_not_range?/1`](REnum.Support.html#map_and_not_range?/1). [map_every(arg1, arg2, arg3)](#map_every/3) See [`Enum.map_every/3`](https://hexdocs.pm/elixir/Enum.html#map_every/3). [map_intersperse(arg1, arg2, arg3)](#map_intersperse/3) See [`Enum.map_intersperse/3`](https://hexdocs.pm/elixir/Enum.html#map_intersperse/3). [map_join(arg1, arg2)](#map_join/2) See [`Enum.map_join/2`](https://hexdocs.pm/elixir/Enum.html#map_join/2). [map_join(arg1, arg2, arg3)](#map_join/3) See [`Enum.map_join/3`](https://hexdocs.pm/elixir/Enum.html#map_join/3). [map_reduce(arg1, arg2, arg3)](#map_reduce/3) See [`Enum.map_reduce/3`](https://hexdocs.pm/elixir/Enum.html#map_reduce/3). [match_function(arg1)](#match_function/1) See [`REnum.Support.match_function/1`](REnum.Support.html#match_function/1). [max(arg1)](#max/1) See [`Enum.max/1`](https://hexdocs.pm/elixir/Enum.html#max/1). [max(arg1, arg2)](#max/2) See [`Enum.max/2`](https://hexdocs.pm/elixir/Enum.html#max/2). [max(arg1, arg2, arg3)](#max/3) See [`Enum.max/3`](https://hexdocs.pm/elixir/Enum.html#max/3). [max_by(arg1, arg2)](#max_by/2) See [`Enum.max_by/2`](https://hexdocs.pm/elixir/Enum.html#max_by/2). [max_by(arg1, arg2, arg3)](#max_by/3) See [`Enum.max_by/3`](https://hexdocs.pm/elixir/Enum.html#max_by/3). [max_by(arg1, arg2, arg3, arg4)](#max_by/4) See [`Enum.max_by/4`](https://hexdocs.pm/elixir/Enum.html#max_by/4). [maximum(arg1, arg2)](#maximum/2) See [`REnum.ActiveSupport.maximum/2`](REnum.ActiveSupport.html#maximum/2). [member?(arg1, arg2)](#member?/2) See [`Enum.member?/2`](https://hexdocs.pm/elixir/Enum.html#member?/2). [min(arg1)](#min/1) See [`Enum.min/1`](https://hexdocs.pm/elixir/Enum.html#min/1). [min(arg1, arg2)](#min/2) See [`Enum.min/2`](https://hexdocs.pm/elixir/Enum.html#min/2). [min(arg1, arg2, arg3)](#min/3) See [`Enum.min/3`](https://hexdocs.pm/elixir/Enum.html#min/3). [min_by(arg1, arg2)](#min_by/2) See [`Enum.min_by/2`](https://hexdocs.pm/elixir/Enum.html#min_by/2). [min_by(arg1, arg2, arg3)](#min_by/3) See [`Enum.min_by/3`](https://hexdocs.pm/elixir/Enum.html#min_by/3). [min_by(arg1, arg2, arg3, arg4)](#min_by/4) See [`Enum.min_by/4`](https://hexdocs.pm/elixir/Enum.html#min_by/4). [min_max(arg1)](#min_max/1) See [`Enum.min_max/1`](https://hexdocs.pm/elixir/Enum.html#min_max/1). [min_max(arg1, arg2)](#min_max/2) See [`Enum.min_max/2`](https://hexdocs.pm/elixir/Enum.html#min_max/2). [min_max_by(arg1, arg2)](#min_max_by/2) See [`Enum.min_max_by/2`](https://hexdocs.pm/elixir/Enum.html#min_max_by/2). [min_max_by(arg1, arg2, arg3)](#min_max_by/3) See [`Enum.min_max_by/3`](https://hexdocs.pm/elixir/Enum.html#min_max_by/3). [min_max_by(arg1, arg2, arg3, arg4)](#min_max_by/4) See [`Enum.min_max_by/4`](https://hexdocs.pm/elixir/Enum.html#min_max_by/4). [minimum(arg1, arg2)](#minimum/2) See [`REnum.ActiveSupport.minimum/2`](REnum.ActiveSupport.html#minimum/2). [minmax(arg1)](#minmax/1) See [`REnum.Ruby.minmax/1`](REnum.Ruby.html#minmax/1). [minmax(arg1, arg2)](#minmax/2) See [`REnum.Ruby.minmax/2`](REnum.Ruby.html#minmax/2). [minmax_by(arg1, arg2)](#minmax_by/2) See [`REnum.Ruby.minmax_by/2`](REnum.Ruby.html#minmax_by/2). [minmax_by(arg1, arg2, arg3)](#minmax_by/3) See [`REnum.Ruby.minmax_by/3`](REnum.Ruby.html#minmax_by/3). [minmax_by(arg1, arg2, arg3, arg4)](#minmax_by/4) See [`REnum.Ruby.minmax_by/4`](REnum.Ruby.html#minmax_by/4). [none?(arg1)](#none?/1) See [`REnum.Ruby.none?/1`](REnum.Ruby.html#none?/1). [none?(arg1, arg2)](#none?/2) See [`REnum.Ruby.none?/2`](REnum.Ruby.html#none?/2). [one?(arg1)](#one?/1) See [`REnum.Ruby.one?/1`](REnum.Ruby.html#one?/1). [one?(arg1, arg2)](#one?/2) See [`REnum.Ruby.one?/2`](REnum.Ruby.html#one?/2). [pick(arg1, arg2)](#pick/2) See [`REnum.ActiveSupport.pick/2`](REnum.ActiveSupport.html#pick/2). [pluck(arg1, arg2)](#pluck/2) See [`REnum.ActiveSupport.pluck/2`](REnum.ActiveSupport.html#pluck/2). [product(arg1)](#product/1) See [`Enum.product/1`](https://hexdocs.pm/elixir/Enum.html#product/1). [random(arg1)](#random/1) See [`Enum.random/1`](https://hexdocs.pm/elixir/Enum.html#random/1). [range?(arg1)](#range?/1) See [`REnum.Support.range?/1`](REnum.Support.html#range?/1). [reduce(arg1, arg2)](#reduce/2) See [`Enum.reduce/2`](https://hexdocs.pm/elixir/Enum.html#reduce/2). [reduce(arg1, arg2, arg3)](#reduce/3) See [`Enum.reduce/3`](https://hexdocs.pm/elixir/Enum.html#reduce/3). [reduce_while(arg1, arg2, arg3)](#reduce_while/3) See [`Enum.reduce_while/3`](https://hexdocs.pm/elixir/Enum.html#reduce_while/3). [reject(arg1, arg2)](#reject/2) See [`Enum.reject/2`](https://hexdocs.pm/elixir/Enum.html#reject/2). [reverse(arg1)](#reverse/1) See [`Enum.reverse/1`](https://hexdocs.pm/elixir/Enum.html#reverse/1). [reverse(arg1, arg2)](#reverse/2) See [`Enum.reverse/2`](https://hexdocs.pm/elixir/Enum.html#reverse/2). [reverse_each(arg1, arg2)](#reverse_each/2) See [`REnum.Ruby.reverse_each/2`](REnum.Ruby.html#reverse_each/2). [reverse_slice(arg1, arg2, arg3)](#reverse_slice/3) See [`Enum.reverse_slice/3`](https://hexdocs.pm/elixir/Enum.html#reverse_slice/3). [scan(arg1, arg2)](#scan/2) See [`Enum.scan/2`](https://hexdocs.pm/elixir/Enum.html#scan/2). [scan(arg1, arg2, arg3)](#scan/3) See [`Enum.scan/3`](https://hexdocs.pm/elixir/Enum.html#scan/3). [select(arg1, arg2)](#select/2) See [`REnum.Ruby.select/2`](REnum.Ruby.html#select/2). [shuffle(arg1)](#shuffle/1) See [`Enum.shuffle/1`](https://hexdocs.pm/elixir/Enum.html#shuffle/1). [slice(arg1, arg2)](#slice/2) See [`Enum.slice/2`](https://hexdocs.pm/elixir/Enum.html#slice/2). [slice(arg1, arg2, arg3)](#slice/3) See [`Enum.slice/3`](https://hexdocs.pm/elixir/Enum.html#slice/3). [slice_after(arg1, arg2)](#slice_after/2) See [`REnum.Ruby.slice_after/2`](REnum.Ruby.html#slice_after/2). [slice_before(arg1, arg2)](#slice_before/2) See [`REnum.Ruby.slice_before/2`](REnum.Ruby.html#slice_before/2). [slice_when(arg1, arg2)](#slice_when/2) See [`REnum.Ruby.slice_when/2`](REnum.Ruby.html#slice_when/2). [slide(arg1, arg2, arg3)](#slide/3) See [`Enum.slide/3`](https://hexdocs.pm/elixir/Enum.html#slide/3). [sole(arg1)](#sole/1) See [`REnum.ActiveSupport.sole/1`](REnum.ActiveSupport.html#sole/1). [sort(arg1)](#sort/1) See [`Enum.sort/1`](https://hexdocs.pm/elixir/Enum.html#sort/1). [sort(arg1, arg2)](#sort/2) See [`Enum.sort/2`](https://hexdocs.pm/elixir/Enum.html#sort/2). [sort_by(arg1, arg2)](#sort_by/2) See [`Enum.sort_by/2`](https://hexdocs.pm/elixir/Enum.html#sort_by/2). [sort_by(arg1, arg2, arg3)](#sort_by/3) See [`Enum.sort_by/3`](https://hexdocs.pm/elixir/Enum.html#sort_by/3). [split(arg1, arg2)](#split/2) See [`Enum.split/2`](https://hexdocs.pm/elixir/Enum.html#split/2). [split_while(arg1, arg2)](#split_while/2) See [`Enum.split_while/2`](https://hexdocs.pm/elixir/Enum.html#split_while/2). [split_with(arg1, arg2)](#split_with/2) See [`Enum.split_with/2`](https://hexdocs.pm/elixir/Enum.html#split_with/2). [sum(arg1)](#sum/1) See [`Enum.sum/1`](https://hexdocs.pm/elixir/Enum.html#sum/1). [take(arg1, arg2)](#take/2) See [`Enum.take/2`](https://hexdocs.pm/elixir/Enum.html#take/2). [take_every(arg1, arg2)](#take_every/2) See [`Enum.take_every/2`](https://hexdocs.pm/elixir/Enum.html#take_every/2). [take_random(arg1, arg2)](#take_random/2) See [`Enum.take_random/2`](https://hexdocs.pm/elixir/Enum.html#take_random/2). [take_while(arg1, arg2)](#take_while/2) See [`Enum.take_while/2`](https://hexdocs.pm/elixir/Enum.html#take_while/2). [tally(arg1)](#tally/1) See [`REnum.Ruby.tally/1`](REnum.Ruby.html#tally/1). [to_a(arg1)](#to_a/1) See [`REnum.Ruby.to_a/1`](REnum.Ruby.html#to_a/1). [to_h(arg1)](#to_h/1) See [`REnum.Ruby.to_h/1`](REnum.Ruby.html#to_h/1). [to_h(arg1, arg2)](#to_h/2) See [`REnum.Ruby.to_h/2`](REnum.Ruby.html#to_h/2). [to_l(arg1)](#to_l/1) See [`REnum.Ruby.to_l/1`](REnum.Ruby.html#to_l/1). [to_list(arg1)](#to_list/1) See [`Enum.to_list/1`](https://hexdocs.pm/elixir/Enum.html#to_list/1). [truthy_count(arg1)](#truthy_count/1) See [`REnum.Support.truthy_count/1`](REnum.Support.html#truthy_count/1). [truthy_count(arg1, arg2)](#truthy_count/2) See [`REnum.Support.truthy_count/2`](REnum.Support.html#truthy_count/2). [uniq_by(arg1, arg2)](#uniq_by/2) See [`Enum.uniq_by/2`](https://hexdocs.pm/elixir/Enum.html#uniq_by/2). [unzip(arg1)](#unzip/1) See [`Enum.unzip/1`](https://hexdocs.pm/elixir/Enum.html#unzip/1). [with_index(arg1)](#with_index/1) See [`Enum.with_index/1`](https://hexdocs.pm/elixir/Enum.html#with_index/1). [with_index(arg1, arg2)](#with_index/2) See [`Enum.with_index/2`](https://hexdocs.pm/elixir/Enum.html#with_index/2). [without(arg1, arg2)](#without/2) See [`REnum.ActiveSupport.without/2`](REnum.ActiveSupport.html#without/2). [zip(arg1)](#zip/1) See [`Enum.zip/1`](https://hexdocs.pm/elixir/Enum.html#zip/1). [zip(arg1, arg2)](#zip/2) See [`Enum.zip/2`](https://hexdocs.pm/elixir/Enum.html#zip/2). [zip_reduce(arg1, arg2, arg3)](#zip_reduce/3) See [`Enum.zip_reduce/3`](https://hexdocs.pm/elixir/Enum.html#zip_reduce/3). [zip_reduce(arg1, arg2, arg3, arg4)](#zip_reduce/4) See [`Enum.zip_reduce/4`](https://hexdocs.pm/elixir/Enum.html#zip_reduce/4). [zip_with(arg1, arg2)](#zip_with/2) See [`Enum.zip_with/2`](https://hexdocs.pm/elixir/Enum.html#zip_with/2). [zip_with(arg1, arg2, arg3)](#zip_with/3) See [`Enum.zip_with/3`](https://hexdocs.pm/elixir/Enum.html#zip_with/3). [Link to this section](#functions) Functions === REnum.ActiveSupport === Summarized all of Enumerable functions in Rails.ActiveSupport. If a function with the same name already exists in Elixir, that is not implemented. Defines all of here functions when `use ActiveSupport`. [Link to this section](#summary) Summary === [Types](#types) --- [type_enumerable()](#t:type_enumerable/0) [type_map_list()](#t:type_map_list/0) [type_pattern()](#t:type_pattern/0) [Functions](#functions) --- [compact_blank(enumerable)](#compact_blank/1) Returns a new enumerable without the blank items. Uses `RUtils.blank?` for determining if an item is blank. [exclude?(enumerable, element)](#exclude?/2) The negative of the `Enum.member?`. Returns +true+ if the collection does not include the object. [excluding(enumerable, elements)](#excluding/2) Returns enumerable excluded the specified elements. [in_order_of(enumerable, key, series)](#in_order_of/3) Returns a list where the order has been set to that provided in the series, based on the key of the elements in the original enumerable. [including(enumerable, elements)](#including/2) Returns enumerable included the specified elements. [index_by(enumerable, key)](#index_by/2) Converts an enumerable to a mao, using the function result or key as the key and the element as the value. [index_with(keys, func)](#index_with/2) Convert an enumerable to a map, using the element as the key and the function result or given value as the value. [many?(enumerable)](#many?/1) Returns true if the enumerable has more than 1 element. [many?(enumerable, pattern_or_func)](#many?/2) Returns true if the enumerable has more than 1 element matched given function result or pattern. [maximum(map_list, key)](#maximum/2) Calculates the maximum from the extracted elements. [minimum(map_list, key)](#minimum/2) Calculates the minimum from the extracted elements. [pick(map_list, keys)](#pick/2) Extract the given key from the first element in the enumerable. [pluck(map_list, keys)](#pluck/2) Extract the given key from each element in the enumerable. [sole(enumerable)](#sole/1) Returns the sole item in the enumerable. If there are no items, or more than one item, raises SoleItemExpectedError. [without(enumerable, elements)](#without/2) See [`REnum.ActiveSupport.excluding/2`](#excluding/2). [Link to this section](#types) Types === [Link to this section](#functions) Functions === REnum.Native === A module defines all of native Enum functions when `use REnum.Native`. [See also.](https://hexdocs.pm/elixir/Enum.html) REnum.Ruby === Summarized all of Ruby's Enumerable functions. If a function with the same name already exists in Elixir, that is not implemented. Also, the function that returns Enumerator in Ruby is customized each behavior on the characteristics. Defines all of here functions when `use REnum.Ruby`. [Link to this section](#summary) Summary === [Types](#types) --- [type_enumerable()](#t:type_enumerable/0) [type_pattern()](#t:type_pattern/0) [Functions](#functions) --- [chain(enumerables)](#chain/1) See [`Stream.concat/1`](https://hexdocs.pm/elixir/Stream.html#concat/1). [chain(first, second)](#chain/2) See [`Stream.concat/2`](https://hexdocs.pm/elixir/Stream.html#concat/2). [collect(enumerable, func)](#collect/2) See [`Enum.map/2`](https://hexdocs.pm/elixir/Enum.html#map/2). [collect_concat(enumerable, func)](#collect_concat/2) See [`Enum.flat_map/2`](https://hexdocs.pm/elixir/Enum.html#flat_map/2). [compact(enumerable)](#compact/1) Returns an list of all non-nil elements. [cycle(enumerable, n, func)](#cycle/3) When called with positive integer argument n and a function, calls the block with each element, then does so again, until it has done so n times; returns given enumerable When called with a function and n is nil, returns Stream cycled forever. [detect(enumerable, func)](#detect/2) See [`Enum.find/2`](https://hexdocs.pm/elixir/Enum.html#find/2). [detect(enumerable, default, func)](#detect/3) See [`Enum.find/3`](https://hexdocs.pm/elixir/Enum.html#find/3). [each_cons(enumerable, n, func)](#each_cons/3) Calls the function with each successive overlapped n-list of elements; returns given enumerable. [each_entry(enumerable, func)](#each_entry/2) Calls the given function with each element, returns given enumerable [each_slice(enumerable, amount)](#each_slice/2) Returns Stream given enumerable sliced by each amount. [each_slice(enumerable, start_index, amount_or_func)](#each_slice/3) Calls the given function with each element, returns given enumerable. [each_with_index(enumerable)](#each_with_index/1) See [`Enum.with_index/1`](https://hexdocs.pm/elixir/Enum.html#with_index/1). [each_with_index(enumerable, func)](#each_with_index/2) See [`Enum.with_index/2`](https://hexdocs.pm/elixir/Enum.html#with_index/2). [each_with_object(enumerable, collectable, func)](#each_with_object/3) See [`Enum.reduce/3`](https://hexdocs.pm/elixir/Enum.html#reduce/3). [entries(enumerable)](#entries/1) See [`REnum.Ruby.to_a/1`](#to_a/1). [find_all(enumerable, func)](#find_all/2) See [`Enum.filter/2`](https://hexdocs.pm/elixir/Enum.html#filter/2). [first(enumerable)](#first/1) Returns the first element. [first(enumerable, n)](#first/2) Returns leading elements. [grep(enumerable, func)](#grep/2) Returns elements selected by a given pattern or function. [grep(enumerable, pattern, func)](#grep/3) Calls the function with each matching element and returned. [grep_v(enumerable, pattern)](#grep_v/2) Returns elements rejected by a given pattern or function. [grep_v(enumerable, pattern, func)](#grep_v/3) Calls the function with each unmatching element and returned. [include?(enumerable, element)](#include?/2) See [`Enum.member?/2`](https://hexdocs.pm/elixir/Enum.html#member?/2). [inject(enumerable, func)](#inject/2) See [`Enum.reduce/2`](https://hexdocs.pm/elixir/Enum.html#reduce/2). [inject(enumerable, acc, func)](#inject/3) See [`Enum.reduce/3`](https://hexdocs.pm/elixir/Enum.html#reduce/3). [lazy(enumerable)](#lazy/1) Returns Stream, which redefines most Enumerable functions to postpone enumeration and enumerate values only on an as-needed basis. [minmax(enumerable)](#minmax/1) See [`Enum.min_max/1`](https://hexdocs.pm/elixir/Enum.html#min_max/1). [minmax(enumerable, func)](#minmax/2) See [`Enum.min_max/2`](https://hexdocs.pm/elixir/Enum.html#min_max/2). [minmax_by(enumerable, func)](#minmax_by/2) See [`Enum.min_max_by/2`](https://hexdocs.pm/elixir/Enum.html#min_max_by/2). [minmax_by(enumerable, func1, func2)](#minmax_by/3) See [`Enum.min_max_by/3`](https://hexdocs.pm/elixir/Enum.html#min_max_by/3). [minmax_by(enumerable, func1, func2, func3)](#minmax_by/4) See [`Enum.min_max_by/4`](https://hexdocs.pm/elixir/Enum.html#min_max_by/4). [none?(enumerable)](#none?/1) Returns true if enumerable does not include truthy value; false otherwise. [none?(enumerable, pattern_or_func)](#none?/2) Returns whether no element meets a given criterion. [one?(enumerable)](#one?/1) Return true if enumerable has only one truthy element; false otherwise. [one?(enumerable, pattern_or_func)](#one?/2) Returns true if exactly one element meets a specified criterion; false otherwise. [reverse_each(enumerable, func)](#reverse_each/2) Calls the function with each element, but in reverse order; returns given enumerable. [select(enumerable, func)](#select/2) See [`Enum.filter/2`](https://hexdocs.pm/elixir/Enum.html#filter/2). [slice_after(enumerable, func)](#slice_after/2) With argument pattern, returns an elements that uses the pattern to partition elements into lists (“slices”). An element ends the current slice if element matches pattern. With a function, returns an elements that uses the function to partition elements into list. An element ends the current slice if its function return is a truthy value. [slice_before(enumerable, func)](#slice_before/2) With argument pattern, returns an elements that uses the pattern to partition elements into lists (“slices”). An element begins a new slice if element matches pattern. (or if it is the first element). With a function, returns an elements that uses the function to partition elements into list. An element ends the current slice if its function return is a truthy value. [slice_when(enumerable, func)](#slice_when/2) The returned elements uses the function to partition elements into lists (“slices”). It calls the function with each element and its successor. Begins a new slice if and only if the function returns a truthy value. &1 is current_element and &2 is next_element in function arguments. [tally(enumerable)](#tally/1) See [`Enum.frequencies/1`](https://hexdocs.pm/elixir/Enum.html#frequencies/1). [to_a(enumerables)](#to_a/1) See [`Enum.to_list/1`](https://hexdocs.pm/elixir/Enum.html#to_list/1). [to_h(enumerable)](#to_h/1) Returns a map each of whose entries is the key-value pair formed from one of those list. [to_h(enumerable, func)](#to_h/2) The function is called with each element. The function should return a 2-element tuple which becomes a key-value pair in the returned map. [to_l(enumerables)](#to_l/1) See [`Enum.to_list/1`](https://hexdocs.pm/elixir/Enum.html#to_list/1). [Link to this section](#types) Types === [Link to this section](#functions) Functions === REnum.Support === Summarized other useful functions related to enumerable. Defines all of here functions when `use REnum.Support`. [Link to this section](#summary) Summary === [Types](#types) --- [type_enumerable()](#t:type_enumerable/0) [type_pattern()](#t:type_pattern/0) [Functions](#functions) --- [find_index_with_index(enumerable, func)](#find_index_with_index/2) Returns the first element for which function(with each element index) returns a truthy value. [list_and_not_keyword?(enumerable)](#list_and_not_keyword?/1) Returns true if argument is list and not keyword list. [map_and_not_range?(enumerable)](#map_and_not_range?/1) Returns true if argument is map and not range. [match_function(pattern)](#match_function/1) Returns matching function required one argument by given pattern. [range?(arg1)](#range?/1) Returns true if argument is range. [truthy_count(enumerable)](#truthy_count/1) Returns truthy count. [truthy_count(enumerable, func)](#truthy_count/2) Returns truthy count that judged by given function. [Link to this section](#types) Types === [Link to this section](#functions) Functions === RList === Entry point of List extensions, and can use all of RList.* and REnum functions. See also. * [RList.Native](https://hexdocs.pm/r_enum/RList.Native.html#content) * [RList.Ruby](https://hexdocs.pm/r_enum/RList.Ruby.html#content) * [RList.ActiveSupport](https://hexdocs.pm/r_enum/RList.ActiveSupport.html#content) * [RList.Support](https://hexdocs.pm/r_enum/RList.SupportSupport.html#content) * [REnum](https://hexdocs.pm/r_enum/REnum.html#content) [Link to this section](#summary) Summary === [Functions](#functions) --- [all?(arg1)](#all?/1) See [`REnum.all?/1`](REnum.html#all?/1). [all?(arg1, arg2)](#all?/2) See [`REnum.all?/2`](REnum.html#all?/2). [all_combination(arg1, arg2)](#all_combination/2) See [`RList.Ruby.all_combination/2`](RList.Ruby.html#all_combination/2). [all_combination(arg1, arg2, arg3)](#all_combination/3) See [`RList.Ruby.all_combination/3`](RList.Ruby.html#all_combination/3). [any?(arg1)](#any?/1) See [`REnum.any?/1`](REnum.html#any?/1). [any?(arg1, arg2)](#any?/2) See [`REnum.any?/2`](REnum.html#any?/2). [append(arg1, arg2)](#append/2) See [`RList.Ruby.append/2`](RList.Ruby.html#append/2). [ascii_printable?(arg1)](#ascii_printable?/1) See [`List.ascii_printable?/1`](https://hexdocs.pm/elixir/List.html#ascii_printable?/1). [ascii_printable?(arg1, arg2)](#ascii_printable?/2) See [`List.ascii_printable?/2`](https://hexdocs.pm/elixir/List.html#ascii_printable?/2). [assoc(arg1, arg2)](#assoc/2) See [`RList.Ruby.assoc/2`](RList.Ruby.html#assoc/2). [at(arg1, arg2)](#at/2) See [`REnum.at/2`](REnum.html#at/2). [at(arg1, arg2, arg3)](#at/3) See [`REnum.at/3`](REnum.html#at/3). [chain(arg1)](#chain/1) See [`REnum.chain/1`](REnum.html#chain/1). [chain(arg1, arg2)](#chain/2) See [`REnum.chain/2`](REnum.html#chain/2). [chunk_by(arg1, arg2)](#chunk_by/2) See [`REnum.chunk_by/2`](REnum.html#chunk_by/2). [chunk_every(arg1, arg2)](#chunk_every/2) See [`REnum.chunk_every/2`](REnum.html#chunk_every/2). [chunk_every(arg1, arg2, arg3)](#chunk_every/3) See [`REnum.chunk_every/3`](REnum.html#chunk_every/3). [chunk_every(arg1, arg2, arg3, arg4)](#chunk_every/4) See [`REnum.chunk_every/4`](REnum.html#chunk_every/4). [chunk_while(arg1, arg2, arg3, arg4)](#chunk_while/4) See [`REnum.chunk_while/4`](REnum.html#chunk_while/4). [clear(arg1)](#clear/1) See [`RList.Ruby.clear/1`](RList.Ruby.html#clear/1). [collect(arg1, arg2)](#collect/2) See [`REnum.collect/2`](REnum.html#collect/2). [collect_concat(arg1, arg2)](#collect_concat/2) See [`REnum.collect_concat/2`](REnum.html#collect_concat/2). [combination(arg1, arg2)](#combination/2) See [`RList.Ruby.combination/2`](RList.Ruby.html#combination/2). [combination(arg1, arg2, arg3)](#combination/3) See [`RList.Ruby.combination/3`](RList.Ruby.html#combination/3). [compact(arg1)](#compact/1) See [`REnum.compact/1`](REnum.html#compact/1). [compact_blank(arg1)](#compact_blank/1) See [`REnum.compact_blank/1`](REnum.html#compact_blank/1). [concat(arg1)](#concat/1) See [`REnum.concat/1`](REnum.html#concat/1). [concat(arg1, arg2)](#concat/2) See [`REnum.concat/2`](REnum.html#concat/2). [count(arg1)](#count/1) See [`REnum.count/1`](REnum.html#count/1). [count(arg1, arg2)](#count/2) See [`REnum.count/2`](REnum.html#count/2). [count_until(arg1, arg2)](#count_until/2) See [`REnum.count_until/2`](REnum.html#count_until/2). [count_until(arg1, arg2, arg3)](#count_until/3) See [`REnum.count_until/3`](REnum.html#count_until/3). [cycle(arg1, arg2, arg3)](#cycle/3) See [`REnum.cycle/3`](REnum.html#cycle/3). [dedup(arg1)](#dedup/1) See [`REnum.dedup/1`](REnum.html#dedup/1). [dedup_by(arg1, arg2)](#dedup_by/2) See [`REnum.dedup_by/2`](REnum.html#dedup_by/2). [delete(arg1, arg2)](#delete/2) See [`List.delete/2`](https://hexdocs.pm/elixir/List.html#delete/2). [delete_at(arg1, arg2)](#delete_at/2) See [`List.delete_at/2`](https://hexdocs.pm/elixir/List.html#delete_at/2). [delete_if(arg1, arg2)](#delete_if/2) See [`RList.Ruby.delete_if/2`](RList.Ruby.html#delete_if/2). [detect(arg1, arg2)](#detect/2) See [`REnum.detect/2`](REnum.html#detect/2). [detect(arg1, arg2, arg3)](#detect/3) See [`REnum.detect/3`](REnum.html#detect/3). [difference(arg1, arg2)](#difference/2) See [`RList.Ruby.difference/2`](RList.Ruby.html#difference/2). [dig(arg1, arg2)](#dig/2) See [`RList.Ruby.dig/2`](RList.Ruby.html#dig/2). [dig(arg1, arg2, arg3)](#dig/3) See [`RList.Ruby.dig/3`](RList.Ruby.html#dig/3). [drop(arg1, arg2)](#drop/2) See [`REnum.drop/2`](REnum.html#drop/2). [drop_every(arg1, arg2)](#drop_every/2) See [`REnum.drop_every/2`](REnum.html#drop_every/2). [drop_while(arg1, arg2)](#drop_while/2) See [`REnum.drop_while/2`](REnum.html#drop_while/2). [duplicate(arg1, arg2)](#duplicate/2) See [`List.duplicate/2`](https://hexdocs.pm/elixir/List.html#duplicate/2). [each(arg1, arg2)](#each/2) See [`REnum.each/2`](REnum.html#each/2). [each_cons(arg1, arg2, arg3)](#each_cons/3) See [`REnum.each_cons/3`](REnum.html#each_cons/3). [each_entry(arg1, arg2)](#each_entry/2) See [`REnum.each_entry/2`](REnum.html#each_entry/2). [each_index(arg1, arg2)](#each_index/2) See [`RList.Ruby.each_index/2`](RList.Ruby.html#each_index/2). [each_slice(arg1, arg2)](#each_slice/2) See [`REnum.each_slice/2`](REnum.html#each_slice/2). [each_slice(arg1, arg2, arg3)](#each_slice/3) See [`REnum.each_slice/3`](REnum.html#each_slice/3). [each_with_index(arg1)](#each_with_index/1) See [`REnum.each_with_index/1`](REnum.html#each_with_index/1). [each_with_index(arg1, arg2)](#each_with_index/2) See [`REnum.each_with_index/2`](REnum.html#each_with_index/2). [each_with_object(arg1, arg2, arg3)](#each_with_object/3) See [`REnum.each_with_object/3`](REnum.html#each_with_object/3). [empty?(arg1)](#empty?/1) See [`REnum.empty?/1`](REnum.html#empty?/1). [entries(arg1)](#entries/1) See [`REnum.entries/1`](REnum.html#entries/1). [eql?(arg1, arg2)](#eql?/2) See [`RList.Ruby.eql?/2`](RList.Ruby.html#eql?/2). [exclude?(arg1, arg2)](#exclude?/2) See [`REnum.exclude?/2`](REnum.html#exclude?/2). [excluding(arg1, arg2)](#excluding/2) See [`REnum.excluding/2`](REnum.html#excluding/2). [fetch(arg1, arg2)](#fetch/2) See [`REnum.fetch/2`](REnum.html#fetch/2). [fetch!(arg1, arg2)](#fetch!/2) See [`REnum.fetch!/2`](REnum.html#fetch!/2). [fifth(arg1)](#fifth/1) See [`RList.ActiveSupport.fifth/1`](RList.ActiveSupport.html#fifth/1). [fill(arg1, arg2)](#fill/2) See [`RList.Ruby.fill/2`](RList.Ruby.html#fill/2). [fill(arg1, arg2, arg3)](#fill/3) See [`RList.Ruby.fill/3`](RList.Ruby.html#fill/3). [filter(arg1, arg2)](#filter/2) See [`REnum.filter/2`](REnum.html#filter/2). [find(arg1, arg2)](#find/2) See [`REnum.find/2`](REnum.html#find/2). [find(arg1, arg2, arg3)](#find/3) See [`REnum.find/3`](REnum.html#find/3). [find_all(arg1, arg2)](#find_all/2) See [`REnum.find_all/2`](REnum.html#find_all/2). [find_index(arg1, arg2)](#find_index/2) See [`REnum.find_index/2`](REnum.html#find_index/2). [find_index_with_index(arg1, arg2)](#find_index_with_index/2) See [`REnum.find_index_with_index/2`](REnum.html#find_index_with_index/2). [find_value(arg1, arg2)](#find_value/2) See [`REnum.find_value/2`](REnum.html#find_value/2). [find_value(arg1, arg2, arg3)](#find_value/3) See [`REnum.find_value/3`](REnum.html#find_value/3). [first(arg1)](#first/1) See [`List.first/1`](https://hexdocs.pm/elixir/List.html#first/1). [first(arg1, arg2)](#first/2) See [`List.first/2`](https://hexdocs.pm/elixir/List.html#first/2). [flat_map(arg1, arg2)](#flat_map/2) See [`REnum.flat_map/2`](REnum.html#flat_map/2). [flat_map_reduce(arg1, arg2, arg3)](#flat_map_reduce/3) See [`REnum.flat_map_reduce/3`](REnum.html#flat_map_reduce/3). [flatten(arg1)](#flatten/1) See [`List.flatten/1`](https://hexdocs.pm/elixir/List.html#flatten/1). [flatten(arg1, arg2)](#flatten/2) See [`List.flatten/2`](https://hexdocs.pm/elixir/List.html#flatten/2). [foldl(arg1, arg2, arg3)](#foldl/3) See [`List.foldl/3`](https://hexdocs.pm/elixir/List.html#foldl/3). [foldr(arg1, arg2, arg3)](#foldr/3) See [`List.foldr/3`](https://hexdocs.pm/elixir/List.html#foldr/3). [forty_two(arg1)](#forty_two/1) See [`RList.ActiveSupport.forty_two/1`](RList.ActiveSupport.html#forty_two/1). [fourth(arg1)](#fourth/1) See [`RList.ActiveSupport.fourth/1`](RList.ActiveSupport.html#fourth/1). [frequencies(arg1)](#frequencies/1) See [`REnum.frequencies/1`](REnum.html#frequencies/1). [frequencies_by(arg1, arg2)](#frequencies_by/2) See [`REnum.frequencies_by/2`](REnum.html#frequencies_by/2). [from(arg1, arg2)](#from/2) See [`RList.ActiveSupport.from/2`](RList.ActiveSupport.html#from/2). [grep(arg1, arg2)](#grep/2) See [`REnum.grep/2`](REnum.html#grep/2). [grep(arg1, arg2, arg3)](#grep/3) See [`REnum.grep/3`](REnum.html#grep/3). [grep_v(arg1, arg2)](#grep_v/2) See [`REnum.grep_v/2`](REnum.html#grep_v/2). [grep_v(arg1, arg2, arg3)](#grep_v/3) See [`REnum.grep_v/3`](REnum.html#grep_v/3). [group_by(arg1, arg2)](#group_by/2) See [`REnum.group_by/2`](REnum.html#group_by/2). [group_by(arg1, arg2, arg3)](#group_by/3) See [`REnum.group_by/3`](REnum.html#group_by/3). [improper?(arg1)](#improper?/1) See [`List.improper?/1`](https://hexdocs.pm/elixir/List.html#improper?/1). [in_groups(arg1, arg2)](#in_groups/2) See [`RList.ActiveSupport.in_groups/2`](RList.ActiveSupport.html#in_groups/2). [in_groups(arg1, arg2, arg3)](#in_groups/3) See [`RList.ActiveSupport.in_groups/3`](RList.ActiveSupport.html#in_groups/3). [in_groups_of(arg1, arg2)](#in_groups_of/2) See [`RList.ActiveSupport.in_groups_of/2`](RList.ActiveSupport.html#in_groups_of/2). [in_groups_of(arg1, arg2, arg3)](#in_groups_of/3) See [`RList.ActiveSupport.in_groups_of/3`](RList.ActiveSupport.html#in_groups_of/3). [in_order_of(arg1, arg2, arg3)](#in_order_of/3) See [`REnum.in_order_of/3`](REnum.html#in_order_of/3). [include?(arg1, arg2)](#include?/2) See [`REnum.include?/2`](REnum.html#include?/2). [including(arg1, arg2)](#including/2) See [`REnum.including/2`](REnum.html#including/2). [index(arg1, arg2)](#index/2) See [`RList.Ruby.index/2`](RList.Ruby.html#index/2). [index_by(arg1, arg2)](#index_by/2) See [`REnum.index_by/2`](REnum.html#index_by/2). [index_with(arg1, arg2)](#index_with/2) See [`REnum.index_with/2`](REnum.html#index_with/2). [inject(arg1, arg2)](#inject/2) See [`REnum.inject/2`](REnum.html#inject/2). [inject(arg1, arg2, arg3)](#inject/3) See [`REnum.inject/3`](REnum.html#inject/3). [insert(arg1, arg2, arg3)](#insert/3) See [`RList.Ruby.insert/3`](RList.Ruby.html#insert/3). [insert_at(arg1, arg2, arg3)](#insert_at/3) See [`List.insert_at/3`](https://hexdocs.pm/elixir/List.html#insert_at/3). [inspect(arg1)](#inspect/1) See [`RList.Ruby.inspect/1`](RList.Ruby.html#inspect/1). [intersect?(arg1, arg2)](#intersect?/2) See [`RList.Ruby.intersect?/2`](RList.Ruby.html#intersect?/2). [intersection(arg1, arg2)](#intersection/2) See [`RList.Ruby.intersection/2`](RList.Ruby.html#intersection/2). [intersperse(arg1, arg2)](#intersperse/2) See [`REnum.intersperse/2`](REnum.html#intersperse/2). [into(arg1, arg2)](#into/2) See [`REnum.into/2`](REnum.html#into/2). [into(arg1, arg2, arg3)](#into/3) See [`REnum.into/3`](REnum.html#into/3). [join(arg1)](#join/1) See [`REnum.join/1`](REnum.html#join/1). [join(arg1, arg2)](#join/2) See [`REnum.join/2`](REnum.html#join/2). [keep_if(arg1, arg2)](#keep_if/2) See [`RList.Ruby.keep_if/2`](RList.Ruby.html#keep_if/2). [keydelete(arg1, arg2, arg3)](#keydelete/3) See [`List.keydelete/3`](https://hexdocs.pm/elixir/List.html#keydelete/3). [keyfind(arg1, arg2, arg3)](#keyfind/3) See [`List.keyfind/3`](https://hexdocs.pm/elixir/List.html#keyfind/3). [keyfind(arg1, arg2, arg3, arg4)](#keyfind/4) See [`List.keyfind/4`](https://hexdocs.pm/elixir/List.html#keyfind/4). [keyfind!(arg1, arg2, arg3)](#keyfind!/3) See [`List.keyfind!/3`](https://hexdocs.pm/elixir/List.html#keyfind!/3). [keymember?(arg1, arg2, arg3)](#keymember?/3) See [`List.keymember?/3`](https://hexdocs.pm/elixir/List.html#keymember?/3). [keyreplace(arg1, arg2, arg3, arg4)](#keyreplace/4) See [`List.keyreplace/4`](https://hexdocs.pm/elixir/List.html#keyreplace/4). [keysort(arg1, arg2)](#keysort/2) See [`List.keysort/2`](https://hexdocs.pm/elixir/List.html#keysort/2). [keystore(arg1, arg2, arg3, arg4)](#keystore/4) See [`List.keystore/4`](https://hexdocs.pm/elixir/List.html#keystore/4). [keytake(arg1, arg2, arg3)](#keytake/3) See [`List.keytake/3`](https://hexdocs.pm/elixir/List.html#keytake/3). [last(arg1)](#last/1) See [`List.last/1`](https://hexdocs.pm/elixir/List.html#last/1). [last(arg1, arg2)](#last/2) See [`List.last/2`](https://hexdocs.pm/elixir/List.html#last/2). [lazy(arg1)](#lazy/1) See [`REnum.lazy/1`](REnum.html#lazy/1). [length(arg1)](#length/1) See [`RList.Ruby.length/1`](RList.Ruby.html#length/1). [list_and_not_keyword?(arg1)](#list_and_not_keyword?/1) See [`REnum.list_and_not_keyword?/1`](REnum.html#list_and_not_keyword?/1). [many?(arg1)](#many?/1) See [`REnum.many?/1`](REnum.html#many?/1). [many?(arg1, arg2)](#many?/2) See [`REnum.many?/2`](REnum.html#many?/2). [map(arg1, arg2)](#map/2) See [`REnum.map/2`](REnum.html#map/2). [map_and_not_range?(arg1)](#map_and_not_range?/1) See [`REnum.map_and_not_range?/1`](REnum.html#map_and_not_range?/1). [map_every(arg1, arg2, arg3)](#map_every/3) See [`REnum.map_every/3`](REnum.html#map_every/3). [map_intersperse(arg1, arg2, arg3)](#map_intersperse/3) See [`REnum.map_intersperse/3`](REnum.html#map_intersperse/3). [map_join(arg1, arg2)](#map_join/2) See [`REnum.map_join/2`](REnum.html#map_join/2). [map_join(arg1, arg2, arg3)](#map_join/3) See [`REnum.map_join/3`](REnum.html#map_join/3). [map_reduce(arg1, arg2, arg3)](#map_reduce/3) See [`REnum.map_reduce/3`](REnum.html#map_reduce/3). [match_function(arg1)](#match_function/1) See [`REnum.match_function/1`](REnum.html#match_function/1). [max(arg1)](#max/1) See [`REnum.max/1`](REnum.html#max/1). [max(arg1, arg2)](#max/2) See [`REnum.max/2`](REnum.html#max/2). [max(arg1, arg2, arg3)](#max/3) See [`REnum.max/3`](REnum.html#max/3). [max_by(arg1, arg2)](#max_by/2) See [`REnum.max_by/2`](REnum.html#max_by/2). [max_by(arg1, arg2, arg3)](#max_by/3) See [`REnum.max_by/3`](REnum.html#max_by/3). [max_by(arg1, arg2, arg3, arg4)](#max_by/4) See [`REnum.max_by/4`](REnum.html#max_by/4). [maximum(arg1, arg2)](#maximum/2) See [`REnum.maximum/2`](REnum.html#maximum/2). [member?(arg1, arg2)](#member?/2) See [`REnum.member?/2`](REnum.html#member?/2). [min(arg1)](#min/1) See [`REnum.min/1`](REnum.html#min/1). [min(arg1, arg2)](#min/2) See [`REnum.min/2`](REnum.html#min/2). [min(arg1, arg2, arg3)](#min/3) See [`REnum.min/3`](REnum.html#min/3). [min_by(arg1, arg2)](#min_by/2) See [`REnum.min_by/2`](REnum.html#min_by/2). [min_by(arg1, arg2, arg3)](#min_by/3) See [`REnum.min_by/3`](REnum.html#min_by/3). [min_by(arg1, arg2, arg3, arg4)](#min_by/4) See [`REnum.min_by/4`](REnum.html#min_by/4). [min_max(arg1)](#min_max/1) See [`REnum.min_max/1`](REnum.html#min_max/1). [min_max(arg1, arg2)](#min_max/2) See [`REnum.min_max/2`](REnum.html#min_max/2). [min_max_by(arg1, arg2)](#min_max_by/2) See [`REnum.min_max_by/2`](REnum.html#min_max_by/2). [min_max_by(arg1, arg2, arg3)](#min_max_by/3) See [`REnum.min_max_by/3`](REnum.html#min_max_by/3). [min_max_by(arg1, arg2, arg3, arg4)](#min_max_by/4) See [`REnum.min_max_by/4`](REnum.html#min_max_by/4). [minimum(arg1, arg2)](#minimum/2) See [`REnum.minimum/2`](REnum.html#minimum/2). [minmax(arg1)](#minmax/1) See [`REnum.minmax/1`](REnum.html#minmax/1). [minmax(arg1, arg2)](#minmax/2) See [`REnum.minmax/2`](REnum.html#minmax/2). [minmax_by(arg1, arg2)](#minmax_by/2) See [`REnum.minmax_by/2`](REnum.html#minmax_by/2). [minmax_by(arg1, arg2, arg3)](#minmax_by/3) See [`REnum.minmax_by/3`](REnum.html#minmax_by/3). [minmax_by(arg1, arg2, arg3, arg4)](#minmax_by/4) See [`REnum.minmax_by/4`](REnum.html#minmax_by/4). [myers_difference(arg1, arg2)](#myers_difference/2) See [`List.myers_difference/2`](https://hexdocs.pm/elixir/List.html#myers_difference/2). [myers_difference(arg1, arg2, arg3)](#myers_difference/3) See [`List.myers_difference/3`](https://hexdocs.pm/elixir/List.html#myers_difference/3). [new(arg1)](#new/1) See [`RList.Support.new/1`](RList.Support.html#new/1). [new(arg1, arg2)](#new/2) See [`RList.Support.new/2`](RList.Support.html#new/2). [none?(arg1)](#none?/1) See [`REnum.none?/1`](REnum.html#none?/1). [none?(arg1, arg2)](#none?/2) See [`REnum.none?/2`](REnum.html#none?/2). [one?(arg1)](#one?/1) See [`REnum.one?/1`](REnum.html#one?/1). [one?(arg1, arg2)](#one?/2) See [`REnum.one?/2`](REnum.html#one?/2). [permutation(arg1)](#permutation/1) See [`RList.Ruby.permutation/1`](RList.Ruby.html#permutation/1). [permutation(arg1, arg2)](#permutation/2) See [`RList.Ruby.permutation/2`](RList.Ruby.html#permutation/2). [pick(arg1, arg2)](#pick/2) See [`REnum.pick/2`](REnum.html#pick/2). [pluck(arg1, arg2)](#pluck/2) See [`REnum.pluck/2`](REnum.html#pluck/2). [pop(arg1)](#pop/1) See [`RList.Ruby.pop/1`](RList.Ruby.html#pop/1). [pop(arg1, arg2)](#pop/2) See [`RList.Ruby.pop/2`](RList.Ruby.html#pop/2). [pop_at(arg1, arg2)](#pop_at/2) See [`List.pop_at/2`](https://hexdocs.pm/elixir/List.html#pop_at/2). [pop_at(arg1, arg2, arg3)](#pop_at/3) See [`List.pop_at/3`](https://hexdocs.pm/elixir/List.html#pop_at/3). [prepend(arg1)](#prepend/1) See [`RList.Ruby.prepend/1`](RList.Ruby.html#prepend/1). [prepend(arg1, arg2)](#prepend/2) See [`RList.Ruby.prepend/2`](RList.Ruby.html#prepend/2). [product(arg1)](#product/1) See [`REnum.product/1`](REnum.html#product/1). [push(arg1, arg2)](#push/2) See [`RList.Ruby.push/2`](RList.Ruby.html#push/2). [random(arg1)](#random/1) See [`REnum.random/1`](REnum.html#random/1). [range?(arg1)](#range?/1) See [`REnum.range?/1`](REnum.html#range?/1). [rassoc(arg1, arg2)](#rassoc/2) See [`RList.Ruby.rassoc/2`](RList.Ruby.html#rassoc/2). [reduce(arg1, arg2)](#reduce/2) See [`REnum.reduce/2`](REnum.html#reduce/2). [reduce(arg1, arg2, arg3)](#reduce/3) See [`REnum.reduce/3`](REnum.html#reduce/3). [reduce_while(arg1, arg2, arg3)](#reduce_while/3) See [`REnum.reduce_while/3`](REnum.html#reduce_while/3). [reject(arg1, arg2)](#reject/2) See [`REnum.reject/2`](REnum.html#reject/2). [repeated_combination(arg1, arg2)](#repeated_combination/2) See [`RList.Ruby.repeated_combination/2`](RList.Ruby.html#repeated_combination/2). [repeated_combination(arg1, arg2, arg3)](#repeated_combination/3) See [`RList.Ruby.repeated_combination/3`](RList.Ruby.html#repeated_combination/3). [repeated_permutation(arg1, arg2)](#repeated_permutation/2) See [`RList.Ruby.repeated_permutation/2`](RList.Ruby.html#repeated_permutation/2). [replace_at(arg1, arg2, arg3)](#replace_at/3) See [`List.replace_at/3`](https://hexdocs.pm/elixir/List.html#replace_at/3). [reverse(arg1)](#reverse/1) See [`REnum.reverse/1`](REnum.html#reverse/1). [reverse(arg1, arg2)](#reverse/2) See [`REnum.reverse/2`](REnum.html#reverse/2). [reverse_each(arg1, arg2)](#reverse_each/2) See [`REnum.reverse_each/2`](REnum.html#reverse_each/2). [reverse_slice(arg1, arg2, arg3)](#reverse_slice/3) See [`REnum.reverse_slice/3`](REnum.html#reverse_slice/3). [rindex(arg1, arg2)](#rindex/2) See [`RList.Ruby.rindex/2`](RList.Ruby.html#rindex/2). [rotate(arg1)](#rotate/1) See [`RList.Ruby.rotate/1`](RList.Ruby.html#rotate/1). [rotate(arg1, arg2)](#rotate/2) See [`RList.Ruby.rotate/2`](RList.Ruby.html#rotate/2). [sample(arg1)](#sample/1) See [`RList.Ruby.sample/1`](RList.Ruby.html#sample/1). [sample(arg1, arg2)](#sample/2) See [`RList.Ruby.sample/2`](RList.Ruby.html#sample/2). [scan(arg1, arg2)](#scan/2) See [`REnum.scan/2`](REnum.html#scan/2). [scan(arg1, arg2, arg3)](#scan/3) See [`REnum.scan/3`](REnum.html#scan/3). [second(arg1)](#second/1) See [`RList.ActiveSupport.second/1`](RList.ActiveSupport.html#second/1). [second_to_last(arg1)](#second_to_last/1) See [`RList.ActiveSupport.second_to_last/1`](RList.ActiveSupport.html#second_to_last/1). [select(arg1, arg2)](#select/2) See [`REnum.select/2`](REnum.html#select/2). [shift(arg1)](#shift/1) See [`RList.Ruby.shift/1`](RList.Ruby.html#shift/1). [shift(arg1, arg2)](#shift/2) See [`RList.Ruby.shift/2`](RList.Ruby.html#shift/2). [shuffle(arg1)](#shuffle/1) See [`REnum.shuffle/1`](REnum.html#shuffle/1). [size(arg1)](#size/1) See [`RList.Ruby.size/1`](RList.Ruby.html#size/1). [slice(arg1, arg2)](#slice/2) See [`REnum.slice/2`](REnum.html#slice/2). [slice(arg1, arg2, arg3)](#slice/3) See [`REnum.slice/3`](REnum.html#slice/3). [slice_after(arg1, arg2)](#slice_after/2) See [`REnum.slice_after/2`](REnum.html#slice_after/2). [slice_before(arg1, arg2)](#slice_before/2) See [`REnum.slice_before/2`](REnum.html#slice_before/2). [slice_when(arg1, arg2)](#slice_when/2) See [`REnum.slice_when/2`](REnum.html#slice_when/2). [slide(arg1, arg2, arg3)](#slide/3) See [`REnum.slide/3`](REnum.html#slide/3). [sole(arg1)](#sole/1) See [`REnum.sole/1`](REnum.html#sole/1). [sort(arg1)](#sort/1) See [`REnum.sort/1`](REnum.html#sort/1). [sort(arg1, arg2)](#sort/2) See [`REnum.sort/2`](REnum.html#sort/2). [sort_by(arg1, arg2)](#sort_by/2) See [`REnum.sort_by/2`](REnum.html#sort_by/2). [sort_by(arg1, arg2, arg3)](#sort_by/3) See [`REnum.sort_by/3`](REnum.html#sort_by/3). [split(arg1, arg2)](#split/2) See [`REnum.split/2`](REnum.html#split/2). [split_while(arg1, arg2)](#split_while/2) See [`REnum.split_while/2`](REnum.html#split_while/2). [split_with(arg1, arg2)](#split_with/2) See [`REnum.split_with/2`](REnum.html#split_with/2). [starts_with?(arg1, arg2)](#starts_with?/2) See [`List.starts_with?/2`](https://hexdocs.pm/elixir/List.html#starts_with?/2). [sum(arg1)](#sum/1) See [`REnum.sum/1`](REnum.html#sum/1). [take(arg1, arg2)](#take/2) See [`REnum.take/2`](REnum.html#take/2). [take_every(arg1, arg2)](#take_every/2) See [`REnum.take_every/2`](REnum.html#take_every/2). [take_random(arg1, arg2)](#take_random/2) See [`REnum.take_random/2`](REnum.html#take_random/2). [take_while(arg1, arg2)](#take_while/2) See [`REnum.take_while/2`](REnum.html#take_while/2). [tally(arg1)](#tally/1) See [`REnum.tally/1`](REnum.html#tally/1). [third(arg1)](#third/1) See [`RList.ActiveSupport.third/1`](RList.ActiveSupport.html#third/1). [third_to_last(arg1)](#third_to_last/1) See [`RList.ActiveSupport.third_to_last/1`](RList.ActiveSupport.html#third_to_last/1). [to(arg1, arg2)](#to/2) See [`RList.ActiveSupport.to/2`](RList.ActiveSupport.html#to/2). [to_a(arg1)](#to_a/1) See [`REnum.to_a/1`](REnum.html#to_a/1). [to_ary(arg1)](#to_ary/1) See [`RList.Ruby.to_ary/1`](RList.Ruby.html#to_ary/1). [to_atom(arg1)](#to_atom/1) See [`List.to_atom/1`](https://hexdocs.pm/elixir/List.html#to_atom/1). [to_charlist(arg1)](#to_charlist/1) See [`List.to_charlist/1`](https://hexdocs.pm/elixir/List.html#to_charlist/1). [to_default_s(arg1)](#to_default_s/1) See [`RList.ActiveSupport.to_default_s/1`](RList.ActiveSupport.html#to_default_s/1). [to_existing_atom(arg1)](#to_existing_atom/1) See [`List.to_existing_atom/1`](https://hexdocs.pm/elixir/List.html#to_existing_atom/1). [to_float(arg1)](#to_float/1) See [`List.to_float/1`](https://hexdocs.pm/elixir/List.html#to_float/1). [to_h(arg1)](#to_h/1) See [`REnum.to_h/1`](REnum.html#to_h/1). [to_h(arg1, arg2)](#to_h/2) See [`REnum.to_h/2`](REnum.html#to_h/2). [to_integer(arg1)](#to_integer/1) See [`List.to_integer/1`](https://hexdocs.pm/elixir/List.html#to_integer/1). [to_integer(arg1, arg2)](#to_integer/2) See [`List.to_integer/2`](https://hexdocs.pm/elixir/List.html#to_integer/2). [to_l(arg1)](#to_l/1) See [`REnum.to_l/1`](REnum.html#to_l/1). [to_list(arg1)](#to_list/1) See [`REnum.to_list/1`](REnum.html#to_list/1). [to_s(arg1)](#to_s/1) See [`RList.Ruby.to_s/1`](RList.Ruby.html#to_s/1). [to_sentence(arg1)](#to_sentence/1) See [`RList.ActiveSupport.to_sentence/1`](RList.ActiveSupport.html#to_sentence/1). [to_sentence(arg1, arg2)](#to_sentence/2) See [`RList.ActiveSupport.to_sentence/2`](RList.ActiveSupport.html#to_sentence/2). [to_string(arg1)](#to_string/1) See [`List.to_string/1`](https://hexdocs.pm/elixir/List.html#to_string/1). [to_tuple(arg1)](#to_tuple/1) See [`List.to_tuple/1`](https://hexdocs.pm/elixir/List.html#to_tuple/1). [transpose(arg1)](#transpose/1) See [`RList.Ruby.transpose/1`](RList.Ruby.html#transpose/1). [truthy_count(arg1)](#truthy_count/1) See [`REnum.truthy_count/1`](REnum.html#truthy_count/1). [truthy_count(arg1, arg2)](#truthy_count/2) See [`REnum.truthy_count/2`](REnum.html#truthy_count/2). [union(arg1, arg2)](#union/2) See [`RList.Ruby.union/2`](RList.Ruby.html#union/2). [uniq_by(arg1, arg2)](#uniq_by/2) See [`REnum.uniq_by/2`](REnum.html#uniq_by/2). [unshift(arg1, arg2)](#unshift/2) See [`RList.Ruby.unshift/2`](RList.Ruby.html#unshift/2). [unzip(arg1)](#unzip/1) See [`REnum.unzip/1`](REnum.html#unzip/1). [update_at(arg1, arg2, arg3)](#update_at/3) See [`List.update_at/3`](https://hexdocs.pm/elixir/List.html#update_at/3). [values_at(arg1, arg2)](#values_at/2) See [`RList.Ruby.values_at/2`](RList.Ruby.html#values_at/2). [with_index(arg1)](#with_index/1) See [`REnum.with_index/1`](REnum.html#with_index/1). [with_index(arg1, arg2)](#with_index/2) See [`REnum.with_index/2`](REnum.html#with_index/2). [without(arg1, arg2)](#without/2) See [`REnum.without/2`](REnum.html#without/2). [wrap(arg1)](#wrap/1) See [`List.wrap/1`](https://hexdocs.pm/elixir/List.html#wrap/1). [zip(arg1)](#zip/1) See [`List.zip/1`](https://hexdocs.pm/elixir/List.html#zip/1). [zip_reduce(arg1, arg2, arg3)](#zip_reduce/3) See [`REnum.zip_reduce/3`](REnum.html#zip_reduce/3). [zip_reduce(arg1, arg2, arg3, arg4)](#zip_reduce/4) See [`REnum.zip_reduce/4`](REnum.html#zip_reduce/4). [zip_with(arg1, arg2)](#zip_with/2) See [`REnum.zip_with/2`](REnum.html#zip_with/2). [zip_with(arg1, arg2, arg3)](#zip_with/3) See [`REnum.zip_with/3`](REnum.html#zip_with/3). [Link to this section](#functions) Functions === RList.ActiveSupport === Summarized all of List functions in Rails.ActiveSupport. If a function with the same name already exists in Elixir, that is not implemented. Defines all of here functions when `use RList.ActiveSupport`. [Link to this section](#summary) Summary === [Functions](#functions) --- [fifth(list)](#fifth/1) Equal to `Enum.at(list, 4)`. [forty_two(list)](#forty_two/1) Equal to `Enum.at(list, 41)`. Also known as accessing "the reddit". [fourth(list)](#fourth/1) Equal to `Enum.at(list, 3)`. [from(list, position)](#from/2) Returns the tail of the list from position. [in_groups(list, number, fill_with \\ nil)](#in_groups/3) Splits or iterates over the list in number of groups, padding any remaining slots with fill_with unless it is false. [in_groups_of(list, number, fill_with \\ nil)](#in_groups_of/3) Splits or iterates over the list in groups of size number, padding any remaining slots with fill_with unless it is +false+. [second(list)](#second/1) Equal to `Enum.at(list, 1)`. [second_to_last(list)](#second_to_last/1) Equal to `Enum.at(list, -2)`. [third(list)](#third/1) Equal to `Enum.at(list, 2)`. [third_to_last(list)](#third_to_last/1) Equal to `Enum.at(list, -3)`. [to(list, position)](#to/2) Returns the beginning of the list up to position. [to_default_s(list)](#to_default_s/1) See [`Kernel.inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1). [to_sentence(list, opts \\ [])](#to_sentence/2) Converts the list to a comma-separated sentence where the last element is joined by the connector word. [Link to this section](#functions) Functions === RList.Native === A module defines all of native List functions when `use RList.Native`. [See also.](https://hexdocs.pm/elixir/List.html) RList.Ruby === Summarized all of Ruby's Array functions. Functions corresponding to the following patterns are not implemented * When a function with the same name already exists in Elixir. * When a method name includes `!`. * &, *, +, -, <<, <=>, ==, [], []=. [Link to this section](#summary) Summary === [Types](#types) --- [type_enumerable()](#t:type_enumerable/0) [type_pattern()](#t:type_pattern/0) [Functions](#functions) --- [all_combination(list, length)](#all_combination/2) See [`RList.Ruby.repeated_combination/2`](#repeated_combination/2). [all_combination(list, length, func)](#all_combination/3) See [`RList.Ruby.repeated_combination/3`](#repeated_combination/3). [append(list, elements)](#append/2) See [`RList.Ruby.push/2`](#push/2). [assoc(list, key)](#assoc/2) Returns the first element in list that is an List whose first key == obj [clear(list)](#clear/1) Returns []. [combination(list, length)](#combination/2) Returns Stream that is each repeated combinations of elements of given list. The order of combinations is indeterminate. [combination(list, n, func)](#combination/3) Calls the function with combinations of elements of given list; returns :ok. The order of combinations is indeterminate. [delete_if(list, func)](#delete_if/2) See [`Enum.reject/2`](https://hexdocs.pm/elixir/Enum.html#reject/2). [difference(list1, list2)](#difference/2) Returns differences between list1 and list2. [dig(list, index, identifiers \\ [])](#dig/3) Finds and returns the element in nested elements that is specified by index and identifiers. [each_index(list, func)](#each_index/2) See [`Enum.with_index/2`](https://hexdocs.pm/elixir/Enum.html#with_index/2). [eql?(list1, list2)](#eql?/2) Returns true if list1 == list2. [fill(list, filler_fun)](#fill/2) Fills the list with the provided value. The filler can be either a function or a fixed value. [fill(list, filler_fun, fill_range)](#fill/3) [index(list, func_or_pattern)](#index/2) Returns the index of a specified element. [insert(list, index, element)](#insert/3) See [`List.insert_at/3`](https://hexdocs.pm/elixir/List.html#insert_at/3). [inspect(list)](#inspect/1) See [`Kernel.inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1). [intersect?(list1, list2)](#intersect?/2) Returns true if the list1 and list2 have at least one element in common, otherwise returns false. [intersection(list1, list2)](#intersection/2) Returns a new list containing each element found both in list1 and in all of the given list2; duplicates are omitted. [keep_if(list, func)](#keep_if/2) See [`Enum.filter/2`](https://hexdocs.pm/elixir/Enum.html#filter/2). [length(list)](#length/1) See [`Enum.count/1`](https://hexdocs.pm/elixir/Enum.html#count/1). [permutation(list, length \\ nil)](#permutation/2) Returns Stream that is each repeated permutations of elements of given list. The order of permutations is indeterminate. [pop(list, count \\ 1)](#pop/2) Splits the list into the last n elements and the rest. Returns nil if the list is empty. [prepend(list, count \\ 1)](#prepend/2) See [`RList.Ruby.shift/2`](#shift/2). [push(list, elements_or_element)](#push/2) Appends trailing elements. [rassoc(list, key)](#rassoc/2) Returns the first element that is a List whose last element `==` the specified term. [repeated_combination(list, length)](#repeated_combination/2) Returns Stream that is each repeated combinations of elements of given list. The order of combinations is indeterminate. [repeated_combination(list, n, func)](#repeated_combination/3) Calls the function with each repeated combinations of elements of given list; returns :ok. The order of combinations is indeterminate. [repeated_permutation(list, length)](#repeated_permutation/2) Returns Stream that is each repeated permutations of elements of given list. The order of permutations is indeterminate. [rindex(list, finder)](#rindex/2) Returns the index of the last element found in in the list. Returns nil if no match is found. [rotate(list, count \\ 1)](#rotate/2) Rotate the list so that the element at count is the first element of the list. [sample(list, n \\ 1)](#sample/2) Returns one or more random elements. [shift(list, count \\ 1)](#shift/2) Splits the list into the first n elements and the rest. Returns nil if the list is empty. [size(list)](#size/1) See [`Enum.count/1`](https://hexdocs.pm/elixir/Enum.html#count/1). [to_ary(list)](#to_ary/1) Returns list. [to_s(list)](#to_s/1) See [`Kernel.inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1). [transpose(list_of_lists)](#transpose/1) See [`List.zip/1`](https://hexdocs.pm/elixir/List.html#zip/1). [union(list_a, list_b)](#union/2) Returns a new list by joining two lists, excluding any duplicates and preserving the order from the given lists. [unshift(list, prepend)](#unshift/2) Prepends elements to the front of the list, moving other elements upwards. [values_at(list, indices)](#values_at/2) Returns a list containing the elements in list corresponding to the given selector(s). The selectors may be either integer indices or ranges. [Link to this section](#types) Types === [Link to this section](#functions) Functions === RList.Support === Summarized other useful functions related to Lit. Defines all of here functions when `use RList.Support`. [Link to this section](#summary) Summary === [Types](#types) --- [type_enumerable()](#t:type_enumerable/0) [Functions](#functions) --- [new(el)](#new/1) Equal to `[el]`. [new(el, amount)](#new/2) Make a list of size amount. [Link to this section](#types) Types === [Link to this section](#functions) Functions === RMap === Entry point of Map extensions, and can use all of RMap.* and REnum functions. See also. * [RMap.Native](https://hexdocs.pm/r_enum/RMap.Native.html#content) * [RMap.Ruby](https://hexdocs.pm/r_enum/RMap.Ruby.html#content) * [RMap.ActiveSupport](https://hexdocs.pm/r_enum/RMap.ActiveSupport.html#content) * [RMap.Support](https://hexdocs.pm/r_enum/RMap.Support.html#content) * [REnum](https://hexdocs.pm/r_enum/REnum.html#content) [Link to this section](#summary) Summary === [Functions](#functions) --- [all?(arg1)](#all?/1) See [`REnum.all?/1`](REnum.html#all?/1). [all?(arg1, arg2)](#all?/2) See [`REnum.all?/2`](REnum.html#all?/2). [any?(arg1)](#any?/1) See [`REnum.any?/1`](REnum.html#any?/1). [any?(arg1, arg2)](#any?/2) See [`REnum.any?/2`](REnum.html#any?/2). [assert_valid_keys(arg1, arg2)](#assert_valid_keys/2) See [`RMap.ActiveSupport.assert_valid_keys/2`](RMap.ActiveSupport.html#assert_valid_keys/2). [assoc(arg1, arg2)](#assoc/2) See [`RMap.Ruby.assoc/2`](RMap.Ruby.html#assoc/2). [at(arg1, arg2)](#at/2) See [`REnum.at/2`](REnum.html#at/2). [at(arg1, arg2, arg3)](#at/3) See [`REnum.at/3`](REnum.html#at/3). [atomize_keys(arg1)](#atomize_keys/1) See [`RMap.ActiveSupport.atomize_keys/1`](RMap.ActiveSupport.html#atomize_keys/1). [chain(arg1)](#chain/1) See [`REnum.chain/1`](REnum.html#chain/1). [chain(arg1, arg2)](#chain/2) See [`REnum.chain/2`](REnum.html#chain/2). [chunk_by(arg1, arg2)](#chunk_by/2) See [`REnum.chunk_by/2`](REnum.html#chunk_by/2). [chunk_every(arg1, arg2)](#chunk_every/2) See [`REnum.chunk_every/2`](REnum.html#chunk_every/2). [chunk_every(arg1, arg2, arg3)](#chunk_every/3) See [`REnum.chunk_every/3`](REnum.html#chunk_every/3). [chunk_every(arg1, arg2, arg3, arg4)](#chunk_every/4) See [`REnum.chunk_every/4`](REnum.html#chunk_every/4). [chunk_while(arg1, arg2, arg3, arg4)](#chunk_while/4) See [`REnum.chunk_while/4`](REnum.html#chunk_while/4). [clear(arg1)](#clear/1) See [`RMap.Ruby.clear/1`](RMap.Ruby.html#clear/1). [collect(arg1, arg2)](#collect/2) See [`REnum.collect/2`](REnum.html#collect/2). [collect_concat(arg1, arg2)](#collect_concat/2) See [`REnum.collect_concat/2`](REnum.html#collect_concat/2). [compact(arg1)](#compact/1) See [`REnum.compact/1`](REnum.html#compact/1). [compact_blank(arg1)](#compact_blank/1) See [`REnum.compact_blank/1`](REnum.html#compact_blank/1). [concat(arg1)](#concat/1) See [`REnum.concat/1`](REnum.html#concat/1). [concat(arg1, arg2)](#concat/2) See [`REnum.concat/2`](REnum.html#concat/2). [count(arg1)](#count/1) See [`REnum.count/1`](REnum.html#count/1). [count(arg1, arg2)](#count/2) See [`REnum.count/2`](REnum.html#count/2). [count_until(arg1, arg2)](#count_until/2) See [`REnum.count_until/2`](REnum.html#count_until/2). [count_until(arg1, arg2, arg3)](#count_until/3) See [`REnum.count_until/3`](REnum.html#count_until/3). [cycle(arg1, arg2, arg3)](#cycle/3) See [`REnum.cycle/3`](REnum.html#cycle/3). [dedup(arg1)](#dedup/1) See [`REnum.dedup/1`](REnum.html#dedup/1). [dedup_by(arg1, arg2)](#dedup_by/2) See [`REnum.dedup_by/2`](REnum.html#dedup_by/2). [deep_atomize_keys(arg1)](#deep_atomize_keys/1) See [`RMap.ActiveSupport.deep_atomize_keys/1`](RMap.ActiveSupport.html#deep_atomize_keys/1). [deep_stringify_keys(arg1)](#deep_stringify_keys/1) See [`RMap.ActiveSupport.deep_stringify_keys/1`](RMap.ActiveSupport.html#deep_stringify_keys/1). [deep_symbolize_keys(arg1)](#deep_symbolize_keys/1) See [`RMap.ActiveSupport.deep_symbolize_keys/1`](RMap.ActiveSupport.html#deep_symbolize_keys/1). [deep_to_list(arg1)](#deep_to_list/1) See [`RMap.Support.deep_to_list/1`](RMap.Support.html#deep_to_list/1). [deep_transform_keys(arg1, arg2)](#deep_transform_keys/2) See [`RMap.ActiveSupport.deep_transform_keys/2`](RMap.ActiveSupport.html#deep_transform_keys/2). [deep_transform_values(arg1, arg2)](#deep_transform_values/2) See [`RMap.ActiveSupport.deep_transform_values/2`](RMap.ActiveSupport.html#deep_transform_values/2). [delete(arg1, arg2)](#delete/2) See [`Map.delete/2`](https://hexdocs.pm/elixir/Map.html#delete/2). [delete_if(arg1, arg2)](#delete_if/2) See [`RMap.Ruby.delete_if/2`](RMap.Ruby.html#delete_if/2). [detect(arg1, arg2)](#detect/2) See [`REnum.detect/2`](REnum.html#detect/2). [detect(arg1, arg2, arg3)](#detect/3) See [`REnum.detect/3`](REnum.html#detect/3). [dig(arg1, arg2)](#dig/2) See [`RMap.Ruby.dig/2`](RMap.Ruby.html#dig/2). [drop(arg1, arg2)](#drop/2) See [`Map.drop/2`](https://hexdocs.pm/elixir/Map.html#drop/2). [drop_every(arg1, arg2)](#drop_every/2) See [`REnum.drop_every/2`](REnum.html#drop_every/2). [drop_while(arg1, arg2)](#drop_while/2) See [`REnum.drop_while/2`](REnum.html#drop_while/2). [each(arg1, arg2)](#each/2) See [`REnum.each/2`](REnum.html#each/2). [each_cons(arg1, arg2, arg3)](#each_cons/3) See [`REnum.each_cons/3`](REnum.html#each_cons/3). [each_entry(arg1, arg2)](#each_entry/2) See [`REnum.each_entry/2`](REnum.html#each_entry/2). [each_key(arg1, arg2)](#each_key/2) See [`RMap.Ruby.each_key/2`](RMap.Ruby.html#each_key/2). [each_pair(arg1, arg2)](#each_pair/2) See [`RMap.Ruby.each_pair/2`](RMap.Ruby.html#each_pair/2). [each_slice(arg1, arg2)](#each_slice/2) See [`REnum.each_slice/2`](REnum.html#each_slice/2). [each_slice(arg1, arg2, arg3)](#each_slice/3) See [`REnum.each_slice/3`](REnum.html#each_slice/3). [each_value(arg1, arg2)](#each_value/2) See [`RMap.Ruby.each_value/2`](RMap.Ruby.html#each_value/2). [each_with_index(arg1)](#each_with_index/1) See [`REnum.each_with_index/1`](REnum.html#each_with_index/1). [each_with_index(arg1, arg2)](#each_with_index/2) See [`REnum.each_with_index/2`](REnum.html#each_with_index/2). [each_with_object(arg1, arg2, arg3)](#each_with_object/3) See [`REnum.each_with_object/3`](REnum.html#each_with_object/3). [empty?(arg1)](#empty?/1) See [`REnum.empty?/1`](REnum.html#empty?/1). [entries(arg1)](#entries/1) See [`REnum.entries/1`](REnum.html#entries/1). [eql?(arg1, arg2)](#eql?/2) See [`RMap.Ruby.eql?/2`](RMap.Ruby.html#eql?/2). [equal?(arg1, arg2)](#equal?/2) See [`Map.equal?/2`](https://hexdocs.pm/elixir/Map.html#equal?/2). [except(arg1, arg2)](#except/2) See [`RMap.Ruby.except/2`](RMap.Ruby.html#except/2). [exclude?(arg1, arg2)](#exclude?/2) See [`REnum.exclude?/2`](REnum.html#exclude?/2). [excluding(arg1, arg2)](#excluding/2) See [`REnum.excluding/2`](REnum.html#excluding/2). [fetch(arg1, arg2)](#fetch/2) See [`Map.fetch/2`](https://hexdocs.pm/elixir/Map.html#fetch/2). [fetch!(arg1, arg2)](#fetch!/2) See [`Map.fetch!/2`](https://hexdocs.pm/elixir/Map.html#fetch!/2). [fetch_values(arg1, arg2)](#fetch_values/2) See [`RMap.Ruby.fetch_values/2`](RMap.Ruby.html#fetch_values/2). [fetch_values(arg1, arg2, arg3)](#fetch_values/3) See [`RMap.Ruby.fetch_values/3`](RMap.Ruby.html#fetch_values/3). [filter(arg1, arg2)](#filter/2) See [`RMap.Ruby.filter/2`](RMap.Ruby.html#filter/2). [find(arg1, arg2)](#find/2) See [`REnum.find/2`](REnum.html#find/2). [find(arg1, arg2, arg3)](#find/3) See [`REnum.find/3`](REnum.html#find/3). [find_all(arg1, arg2)](#find_all/2) See [`REnum.find_all/2`](REnum.html#find_all/2). [find_index(arg1, arg2)](#find_index/2) See [`REnum.find_index/2`](REnum.html#find_index/2). [find_index_with_index(arg1, arg2)](#find_index_with_index/2) See [`REnum.find_index_with_index/2`](REnum.html#find_index_with_index/2). [find_value(arg1, arg2)](#find_value/2) See [`REnum.find_value/2`](REnum.html#find_value/2). [find_value(arg1, arg2, arg3)](#find_value/3) See [`REnum.find_value/3`](REnum.html#find_value/3). [first(arg1)](#first/1) See [`REnum.first/1`](REnum.html#first/1). [first(arg1, arg2)](#first/2) See [`REnum.first/2`](REnum.html#first/2). [flat_map(arg1, arg2)](#flat_map/2) See [`REnum.flat_map/2`](REnum.html#flat_map/2). [flat_map_reduce(arg1, arg2, arg3)](#flat_map_reduce/3) See [`REnum.flat_map_reduce/3`](REnum.html#flat_map_reduce/3). [flatten(arg1)](#flatten/1) See [`RMap.Ruby.flatten/1`](RMap.Ruby.html#flatten/1). [frequencies(arg1)](#frequencies/1) See [`REnum.frequencies/1`](REnum.html#frequencies/1). [frequencies_by(arg1, arg2)](#frequencies_by/2) See [`REnum.frequencies_by/2`](REnum.html#frequencies_by/2). [from_struct(arg1)](#from_struct/1) See [`Map.from_struct/1`](https://hexdocs.pm/elixir/Map.html#from_struct/1). [get(arg1, arg2)](#get/2) See [`Map.get/2`](https://hexdocs.pm/elixir/Map.html#get/2). [get(arg1, arg2, arg3)](#get/3) See [`Map.get/3`](https://hexdocs.pm/elixir/Map.html#get/3). [get_and_update(arg1, arg2, arg3)](#get_and_update/3) See [`Map.get_and_update/3`](https://hexdocs.pm/elixir/Map.html#get_and_update/3). [get_and_update!(arg1, arg2, arg3)](#get_and_update!/3) See [`Map.get_and_update!/3`](https://hexdocs.pm/elixir/Map.html#get_and_update!/3). [get_lazy(arg1, arg2, arg3)](#get_lazy/3) See [`Map.get_lazy/3`](https://hexdocs.pm/elixir/Map.html#get_lazy/3). [grep(arg1, arg2)](#grep/2) See [`REnum.grep/2`](REnum.html#grep/2). [grep(arg1, arg2, arg3)](#grep/3) See [`REnum.grep/3`](REnum.html#grep/3). [grep_v(arg1, arg2)](#grep_v/2) See [`REnum.grep_v/2`](REnum.html#grep_v/2). [grep_v(arg1, arg2, arg3)](#grep_v/3) See [`REnum.grep_v/3`](REnum.html#grep_v/3). [group_by(arg1, arg2)](#group_by/2) See [`REnum.group_by/2`](REnum.html#group_by/2). [group_by(arg1, arg2, arg3)](#group_by/3) See [`REnum.group_by/3`](REnum.html#group_by/3). [has_key?(arg1, arg2)](#has_key?/2) See [`Map.has_key?/2`](https://hexdocs.pm/elixir/Map.html#has_key?/2). [has_value?(arg1, arg2)](#has_value?/2) See [`RMap.Ruby.has_value?/2`](RMap.Ruby.html#has_value?/2). [in_order_of(arg1, arg2, arg3)](#in_order_of/3) See [`REnum.in_order_of/3`](REnum.html#in_order_of/3). [include?(arg1, arg2)](#include?/2) See [`REnum.include?/2`](REnum.html#include?/2). [including(arg1, arg2)](#including/2) See [`REnum.including/2`](REnum.html#including/2). [index_by(arg1, arg2)](#index_by/2) See [`REnum.index_by/2`](REnum.html#index_by/2). [index_with(arg1, arg2)](#index_with/2) See [`REnum.index_with/2`](REnum.html#index_with/2). [inject(arg1, arg2)](#inject/2) See [`REnum.inject/2`](REnum.html#inject/2). [inject(arg1, arg2, arg3)](#inject/3) See [`REnum.inject/3`](REnum.html#inject/3). [inspect(arg1)](#inspect/1) See [`RMap.Ruby.inspect/1`](RMap.Ruby.html#inspect/1). [intersperse(arg1, arg2)](#intersperse/2) See [`REnum.intersperse/2`](REnum.html#intersperse/2). [into(arg1, arg2)](#into/2) See [`REnum.into/2`](REnum.html#into/2). [into(arg1, arg2, arg3)](#into/3) See [`REnum.into/3`](REnum.html#into/3). [invert(arg1)](#invert/1) See [`RMap.Ruby.invert/1`](RMap.Ruby.html#invert/1). [join(arg1)](#join/1) See [`REnum.join/1`](REnum.html#join/1). [join(arg1, arg2)](#join/2) See [`REnum.join/2`](REnum.html#join/2). [keep_if(arg1, arg2)](#keep_if/2) See [`RMap.Ruby.keep_if/2`](RMap.Ruby.html#keep_if/2). [key(arg1, arg2)](#key/2) See [`RMap.Ruby.key/2`](RMap.Ruby.html#key/2). [key(arg1, arg2, arg3)](#key/3) See [`RMap.Ruby.key/3`](RMap.Ruby.html#key/3). [key?(arg1, arg2)](#key?/2) See [`RMap.Ruby.key?/2`](RMap.Ruby.html#key?/2). [keys(arg1)](#keys/1) See [`Map.keys/1`](https://hexdocs.pm/elixir/Map.html#keys/1). [lazy(arg1)](#lazy/1) See [`REnum.lazy/1`](REnum.html#lazy/1). [length(arg1)](#length/1) See [`RMap.Ruby.length/1`](RMap.Ruby.html#length/1). [list_and_not_keyword?(arg1)](#list_and_not_keyword?/1) See [`REnum.list_and_not_keyword?/1`](REnum.html#list_and_not_keyword?/1). [many?(arg1)](#many?/1) See [`REnum.many?/1`](REnum.html#many?/1). [many?(arg1, arg2)](#many?/2) See [`REnum.many?/2`](REnum.html#many?/2). [map_and_not_range?(arg1)](#map_and_not_range?/1) See [`REnum.map_and_not_range?/1`](REnum.html#map_and_not_range?/1). [map_every(arg1, arg2, arg3)](#map_every/3) See [`REnum.map_every/3`](REnum.html#map_every/3). [map_intersperse(arg1, arg2, arg3)](#map_intersperse/3) See [`REnum.map_intersperse/3`](REnum.html#map_intersperse/3). [map_join(arg1, arg2)](#map_join/2) See [`REnum.map_join/2`](REnum.html#map_join/2). [map_join(arg1, arg2, arg3)](#map_join/3) See [`REnum.map_join/3`](REnum.html#map_join/3). [map_reduce(arg1, arg2, arg3)](#map_reduce/3) See [`REnum.map_reduce/3`](REnum.html#map_reduce/3). [match_function(arg1)](#match_function/1) See [`REnum.match_function/1`](REnum.html#match_function/1). [max(arg1)](#max/1) See [`REnum.max/1`](REnum.html#max/1). [max(arg1, arg2)](#max/2) See [`REnum.max/2`](REnum.html#max/2). [max(arg1, arg2, arg3)](#max/3) See [`REnum.max/3`](REnum.html#max/3). [max_by(arg1, arg2)](#max_by/2) See [`REnum.max_by/2`](REnum.html#max_by/2). [max_by(arg1, arg2, arg3)](#max_by/3) See [`REnum.max_by/3`](REnum.html#max_by/3). [max_by(arg1, arg2, arg3, arg4)](#max_by/4) See [`REnum.max_by/4`](REnum.html#max_by/4). [maximum(arg1, arg2)](#maximum/2) See [`REnum.maximum/2`](REnum.html#maximum/2). [member?(arg1, arg2)](#member?/2) See [`REnum.member?/2`](REnum.html#member?/2). [merge(arg1, arg2)](#merge/2) See [`Map.merge/2`](https://hexdocs.pm/elixir/Map.html#merge/2). [merge(arg1, arg2, arg3)](#merge/3) See [`Map.merge/3`](https://hexdocs.pm/elixir/Map.html#merge/3). [min(arg1)](#min/1) See [`REnum.min/1`](REnum.html#min/1). [min(arg1, arg2)](#min/2) See [`REnum.min/2`](REnum.html#min/2). [min(arg1, arg2, arg3)](#min/3) See [`REnum.min/3`](REnum.html#min/3). [min_by(arg1, arg2)](#min_by/2) See [`REnum.min_by/2`](REnum.html#min_by/2). [min_by(arg1, arg2, arg3)](#min_by/3) See [`REnum.min_by/3`](REnum.html#min_by/3). [min_by(arg1, arg2, arg3, arg4)](#min_by/4) See [`REnum.min_by/4`](REnum.html#min_by/4). [min_max(arg1)](#min_max/1) See [`REnum.min_max/1`](REnum.html#min_max/1). [min_max(arg1, arg2)](#min_max/2) See [`REnum.min_max/2`](REnum.html#min_max/2). [min_max_by(arg1, arg2)](#min_max_by/2) See [`REnum.min_max_by/2`](REnum.html#min_max_by/2). [min_max_by(arg1, arg2, arg3)](#min_max_by/3) See [`REnum.min_max_by/3`](REnum.html#min_max_by/3). [min_max_by(arg1, arg2, arg3, arg4)](#min_max_by/4) See [`REnum.min_max_by/4`](REnum.html#min_max_by/4). [minimum(arg1, arg2)](#minimum/2) See [`REnum.minimum/2`](REnum.html#minimum/2). [minmax(arg1)](#minmax/1) See [`REnum.minmax/1`](REnum.html#minmax/1). [minmax(arg1, arg2)](#minmax/2) See [`REnum.minmax/2`](REnum.html#minmax/2). [minmax_by(arg1, arg2)](#minmax_by/2) See [`REnum.minmax_by/2`](REnum.html#minmax_by/2). [minmax_by(arg1, arg2, arg3)](#minmax_by/3) See [`REnum.minmax_by/3`](REnum.html#minmax_by/3). [minmax_by(arg1, arg2, arg3, arg4)](#minmax_by/4) See [`REnum.minmax_by/4`](REnum.html#minmax_by/4). [new()](#new/0) See [`Map.new/0`](https://hexdocs.pm/elixir/Map.html#new/0). [new(arg1)](#new/1) See [`Map.new/1`](https://hexdocs.pm/elixir/Map.html#new/1). [new(arg1, arg2)](#new/2) See [`Map.new/2`](https://hexdocs.pm/elixir/Map.html#new/2). [none?(arg1)](#none?/1) See [`REnum.none?/1`](REnum.html#none?/1). [none?(arg1, arg2)](#none?/2) See [`REnum.none?/2`](REnum.html#none?/2). [one?(arg1)](#one?/1) See [`REnum.one?/1`](REnum.html#one?/1). [one?(arg1, arg2)](#one?/2) See [`REnum.one?/2`](REnum.html#one?/2). [pick(arg1, arg2)](#pick/2) See [`REnum.pick/2`](REnum.html#pick/2). [pluck(arg1, arg2)](#pluck/2) See [`REnum.pluck/2`](REnum.html#pluck/2). [pop(arg1, arg2)](#pop/2) See [`Map.pop/2`](https://hexdocs.pm/elixir/Map.html#pop/2). [pop(arg1, arg2, arg3)](#pop/3) See [`Map.pop/3`](https://hexdocs.pm/elixir/Map.html#pop/3). [pop!(arg1, arg2)](#pop!/2) See [`Map.pop!/2`](https://hexdocs.pm/elixir/Map.html#pop!/2). [pop_lazy(arg1, arg2, arg3)](#pop_lazy/3) See [`Map.pop_lazy/3`](https://hexdocs.pm/elixir/Map.html#pop_lazy/3). [product(arg1)](#product/1) See [`REnum.product/1`](REnum.html#product/1). [put(arg1, arg2, arg3)](#put/3) See [`Map.put/3`](https://hexdocs.pm/elixir/Map.html#put/3). [put_new(arg1, arg2, arg3)](#put_new/3) See [`Map.put_new/3`](https://hexdocs.pm/elixir/Map.html#put_new/3). [put_new_lazy(arg1, arg2, arg3)](#put_new_lazy/3) See [`Map.put_new_lazy/3`](https://hexdocs.pm/elixir/Map.html#put_new_lazy/3). [random(arg1)](#random/1) See [`REnum.random/1`](REnum.html#random/1). [range?(arg1)](#range?/1) See [`REnum.range?/1`](REnum.html#range?/1). [rassoc(arg1, arg2)](#rassoc/2) See [`RMap.Ruby.rassoc/2`](RMap.Ruby.html#rassoc/2). [reduce(arg1, arg2)](#reduce/2) See [`REnum.reduce/2`](REnum.html#reduce/2). [reduce(arg1, arg2, arg3)](#reduce/3) See [`REnum.reduce/3`](REnum.html#reduce/3). [reduce_while(arg1, arg2, arg3)](#reduce_while/3) See [`REnum.reduce_while/3`](REnum.html#reduce_while/3). [reject(arg1, arg2)](#reject/2) See [`RMap.Ruby.reject/2`](RMap.Ruby.html#reject/2). [replace(arg1, arg2, arg3)](#replace/3) See [`Map.replace/3`](https://hexdocs.pm/elixir/Map.html#replace/3). [replace!(arg1, arg2, arg3)](#replace!/3) See [`Map.replace!/3`](https://hexdocs.pm/elixir/Map.html#replace!/3). [reverse(arg1)](#reverse/1) See [`REnum.reverse/1`](REnum.html#reverse/1). [reverse(arg1, arg2)](#reverse/2) See [`REnum.reverse/2`](REnum.html#reverse/2). [reverse_each(arg1, arg2)](#reverse_each/2) See [`REnum.reverse_each/2`](REnum.html#reverse_each/2). [reverse_slice(arg1, arg2, arg3)](#reverse_slice/3) See [`REnum.reverse_slice/3`](REnum.html#reverse_slice/3). [scan(arg1, arg2)](#scan/2) See [`REnum.scan/2`](REnum.html#scan/2). [scan(arg1, arg2, arg3)](#scan/3) See [`REnum.scan/3`](REnum.html#scan/3). [select(arg1, arg2)](#select/2) See [`RMap.Ruby.select/2`](RMap.Ruby.html#select/2). [shift(arg1)](#shift/1) See [`RMap.Ruby.shift/1`](RMap.Ruby.html#shift/1). [shuffle(arg1)](#shuffle/1) See [`REnum.shuffle/1`](REnum.html#shuffle/1). [size(arg1)](#size/1) See [`RMap.Ruby.size/1`](RMap.Ruby.html#size/1). [slice(arg1, arg2)](#slice/2) See [`REnum.slice/2`](REnum.html#slice/2). [slice(arg1, arg2, arg3)](#slice/3) See [`REnum.slice/3`](REnum.html#slice/3). [slice_after(arg1, arg2)](#slice_after/2) See [`REnum.slice_after/2`](REnum.html#slice_after/2). [slice_before(arg1, arg2)](#slice_before/2) See [`REnum.slice_before/2`](REnum.html#slice_before/2). [slice_when(arg1, arg2)](#slice_when/2) See [`REnum.slice_when/2`](REnum.html#slice_when/2). [slide(arg1, arg2, arg3)](#slide/3) See [`REnum.slide/3`](REnum.html#slide/3). [sole(arg1)](#sole/1) See [`REnum.sole/1`](REnum.html#sole/1). [sort(arg1)](#sort/1) See [`REnum.sort/1`](REnum.html#sort/1). [sort(arg1, arg2)](#sort/2) See [`REnum.sort/2`](REnum.html#sort/2). [sort_by(arg1, arg2)](#sort_by/2) See [`REnum.sort_by/2`](REnum.html#sort_by/2). [sort_by(arg1, arg2, arg3)](#sort_by/3) See [`REnum.sort_by/3`](REnum.html#sort_by/3). [split(arg1, arg2)](#split/2) See [`Map.split/2`](https://hexdocs.pm/elixir/Map.html#split/2). [split_while(arg1, arg2)](#split_while/2) See [`REnum.split_while/2`](REnum.html#split_while/2). [split_with(arg1, arg2)](#split_with/2) See [`REnum.split_with/2`](REnum.html#split_with/2). [store(arg1, arg2, arg3)](#store/3) See [`RMap.Ruby.store/3`](RMap.Ruby.html#store/3). [stringify_keys(arg1)](#stringify_keys/1) See [`RMap.ActiveSupport.stringify_keys/1`](RMap.ActiveSupport.html#stringify_keys/1). [sum(arg1)](#sum/1) See [`REnum.sum/1`](REnum.html#sum/1). [symbolize_keys(arg1)](#symbolize_keys/1) See [`RMap.ActiveSupport.symbolize_keys/1`](RMap.ActiveSupport.html#symbolize_keys/1). [take(arg1, arg2)](#take/2) See [`Map.take/2`](https://hexdocs.pm/elixir/Map.html#take/2). [take_every(arg1, arg2)](#take_every/2) See [`REnum.take_every/2`](REnum.html#take_every/2). [take_random(arg1, arg2)](#take_random/2) See [`REnum.take_random/2`](REnum.html#take_random/2). [take_while(arg1, arg2)](#take_while/2) See [`REnum.take_while/2`](REnum.html#take_while/2). [tally(arg1)](#tally/1) See [`REnum.tally/1`](REnum.html#tally/1). [to_a(arg1)](#to_a/1) See [`REnum.to_a/1`](REnum.html#to_a/1). [to_h(arg1)](#to_h/1) See [`REnum.to_h/1`](REnum.html#to_h/1). [to_h(arg1, arg2)](#to_h/2) See [`REnum.to_h/2`](REnum.html#to_h/2). [to_hash(arg1)](#to_hash/1) See [`RMap.Ruby.to_hash/1`](RMap.Ruby.html#to_hash/1). [to_l(arg1)](#to_l/1) See [`REnum.to_l/1`](REnum.html#to_l/1). [to_list(arg1)](#to_list/1) See [`Map.to_list/1`](https://hexdocs.pm/elixir/Map.html#to_list/1). [to_s(arg1)](#to_s/1) See [`RMap.Ruby.to_s/1`](RMap.Ruby.html#to_s/1). [transform_keys(arg1, arg2)](#transform_keys/2) See [`RMap.Ruby.transform_keys/2`](RMap.Ruby.html#transform_keys/2). [transform_values(arg1, arg2)](#transform_values/2) See [`RMap.Ruby.transform_values/2`](RMap.Ruby.html#transform_values/2). [truthy_count(arg1)](#truthy_count/1) See [`REnum.truthy_count/1`](REnum.html#truthy_count/1). [truthy_count(arg1, arg2)](#truthy_count/2) See [`REnum.truthy_count/2`](REnum.html#truthy_count/2). [uniq_by(arg1, arg2)](#uniq_by/2) See [`REnum.uniq_by/2`](REnum.html#uniq_by/2). [unzip(arg1)](#unzip/1) See [`REnum.unzip/1`](REnum.html#unzip/1). [update(arg1, arg2, arg3, arg4)](#update/4) See [`Map.update/4`](https://hexdocs.pm/elixir/Map.html#update/4). [update!(arg1, arg2, arg3)](#update!/3) See [`Map.update!/3`](https://hexdocs.pm/elixir/Map.html#update!/3). [value?(arg1, arg2)](#value?/2) See [`RMap.Ruby.value?/2`](RMap.Ruby.html#value?/2). [values(arg1)](#values/1) See [`Map.values/1`](https://hexdocs.pm/elixir/Map.html#values/1). [values_at(arg1, arg2)](#values_at/2) See [`RMap.Ruby.values_at/2`](RMap.Ruby.html#values_at/2). [with_index(arg1)](#with_index/1) See [`REnum.with_index/1`](REnum.html#with_index/1). [with_index(arg1, arg2)](#with_index/2) See [`REnum.with_index/2`](REnum.html#with_index/2). [without(arg1, arg2)](#without/2) See [`REnum.without/2`](REnum.html#without/2). [zip(arg1)](#zip/1) See [`REnum.zip/1`](REnum.html#zip/1). [zip(arg1, arg2)](#zip/2) See [`REnum.zip/2`](REnum.html#zip/2). [zip_reduce(arg1, arg2, arg3)](#zip_reduce/3) See [`REnum.zip_reduce/3`](REnum.html#zip_reduce/3). [zip_reduce(arg1, arg2, arg3, arg4)](#zip_reduce/4) See [`REnum.zip_reduce/4`](REnum.html#zip_reduce/4). [zip_with(arg1, arg2)](#zip_with/2) See [`REnum.zip_with/2`](REnum.html#zip_with/2). [zip_with(arg1, arg2, arg3)](#zip_with/3) See [`REnum.zip_with/3`](REnum.html#zip_with/3). [Link to this section](#functions) Functions === RMap.ActiveSupport === Summarized all of Hash functions in Rails.ActiveSupport. If a function with the same name already exists in Elixir, that is not implemented. Defines all of here functions when `use RMap.ActiveSupport`. [Link to this section](#summary) Summary === [Functions](#functions) --- [assert_valid_keys(map, keys)](#assert_valid_keys/2) Validates all keys in a map match given keys, raising ArgumentError on a mismatch. [atomize_keys(map)](#atomize_keys/1) See [`RMap.ActiveSupport.symbolize_keys/1`](#symbolize_keys/1). [deep_atomize_keys(map)](#deep_atomize_keys/1) See [`RMap.ActiveSupport.deep_symbolize_keys/1`](#deep_symbolize_keys/1). [deep_stringify_keys(map)](#deep_stringify_keys/1) Returns a list with all keys converted to strings. This includes the keys from the root map and from all nested maps and arrays. [deep_symbolize_keys(map)](#deep_symbolize_keys/1) Returns a list with all keys converted to atom. This includes the keys from the root map and from all nested maps and arrays. [deep_transform_keys(map, func)](#deep_transform_keys/2) Returns a map with all keys converted by the function. This includes the keys from the root map and from all nested maps and arrays. [deep_transform_values(map, func)](#deep_transform_values/2) Returns a map with all values converted by the function. This includes the keys from the root map and from all nested maps and arrays. [stringify_keys(map)](#stringify_keys/1) Returns a map with all keys converted to strings. [symbolize_keys(map)](#symbolize_keys/1) Returns a map with all keys converted to atom. [Link to this section](#functions) Functions === RMap.Native === A module defines all of native Map functions when `use RMap.Native`. [See also.](https://hexdocs.pm/elixir/Map.html) RMap.Ruby === Summarized all of Ruby's Hash functions. Functions corresponding to the following patterns are not implemented * When a function with the same name already exists in Elixir. * When a method name includes `!`. * <, <=, ==, >, >=, [], []=, default_* [Link to this section](#summary) Summary === [Functions](#functions) --- [assoc(map, key)](#assoc/2) Returns a 2-element tuple containing a given key and its value. [clear(_)](#clear/1) Returns %{}. [delete_if(map, func)](#delete_if/2) See [`RMap.Ruby.reject/2`](#reject/2). [dig(result, keys)](#dig/2) Returns the object in nested map that is specified by a given key and additional arguments. [each_key(map, func)](#each_key/2) Calls the function with each key; returns :ok. [each_pair(map, func)](#each_pair/2) See [`Enum.each/2`](https://hexdocs.pm/elixir/Enum.html#each/2). [each_value(map, func)](#each_value/2) Calls the function with each value; returns :ok. [eql?(map1, map2)](#eql?/2) See [`Map.equal?/2`](https://hexdocs.pm/elixir/Map.html#equal?/2). [except(map, keys)](#except/2) Returns a map excluding entries for the given keys. [fetch_values(map, keys)](#fetch_values/2) Returns a list containing the values associated with the given keys. [fetch_values(map, keys, func)](#fetch_values/3) When a function is given, calls the function with each missing key, treating the block's return value as the value for that key. [filter(map, func)](#filter/2) Returns a list whose entries are those for which the function returns a truthy value. [flatten(map)](#flatten/1) Returns a flatten list. [has_value?(map, value)](#has_value?/2) See [`RMap.Ruby.value?/2`](#value?/2). [inspect(map)](#inspect/1) See [`Kernel.inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1). [invert(map)](#invert/1) Returns a map object with the each key-value pair inverted. [keep_if(map, func)](#keep_if/2) See [`RMap.Ruby.filter/2`](#filter/2). [key(map, key, default \\ nil)](#key/3) See [`Map.get/3`](https://hexdocs.pm/elixir/Map.html#get/3). [key?(map, key)](#key?/2) See [`Map.has_key?/2`](https://hexdocs.pm/elixir/Map.html#has_key?/2). [length(map)](#length/1) See [`Enum.count/1`](https://hexdocs.pm/elixir/Enum.html#count/1). [rassoc(map, value)](#rassoc/2) Returns a 2-element tuple consisting of the key and value of the first-found entry having a given value. [reject(map, func)](#reject/2) Returns a list whose entries are all those from self for which the function returns false or nil. [select(map, func)](#select/2) See [`RMap.Ruby.filter/2`](#filter/2). [shift(map)](#shift/1) Removes the first map entry; returns a 2-element tuple. First element is {key, value}. Second element is a map without first pair. [size(map)](#size/1) See [`Enum.count/1`](https://hexdocs.pm/elixir/Enum.html#count/1). [store(map, key, value)](#store/3) See [`Map.put/3`](https://hexdocs.pm/elixir/Map.html#put/3). [to_hash(map)](#to_hash/1) Returns given map. [to_s(map)](#to_s/1) See [`Kernel.inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1). [transform_keys(map, func)](#transform_keys/2) Returns a map with modified keys. [transform_values(map, func)](#transform_values/2) Returns a map with modified values. [value?(map, value)](#value?/2) Returns true if value is a value in list, otherwise false. [values_at(map, keys)](#values_at/2) Returns a list containing values for the given keys. [Link to this section](#functions) Functions === RMap.Support === Summarized other useful functions related to Lit. Defines all of here functions when `use RMap.Support`. [Link to this section](#summary) Summary === [Functions](#functions) --- [deep_to_list(map)](#deep_to_list/1) Returns list recursively converted  from given map to list. [Link to this section](#functions) Functions === RRange === Entry point of Range extensions, and can use all of RRange.* and REnum functions. See also. * [RRange.Native](https://hexdocs.pm/r_enum/RRange.Native.html#content) * [RRange.Ruby](https://hexdocs.pm/r_enum/RRange.Ruby.html#content) * [RRange.ActiveSupport](https://hexdocs.pm/r_enum/RRange.ActiveSupport.html#content) * [REnum](https://hexdocs.pm/r_enum/REnum.html#content) [Link to this section](#summary) Summary === [Functions](#functions) --- [all?(arg1)](#all?/1) See [`REnum.all?/1`](REnum.html#all?/1). [all?(arg1, arg2)](#all?/2) See [`REnum.all?/2`](REnum.html#all?/2). [any?(arg1)](#any?/1) See [`REnum.any?/1`](REnum.html#any?/1). [any?(arg1, arg2)](#any?/2) See [`REnum.any?/2`](REnum.html#any?/2). [at(arg1, arg2)](#at/2) See [`REnum.at/2`](REnum.html#at/2). [at(arg1, arg2, arg3)](#at/3) See [`REnum.at/3`](REnum.html#at/3). [begin(arg1)](#begin/1) See [`RRange.Ruby.begin/1`](RRange.Ruby.html#begin/1). [chain(arg1)](#chain/1) See [`REnum.chain/1`](REnum.html#chain/1). [chain(arg1, arg2)](#chain/2) See [`REnum.chain/2`](REnum.html#chain/2). [chunk_by(arg1, arg2)](#chunk_by/2) See [`REnum.chunk_by/2`](REnum.html#chunk_by/2). [chunk_every(arg1, arg2)](#chunk_every/2) See [`REnum.chunk_every/2`](REnum.html#chunk_every/2). [chunk_every(arg1, arg2, arg3)](#chunk_every/3) See [`REnum.chunk_every/3`](REnum.html#chunk_every/3). [chunk_every(arg1, arg2, arg3, arg4)](#chunk_every/4) See [`REnum.chunk_every/4`](REnum.html#chunk_every/4). [chunk_while(arg1, arg2, arg3, arg4)](#chunk_while/4) See [`REnum.chunk_while/4`](REnum.html#chunk_while/4). [collect(arg1, arg2)](#collect/2) See [`REnum.collect/2`](REnum.html#collect/2). [collect_concat(arg1, arg2)](#collect_concat/2) See [`REnum.collect_concat/2`](REnum.html#collect_concat/2). [compact(arg1)](#compact/1) See [`REnum.compact/1`](REnum.html#compact/1). [compact_blank(arg1)](#compact_blank/1) See [`REnum.compact_blank/1`](REnum.html#compact_blank/1). [concat(arg1)](#concat/1) See [`REnum.concat/1`](REnum.html#concat/1). [concat(arg1, arg2)](#concat/2) See [`REnum.concat/2`](REnum.html#concat/2). [count(arg1)](#count/1) See [`REnum.count/1`](REnum.html#count/1). [count(arg1, arg2)](#count/2) See [`REnum.count/2`](REnum.html#count/2). [count_until(arg1, arg2)](#count_until/2) See [`REnum.count_until/2`](REnum.html#count_until/2). [count_until(arg1, arg2, arg3)](#count_until/3) See [`REnum.count_until/3`](REnum.html#count_until/3). [cover?(arg1, arg2)](#cover?/2) See [`RRange.Ruby.cover?/2`](RRange.Ruby.html#cover?/2). [cycle(arg1, arg2, arg3)](#cycle/3) See [`REnum.cycle/3`](REnum.html#cycle/3). [dedup(arg1)](#dedup/1) See [`REnum.dedup/1`](REnum.html#dedup/1). [dedup_by(arg1, arg2)](#dedup_by/2) See [`REnum.dedup_by/2`](REnum.html#dedup_by/2). [detect(arg1, arg2)](#detect/2) See [`REnum.detect/2`](REnum.html#detect/2). [detect(arg1, arg2, arg3)](#detect/3) See [`REnum.detect/3`](REnum.html#detect/3). [disjoint?(arg1, arg2)](#disjoint?/2) See [`Range.disjoint?/2`](https://hexdocs.pm/elixir/Range.html#disjoint?/2). [drop(arg1, arg2)](#drop/2) See [`REnum.drop/2`](REnum.html#drop/2). [drop_every(arg1, arg2)](#drop_every/2) See [`REnum.drop_every/2`](REnum.html#drop_every/2). [drop_while(arg1, arg2)](#drop_while/2) See [`REnum.drop_while/2`](REnum.html#drop_while/2). [each(arg1, arg2)](#each/2) See [`REnum.each/2`](REnum.html#each/2). [each_cons(arg1, arg2, arg3)](#each_cons/3) See [`REnum.each_cons/3`](REnum.html#each_cons/3). [each_entry(arg1, arg2)](#each_entry/2) See [`REnum.each_entry/2`](REnum.html#each_entry/2). [each_slice(arg1, arg2)](#each_slice/2) See [`REnum.each_slice/2`](REnum.html#each_slice/2). [each_slice(arg1, arg2, arg3)](#each_slice/3) See [`REnum.each_slice/3`](REnum.html#each_slice/3). [each_with_index(arg1)](#each_with_index/1) See [`REnum.each_with_index/1`](REnum.html#each_with_index/1). [each_with_index(arg1, arg2)](#each_with_index/2) See [`REnum.each_with_index/2`](REnum.html#each_with_index/2). [each_with_object(arg1, arg2, arg3)](#each_with_object/3) See [`REnum.each_with_object/3`](REnum.html#each_with_object/3). [empty?(arg1)](#empty?/1) See [`REnum.empty?/1`](REnum.html#empty?/1). [end(arg1)](#end/1) See `RRange.Ruby.end/1`. [entries(arg1)](#entries/1) See [`REnum.entries/1`](REnum.html#entries/1). [eql?(arg1, arg2)](#eql?/2) See [`RRange.Ruby.eql?/2`](RRange.Ruby.html#eql?/2). [exclude?(arg1, arg2)](#exclude?/2) See [`REnum.exclude?/2`](REnum.html#exclude?/2). [excluding(arg1, arg2)](#excluding/2) See [`REnum.excluding/2`](REnum.html#excluding/2). [fetch(arg1, arg2)](#fetch/2) See [`REnum.fetch/2`](REnum.html#fetch/2). [fetch!(arg1, arg2)](#fetch!/2) See [`REnum.fetch!/2`](REnum.html#fetch!/2). [filter(arg1, arg2)](#filter/2) See [`REnum.filter/2`](REnum.html#filter/2). [find(arg1, arg2)](#find/2) See [`REnum.find/2`](REnum.html#find/2). [find(arg1, arg2, arg3)](#find/3) See [`REnum.find/3`](REnum.html#find/3). [find_all(arg1, arg2)](#find_all/2) See [`REnum.find_all/2`](REnum.html#find_all/2). [find_index(arg1, arg2)](#find_index/2) See [`REnum.find_index/2`](REnum.html#find_index/2). [find_index_with_index(arg1, arg2)](#find_index_with_index/2) See [`REnum.find_index_with_index/2`](REnum.html#find_index_with_index/2). [find_value(arg1, arg2)](#find_value/2) See [`REnum.find_value/2`](REnum.html#find_value/2). [find_value(arg1, arg2, arg3)](#find_value/3) See [`REnum.find_value/3`](REnum.html#find_value/3). [first(arg1)](#first/1) See [`REnum.first/1`](REnum.html#first/1). [first(arg1, arg2)](#first/2) See [`REnum.first/2`](REnum.html#first/2). [flat_map(arg1, arg2)](#flat_map/2) See [`REnum.flat_map/2`](REnum.html#flat_map/2). [flat_map_reduce(arg1, arg2, arg3)](#flat_map_reduce/3) See [`REnum.flat_map_reduce/3`](REnum.html#flat_map_reduce/3). [frequencies(arg1)](#frequencies/1) See [`REnum.frequencies/1`](REnum.html#frequencies/1). [frequencies_by(arg1, arg2)](#frequencies_by/2) See [`REnum.frequencies_by/2`](REnum.html#frequencies_by/2). [grep(arg1, arg2)](#grep/2) See [`REnum.grep/2`](REnum.html#grep/2). [grep(arg1, arg2, arg3)](#grep/3) See [`REnum.grep/3`](REnum.html#grep/3). [grep_v(arg1, arg2)](#grep_v/2) See [`REnum.grep_v/2`](REnum.html#grep_v/2). [grep_v(arg1, arg2, arg3)](#grep_v/3) See [`REnum.grep_v/3`](REnum.html#grep_v/3). [group_by(arg1, arg2)](#group_by/2) See [`REnum.group_by/2`](REnum.html#group_by/2). [group_by(arg1, arg2, arg3)](#group_by/3) See [`REnum.group_by/3`](REnum.html#group_by/3). [in_order_of(arg1, arg2, arg3)](#in_order_of/3) See [`REnum.in_order_of/3`](REnum.html#in_order_of/3). [include?(arg1, arg2)](#include?/2) See [`REnum.include?/2`](REnum.html#include?/2). [including(arg1, arg2)](#including/2) See [`REnum.including/2`](REnum.html#including/2). [index_by(arg1, arg2)](#index_by/2) See [`REnum.index_by/2`](REnum.html#index_by/2). [index_with(arg1, arg2)](#index_with/2) See [`REnum.index_with/2`](REnum.html#index_with/2). [inject(arg1, arg2)](#inject/2) See [`REnum.inject/2`](REnum.html#inject/2). [inject(arg1, arg2, arg3)](#inject/3) See [`REnum.inject/3`](REnum.html#inject/3). [inspect(arg1)](#inspect/1) See [`RRange.Ruby.inspect/1`](RRange.Ruby.html#inspect/1). [intersperse(arg1, arg2)](#intersperse/2) See [`REnum.intersperse/2`](REnum.html#intersperse/2). [into(arg1, arg2)](#into/2) See [`REnum.into/2`](REnum.html#into/2). [into(arg1, arg2, arg3)](#into/3) See [`REnum.into/3`](REnum.html#into/3). [join(arg1)](#join/1) See [`REnum.join/1`](REnum.html#join/1). [join(arg1, arg2)](#join/2) See [`REnum.join/2`](REnum.html#join/2). [last(arg1)](#last/1) See [`RRange.Ruby.last/1`](RRange.Ruby.html#last/1). [lazy(arg1)](#lazy/1) See [`REnum.lazy/1`](REnum.html#lazy/1). [list_and_not_keyword?(arg1)](#list_and_not_keyword?/1) See [`REnum.list_and_not_keyword?/1`](REnum.html#list_and_not_keyword?/1). [many?(arg1)](#many?/1) See [`REnum.many?/1`](REnum.html#many?/1). [many?(arg1, arg2)](#many?/2) See [`REnum.many?/2`](REnum.html#many?/2). [map(arg1, arg2)](#map/2) See [`REnum.map/2`](REnum.html#map/2). [map_and_not_range?(arg1)](#map_and_not_range?/1) See [`REnum.map_and_not_range?/1`](REnum.html#map_and_not_range?/1). [map_every(arg1, arg2, arg3)](#map_every/3) See [`REnum.map_every/3`](REnum.html#map_every/3). [map_intersperse(arg1, arg2, arg3)](#map_intersperse/3) See [`REnum.map_intersperse/3`](REnum.html#map_intersperse/3). [map_join(arg1, arg2)](#map_join/2) See [`REnum.map_join/2`](REnum.html#map_join/2). [map_join(arg1, arg2, arg3)](#map_join/3) See [`REnum.map_join/3`](REnum.html#map_join/3). [map_reduce(arg1, arg2, arg3)](#map_reduce/3) See [`REnum.map_reduce/3`](REnum.html#map_reduce/3). [match_function(arg1)](#match_function/1) See [`REnum.match_function/1`](REnum.html#match_function/1). [max(arg1)](#max/1) See [`REnum.max/1`](REnum.html#max/1). [max(arg1, arg2)](#max/2) See [`REnum.max/2`](REnum.html#max/2). [max(arg1, arg2, arg3)](#max/3) See [`REnum.max/3`](REnum.html#max/3). [max_by(arg1, arg2)](#max_by/2) See [`REnum.max_by/2`](REnum.html#max_by/2). [max_by(arg1, arg2, arg3)](#max_by/3) See [`REnum.max_by/3`](REnum.html#max_by/3). [max_by(arg1, arg2, arg3, arg4)](#max_by/4) See [`REnum.max_by/4`](REnum.html#max_by/4). [maximum(arg1, arg2)](#maximum/2) See [`REnum.maximum/2`](REnum.html#maximum/2). [member?(arg1, arg2)](#member?/2) See [`REnum.member?/2`](REnum.html#member?/2). [min(arg1)](#min/1) See [`REnum.min/1`](REnum.html#min/1). [min(arg1, arg2)](#min/2) See [`REnum.min/2`](REnum.html#min/2). [min(arg1, arg2, arg3)](#min/3) See [`REnum.min/3`](REnum.html#min/3). [min_by(arg1, arg2)](#min_by/2) See [`REnum.min_by/2`](REnum.html#min_by/2). [min_by(arg1, arg2, arg3)](#min_by/3) See [`REnum.min_by/3`](REnum.html#min_by/3). [min_by(arg1, arg2, arg3, arg4)](#min_by/4) See [`REnum.min_by/4`](REnum.html#min_by/4). [min_max(arg1)](#min_max/1) See [`REnum.min_max/1`](REnum.html#min_max/1). [min_max(arg1, arg2)](#min_max/2) See [`REnum.min_max/2`](REnum.html#min_max/2). [min_max_by(arg1, arg2)](#min_max_by/2) See [`REnum.min_max_by/2`](REnum.html#min_max_by/2). [min_max_by(arg1, arg2, arg3)](#min_max_by/3) See [`REnum.min_max_by/3`](REnum.html#min_max_by/3). [min_max_by(arg1, arg2, arg3, arg4)](#min_max_by/4) See [`REnum.min_max_by/4`](REnum.html#min_max_by/4). [minimum(arg1, arg2)](#minimum/2) See [`REnum.minimum/2`](REnum.html#minimum/2). [minmax(arg1)](#minmax/1) See [`REnum.minmax/1`](REnum.html#minmax/1). [minmax(arg1, arg2)](#minmax/2) See [`REnum.minmax/2`](REnum.html#minmax/2). [minmax_by(arg1, arg2)](#minmax_by/2) See [`REnum.minmax_by/2`](REnum.html#minmax_by/2). [minmax_by(arg1, arg2, arg3)](#minmax_by/3) See [`REnum.minmax_by/3`](REnum.html#minmax_by/3). [minmax_by(arg1, arg2, arg3, arg4)](#minmax_by/4) See [`REnum.minmax_by/4`](REnum.html#minmax_by/4). [new(arg1, arg2)](#new/2) See [`Range.new/2`](https://hexdocs.pm/elixir/Range.html#new/2). [new(arg1, arg2, arg3)](#new/3) See [`Range.new/3`](https://hexdocs.pm/elixir/Range.html#new/3). [none?(arg1)](#none?/1) See [`REnum.none?/1`](REnum.html#none?/1). [none?(arg1, arg2)](#none?/2) See [`REnum.none?/2`](REnum.html#none?/2). [one?(arg1)](#one?/1) See [`REnum.one?/1`](REnum.html#one?/1). [one?(arg1, arg2)](#one?/2) See [`REnum.one?/2`](REnum.html#one?/2). [overlaps?(arg1, arg2)](#overlaps?/2) See [`RRange.ActiveSupport.overlaps?/2`](RRange.ActiveSupport.html#overlaps?/2). [pick(arg1, arg2)](#pick/2) See [`REnum.pick/2`](REnum.html#pick/2). [pluck(arg1, arg2)](#pluck/2) See [`REnum.pluck/2`](REnum.html#pluck/2). [product(arg1)](#product/1) See [`REnum.product/1`](REnum.html#product/1). [random(arg1)](#random/1) See [`REnum.random/1`](REnum.html#random/1). [reduce(arg1, arg2)](#reduce/2) See [`REnum.reduce/2`](REnum.html#reduce/2). [reduce(arg1, arg2, arg3)](#reduce/3) See [`REnum.reduce/3`](REnum.html#reduce/3). [reduce_while(arg1, arg2, arg3)](#reduce_while/3) See [`REnum.reduce_while/3`](REnum.html#reduce_while/3). [reject(arg1, arg2)](#reject/2) See [`REnum.reject/2`](REnum.html#reject/2). [reverse(arg1)](#reverse/1) See [`REnum.reverse/1`](REnum.html#reverse/1). [reverse(arg1, arg2)](#reverse/2) See [`REnum.reverse/2`](REnum.html#reverse/2). [reverse_each(arg1, arg2)](#reverse_each/2) See [`REnum.reverse_each/2`](REnum.html#reverse_each/2). [reverse_slice(arg1, arg2, arg3)](#reverse_slice/3) See [`REnum.reverse_slice/3`](REnum.html#reverse_slice/3). [scan(arg1, arg2)](#scan/2) See [`REnum.scan/2`](REnum.html#scan/2). [scan(arg1, arg2, arg3)](#scan/3) See [`REnum.scan/3`](REnum.html#scan/3). [select(arg1, arg2)](#select/2) See [`REnum.select/2`](REnum.html#select/2). [shuffle(arg1)](#shuffle/1) See [`REnum.shuffle/1`](REnum.html#shuffle/1). [size(arg1)](#size/1) See [`Range.size/1`](https://hexdocs.pm/elixir/Range.html#size/1). [slice(arg1, arg2)](#slice/2) See [`REnum.slice/2`](REnum.html#slice/2). [slice(arg1, arg2, arg3)](#slice/3) See [`REnum.slice/3`](REnum.html#slice/3). [slice_after(arg1, arg2)](#slice_after/2) See [`REnum.slice_after/2`](REnum.html#slice_after/2). [slice_before(arg1, arg2)](#slice_before/2) See [`REnum.slice_before/2`](REnum.html#slice_before/2). [slice_when(arg1, arg2)](#slice_when/2) See [`REnum.slice_when/2`](REnum.html#slice_when/2). [slide(arg1, arg2, arg3)](#slide/3) See [`REnum.slide/3`](REnum.html#slide/3). [sole(arg1)](#sole/1) See [`REnum.sole/1`](REnum.html#sole/1). [sort(arg1)](#sort/1) See [`REnum.sort/1`](REnum.html#sort/1). [sort(arg1, arg2)](#sort/2) See [`REnum.sort/2`](REnum.html#sort/2). [sort_by(arg1, arg2)](#sort_by/2) See [`REnum.sort_by/2`](REnum.html#sort_by/2). [sort_by(arg1, arg2, arg3)](#sort_by/3) See [`REnum.sort_by/3`](REnum.html#sort_by/3). [split(arg1, arg2)](#split/2) See [`REnum.split/2`](REnum.html#split/2). [split_while(arg1, arg2)](#split_while/2) See [`REnum.split_while/2`](REnum.html#split_while/2). [split_with(arg1, arg2)](#split_with/2) See [`REnum.split_with/2`](REnum.html#split_with/2). [step(arg1, arg2)](#step/2) See [`RRange.Ruby.step/2`](RRange.Ruby.html#step/2). [step(arg1, arg2, arg3)](#step/3) See [`RRange.Ruby.step/3`](RRange.Ruby.html#step/3). [sum(arg1)](#sum/1) See [`REnum.sum/1`](REnum.html#sum/1). [take(arg1, arg2)](#take/2) See [`REnum.take/2`](REnum.html#take/2). [take_every(arg1, arg2)](#take_every/2) See [`REnum.take_every/2`](REnum.html#take_every/2). [take_random(arg1, arg2)](#take_random/2) See [`REnum.take_random/2`](REnum.html#take_random/2). [take_while(arg1, arg2)](#take_while/2) See [`REnum.take_while/2`](REnum.html#take_while/2). [tally(arg1)](#tally/1) See [`REnum.tally/1`](REnum.html#tally/1). [to_a(arg1)](#to_a/1) See [`REnum.to_a/1`](REnum.html#to_a/1). [to_h(arg1)](#to_h/1) See [`REnum.to_h/1`](REnum.html#to_h/1). [to_h(arg1, arg2)](#to_h/2) See [`REnum.to_h/2`](REnum.html#to_h/2). [to_l(arg1)](#to_l/1) See [`REnum.to_l/1`](REnum.html#to_l/1). [to_list(arg1)](#to_list/1) See [`REnum.to_list/1`](REnum.html#to_list/1). [to_s(arg1)](#to_s/1) See [`RRange.Ruby.to_s/1`](RRange.Ruby.html#to_s/1). [truthy_count(arg1)](#truthy_count/1) See [`REnum.truthy_count/1`](REnum.html#truthy_count/1). [truthy_count(arg1, arg2)](#truthy_count/2) See [`REnum.truthy_count/2`](REnum.html#truthy_count/2). [uniq_by(arg1, arg2)](#uniq_by/2) See [`REnum.uniq_by/2`](REnum.html#uniq_by/2). [unzip(arg1)](#unzip/1) See [`REnum.unzip/1`](REnum.html#unzip/1). [with_index(arg1)](#with_index/1) See [`REnum.with_index/1`](REnum.html#with_index/1). [with_index(arg1, arg2)](#with_index/2) See [`REnum.with_index/2`](REnum.html#with_index/2). [without(arg1, arg2)](#without/2) See [`REnum.without/2`](REnum.html#without/2). [zip(arg1)](#zip/1) See [`REnum.zip/1`](REnum.html#zip/1). [zip(arg1, arg2)](#zip/2) See [`REnum.zip/2`](REnum.html#zip/2). [zip_reduce(arg1, arg2, arg3)](#zip_reduce/3) See [`REnum.zip_reduce/3`](REnum.html#zip_reduce/3). [zip_reduce(arg1, arg2, arg3, arg4)](#zip_reduce/4) See [`REnum.zip_reduce/4`](REnum.html#zip_reduce/4). [zip_with(arg1, arg2)](#zip_with/2) See [`REnum.zip_with/2`](REnum.html#zip_with/2). [zip_with(arg1, arg2, arg3)](#zip_with/3) See [`REnum.zip_with/3`](REnum.html#zip_with/3). [Link to this section](#functions) Functions === RRange.ActiveSupport === Summarized all of List functions in Rails.ActiveSupport. If a function with the same name already exists in Elixir, that is not implemented. Defines all of here functions when `use RRange.ActiveSupport`. [Link to this section](#summary) Summary === [Functions](#functions) --- [overlaps?(range1, range2)](#overlaps?/2) Compare two ranges and see if they overlap each other. [Link to this section](#functions) Functions === RRange.Native === A module defines all of native Range functions when `use RRange.Native`. [See also.](https://hexdocs.pm/elixir/Range.html) RRange.Ruby === Summarized all of Ruby's Range functions. Functions corresponding to the following patterns are not implemented * When a function with the same name already exists in Elixir. * When a method name includes `!`. * %, ==, === [Link to this section](#summary) Summary === [Functions](#functions) --- [begin(arg)](#begin/1) Returns the first element of range. [cover?(range, n)](#cover?/2) See [`Enum.member?/2`](https://hexdocs.pm/elixir/Enum.html#member?/2). [end(range)](#end/1) See [`RRange.Ruby.last/1`](#last/1). [eql?(range1, range2)](#eql?/2) Returns true if list1 == list2. [inspect(range)](#inspect/1) See [`Kernel.inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1). [last(arg)](#last/1) Returns the last element of range. [step(arg, step)](#step/2) Returns Stream that from given range split into by given step. [step(arg, step, func)](#step/3) Executes `Enum.each` to g given range split into by given step. [to_s(range)](#to_s/1) See [`Kernel.inspect/1`](https://hexdocs.pm/elixir/Kernel.html#inspect/1). [Link to this section](#functions) Functions === RRange.RubyEnd === RStream === Entry point of Stream extensions, and can use all of RStream.* and REnum functions. See also. * [RStream.Native](https://hexdocs.pm/r_enum/RStream.Native.html#content) * [REnum](https://hexdocs.pm/r_enum/REnum.html#content) [Link to this section](#summary) Summary === [Functions](#functions) --- [all?(arg1)](#all?/1) See [`REnum.all?/1`](REnum.html#all?/1). [all?(arg1, arg2)](#all?/2) See [`REnum.all?/2`](REnum.html#all?/2). [any?(arg1)](#any?/1) See [`REnum.any?/1`](REnum.html#any?/1). [any?(arg1, arg2)](#any?/2) See [`REnum.any?/2`](REnum.html#any?/2). [at(arg1, arg2)](#at/2) See [`REnum.at/2`](REnum.html#at/2). [at(arg1, arg2, arg3)](#at/3) See [`REnum.at/3`](REnum.html#at/3). [chain(arg1)](#chain/1) See [`REnum.chain/1`](REnum.html#chain/1). [chain(arg1, arg2)](#chain/2) See [`REnum.chain/2`](REnum.html#chain/2). [chunk_by(arg1, arg2)](#chunk_by/2) See [`Stream.chunk_by/2`](https://hexdocs.pm/elixir/Stream.html#chunk_by/2). [chunk_every(arg1, arg2)](#chunk_every/2) See [`Stream.chunk_every/2`](https://hexdocs.pm/elixir/Stream.html#chunk_every/2). [chunk_every(arg1, arg2, arg3)](#chunk_every/3) See [`Stream.chunk_every/3`](https://hexdocs.pm/elixir/Stream.html#chunk_every/3). [chunk_every(arg1, arg2, arg3, arg4)](#chunk_every/4) See [`Stream.chunk_every/4`](https://hexdocs.pm/elixir/Stream.html#chunk_every/4). [chunk_while(arg1, arg2, arg3, arg4)](#chunk_while/4) See [`Stream.chunk_while/4`](https://hexdocs.pm/elixir/Stream.html#chunk_while/4). [collect(arg1, arg2)](#collect/2) See [`REnum.collect/2`](REnum.html#collect/2). [collect_concat(arg1, arg2)](#collect_concat/2) See [`REnum.collect_concat/2`](REnum.html#collect_concat/2). [compact(arg1)](#compact/1) See [`REnum.compact/1`](REnum.html#compact/1). [compact_blank(arg1)](#compact_blank/1) See [`REnum.compact_blank/1`](REnum.html#compact_blank/1). [concat(arg1)](#concat/1) See [`Stream.concat/1`](https://hexdocs.pm/elixir/Stream.html#concat/1). [concat(arg1, arg2)](#concat/2) See [`Stream.concat/2`](https://hexdocs.pm/elixir/Stream.html#concat/2). [count(arg1)](#count/1) See [`REnum.count/1`](REnum.html#count/1). [count(arg1, arg2)](#count/2) See [`REnum.count/2`](REnum.html#count/2). [count_until(arg1, arg2)](#count_until/2) See [`REnum.count_until/2`](REnum.html#count_until/2). [count_until(arg1, arg2, arg3)](#count_until/3) See [`REnum.count_until/3`](REnum.html#count_until/3). [cycle(arg1)](#cycle/1) See [`Stream.cycle/1`](https://hexdocs.pm/elixir/Stream.html#cycle/1). [dedup(arg1)](#dedup/1) See [`Stream.dedup/1`](https://hexdocs.pm/elixir/Stream.html#dedup/1). [dedup_by(arg1, arg2)](#dedup_by/2) See [`Stream.dedup_by/2`](https://hexdocs.pm/elixir/Stream.html#dedup_by/2). [detect(arg1, arg2)](#detect/2) See [`REnum.detect/2`](REnum.html#detect/2). [detect(arg1, arg2, arg3)](#detect/3) See [`REnum.detect/3`](REnum.html#detect/3). [drop(arg1, arg2)](#drop/2) See [`Stream.drop/2`](https://hexdocs.pm/elixir/Stream.html#drop/2). [drop_every(arg1, arg2)](#drop_every/2) See [`Stream.drop_every/2`](https://hexdocs.pm/elixir/Stream.html#drop_every/2). [drop_while(arg1, arg2)](#drop_while/2) See [`Stream.drop_while/2`](https://hexdocs.pm/elixir/Stream.html#drop_while/2). [each(arg1, arg2)](#each/2) See [`Stream.each/2`](https://hexdocs.pm/elixir/Stream.html#each/2). [each_cons(arg1, arg2, arg3)](#each_cons/3) See [`REnum.each_cons/3`](REnum.html#each_cons/3). [each_entry(arg1, arg2)](#each_entry/2) See [`REnum.each_entry/2`](REnum.html#each_entry/2). [each_slice(arg1, arg2)](#each_slice/2) See [`REnum.each_slice/2`](REnum.html#each_slice/2). [each_slice(arg1, arg2, arg3)](#each_slice/3) See [`REnum.each_slice/3`](REnum.html#each_slice/3). [each_with_index(arg1)](#each_with_index/1) See [`REnum.each_with_index/1`](REnum.html#each_with_index/1). [each_with_index(arg1, arg2)](#each_with_index/2) See [`REnum.each_with_index/2`](REnum.html#each_with_index/2). [each_with_object(arg1, arg2, arg3)](#each_with_object/3) See [`REnum.each_with_object/3`](REnum.html#each_with_object/3). [empty?(arg1)](#empty?/1) See [`REnum.empty?/1`](REnum.html#empty?/1). [entries(arg1)](#entries/1) See [`REnum.entries/1`](REnum.html#entries/1). [exclude?(arg1, arg2)](#exclude?/2) See [`REnum.exclude?/2`](REnum.html#exclude?/2). [excluding(arg1, arg2)](#excluding/2) See [`REnum.excluding/2`](REnum.html#excluding/2). [fetch(arg1, arg2)](#fetch/2) See [`REnum.fetch/2`](REnum.html#fetch/2). [fetch!(arg1, arg2)](#fetch!/2) See [`REnum.fetch!/2`](REnum.html#fetch!/2). [filter(arg1, arg2)](#filter/2) See [`Stream.filter/2`](https://hexdocs.pm/elixir/Stream.html#filter/2). [find(arg1, arg2)](#find/2) See [`REnum.find/2`](REnum.html#find/2). [find(arg1, arg2, arg3)](#find/3) See [`REnum.find/3`](REnum.html#find/3). [find_all(arg1, arg2)](#find_all/2) See [`REnum.find_all/2`](REnum.html#find_all/2). [find_index(arg1, arg2)](#find_index/2) See [`REnum.find_index/2`](REnum.html#find_index/2). [find_index_with_index(arg1, arg2)](#find_index_with_index/2) See [`REnum.find_index_with_index/2`](REnum.html#find_index_with_index/2). [find_value(arg1, arg2)](#find_value/2) See [`REnum.find_value/2`](REnum.html#find_value/2). [find_value(arg1, arg2, arg3)](#find_value/3) See [`REnum.find_value/3`](REnum.html#find_value/3). [first(arg1)](#first/1) See [`REnum.first/1`](REnum.html#first/1). [first(arg1, arg2)](#first/2) See [`REnum.first/2`](REnum.html#first/2). [flat_map(arg1, arg2)](#flat_map/2) See [`Stream.flat_map/2`](https://hexdocs.pm/elixir/Stream.html#flat_map/2). [flat_map_reduce(arg1, arg2, arg3)](#flat_map_reduce/3) See [`REnum.flat_map_reduce/3`](REnum.html#flat_map_reduce/3). [frequencies(arg1)](#frequencies/1) See [`REnum.frequencies/1`](REnum.html#frequencies/1). [frequencies_by(arg1, arg2)](#frequencies_by/2) See [`REnum.frequencies_by/2`](REnum.html#frequencies_by/2). [grep(arg1, arg2)](#grep/2) See [`REnum.grep/2`](REnum.html#grep/2). [grep(arg1, arg2, arg3)](#grep/3) See [`REnum.grep/3`](REnum.html#grep/3). [grep_v(arg1, arg2)](#grep_v/2) See [`REnum.grep_v/2`](REnum.html#grep_v/2). [grep_v(arg1, arg2, arg3)](#grep_v/3) See [`REnum.grep_v/3`](REnum.html#grep_v/3). [group_by(arg1, arg2)](#group_by/2) See [`REnum.group_by/2`](REnum.html#group_by/2). [group_by(arg1, arg2, arg3)](#group_by/3) See [`REnum.group_by/3`](REnum.html#group_by/3). [in_order_of(arg1, arg2, arg3)](#in_order_of/3) See [`REnum.in_order_of/3`](REnum.html#in_order_of/3). [include?(arg1, arg2)](#include?/2) See [`REnum.include?/2`](REnum.html#include?/2). [including(arg1, arg2)](#including/2) See [`REnum.including/2`](REnum.html#including/2). [index_by(arg1, arg2)](#index_by/2) See [`REnum.index_by/2`](REnum.html#index_by/2). [index_with(arg1, arg2)](#index_with/2) See [`REnum.index_with/2`](REnum.html#index_with/2). [inject(arg1, arg2)](#inject/2) See [`REnum.inject/2`](REnum.html#inject/2). [inject(arg1, arg2, arg3)](#inject/3) See [`REnum.inject/3`](REnum.html#inject/3). [intersperse(arg1, arg2)](#intersperse/2) See [`Stream.intersperse/2`](https://hexdocs.pm/elixir/Stream.html#intersperse/2). [interval(arg1)](#interval/1) See [`Stream.interval/1`](https://hexdocs.pm/elixir/Stream.html#interval/1). [into(arg1, arg2)](#into/2) See [`Stream.into/2`](https://hexdocs.pm/elixir/Stream.html#into/2). [into(arg1, arg2, arg3)](#into/3) See [`Stream.into/3`](https://hexdocs.pm/elixir/Stream.html#into/3). [iterate(arg1, arg2)](#iterate/2) See [`Stream.iterate/2`](https://hexdocs.pm/elixir/Stream.html#iterate/2). [join(arg1)](#join/1) See [`REnum.join/1`](REnum.html#join/1). [join(arg1, arg2)](#join/2) See [`REnum.join/2`](REnum.html#join/2). [lazy(arg1)](#lazy/1) See [`REnum.lazy/1`](REnum.html#lazy/1). [list_and_not_keyword?(arg1)](#list_and_not_keyword?/1) See [`REnum.list_and_not_keyword?/1`](REnum.html#list_and_not_keyword?/1). [many?(arg1)](#many?/1) See [`REnum.many?/1`](REnum.html#many?/1). [many?(arg1, arg2)](#many?/2) See [`REnum.many?/2`](REnum.html#many?/2). [map(arg1, arg2)](#map/2) See [`Stream.map/2`](https://hexdocs.pm/elixir/Stream.html#map/2). [map_and_not_range?(arg1)](#map_and_not_range?/1) See [`REnum.map_and_not_range?/1`](REnum.html#map_and_not_range?/1). [map_every(arg1, arg2, arg3)](#map_every/3) See [`Stream.map_every/3`](https://hexdocs.pm/elixir/Stream.html#map_every/3). [map_intersperse(arg1, arg2, arg3)](#map_intersperse/3) See [`REnum.map_intersperse/3`](REnum.html#map_intersperse/3). [map_join(arg1, arg2)](#map_join/2) See [`REnum.map_join/2`](REnum.html#map_join/2). [map_join(arg1, arg2, arg3)](#map_join/3) See [`REnum.map_join/3`](REnum.html#map_join/3). [map_reduce(arg1, arg2, arg3)](#map_reduce/3) See [`REnum.map_reduce/3`](REnum.html#map_reduce/3). [match_function(arg1)](#match_function/1) See [`REnum.match_function/1`](REnum.html#match_function/1). [max(arg1)](#max/1) See [`REnum.max/1`](REnum.html#max/1). [max(arg1, arg2)](#max/2) See [`REnum.max/2`](REnum.html#max/2). [max(arg1, arg2, arg3)](#max/3) See [`REnum.max/3`](REnum.html#max/3). [max_by(arg1, arg2)](#max_by/2) See [`REnum.max_by/2`](REnum.html#max_by/2). [max_by(arg1, arg2, arg3)](#max_by/3) See [`REnum.max_by/3`](REnum.html#max_by/3). [max_by(arg1, arg2, arg3, arg4)](#max_by/4) See [`REnum.max_by/4`](REnum.html#max_by/4). [maximum(arg1, arg2)](#maximum/2) See [`REnum.maximum/2`](REnum.html#maximum/2). [member?(arg1, arg2)](#member?/2) See [`REnum.member?/2`](REnum.html#member?/2). [min(arg1)](#min/1) See [`REnum.min/1`](REnum.html#min/1). [min(arg1, arg2)](#min/2) See [`REnum.min/2`](REnum.html#min/2). [min(arg1, arg2, arg3)](#min/3) See [`REnum.min/3`](REnum.html#min/3). [min_by(arg1, arg2)](#min_by/2) See [`REnum.min_by/2`](REnum.html#min_by/2). [min_by(arg1, arg2, arg3)](#min_by/3) See [`REnum.min_by/3`](REnum.html#min_by/3). [min_by(arg1, arg2, arg3, arg4)](#min_by/4) See [`REnum.min_by/4`](REnum.html#min_by/4). [min_max(arg1)](#min_max/1) See [`REnum.min_max/1`](REnum.html#min_max/1). [min_max(arg1, arg2)](#min_max/2) See [`REnum.min_max/2`](REnum.html#min_max/2). [min_max_by(arg1, arg2)](#min_max_by/2) See [`REnum.min_max_by/2`](REnum.html#min_max_by/2). [min_max_by(arg1, arg2, arg3)](#min_max_by/3) See [`REnum.min_max_by/3`](REnum.html#min_max_by/3). [min_max_by(arg1, arg2, arg3, arg4)](#min_max_by/4) See [`REnum.min_max_by/4`](REnum.html#min_max_by/4). [minimum(arg1, arg2)](#minimum/2) See [`REnum.minimum/2`](REnum.html#minimum/2). [minmax(arg1)](#minmax/1) See [`REnum.minmax/1`](REnum.html#minmax/1). [minmax(arg1, arg2)](#minmax/2) See [`REnum.minmax/2`](REnum.html#minmax/2). [minmax_by(arg1, arg2)](#minmax_by/2) See [`REnum.minmax_by/2`](REnum.html#minmax_by/2). [minmax_by(arg1, arg2, arg3)](#minmax_by/3) See [`REnum.minmax_by/3`](REnum.html#minmax_by/3). [minmax_by(arg1, arg2, arg3, arg4)](#minmax_by/4) See [`REnum.minmax_by/4`](REnum.html#minmax_by/4). [none?(arg1)](#none?/1) See [`REnum.none?/1`](REnum.html#none?/1). [none?(arg1, arg2)](#none?/2) See [`REnum.none?/2`](REnum.html#none?/2). [one?(arg1)](#one?/1) See [`REnum.one?/1`](REnum.html#one?/1). [one?(arg1, arg2)](#one?/2) See [`REnum.one?/2`](REnum.html#one?/2). [pick(arg1, arg2)](#pick/2) See [`REnum.pick/2`](REnum.html#pick/2). [pluck(arg1, arg2)](#pluck/2) See [`REnum.pluck/2`](REnum.html#pluck/2). [product(arg1)](#product/1) See [`REnum.product/1`](REnum.html#product/1). [random(arg1)](#random/1) See [`REnum.random/1`](REnum.html#random/1). [range?(arg1)](#range?/1) See [`REnum.range?/1`](REnum.html#range?/1). [reduce(arg1, arg2)](#reduce/2) See [`REnum.reduce/2`](REnum.html#reduce/2). [reduce(arg1, arg2, arg3)](#reduce/3) See [`REnum.reduce/3`](REnum.html#reduce/3). [reduce_while(arg1, arg2, arg3)](#reduce_while/3) See [`REnum.reduce_while/3`](REnum.html#reduce_while/3). [reject(arg1, arg2)](#reject/2) See [`Stream.reject/2`](https://hexdocs.pm/elixir/Stream.html#reject/2). [repeatedly(arg1)](#repeatedly/1) See [`Stream.repeatedly/1`](https://hexdocs.pm/elixir/Stream.html#repeatedly/1). [resource(arg1, arg2, arg3)](#resource/3) See [`Stream.resource/3`](https://hexdocs.pm/elixir/Stream.html#resource/3). [reverse(arg1)](#reverse/1) See [`REnum.reverse/1`](REnum.html#reverse/1). [reverse(arg1, arg2)](#reverse/2) See [`REnum.reverse/2`](REnum.html#reverse/2). [reverse_each(arg1, arg2)](#reverse_each/2) See [`REnum.reverse_each/2`](REnum.html#reverse_each/2). [reverse_slice(arg1, arg2, arg3)](#reverse_slice/3) See [`REnum.reverse_slice/3`](REnum.html#reverse_slice/3). [run(arg1)](#run/1) See [`Stream.run/1`](https://hexdocs.pm/elixir/Stream.html#run/1). [scan(arg1, arg2)](#scan/2) See [`Stream.scan/2`](https://hexdocs.pm/elixir/Stream.html#scan/2). [scan(arg1, arg2, arg3)](#scan/3) See [`Stream.scan/3`](https://hexdocs.pm/elixir/Stream.html#scan/3). [select(arg1, arg2)](#select/2) See [`REnum.select/2`](REnum.html#select/2). [shuffle(arg1)](#shuffle/1) See [`REnum.shuffle/1`](REnum.html#shuffle/1). [slice(arg1, arg2)](#slice/2) See [`REnum.slice/2`](REnum.html#slice/2). [slice(arg1, arg2, arg3)](#slice/3) See [`REnum.slice/3`](REnum.html#slice/3). [slice_after(arg1, arg2)](#slice_after/2) See [`REnum.slice_after/2`](REnum.html#slice_after/2). [slice_before(arg1, arg2)](#slice_before/2) See [`REnum.slice_before/2`](REnum.html#slice_before/2). [slice_when(arg1, arg2)](#slice_when/2) See [`REnum.slice_when/2`](REnum.html#slice_when/2). [slide(arg1, arg2, arg3)](#slide/3) See [`REnum.slide/3`](REnum.html#slide/3). [sole(arg1)](#sole/1) See [`REnum.sole/1`](REnum.html#sole/1). [sort(arg1)](#sort/1) See [`REnum.sort/1`](REnum.html#sort/1). [sort(arg1, arg2)](#sort/2) See [`REnum.sort/2`](REnum.html#sort/2). [sort_by(arg1, arg2)](#sort_by/2) See [`REnum.sort_by/2`](REnum.html#sort_by/2). [sort_by(arg1, arg2, arg3)](#sort_by/3) See [`REnum.sort_by/3`](REnum.html#sort_by/3). [split(arg1, arg2)](#split/2) See [`REnum.split/2`](REnum.html#split/2). [split_while(arg1, arg2)](#split_while/2) See [`REnum.split_while/2`](REnum.html#split_while/2). [split_with(arg1, arg2)](#split_with/2) See [`REnum.split_with/2`](REnum.html#split_with/2). [sum(arg1)](#sum/1) See [`REnum.sum/1`](REnum.html#sum/1). [take(arg1, arg2)](#take/2) See [`Stream.take/2`](https://hexdocs.pm/elixir/Stream.html#take/2). [take_every(arg1, arg2)](#take_every/2) See [`Stream.take_every/2`](https://hexdocs.pm/elixir/Stream.html#take_every/2). [take_random(arg1, arg2)](#take_random/2) See [`REnum.take_random/2`](REnum.html#take_random/2). [take_while(arg1, arg2)](#take_while/2) See [`Stream.take_while/2`](https://hexdocs.pm/elixir/Stream.html#take_while/2). [tally(arg1)](#tally/1) See [`REnum.tally/1`](REnum.html#tally/1). [timer(arg1)](#timer/1) See [`Stream.timer/1`](https://hexdocs.pm/elixir/Stream.html#timer/1). [to_a(arg1)](#to_a/1) See [`REnum.to_a/1`](REnum.html#to_a/1). [to_h(arg1)](#to_h/1) See [`REnum.to_h/1`](REnum.html#to_h/1). [to_h(arg1, arg2)](#to_h/2) See [`REnum.to_h/2`](REnum.html#to_h/2). [to_l(arg1)](#to_l/1) See [`REnum.to_l/1`](REnum.html#to_l/1). [to_list(arg1)](#to_list/1) See [`REnum.to_list/1`](REnum.html#to_list/1). [transform(arg1, arg2, arg3)](#transform/3) See [`Stream.transform/3`](https://hexdocs.pm/elixir/Stream.html#transform/3). [transform(arg1, arg2, arg3, arg4)](#transform/4) See [`Stream.transform/4`](https://hexdocs.pm/elixir/Stream.html#transform/4). [truthy_count(arg1)](#truthy_count/1) See [`REnum.truthy_count/1`](REnum.html#truthy_count/1). [truthy_count(arg1, arg2)](#truthy_count/2) See [`REnum.truthy_count/2`](REnum.html#truthy_count/2). [unfold(arg1, arg2)](#unfold/2) See [`Stream.unfold/2`](https://hexdocs.pm/elixir/Stream.html#unfold/2). [uniq_by(arg1, arg2)](#uniq_by/2) See [`Stream.uniq_by/2`](https://hexdocs.pm/elixir/Stream.html#uniq_by/2). [unzip(arg1)](#unzip/1) See [`REnum.unzip/1`](REnum.html#unzip/1). [with_index(arg1)](#with_index/1) See [`Stream.with_index/1`](https://hexdocs.pm/elixir/Stream.html#with_index/1). [with_index(arg1, arg2)](#with_index/2) See [`Stream.with_index/2`](https://hexdocs.pm/elixir/Stream.html#with_index/2). [without(arg1, arg2)](#without/2) See [`REnum.without/2`](REnum.html#without/2). [zip(arg1)](#zip/1) See [`Stream.zip/1`](https://hexdocs.pm/elixir/Stream.html#zip/1). [zip(arg1, arg2)](#zip/2) See [`Stream.zip/2`](https://hexdocs.pm/elixir/Stream.html#zip/2). [zip_reduce(arg1, arg2, arg3)](#zip_reduce/3) See [`REnum.zip_reduce/3`](REnum.html#zip_reduce/3). [zip_reduce(arg1, arg2, arg3, arg4)](#zip_reduce/4) See [`REnum.zip_reduce/4`](REnum.html#zip_reduce/4). [zip_with(arg1, arg2)](#zip_with/2) See [`Stream.zip_with/2`](https://hexdocs.pm/elixir/Stream.html#zip_with/2). [zip_with(arg1, arg2, arg3)](#zip_with/3) See [`Stream.zip_with/3`](https://hexdocs.pm/elixir/Stream.html#zip_with/3). [Link to this section](#functions) Functions === RStream.ActiveSupport === Unimplemented. RStream.Native === A module defines all of native Stream functions when `use RStream.Native`. [See also.](https://hexdocs.pm/elixir/Stream.html) RStream.Ruby === Unimplemented. RUtils === Utils for REnum. [Link to this section](#summary) Summary === [Functions](#functions) --- [blank?(map)](#blank?/1) Return true if object is blank, false, empty, or a whitespace string. For example, +nil+, '', ' ', [], {}, and +false+ are all blank. [define_all_functions!(mod, undelegate_functions \\ [])](#define_all_functions!/2) Defines in the module that called all the functions of the argument module. [make_args(n)](#make_args/1) Creates tuple for `unquote_splicing`. [present?(obj)](#present?/1) Returns true if not `RUtils.blank?` [Link to this section](#functions) Functions === SoleItemExpectedError exception ===
github.com/shurcool/vfsgen
go
Go
README [¶](#section-readme) --- ### vfsgen [![Build Status](https://travis-ci.org/shurcooL/vfsgen.svg?branch=master)](https://travis-ci.org/shurcooL/vfsgen) [![GoDoc](https://godoc.org/github.com/shurcooL/vfsgen?status.svg)](https://godoc.org/github.com/shurcooL/vfsgen) Package vfsgen takes an http.FileSystem (likely at `go generate` time) and generates Go code that statically implements the provided http.FileSystem. Features: * Efficient generated code without unneccessary overhead. * Uses gzip compression internally (selectively, only for files that compress well). * Enables direct access to internal gzip compressed bytes via an optional interface. * Outputs `gofmt`ed Go code. #### Installation ``` go get -u github.com/shurcooL/vfsgen ``` #### Usage Package `vfsgen` is a Go code generator library. It has a `Generate` function that takes an input filesystem (as a [`http.FileSystem`](https://godoc.org/net/http#FileSystem) type), and generates a Go code file that statically implements the contents of the input filesystem. For example, we can use [`http.Dir`](https://godoc.org/net/http#Dir) as a `http.FileSystem` implementation that uses the contents of the `/path/to/assets` directory: ``` var fs http.FileSystem = http.Dir("/path/to/assets") ``` Now, when you execute the following code: ``` err := vfsgen.Generate(fs, vfsgen.Options{}) if err != nil { log.Fatalln(err) } ``` An assets_vfsdata.go file will be generated in the current directory: ``` // Code generated by vfsgen; DO NOT EDIT. package main import ... // assets statically implements the virtual filesystem provided to vfsgen.Generate. var assets http.FileSystem = ... ``` Then, in your program, you can use `assets` as any other [`http.FileSystem`](https://godoc.org/net/http#FileSystem), for example: ``` file, err := assets.Open("/some/file.txt") if err != nil { return err } defer file.Close() ``` ``` http.Handle("/assets/", http.FileServer(assets)) ``` `vfsgen` can be more useful when combined with build tags and go generate directives. This is described below. ##### `go generate` Usage vfsgen is great to use with go generate directives. The code invoking `vfsgen.Generate` can go in an assets_generate.go file, which can then be invoked via "//go:generate go run assets_generate.go". The input virtual filesystem can read directly from disk, or it can be more involved. By using build tags, you can create a development mode where assets are loaded directly from disk via `http.Dir`, but then statically implemented for final releases. For example, suppose your source filesystem is defined in a package with import path "example.com/project/data" as: ``` // +build dev package data import "net/http" // Assets contains project assets. var Assets http.FileSystem = http.Dir("assets") ``` When built with the "dev" build tag, accessing `data.Assets` will read from disk directly via `http.Dir`. A generate helper file assets_generate.go can be invoked via "//go:generate go run -tags=dev assets_generate.go" directive: ``` // +build ignore package main import ( "log" "example.com/project/data" "github.com/shurcooL/vfsgen" ) func main() { err := vfsgen.Generate(data.Assets, vfsgen.Options{ PackageName: "data", BuildTags: "!dev", VariableName: "Assets", }) if err != nil { log.Fatalln(err) } } ``` Note that "dev" build tag is used to access the source filesystem, and the output file will contain "!dev" build tag. That way, the statically implemented version will be used during normal builds and `go get`, when custom builds tags are not specified. ##### `vfsgendev` Usage `vfsgendev` is a binary that can be used to replace the need for the assets_generate.go file. Make sure it's installed and available in your PATH. ``` go get -u github.com/shurcooL/vfsgen/cmd/vfsgendev ``` Then the "//go:generate go run -tags=dev assets_generate.go" directive can be replaced with: ``` //go:generate vfsgendev -source="example.com/project/data".Assets ``` vfsgendev accesses the source variable using "dev" build tag, and generates an output file with "!dev" build tag. ##### Additional Embedded Information All compressed files implement [`httpgzip.GzipByter` interface](https://godoc.org/github.com/shurcooL/httpgzip#GzipByter) for efficient direct access to the internal compressed bytes: ``` // GzipByter is implemented by compressed files for // efficient direct access to the internal compressed bytes. type GzipByter interface { // GzipBytes returns gzip compressed contents of the file. GzipBytes() []byte } ``` Files that have been determined to not be worth gzip compressing (their compressed size is larger than original) implement [`httpgzip.NotWorthGzipCompressing` interface](https://godoc.org/github.com/shurcooL/httpgzip#NotWorthGzipCompressing): ``` // NotWorthGzipCompressing is implemented by files that were determined // not to be worth gzip compressing (the file size did not decrease as a result). type NotWorthGzipCompressing interface { // NotWorthGzipCompressing is a noop. It's implemented in order to indicate // the file is not worth gzip compressing. NotWorthGzipCompressing() } ``` #### Comparison vfsgen aims to be conceptually simple to use. The [`http.FileSystem`](https://godoc.org/net/http#FileSystem) abstraction is central to vfsgen. It's used as both input for code generation, and as output in the generated code. That enables great flexibility through orthogonality, since helpers and wrappers can operate on `http.FileSystem` without knowing about vfsgen. If you want, you can perform pre-processing, minifying assets, merging folders, filtering out files and otherwise modifying input via generic `http.FileSystem` middleware. It avoids unneccessary overhead by merging what was previously done with two distinct packages into a single package. It strives to be the best in its class in terms of code quality and efficiency of generated code. However, if your use goals are different, there are other similar packages that may fit your needs better. ##### Alternatives * [`go-bindata`](https://github.com/jteeuwen/go-bindata) - Reads from disk, generates Go code that provides access to data via a [custom API](https://github.com/jteeuwen/go-bindata#accessing-an-asset). * [`go-bindata-assetfs`](https://github.com/elazarl/go-bindata-assetfs) - Takes output of go-bindata and provides a wrapper that implements `http.FileSystem` interface (the same as what vfsgen outputs directly). * [`becky`](https://github.com/tv42/becky) - Embeds assets as string literals in Go source. * [`statik`](https://github.com/rakyll/statik) - Embeds a directory of static files to be accessed via `http.FileSystem` interface (sounds very similar to vfsgen); implementation sourced from [camlistore](https://camlistore.org). * [`go.rice`](https://github.com/GeertJohan/go.rice) - Makes working with resources such as HTML, JS, CSS, images and templates very easy. * [`esc`](https://github.com/mjibson/esc) - Embeds files into Go programs and provides `http.FileSystem` interfaces to them. * [`staticfiles`](https://github.com/bouk/staticfiles) - Allows you to embed a directory of files into your Go binary. * [`togo`](https://github.com/flazz/togo) - Generates a Go source file with a `[]byte` var containing the given file's contents. * [`fileb0x`](https://github.com/UnnoTed/fileb0x) - Simple customizable tool to embed files in Go. * [`embedfiles`](https://github.com/leighmcculloch/embedfiles) - Simple tool for embedding files in Go code as a map. * [`packr`](https://github.com/gobuffalo/packr) - Simple solution for bundling static assets inside of Go binaries. * [`rsrc`](https://github.com/akavel/rsrc) - Tool for embedding .ico & manifest resources in Go programs for Windows. #### Attribution This package was originally based on the excellent work by [@jteeuwen](https://github.com/jteeuwen) on [`go-bindata`](https://github.com/jteeuwen/go-bindata) and [@elazarl](https://github.com/elazarl) on [`go-bindata-assetfs`](https://github.com/elazarl/go-bindata-assetfs). #### License * [MIT License](https://github.com/shurcool/vfsgen/blob/0d455de96546/LICENSE) Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package vfsgen takes an http.FileSystem (likely at `go generate` time) and generates Go code that statically implements the provided http.FileSystem. Features: - Efficient generated code without unneccessary overhead. - Uses gzip compression internally (selectively, only for files that compress well). - Enables direct access to internal gzip compressed bytes via an optional interface. - Outputs `gofmt`ed Go code. Example [¶](#example-package) This code will generate an assets_vfsdata.go file with `var assets http.FileSystem = ...` that statically implements the contents of "assets" directory. vfsgen is great to use with go generate directives. This code can go in an assets_gen.go file, which can then be invoked via "//go:generate go run assets_gen.go". The input virtual filesystem can read directly from disk, or it can be more involved. ``` package main import ( "log" "net/http" "github.com/shurcooL/vfsgen" ) func main() { var fs http.FileSystem = http.Dir("assets") err := vfsgen.Generate(fs, vfsgen.Options{}) if err != nil { log.Fatalln(err) } } ``` ``` Output: ``` Share Format Run ### Index [¶](#pkg-index) * [func Generate(input http.FileSystem, opt Options) error](#Generate) * [type Options](#Options) #### Examples [¶](#pkg-examples) * [Package](#example-package) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) #### func [Generate](https://github.com/shurcool/vfsgen/blob/0d455de96546/generator.go#L22) [¶](#Generate) ``` func Generate(input [http](/net/http).[FileSystem](/net/http#FileSystem), opt [Options](#Options)) [error](/builtin#error) ``` Generate Go code that statically implements input filesystem, write the output to a file specified in opt. ### Types [¶](#pkg-types) #### type [Options](https://github.com/shurcool/vfsgen/blob/0d455de96546/options.go#L9) [¶](#Options) ``` type Options struct { // Filename of the generated Go code output (including extension). // If left empty, it defaults to "{{toLower .VariableName}}_vfsdata.go". Filename [string](/builtin#string) // PackageName is the name of the package in the generated code. // If left empty, it defaults to "main". PackageName [string](/builtin#string) // BuildTags are the optional build tags in the generated code. // The build tags syntax is specified by the go tool. BuildTags [string](/builtin#string) // VariableName is the name of the http.FileSystem variable in the generated code. // If left empty, it defaults to "assets". VariableName [string](/builtin#string) // VariableComment is the comment of the http.FileSystem variable in the generated code. // If left empty, it defaults to "{{.VariableName}} statically implements the virtual filesystem provided to vfsgen.". VariableComment [string](/builtin#string) } ``` Options for vfsgen code generation.
asynci-box
readthedoc
Python
aiotools 2.1.0.dev15+g14aa2b4 documentation [aiotools](#) --- aiotools Documentation[](#aiotools-documentation) === **aiotools** is a set of idiomatic utilities to reduce asyncio boiler-plates. Async Context Manager[](#module-aiotools.context) --- Provides an implementation of asynchronous context manager and its applications. Note The async context managers in this module are transparent aliases to `contextlib.asynccontextmanager` of the standard library in Python 3.7 and later. *class* AbstractAsyncContextManager[[source]](_modules/contextlib.html#AbstractAsyncContextManager)[](#aiotools.context.AbstractAsyncContextManager) An abstract base class for asynchronous context managers. AsyncContextManager[](#aiotools.context.AsyncContextManager) alias of `contextlib._AsyncGeneratorContextManager` async_ctx_manager(*func*)[](#aiotools.context.async_ctx_manager) A helper function to ease use of `AsyncContextManager`. actxmgr(*func*)[](#aiotools.context.actxmgr) An alias of [`async_ctx_manager()`](#aiotools.context.async_ctx_manager). *class* aclosing(*thing*)[[source]](_modules/contextlib.html#aclosing)[](#aiotools.context.aclosing) Async context manager for safely finalizing an asynchronously cleaned-up resource such as an async generator, calling its `aclose()` method. Code like this: > async with aclosing(<module>.fetch(<arguments>)) as agen:<block> is equivalent to this: > agen = <module>.fetch(<arguments>) > try: > > > <block> > > > > finally:await agen.aclose() *class* closing_async(*thing: aiotools.context.T_AsyncClosable*)[[source]](_modules/aiotools/context.html#closing_async)[](#aiotools.context.closing_async) An analogy to [`contextlib.closing()`](https://docs.python.org/3/library/contextlib.html#contextlib.closing) for objects defining the `close()` method as an async function. New in version 1.5.6. *class* AsyncContextGroup(*context_managers: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional)[[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable)[[contextlib.AbstractAsyncContextManager](index.html#aiotools.context.AbstractAsyncContextManager)]] = None*)[[source]](_modules/aiotools/context.html#AsyncContextGroup)[](#aiotools.context.AsyncContextGroup) Merges a group of context managers into a single context manager. Internally it uses [`asyncio.gather()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) to execute them with overlapping, to reduce the execution time via asynchrony. Upon entering, you can get values produced by the entering steps from the passed context managers (those `yield`-ed) using an `as` clause of the `async with` statement. After exits, you can check if the context managers have finished successfully by ensuring that the return values of `exit_states()` method are `None`. Note You cannot return values in context managers because they are generators. If an exception is raised before the `yield` statement of an async context manager, it is stored at the corresponding manager index in the as-clause variable. Similarly, if an exception is raised after the `yield` statement of an async context manager, it is stored at the corresponding manager index in the `exit_states()` return value. Any exceptions in a specific context manager does not interrupt others; this semantic is same to `asyncio.gather()`’s when `return_exceptions=True`. This means that, it is user’s responsibility to check if the returned context values are exceptions or the intended ones inside the context body after entering. Parameters **context_managers** – An iterable of async context managers. If this is `None`, you may add async context managers one by one using the [`add()`](#aiotools.context.AsyncContextGroup.add) method. Example: ``` @aiotools.actxmgr async def ctx(v): yield v + 10 g = aiotools.actxgroup([ctx(1), ctx(2)]) async with g as values: assert values[0] == 11 assert values[1] == 12 rets = g.exit_states() assert rets[0] is None # successful shutdown assert rets[1] is None ``` add(*cm*)[[source]](_modules/aiotools/context.html#AsyncContextGroup.add)[](#aiotools.context.AsyncContextGroup.add) TODO: fill description exit_states()[[source]](_modules/aiotools/context.html#AsyncContextGroup.exit_states)[](#aiotools.context.AsyncContextGroup.exit_states) TODO: fill description *class* actxgroup[](#aiotools.context.actxgroup) An alias of [`AsyncContextGroup`](#aiotools.context.AsyncContextGroup). Async Deferred Function Tools[](#module-aiotools.defer) --- Provides a Golang-like `defer()` API using decorators, which allows grouping resource initialization and cleanup in one place without extra indentations. Example: ``` async def init(x): ... async def cleanup(x): ... @aiotools.adefer async def do(defer): # <-- be aware of defer argument! x = SomeResource() await init(x) defer(cleanup(x)) ... ... ``` This is equivalent to: ``` async def do(): x = SomeResource() await init(x) try: ... ... finally: await cleanup(x) ``` Note that [`aiotools.context.AsyncContextGroup`](index.html#aiotools.context.AsyncContextGroup) or [`contextlib.AsyncExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.AsyncExitStack) serves well for the same purpose, but for simple cleanups, this defer API makes your codes simple because it steps aside the main execution context without extra indentations. Warning Any exception in the deferred functions is raised transparently, and may block execution of the remaining deferred functions. This behavior may be changed in the future versions, though. defer(*func*)[[source]](_modules/aiotools/defer.html#defer)[](#aiotools.defer.defer) A synchronous version of the defer API. It can only defer normal functions. adefer(*func*)[[source]](_modules/aiotools/defer.html#adefer)[](#aiotools.defer.adefer) An asynchronous version of the defer API. It can defer coroutine functions, coroutines, and normal functions. Async Fork[](#module-aiotools.fork) --- This module implements a simple [`os.fork()`](https://docs.python.org/3/library/os.html#os.fork)-like interface, but in an asynchronous way with full support for PID file descriptors on Python 3.9 or higher and the Linux kernel 5.4 or higher. It internally synchronizes the beginning and readiness status of child processes so that the users may assume that the child process is completely interruptible after [`afork()`](#aiotools.fork.afork) returns. *class* AbstractChildProcess[[source]](_modules/aiotools/fork.html#AbstractChildProcess)[](#aiotools.fork.AbstractChildProcess) The abstract interface to control and monitor a forked child process. *abstract* send_signal(*signum: [int](https://docs.python.org/3/library/functions.html#int)*) → [None](https://docs.python.org/3/library/constants.html#None)[[source]](_modules/aiotools/fork.html#AbstractChildProcess.send_signal)[](#aiotools.fork.AbstractChildProcess.send_signal) Send a UNIX signal to the child process. If the child process is already terminated, it will log a warning message and return. *abstract async* wait() → [int](https://docs.python.org/3/library/functions.html#int)[[source]](_modules/aiotools/fork.html#AbstractChildProcess.wait)[](#aiotools.fork.AbstractChildProcess.wait) Wait until the child process terminates or reclaim the child process’ exit code if already terminated. If there are other coroutines that has waited the same process, it may return 255 and log a warning message. PosixChildProcess(*pid: [int](https://docs.python.org/3/library/functions.html#int)*) → [None](https://docs.python.org/3/library/constants.html#None)[[source]](_modules/aiotools/fork.html#PosixChildProcess)[](#aiotools.fork.PosixChildProcess) A POSIX-compatible version of [`AbstractChildProcess`](#aiotools.fork.AbstractChildProcess). PidfdChildProcess(*pid: [int](https://docs.python.org/3/library/functions.html#int)*, *pidfd: [int](https://docs.python.org/3/library/functions.html#int)*) → [None](https://docs.python.org/3/library/constants.html#None)[[source]](_modules/aiotools/fork.html#PidfdChildProcess)[](#aiotools.fork.PidfdChildProcess) A PID file descriptor-based version of [`AbstractChildProcess`](#aiotools.fork.AbstractChildProcess). *async* afork(*child_func: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable)[[], [int](https://docs.python.org/3/library/functions.html#int)]*) → [aiotools.fork.AbstractChildProcess](index.html#aiotools.fork.AbstractChildProcess)[[source]](_modules/aiotools/fork.html#afork)[](#aiotools.fork.afork) Fork the current process and execute the given function in the child. The return value of the function will become the exit code of the child process. Parameters **child_func** – A function that represents the main function of the child and returns an integer as its exit code. Note that the function must set up a new event loop if it wants to run asyncio codes. Async Function Tools[](#module-aiotools.func) --- apartial(*coro*, **args*, ***kwargs*)[[source]](_modules/aiotools/func.html#apartial)[](#aiotools.func.apartial) Wraps a coroutine function with pre-defined arguments (including keyword arguments). It is an asynchronous version of [`functools.partial()`](https://docs.python.org/3/library/functools.html#functools.partial). lru_cache(*maxsize: [int](https://docs.python.org/3/library/functions.html#int) = 128*, *typed: [bool](https://docs.python.org/3/library/functions.html#bool) = False*, *expire_after: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional)[[float](https://docs.python.org/3/library/functions.html#float)] = None*)[[source]](_modules/aiotools/func.html#lru_cache)[](#aiotools.func.lru_cache) A simple LRU cache just like [`functools.lru_cache()`](https://docs.python.org/3/library/functools.html#functools.lru_cache), but it works for coroutines. This is not as heavily optimized as [`functools.lru_cache()`](https://docs.python.org/3/library/functools.html#functools.lru_cache) which uses an internal C implementation, as it targets async operations that take a long time. It follows the same API that the standard functools provides. The wrapped function has `cache_clear()` method to flush the cache manually, but leaves `cache_info()` for statistics unimplemented. Note that calling the coroutine multiple times with the same arguments before the first call returns may incur duplicate executions. This function is not thread-safe. Parameters * **maxsize** – The maximum number of cached entries. * **typed** – Cache keys in different types separately (e.g., `3` and `3.0` will be different keys). * **expire_after** – Re-calculate the value if the configured time has passed even when the cache is hit. When re-calculation happens the expiration timer is also reset. Async Itertools[](#module-aiotools.iter) --- *async* aiter(*obj*, *sentinel=<object object>*)[[source]](_modules/aiotools/iter.html#aiter)[](#aiotools.iter.aiter) Analogous to the builtin [`iter()`](https://docs.python.org/3/library/functions.html#iter). Multi-process Server[](#module-aiotools.server) --- Based on [Async Context Manager](index.html#document-aiotools.context), this module provides an automated lifecycle management for multi-process servers with explicit initialization steps and graceful shutdown steps. server(*func*)[](#aiotools.server.server) A decorator wrapper for [`AsyncServerContextManager`](#aiotools.server.AsyncServerContextManager). Usage example: ``` @aiotools.server async def myserver(loop, pidx, args): await do_init(args) stop_sig = yield if stop_sig == signal.SIGINT: await do_graceful_shutdown() else: await do_forced_shutdown() aiotools.start_server(myserver, ...) ``` *class* AsyncServerContextManager(*func: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable)[[...], [Any](https://docs.python.org/3/library/typing.html#typing.Any)]*, *args*, *kwargs*)[[source]](_modules/aiotools/server.html#AsyncServerContextManager)[](#aiotools.server.AsyncServerContextManager) A modified version of [`contextlib.asynccontextmanager()`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager). The implementation detail is mostly taken from the `contextlib` standard library, with a minor change to inject `self.yield_return` into the wrapped async generator. yield_return*: Optional[[signal.Signals](https://docs.python.org/3/library/signal.html#signal.Signals)]*[](#aiotools.server.AsyncServerContextManager.yield_return) *exception* InterruptedBySignal[[source]](_modules/aiotools/server.html#InterruptedBySignal)[](#aiotools.server.InterruptedBySignal) A new [`BaseException`](https://docs.python.org/3/library/exceptions.html#BaseException) that represents interruption by an arbitrary UNIX signal. Since this is a [`BaseException`](https://docs.python.org/3/library/exceptions.html#BaseException) instead of [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception), it behaves like [`KeyboardInterrupt`](https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt) and [`SystemExit`](https://docs.python.org/3/library/exceptions.html#SystemExit) exceptions (i.e., bypassing except clauses catching the [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) type only) The first argument of this exception is the signal number received. *class* ServerMainContextManager(*func*, *args*, *kwargs*)[[source]](_modules/aiotools/server.html#ServerMainContextManager)[](#aiotools.server.ServerMainContextManager) A modified version of [`contextlib.contextmanager()`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager). The implementation detail is mostly taken from the `contextlib` standard library, with a minor change to inject `self.yield_return` into the wrapped generator. yield_return*: Optional[[signal.Signals](https://docs.python.org/3/library/signal.html#signal.Signals)]*[](#aiotools.server.ServerMainContextManager.yield_return) main(*func*)[](#aiotools.server.main) A decorator wrapper for [`ServerMainContextManager`](#aiotools.server.ServerMainContextManager) Usage example: ``` @aiotools.main def mymain(): server_args = do_init() stop_sig = yield server_args if stop_sig == signal.SIGINT: do_graceful_shutdown() else: do_forced_shutdown() aiotools.start_server(..., main_ctxmgr=mymain, ...) ``` start_server(*worker_actxmgr: typing.Callable[[asyncio.events.AbstractEventLoop, int, typing.Sequence[typing.Any]], aiotools.server.AsyncServerContextManager], main_ctxmgr: typing.Optional[typing.Callable[[], aiotools.server.ServerMainContextManager]] = None, extra_procs: typing.Iterable[typing.Callable] = (), stop_signals: typing.Iterable[signal.Signals] = (<Signals.SIGINT: 2>, <Signals.SIGTERM: 15>), num_workers: int = 1, args: typing.Iterable[typing.Any] = (), wait_timeout: typing.Optional[float] = None*) → [None](https://docs.python.org/3/library/constants.html#None)[[source]](_modules/aiotools/server.html#start_server)[](#aiotools.server.start_server) Starts a multi-process server where each process has their own individual asyncio event loop. Their lifecycles are automantically managed – if the main program receives one of the signals specified in `stop_signals` it will initiate the shutdown routines on each worker that stops the event loop gracefully. Parameters * **worker_actxmgr** – An asynchronous context manager that dicates the initialization and shutdown steps of each worker. It should accept the following three arguments: + **loop**: the asyncio event loop created and set by aiotools + **pidx**: the 0-based index of the worker (use this for per-worker logging) + **args**: a concatenated tuple of values yielded by **main_ctxmgr** and the user-defined arguments in **args**. aiotools automatically installs an interruption handler that calls `loop.stop()` to the given event loop, regardless of using either threading or multiprocessing. * **main_ctxmgr** – An optional context manager that performs global initialization and shutdown steps of the whole program. It may yield one or more values to be passed to worker processes along with **args** passed to this function. There is no arguments passed to those functions since you can directly access `sys.argv` to parse command line arguments and/or read user configurations. * **extra_procs** – An iterable of functions that consist of extra processes whose lifecycles are synchronized with other workers. They should set up their own signal handlers. It should accept the following three arguments: + **intr_event**: Always `None`, kept for legacy + **pidx**: same to **worker_actxmgr** argument + **args**: same to **worker_actxmgr** argument * **stop_signals** – A list of UNIX signals that the main program to recognize as termination signals. * **num_workers** – The number of children workers. * **args** – The user-defined arguments passed to workers and extra processes. If **main_ctxmgr** yields one or more values, they are *prepended* to this user arguments when passed to workers and extra processes. * **wait_timeout** – The timeout in seconds before forcibly killing all remaining child processes after sending initial stop signals. Returns None Changed in version 0.3.2: The name of argument **num_proc** is changed to **num_workers**. Even if **num_workers** is 1, a child is created instead of doing everything at the main thread. New in version 0.3.2: The argument `extra_procs` and `main_ctxmgr`. New in version 0.4.0: Now supports use of threading instead of multiprocessing via **use_threading** option. Changed in version 0.8.0: Now **worker_actxmgr** must be an instance of [`AsyncServerContextManager`](#aiotools.server.AsyncServerContextManager) or async generators decorated by `@aiotools.server`. Now **main_ctxmgr** must be an instance of [`ServerMainContextManager`](#aiotools.server.ServerMainContextManager) or plain generators decorated by `@aiotools.main`. The usage is same to asynchronous context managers, but optionally you can distinguish the received stop signal by retrieving the return value of the `yield` statement. In **extra_procs** in non-threaded mode, stop signals are converted into either one of [`KeyboardInterrupt`](https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt), [`SystemExit`](https://docs.python.org/3/library/exceptions.html#SystemExit), or [`InterruptedBySignal`](#aiotools.server.InterruptedBySignal) exception. New in version 0.8.4: **start_method** argument can be set to change the subprocess spawning implementation. Deprecated since version 1.2.0: The **start_method** and **use_threading** arguments, in favor of our new `afork()` function which provides better synchronization and pid-fd support. Changed in version 1.2.0: The **extra_procs** will be always separate processes since **use_threading** is deprecated and thus **intr_event** arguments are now always `None`. New in version 1.5.5: The **wait_timeout** argument. Supervisor[](#supervisor) --- This is a superseding replacement of [`PersistentTaskGroup`](index.html#PersistentTaskGroup) and recommend to use in new codes. *class* Supervisor[[source]](_modules/aiotools/supervisor.html#Supervisor)[](#aiotools.supervisor.Supervisor) Supervisor is a primitive structure to provide a long-lived context manager scope for an indefinite set of subtasks. During its lifetime, it is free to spawn new subtasks at any time. If the supervisor itself is cancelled from outside or `shutdown()` is called, it will cancel all running tasks immediately, wait for their completion, and then exit the context manager block. The main difference to [`asyncio.TaskGroup`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup) is that it keeps running sibling subtasks even when there is an unhandled exception from one of the subtasks. To prevent memory leaks, a supervisor does not store any result or exception from its subtasks. Instead, the callers must use additional task-done callbacks to process subtask results and exceptions. Supervisor provides the same analogy to Kotlin’s `SupervisorScope` and Javascript’s `Promise.allSettled()`, while [`asyncio.TaskGroup`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup) provides the same analogy to Kotlin’s `CoroutineScope` and Javascript’s `Promise.all()`. The original implementation is based on DontPanicO’s pull request (<https://github.com/achimnol/cpython/pull/31>) and [`PersistentTaskGroup`](index.html#PersistentTaskGroup), but it is modified *not* to store unhandled subtask exceptions. New in version 2.0. Task Group[](#task-group) --- current_taskgroup[](#current_taskgroup) A [`contextvars.ContextVar`](https://docs.python.org/3/library/contextvars.html#contextvars.ContextVar) that has the reference to the current innermost [`TaskGroup`](#TaskGroup) instance. Available only in Python 3.7 or later. current_ptaskgroup[](#current_ptaskgroup) A [`contextvars.ContextVar`](https://docs.python.org/3/library/contextvars.html#contextvars.ContextVar) that has the reference to the current innermost [`PersistentTaskGroup`](#PersistentTaskGroup) instance. Available only in Python 3.7 or later. Warning This is set only when [`PersistentTaskGroup`](#PersistentTaskGroup) is used with the `async with` statement. *class* TaskGroup(***, *name=None*)[](#TaskGroup) Provides a guard against a group of tasks spawend via its [`create_task()`](#TaskGroup.create_task) method instead of the vanilla fire-and-forgetting [`asyncio.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task). See the motivation and rationale in [the trio’s documentation](https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning). In Python 3.11 or later, this wraps [`asyncio.TaskGroup`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup) with a small extension to set the current taskgroup in a context variable. create_task(*coro*, ***, *name=None*)[](#TaskGroup.create_task) Spawns a new task inside the taskgroup and returns the reference to the task. Setting the name of tasks is supported in Python 3.8 or later only and ignored in older versions. get_name()[](#TaskGroup.get_name) Returns the name set when creating the instance. New in version 1.0.0. Changed in version 1.5.0: Fixed edge-case bugs by referring the Python 3.11 stdlib’s [`asyncio.TaskGroup`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup) implementation, including abrupt cancellation before all nested spawned tasks start without context switches and propagation of the source exception when the context manager (parent task) is getting cancelled but continued. All existing codes should run without any issues, but it is recommended to test thoroughly. *class* PersistentTaskGroup(***, *name=None*, *exception_handler=None*)[](#PersistentTaskGroup) Provides an abstraction of long-running task groups for server applications. The main use case is to implement a dispatcher of async event handlers, to group RPC/API request handlers, etc. with safe and graceful shutdown. Here “long-running” means that all tasks should keep going even when sibling tasks fail with unhandled errors and such errors must be reported immediately. Here “safety” means that all spawned tasks should be reclaimed before exit or shutdown. When used as an async context manager, it works similarly to [`asyncio.gather()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) with `return_exceptions=True` option. It exits the context scope when all tasks finish, just like [`asyncio.TaskGroup`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup), but it does NOT abort when there are unhandled exceptions from child tasks; just keeps sibling tasks running and reporting errors as they occur (see below). When *not* used as an async context maanger (e.g., used as attributes of long-lived objects), it persists running until [`shutdown()`](#PersistentTaskGroup.shutdown) is called explicitly. Note that it is the user’s responsibility to call [`shutdown()`](#PersistentTaskGroup.shutdown) because [`PersistentTaskGroup`](#PersistentTaskGroup) does not provide the `__del__()` method. Regardless how it is executed, it lets all spawned tasks run to their completion and calls the exception handler to report any unhandled exceptions immediately. If there are exceptions occurred again in the exception handlers, then it uses [`loop.call_exception_handler()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_exception_handler) as the last resort. *exception_handler* should be an asynchronous function that accepts the exception type, exception object, and the traceback, just like `__aexit__()` dunder method. The default handler just prints out the exception log using [`traceback.print_exc()`](https://docs.python.org/3/library/traceback.html#traceback.print_exc). Note that the handler is invoked within the exception handling context and thus [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info) is also available. Since the exception handling and reporting takes places immediately, it eliminates potential arbitrary report delay due to other tasks or the execution method. This resolves a critical debugging pain when only termination of the application displays accumulated errors, as sometimes we don’t want to terminate but just inspect what is happening. create_task(*coro*, ***, *name=None*)[](#PersistentTaskGroup.create_task) Spawns a new task inside the taskgroup and returns the reference to a [`future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future) describing the task result. Setting the name of tasks is supported in Python 3.8 or later only and ignored in older versions. You may `await` the retuned future to take the task’s return value or get notified with the exception from it, while the exception handler is still invoked. Since it is just a *secondary* future, you cannot cancel the task explicitly using it. To cancel the task(s), use [`shutdown()`](#PersistentTaskGroup.shutdown) or exit the task group context. Warning In Python 3.6, `await`-ing the returned future hangs indefinitely. We do not fix this issue because Python 3.6 is now EoL (end-of-life) as of December 2021. get_name()[](#PersistentTaskGroup.get_name) Returns the name set when creating the instance. *async* shutdown()[](#PersistentTaskGroup.shutdown) Triggers immediate shutdown of this taskgroup, cancelling all unfinished tasks and waiting for their completion. *classmethod* all_ptaskgroups()[](#PersistentTaskGroup.all_ptaskgroups) Returns a sequence of all currently existing non-exited persistent task groups. New in version 1.5.0. New in version 1.4.0. Changed in version 1.5.0: Rewrote the overall implementation referring the Python 3.11 stdlib’s [`asyncio.TaskGroup`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup) implementation and adapting it to the semantics for “persistency”. All existing codes should run without any issues, but it is recommended to test thoroughly. Changed in version 1.6.1: It no longer raises [`BaseExceptionGroup`](https://docs.python.org/3/library/exceptions.html#BaseExceptionGroup) or [`ExceptionGroup`](https://docs.python.org/3/library/exceptions.html#ExceptionGroup) upon exit or [`shutdown()`](#PersistentTaskGroup.shutdown), because it no longer stores the history of unhnadled exceptions from subtasks to prevent memory leaks for long-running persistent task groups. The users must register explicit exception handlers or task done callbacks to report or process such unhandled exceptions. *exception* TaskGroupError[](#TaskGroupError) Represents a collection of errors raised inside a task group. Callers may iterate over the errors using the `__errors__` attribute. In Python 3.11 or later, this is a mere wrapper of underlying [`BaseExceptionGroup`](https://docs.python.org/3/library/exceptions.html#BaseExceptionGroup). This allows existing user codes to run without modification while users can take advantage of the new `except*` syntax and [`ExceptionGroup`](https://docs.python.org/3/library/exceptions.html#ExceptionGroup) methods if they use Python 3.11 or later. Note that if none of the passed exceptions passed is a [`BaseException`](https://docs.python.org/3/library/exceptions.html#BaseException), it automatically becomes [`ExceptionGroup`](https://docs.python.org/3/library/exceptions.html#ExceptionGroup). Timers[](#module-aiotools.timer) --- Provides a simple implementation of timers run inside asyncio event loops. *class* TimerDelayPolicy(*value*, *names=None*, ***, *module=None*, *qualname=None*, *type=None*, *start=1*, *boundary=None*)[[source]](_modules/aiotools/timer.html#TimerDelayPolicy)[](#aiotools.timer.TimerDelayPolicy) An enumeration of supported policies for when the timer function takes longer on each tick than the given timer interval. CANCEL *= 1*[](#aiotools.timer.TimerDelayPolicy.CANCEL) DEFAULT *= 0*[](#aiotools.timer.TimerDelayPolicy.DEFAULT) *class* VirtualClock[[source]](_modules/aiotools/timer.html#VirtualClock)[](#aiotools.timer.VirtualClock) Provide a virtual clock for an asyncio event loop which makes timing-based tests deterministic and instantly completed. patch_loop()[[source]](_modules/aiotools/timer.html#VirtualClock.patch_loop)[](#aiotools.timer.VirtualClock.patch_loop) Override some methods of the current event loop so that sleep instantly returns while proceeding the virtual clock. virtual_time() → [float](https://docs.python.org/3/library/functions.html#float)[[source]](_modules/aiotools/timer.html#VirtualClock.virtual_time)[](#aiotools.timer.VirtualClock.virtual_time) Return the current virtual time. create_timer(*cb: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable)[[[float](https://docs.python.org/3/library/functions.html#float)], [Union](https://docs.python.org/3/library/typing.html#typing.Union)[[Generator](https://docs.python.org/3/library/typing.html#typing.Generator)[[Any](https://docs.python.org/3/library/typing.html#typing.Any), [None](https://docs.python.org/3/library/constants.html#None), [None](https://docs.python.org/3/library/constants.html#None)], [Coroutine](https://docs.python.org/3/library/typing.html#typing.Coroutine)[[Any](https://docs.python.org/3/library/typing.html#typing.Any), [Any](https://docs.python.org/3/library/typing.html#typing.Any), [None](https://docs.python.org/3/library/constants.html#None)]]]*, *interval: [float](https://docs.python.org/3/library/functions.html#float)*, *delay_policy: [aiotools.timer.TimerDelayPolicy](index.html#aiotools.timer.TimerDelayPolicy) = TimerDelayPolicy.DEFAULT*, *loop: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional)[asyncio.events.AbstractEventLoop] = None*) → _asyncio.Task[[source]](_modules/aiotools/timer.html#create_timer)[](#aiotools.timer.create_timer) Schedule a timer with the given callable and the interval in seconds. The interval value is also passed to the callable. If the callable takes longer than the timer interval, all accumulated callable’s tasks will be cancelled when the timer is cancelled. Parameters **cb** – TODO - fill argument descriptions Returns You can stop the timer by cancelling the returned task. High-level Coroutine Utilities[](#module-aiotools.utils) --- A set of higher-level coroutine aggregation utilities based on `Supervisor`. *async* as_completed_safe(*coros: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable)[[Awaitable](https://docs.python.org/3/library/typing.html#typing.Awaitable)[aiotools.utils.T]]*, ***, *context: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional)[_contextvars.Context] = None*) → [AsyncGenerator](https://docs.python.org/3/library/typing.html#typing.AsyncGenerator)[[Awaitable](https://docs.python.org/3/library/typing.html#typing.Awaitable)[aiotools.utils.T], [None](https://docs.python.org/3/library/constants.html#None)][[source]](_modules/aiotools/utils.html#as_completed_safe)[](#aiotools.utils.as_completed_safe) This is a safer version of [`asyncio.as_completed()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.as_completed) which uses `aiotools.Supervisor` as an underlying coroutine lifecycle keeper. This requires Python 3.11 or higher to work properly with timeouts. New in version 1.6. Changed in version 2.0: It now uses `aiotools.Supervisor` internally and handles timeouts in a bettery way. *async* gather_safe(*coros: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable)[[Awaitable](https://docs.python.org/3/library/typing.html#typing.Awaitable)[aiotools.utils.T]]*, ***, *context: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional)[_contextvars.Context] = None*) → [List](https://docs.python.org/3/library/typing.html#typing.List)[[Union](https://docs.python.org/3/library/typing.html#typing.Union)[aiotools.utils.T, [Exception](https://docs.python.org/3/library/exceptions.html#Exception)]][[source]](_modules/aiotools/utils.html#gather_safe)[](#aiotools.utils.gather_safe) A safer version of [`asyncio.gather()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather). It wraps the passed coroutines with a `Supervisor` to ensure the termination of them when returned. Additionally, it supports manually setting the context of each subtask. Note that if it is cancelled from an outer scope (e.g., timeout), there is no way to retrieve partially completed or failed results. If you need to process them anyway, you must store the results in a separate place in the passed coroutines or use [`as_completed_safe()`](#aiotools.utils.as_completed_safe) instead. New in version 2.0. *async* race(*coros: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable)[[Awaitable](https://docs.python.org/3/library/typing.html#typing.Awaitable)[aiotools.utils.T]]*, ***, *continue_on_error: [bool](https://docs.python.org/3/library/functions.html#bool) = False*, *context: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional)[_contextvars.Context] = None*) → [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple)[aiotools.utils.T, [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence)[[Exception](https://docs.python.org/3/library/exceptions.html#Exception)]][[source]](_modules/aiotools/utils.html#race)[](#aiotools.utils.race) Returns the first result and cancelling all remaining coroutines safely. Passing an empty iterable of coroutines is not allowed. If `continue_on_error` is set False (default), it will raise the first exception immediately, cancelling all remaining coroutines. This behavior is same to Javascript’s `Promise.race()`. The second item of the returned tuple is always empty. If `continue_on_error` is set True, it will keep running until it encounters the first successful result. Then it returns the exceptions as a list in the second item of the returned tuple. If all coroutines fail, it will raise an [`ExceptionGroup`](https://docs.python.org/3/library/exceptions.html#ExceptionGroup) to indicate the explicit failure of the entire operation. You may use this function to implement a “happy eyeball” algorithm. New in version 2.0. Indices and tables[](#indices-and-tables) --- * [Index](genindex.html) * [Search Page](search.html)
BClustLonG
cran
R
Package ‘BClustLonG’ October 12, 2022 Type Package Title A Dirichlet Process Mixture Model for Clustering Longitudinal Gene Expression Data Version 0.1.3 Author <NAME> [aut, cre], <NAME>[aut], <NAME>[aut], <NAME> [aut], and <NAME> [aut], Maintainer <NAME> <<EMAIL>> Description Many clustering methods have been proposed, but most of them cannot work for longitudinal gene expression data. 'BClustLonG' is a package that allows us to perform clustering analysis for longitudinal gene expression data. It adopts a linear-mixed effects framework to model the trajectory of genes over time, while clustering is jointly conducted based on the regression coefficients obtained from all genes. To account for the correlations among genes and alleviate the high dimensionality challenges, factor analysis models are adopted for the regression coefficients. The Dirichlet process prior distribution is utilized for the means of the regression coefficients to induce clustering. This package allows users to specify which variables to use for clustering (intercepts or slopes or both) and whether a factor analysis model is desired. More de- tails about this method can be found in Jiehuan Sun, et al. (2017) <doi:10.1002/sim.7374>. License GPL-2 Encoding UTF-8 LazyData true Depends R (>= 3.4.0), MASS (>= 7.3-47), lme4 (>= 1.1-13), mcclust (>= 1.0) Imports Rcpp (>= 0.12.7) Suggests knitr, lattice VignetteBuilder knitr LinkingTo Rcpp, RcppArmadillo RoxygenNote 7.1.0 NeedsCompilation yes Repository CRAN Date/Publication 2020-05-07 04:10:02 UTC R topics documented: BClustLon... 2 calSi... 3 dat... 4 BClustLonG A Dirichlet process mixture model for clustering longitudinal gene ex- pression data. Description A Dirichlet process mixture model for clustering longitudinal gene expression data. Usage BClustLonG( data = NULL, iter = 20000, thin = 2, savePara = FALSE, infoVar = c("both", "int")[1], factor = TRUE, hyperPara = list(v1 = 0.1, v2 = 0.1, v = 1.5, c = 1, a = 0, b = 10, cd = 1, aa1 = 2, aa2 = 1, alpha0 = -1, alpha1 = -1e-04, cutoff = 1e-04, h = 100) ) Arguments data Data list with three elements: Y (gene expression data with each column being one gene), ID, and years. (The names of the elements have to be matached exactly. See the data in the example section more info) iter Number of iterations (excluding the thinning). thin Number of thinnings. savePara Logical variable indicating if all the parameters needed to be saved. Default value is FALSE, in which case only the membership indicators are saved. infoVar Either "both" (using both intercepts and slopes for clustering) or "int" (using only intercepts for clustering) factor Logical variable indicating whether factor analysis model is wanted. hyperPara A list of hyperparameters with default values. Value returns a list with following objects. e.mat Membership indicators from all iterations. All other parameters only returned when savePara=TRUE. References <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. "A Dirichlet process mixture model for clustering longitudinal gene expression data." Statistics in Medicine 36, No. 22 (2017): 3495-3506. Examples data(data) ## increase the number of iterations ## to ensure convergence of the algorithm res = BClustLonG(data, iter=20, thin=2,savePara=FALSE, infoVar="both",factor=TRUE) ## discard the first 10 burn-ins in the e.mat ## and calculate similarity matrix ## the number of burn-ins has be chosen s.t. the algorithm is converged. mat = calSim(t(res$e.mat[,11:20])) clust = maxpear(mat)$cl ## the clustering results. ## Not run: ## if only want to include intercepts for clustering ## set infoVar="int" res = BClustLonG(data, iter=10, thin=2,savePara=FALSE, infoVar="int",factor=TRUE) ## if no factor analysis model is wanted ## set factor=FALSE res = BClustLonG(data, iter=10, thin=2,savePara=FALSE, infoVar="int",factor=TRUE) ## End(Not run) calSim Function to calculate the similarity matrix based on the cluster mem- bership indicator of each iteration. Description Function to calculate the similarity matrix based on the cluster membership indicator of each itera- tion. Usage calSim(mat) Arguments mat Matrix of cluster membership indicator from all iterations Examples n = 90 ##number of subjects iters = 200 ##number of iterations ## matrix of cluster membership indicators ## perfect clustering with three clusters mat = matrix(rep(1:3,each=n/3),nrow=n,ncol=iters) sim = calSim(t(mat)) data Simulated dataset for testing the algorithm Description Simulated dataset for testing the algorithm Usage data(data) Format An object of class list of length 3. Examples data(data) ## this is the required data input format head(data.frame(ID=data$ID,years=data$years,data$Y))
django-baton
readthedoc
Markdown
django-baton 2.8.0 documentation [django-baton](index.html#document-index) --- django-baton’s documentation[¶](#django-baton-s-documentation) === A cool, modern and responsive django admin application based on bootstrap 5 Baton was developed with one concept in mind: **overwrite as few django templates as possible**. Everything is done with css (sass and bootstrap mixins), and when the markup needs some edit, then DOM manipulation through js is used. Features[¶](#features) --- * Supports django >= 2.1 * Based on bootstrap 5 and FontAwesome 6 * Fully responsive * Custom and flexible sidebar menu * Text input filters facility * Configurable form tabs * Easy way to include templates in the change form page * Collapsable stacke inline entries * Lazy load of current uploaded images * Optional index page filled with google analytics widgets * Full customization available recompiling the provided js app * it translations Getting started[¶](#getting-started) --- ### Installation[¶](#installation) #### Using pip[¶](#using-pip) 1. Install the last available version: ``` pip install django-baton ``` Note In order to use the Google Analytics index, install baton along the optional dependencies with `pip install django-baton[analytics]` 2. Add `baton` and `baton.autodiscover` to your `INSTALLED_APPS`: ``` INSTALLED_APPS = ( # ... 'baton', 'django.contrib.admin', # ... (place baton.autodiscover at the very end) 'baton.autodiscover', ) ``` Important `baton` must be placed before `django.contrib.admin` and `baton.autodiscover` as the last app. 3. Replace django.contrib.admin in your project urls, and add baton urls: ``` from baton.autodiscover import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('baton/', include('baton.urls')), ] ``` Important If you get a “__No crypto library [available__](#system-message-1)” when using the google analytics index, then install this package: $ pip install PyOpenSSL ##### Why two installed apps?[¶](#why-two-installed-apps) The first baton has to be placed before the `django.contrib.admin` app, because it overrides 3 templates and resets all css. The `baton.autodiscover` entry is needed as the last installed app in order to register all applications for the admin. I decided to create a custom `AdminSite` class, in order to allow the customization of some variables the django way (`site_header`, `index_title`, …). I think this is a good approach, better than customizing this vars overwriting the orignal templates. The problem is that when creating a custom `AdminSite`, you should register manually all the apps. I didn’t like this, so I wrote this autodiscover module, which automatically registers all the apps already registered with the django default `AdminSite`. In order to do this, all the apps must be already registered, so it comes as the last installed app. ### Configuration[¶](#configuration) You can configure your baton installation defining a config dictionary in your `settings.py` #### Example[¶](#example) This is an example of configuration: ``` BATON = { 'SITE_HEADER': 'Baton', 'SITE_TITLE': 'Baton', 'INDEX_TITLE': 'Site administration', 'SUPPORT_HREF': 'https://github.com/otto-torino/django-baton/issues', 'COPYRIGHT': 'copyright © 2017 <a href="https://www.otto.to.it">Otto srl</a>', # noqa 'POWERED_BY': '<a href="https://www.otto.to.it">Otto srl</a>', 'CONFIRM_UNSAVED_CHANGES': True, 'SHOW_MULTIPART_UPLOADING': True, 'ENABLE_IMAGES_PREVIEW': True, 'CHANGELIST_FILTERS_IN_MODAL': True, 'CHANGELIST_FILTERS_ALWAYS_OPEN': False, 'CHANGELIST_FILTERS_FORM': True, 'COLLAPSABLE_USER_AREA': False, 'MENU_ALWAYS_COLLAPSED': False, 'MENU_TITLE': 'Menu', 'MESSAGES_TOASTS': False, 'GRAVATAR_DEFAULT_IMG': 'retro', 'GRAVATAR_ENABLED': True, 'FORCE_THEME': None 'LOGIN_SPLASH': '/static/core/img/login-splash.png', 'SEARCH_FIELD': { 'label': 'Search contents...', 'url': '/search/', }, 'MENU': ( { 'type': 'title', 'label': 'main', 'apps': ('auth', ) }, { 'type': 'app', 'name': 'auth', 'label': 'Authentication', 'icon': 'fa fa-lock', 'default_open': True, 'models': ( { 'name': 'user', 'label': 'Users' }, { 'name': 'group', 'label': 'Groups' }, ) }, { 'type': 'title', 'label': 'Contents', 'apps': ('flatpages', ) }, { 'type': 'model', 'label': 'Pages', 'name': 'flatpage', 'app': 'flatpages' }, { 'type': 'free', 'label': 'Custom Link', 'url': 'http://www.google.it', 'perms': ('flatpages.add_flatpage', 'auth.change_user') }, { 'type': 'free', 'label': 'My parent voice', 'children': [ { 'type': 'model', 'label': 'A Model', 'name': 'mymodelname', 'app': 'myapp', 'icon': 'fa fa-gavel' }, { 'type': 'free', 'label': 'Another custom link', 'url': 'http://www.google.it' }, ] }, ), 'ANALYTICS': { 'CREDENTIALS': os.path.join(BASE_DIR, 'credentials.json'), 'VIEW_ID': '12345678', } } ``` #### Site header[¶](#site-header) **Default**: baton logo Important `SITE_HEADER` is marked as safe, so you can include img tags or links #### Site title[¶](#site-title) **Default**: ‘Baton’ #### Index title[¶](#index-title) **Default**: ‘Site administration’ #### Support href[¶](#support-href) This is the content of the href attribute of the support link rendered in the footer. **Default**: ‘<https://github.com/otto-torino/django-baton/issues>’ **Example**: ‘[mailto:<EMAIL>](mailto:support%40company.org)’ #### Copyright[¶](#copyright) A copyright string inserted centered in the footer **Default**: ‘copyright © 2017 <a href=”<https://www.otto.to.it>”>Otto srl</a>’ Important `COPYRIGHT` is marked as safe, so you can include img tags or links #### Powered by[¶](#powered-by) A powered by information included in the right part of the footer, under the `SITE_TITLE` string **Default**: ‘<a href=”<https://www.otto.to.it>”>Otto srl</a>’ Important `POWERED_BY` is marked as safe, so you can include img tags or links #### Confirm unsaved changes[¶](#confirm-unsaved-changes) Alert the user when he’s leaving a change or add form page without saving changes **Default**: True Important The check for a dirty form relies on the jQuery serialize method, so it’s not 100% safe. Disabled inputs, particular widgets (ckeditor) can not be detected. #### Show multipart uploading[¶](#show-multipart-uploading) Show an overlay with a spinner when a `multipart/form-data` form is submitted **Default**: True #### Enable images preview[¶](#enable-images-preview) Displays a preview above all input file fields which contain images. You can control how the preview is displayed overriding the class `.baton-image-preview`. By default previews are 100px height and with a box shadow on over event **Default**: True #### Changelist filters in modal[¶](#changelist-filters-in-modal) If set to `True` the changelist filters are opened in a centered modal above the document, useful when you set many filters. By default, its value is `False` and the changelist filters appears from the right side of the changelist table. **Default**: False #### Changelist filters always open[¶](#changelist-filters-always-open) If set to `True` the changelist filters are opened by default. By default, its value is `False` and the changelist filters can be expanded clicking a toggler button. This option is considered only if `CHANGELIST_FILTERS_IN_MODAL` is `False` **Default**: False #### Changelist filters form[¶](#changelist-filters-form) If set to `True` the changelist filters are treated as in a form, you can set many of them at once and then press a filter button in order to actually perform the filtering. With such option all standard filters are displayed as dropdowns. **Default**: False #### Collapsable user area[¶](#collapsable-user-area) If set to `True` the sidebar user area is collapsed and can be expanded to show links. **Default**: False #### Menu always collapsed[¶](#menu-always-collapsed) If set to `True` the menu is hidden at page load, and the navbar toggler is always visible, just click it to show the sidebar menu. **Default**: False #### Menu title[¶](#menu-title) The menu title shown in the sidebar. If an empty string, the menu title is hidden and takes no space on larger screens, the default menu voice will still be visible in the mobile menu. #### Messages toasts[¶](#messages-toasts) You can decide to show all or specific level admin messages in toasts. Set it to `True` to show all message in toasts. set it to `['warning', 'error']` to show only warning and error messages in toasts. **Default**: False #### Gravatar default image[¶](#gravatar-default-image) The default gravatar image displayed if the user email is not associated to any gravatar image. Possible values: 404, mp, identicon, monsterid, wavatar, retro, robohash, blank (see gravatar docs [http://en.gravatar.com/site/implement/images/]). **Default**: ‘retro’ #### Gravatar enabled[¶](#gravatar-enabled) Should a gravatar image be shown for the user in the menu? **Default**: True #### Login splash image[¶](#login-splash-image) An image used as body background in the login page. The image is centered and covers the whole viewport. **Default**: None #### Force theme[¶](#force-theme) You can force the light or dark theme, and the theme toggle disappears from the user area. **Default**: None #### Menu[¶](#menu) The sidebar menu is rendered through javascript. If you don’t define a custom menu, the default menu is rendered, which includes all the apps and models registered in the admin that the user can view. When defining a custom menu you can use 4 different kinds of voices: * title * app * model * free Title and free voices can have children. Children follow these rules: * children children are ignored (do not place an app voice as child) Voices with children can specify a `default_open` option, used to expand the submenu by default. ##### Title[¶](#title) Like the voices MAIN and CONTENTS in the above image, it represents a menu section. You should set a `label` and optionally an `apps` or `perms` key, used for visualization purposes. If the title voice should act as a section title for a group of apps, you’d want to specify these apps, because if the user can’t operate over them, then the voice is not shown. At the same time you can define some perms (OR condition), something like: ``` { 'type': 'title', 'label': 'main', 'perms': ('auth.add_user', ) }, ``` or ``` { 'type': 'title', 'label': 'main', 'apps': ('auth', ) }, ``` It accepts children voices, though you can specify the `default_open` key. ##### App[¶](#app) In order to add an application with all its models to the menu, you need an app menu voice. You must specify the `type` and `name` keys, optionally an `icon` key (you can use FontAwesome classes which are included by default), a `default_open` key and a `models` key. Important If you don’t define the models key then the default app models are listed under your app, otherwise only the specified models are listed (in the order you provide). The `models` key must be a tuple, where every item represents a model in the form of a dictionary with keys `label` and `name` ``` { 'type': 'app', 'name': 'auth', 'label': 'Authentication', 'icon': 'fa fa-lock', 'models': ( { 'name': 'user', 'label': 'Users' }, { 'name': 'group', 'label': 'Groups' }, ) }, ``` Important App name should be lowercase. ##### Model[¶](#model) If you want to add only a link to the admin page of a single model, you can use this voice. For example, the flatpages app has only one model Flatpage, so I think it may be better to avoid a double selection. In this case you must specify the `type`, `name` and `app` keys, optionally an `icon` key (you can use FontAwesome classes which are included by default). An example: ``` { 'type': 'model', 'label': 'Pages', 'name': 'flatpage', 'app': 'flatpages', 'icon': 'fa fa-file-text-o' }, ``` Important Model name should be lowercase. ##### Free[¶](#free) If you want to link an external site, a documentation page, an add element page and in general every custom resource, you may use this voice. In such case you must define an `url` and if you want some visibility permissions (OR clause) ``` { 'type': 'free', 'label': 'Docs', 'url': 'http://www.mydocssite.com' }, ``` or ``` { 'type': 'free', 'label': 'Add page', 'url': '/admin/flatpages/flatpage/add/', 'perms': ('flatpages.add_flatpage', ) }, ``` It accepts children voices ``` { 'type': 'free', 'label': 'My parent voice', 'children': [ { 'type': 'free', 'label': 'Docs', 'url': 'http://www.mydocssite.com' }, { 'type': 'free', 'label': 'Photos', 'url': 'http://www.myphotossite.com' }, ] }, ``` Since free voices can have children you can specify the `default_open` key. Free voices also accept a _re_ property, which specifies a regular expression used to decide whether to highlight the voice or not (the regular expression is evaluated against the document location pathname): ``` { 'type': 'free', 'label': 'Categories', 'url': '/admin/news/category/', 're': '^/admin/news/category/(\d*)?' } ``` #### Search Field[¶](#search-field) With this functionality, you can configure a sidebar input search field with autocomplete functionality that can let you surf easily and quickly to any page you desire. ``` 'SEARCH_FIELD': { 'label': 'Label shown as placeholder', 'url': '/api/path/', }, ``` The autocomplete field will call a custom api at every keyup event. Such api receives the `text` param in the querystring and should return a json response including the search results in the form: ``` { length: 2, data: [ { label: 'My result #1', icon: 'fa fa-edit', url: '/admin/myapp/mymodel/1/change' }, // ... ] } ``` You should provide the results length and the data as an array of objects which must contain the `label` and `url` keys. The `icon` key is optional and is treated as css class given to an `i` element. Let’s see an example: ``` @staff_member_required def admin_search(request): text = request.GET.get('text', None) res = [] news = News.objects.all() if text: news = news.filter(title__icontains=text) for n in news: res.append({ 'label': str(n) + ' edit', 'url': '/admin/news/news/%d/change' % n.id, 'icon': 'fa fa-edit', }) if text.lower() in 'Lucio Dalla Wikipedia'.lower(): res.append({ 'label': '<NAME> Wikipedia', 'url': 'https://www.google.com', 'icon': 'fab fa-wikipedia-w' }) return JsonResponse({ 'length': len(res), 'data': res }) ``` You can move between the results using the keyboard up and down arrows, and you can browse to the voice url pressing Enter. #### Analytics[¶](#analytics) Note In order to use the Google Analytics index, install baton along the optional dependencies with `pip install django-baton[analytics]` Baton provides an index view which displays google analytics statistics charts for the last 15 days, 1 month, 3 month and 1 year. In order to activate it you need to create a service account and link it to your google analytics view, then you must define the keys: * `CREDENTIALS`: path to the credentials json file * `VIEW_ID`: id of the analytics view which serves the data You can add contents before and after the analytics dashboard by extending the `baton/analytics.html` template and filling the `baton_before_analytics` and `baton_after_analytics` blocks. ##### How to generate a credentials json file[¶](#how-to-generate-a-credentials-json-file) Follow the steps in the Google Identity Platform documentation to [create a service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount) from the [Google Developer Console](https://console.developers.google.com/). Once the service account is created, you can click the Generate New JSON Key button to create and download the key and add it to your project. Add the service account as a user in Google Analytics. The service account you created in the previous step has an email address that you can add to any of the Google Analytics views you’d like to request data from. It’s generally best to only grant the service account read-only access. ### Page Detection[¶](#page-detection) Baton triggers some of its functionalities basing upon the current page. For example, it will trigger the tab functionality only when the current page is an add form or change form page. Baton understands which page is currently displayed performing some basic regular expressions against the location pathname. There may be cases in which you’d like to serve such contents at different and custom urls, in such cases you need a way to tell Baton which kind of page is tied to that url. For this reason you can inject your custom hook, a javascript function which should return the page type and that receives as first argument the Baton’s default function to use as fallback, i.e. ``` <!-- admin/base_site.html --> <script> (function () { Baton.detectPageHook = fn => /newschange/.test(location.pathname) ? 'change_form' : fn() })() </script> <script src="{% static 'baton/js_snippets/init_baton.js' %}"></script> ``` In this case we tell Baton that when the location pathname includes the string `newschange`, then the page should be considered a `change_form`, otherwise we let Baton guess the page type. So, in order to hook into the Baton page detection system, just define a `Baton.detectPageHook` function which receives the default function as first argument and should return the page type. The available page types are the following: `dashboard`, `admindocs`, `login`, `logout`, `passowrd_change`, `password_change_success`, `add_form`, `change_form`, `changelist`, `filer`, `default`. ### Signals[¶](#signals) Baton provides a dispatcher that can be used to register function that will be called when some events occurr. At this moment Baton emits four types of events: * `onNavbarReady`: dispatched when the navbar is fully rendered * `onMenuReady`: dispatched when the menu is fully rendered (probably the last event fired, since the menu contents are retrieves async) * `onTabsReady`: dispatched when the changeform tabs are fully * `onMenuError`: dispatched if the request sent to retrieve menu contents fails * `onReady`: dispatched when Baton js has finished its sync job In order to use them just override the baton admin/base_site.html template and register your listeners **before** calling Baton.init, i.e. ``` <!-- ... --> <script> (function ($, undefined) { // init listeners Baton.Dispatcher.register('onReady', function () { console.log('BATON IS READY') }) Baton.Dispatcher.register('onMenuReady', function () { console.log('BATON MENU IS READY') }) Baton.Dispatcher.register('onNavbarReady', function () { console.log('BATON NAVBAR IS READY') }) // end listeners })(jQuery, undefined) </script> <script src="{% static 'baton/js_snippets/init_baton.js' %}"></script> <!-- ... --> ``` ### Js Utilities[¶](#js-utilities) Baton comes with a number of exported js modules you can use to enhance your admin application. #### Dispatcher[¶](#dispatcher) Baton Dispatcher singleton module lets you subscribe to event and dispatch them, making use of the Mediator pattern. Example: ``` // register a callback tied to the event Baton.Dispatcher.register('myAppLoaded', function (evtName, s) { console.log('COOL ' + s) }) // emit the event Baton.Dispatcher.emit('myAppLoaded', 'STUFF!') ``` #### Modal[¶](#modal) Baton Modal class lets you insert some content on a bootstrap modal without dealing with all the markup. Usage: ``` // modal configuration: // // let config = { // title: 'My modal title', // subtitle: 'My subtitle', // optional // content: '<p>my html content</p>', // alternative to url // url: '/my/url', // url used to perform an ajax request, the response is put inside the modal body. Alternative to content. // hideFooter: false, // optional // showBackBtn: false, // show a back button near the close icon, optional // backBtnCb: function () {}, // back button click callback (useful to have a multi step modal), optional // actionBtnLabel: 'save', // action button label, default 'save', optional // actionBtnCb: null, // action button callback, optional // onUrlLoaded: function () {}, // callback called when the ajax request has completed, optional // size: 'lg', // modal size: sm, md, lg, xl, optional // onClose: function () {} // callback called when the modal is closed, optional // } // // constructs a new modal instance // let myModal = new Baton.Modal(config) let myModal = new Baton.Modal({ title: 'My modal title', content: '<p>my html content</p>', size: 'lg' }) myModal.open(); myModal.close(); myModal.update({ title: 'Step 2', content: '<p>cool</p>' }) myModal.toggle(); ``` ``` ### Js Translations[¶](#js-translations) There are some circustamces in which Baton will print to screen some js message. Baton detects the user locale and will localize such messages, but it comes with just `en` and `it` translations provided. Important Baton retrieves the current user locale from the `lang` attribute of the `html` tag. However you can provide or add your own translations by attaching an object to the Baton namespace: ``` // these are the default translations, you can just edit the one you need, or add some locales. Baton engione will always // pick up your custom translation first, if it find them. // you can define thi object before Baton.init in the base_site template Baton.translations = { unsavedChangesAlert: 'You have some unsaved changes.', uploading: 'Uploading...', filter: 'Filter', close: 'Close', save: 'Save', search: 'Search', cannotCopyToClipboardMessage: 'Cannot copy to clipboard, please do it manually: Ctrl+C, Enter', retrieveDataError: 'There was an error retrieving the data', lightTheme: 'Light theme', darkTheme: 'Dark theme', } ``` Important Just use the `trans` templatetag to deal with multilanguage web applications If Baton can’t find the translations for the user locale, it will default to `en`. Keep in mind that Baton will use `en` translations for all `en-xx` locales, but of course you can specify your custom translations! ### List Filters[¶](#list-filters) #### Input Text Filters[¶](#input-text-filters) Idea taken from this [medium article](https://medium.com/@hakibenita/how-to-add-a-text-filter-to-django-admin-5d1db93772d8). Baton defines a custom InputFilter class that you can use to create text input filters and use them as any other `list_filters`, for example ``` # your app admin from baton.admin import InputFilter class IdFilter(InputFilter): parameter_name = 'id' title = 'id' def queryset(self, request, queryset): if self.value() is not None: search_term = self.value() return queryset.filter( id=search_term ) class MyModelAdmin(admin.ModelAdmin): list_filters = ( 'my_field', IdFilter, 'my_other_field', ) ``` Just define in the `queryset` method the logic used to retrieve the results. #### Dropdown Filters[¶](#dropdown-filters) Taken from the github app [django-admin-list-filter-dropdown](https://github.com/mrts/django-admin-list-filter-dropdown). Baton provides a dropdown form of the following list filters: | Django admin filter name | Baton name | | --- | --- | | SimpleListFilter | SimpleDropdownFilter | | AllValuesFieldListFilter | DropdownFilter | | ChoicesFieldListFilter | ChoicesDropdownFilter | | RelatedFieldListFilter | RelatedDropdownFilter | | RelatedOnlyFieldListFilter | RelatedOnlyDropdownFilter | The dropdown is visible only if the filter contains at least three options, otherwise the default template is used. Usage: ``` from baton.admin import DropdownFilter, RelatedDropdownFilter, ChoicesDropdownFilter class MyModelAdmin(admin.ModelAdmin): list_filter = ( # for ordinary fields ('a_charfield', DropdownFilter), # for choice fields ('a_choicefield', ChoiceDropdownFilter), # for related fields ('a_foreignkey_field', RelatedDropdownFilter), ) ``` #### Multiple Choice Filters[¶](#multiple-choice-filters) Baton defines a custom MultipleChoiceListFilter class that you can use to filter on multiple options, for example: ``` # your app admin from baton.admin import MultipleChoiceListFilter class StatusListFilter(MultipleChoiceListFilter): title = 'Status' parameter_name = 'status__in' def lookups(self, request, model_admin): return News.Status.choices class MyModelAdmin(admin.ModelAdmin): list_filters = ( 'my_field', StatusListFilter, 'my_other_field', ) ``` ### Changelist includes[¶](#changelist-includes) Important In order for this feature to work, the user browser must support html template tags. Baton lets you include templates directly inside the change list page, in any position you desire. It’s as simple as specifying the template path and the position of the template: ``` @admin.register(News) class NewsAdmin(admin.ModelAdmin): #... baton_cl_includes = [ ('news/admin_include_top.html', 'top', ), ('news/admin_include_below.html', 'below', ) ] ``` In this case, Baton will place the content of the `admin_include_top.html` template at the top of the changelist section (above the search field), and the content of the `admin_include_below.html` below the changelist form. You can specify the following positions: | Position | Description | | --- | --- | | top | the template is placed inside the changelist form, at the top | | bottom | the template is placed inside the changelist form, at the bottom | | above | the template is placed above the changelist form | | below | the template is placed below the changelist form | And, of course, you can access the all the changelist view context variables inside your template. ### Changelist filters includes[¶](#changelist-filters-includes) Important In order for this feature to work, the user browser must support html template tags. Baton lets you include templates directly inside the change list filter container, at the top or the bottom. It’s as simple as specifying the template path and the position of the template: ``` @admin.register(News) class NewsAdmin(admin.ModelAdmin): #... baton_cl_filters_includes = [ ('news/admin_filters_include_top.html', 'top', ), ('news/admin_filters_include_below.html', 'bottom', ) ] ``` You can specify the following positions: | Position | Description | | --- | --- | | top | the template is placed inside the changelist filters container, at the top | | bottom | the template is placed inside the changelist filters container, at the bottom | And, of course, you can access the all the changelist view context variables inside your template. ### Changelist Row Attributes[¶](#changelist-row-attributes) Important In order for this feature to work, the user browser must support html template tags. With Baton you can add every kind of html attribute (including css classes) to any element in the changelist table (cell, rows, …) It’s a bit tricky, let’s see how: 1. Add a `baton_cl_rows_attributes` function to your `ModelAdmin` class, which takes `request` and `cl` (changelist view) as parameters. 2. Return a json dictionary where the keys are used to match an element and the values specifies the attributes and other rules to select the element. Better to see an example: ``` class NewsModelAdmin(admin.ModelAdmin): # ... def get_category(self, instance): return mark_safe('<span class="span-category-id-%d">%s</span>' % (instance.id, str(instance.category))) get_category.short_description = 'category' def baton_cl_rows_attributes(self, request, cl): data = {} for news in cl.queryset.filter(category__id=2): data[news.id] = { 'class': 'table-info', } data[news.id] = { 'class': 'table-success', 'data-lol': 'lol', 'title': 'A fantasctic tooltip!', 'selector': '.span-category-id-%d' % 1, 'getParent': 'td', } return json.dumps(data) ``` In such case we’re returning a dictionary with possibly many keys (each key is an id of a news instance). The first kind of dictionary elements will add a `table-info` class to the `tr` (rows) containing the news respecting the rule `category__id=2` The second kind of element instead uses some more options to customize the element selection: you can specify a css selector, and you can specify if Baton should then take one of its parents, and in such case you can give a parent selector also. In the example provided Baton will add the class `table-success`, `data-attribute` and the `title` attribute to the cell which contains the element `.span-category-id-1`. So these are the rules: * the default `selector` is `#result_list tr input[name=_selected_action][value=' + key + ']`, meaning that it can work only if the model is editable (you have the checkox inputs for selecting a row), and selects the row of the instance identified by `key`. If you use a custom selector the dictionary `key` is unuseful. * the default `getParent` is `tr`. You can change it at you will, or set it to False, in such case the element to which apply the given attributes will be the one specified by `selector`. * Every other key different from `selector` and `getParent` will be considered an attribute and added to the element. ### Form tabs[¶](#form-tabs) Baton provides an easy way to define form tabs in yor change form templates. Everything is done through javascript and you only need to add some classes you your `ModelAdmin` fieldsets ``` from django.contrib import admin from .models import Item, Attribute, Feature class AttributeInline(admin.StackedInline): model = Attribute extra = 1 class FeatureInline(admin.StackedInline): model = Feature extra = 1 class ItemAdmin(admin.ModelAdmin): list_display = ('label', 'description', 'main_feature', ) inlines = [AttributeInline, FeatureInline, ] fieldsets = ( ('Main', { 'fields': ('label', ), 'classes': ('baton-tabs-init', 'baton-tab-inline-attribute', 'baton-tab-fs-content', 'baton-tab-group-fs-tech--inline-feature', ), 'description': 'This is a description text' }), ('Content', { 'fields': ('text', ), 'classes': ('tab-fs-content', ), 'description': 'This is another description text' }), ('Tech', { 'fields': ('main_feature', ), 'classes': ('tab-fs-tech', ), 'description': 'This is another description text' }), ) ``` #### Rules[¶](#rules) * Inline classes remain the same, no action needed * In the first fieldset define a `baton-tabs-init` class which enables tabs * On the first fieldset, you can add an `order-[NUMBER]` class, which will be used to determined in which position to place the first fieldset. The order starts from 0, and if omitted, the first fieldset has order 0. If you assign for example the class `order-2` to the first fieldset, then the first fieldset will be the third tab, while all other tabs will respect the order of declaration. * For every `InLine` you want to put in a separate tab, add a class `baton-tab-inline-MODELNAME` or `baton-tab-inline-RELATEDNAME` if you’ve specified a related_name to the foreign key * For every fieldset you want to put in a separate tab, add a class `baton-tab-fs-CUSTOMNAME`, and add a class `tab-fs-CUSTOMNAME` on the fieldset * For every group you want to put in a separate tab, add a class `baton-tab-group-ITEMS`, where items can be inlines (`inline-RELATEDNAME`) and/or fieldsets (`fs-CUSTOMNAME`) separated by a double hypen `--`. Also add a class `tab-fs-CUSTOMNAME` on the fieldset items. * Tabs order respects the defined classes order * Fieldsets without a specified tab will be added to the main tab. If you want the fieldset to instead display outside of any tabs, add a class `tab-fs-none` to the fieldset. The fieldset will then always be visible regardless of the current tab. Other features: * when some field has an error, the first tab containing errors is opened automatically * you can open a tab on page load just by adding an hash to the url, i.e. #inline-feature, #fs-content, #group-fs-tech–inline-feature ### Form includes[¶](#form-includes) Important In order for this feature to work, the user browser must support html template tags. Baton lets you include templates directly inside the change form page, in any position you desire. It’s as simple as specifying the template path, the field name used as anchor and the position of the template: ``` @admin.register(News) class NewsAdmin(admin.ModelAdmin): #... baton_form_includes = [ ('news/admin_datetime_include.html', 'datetime', 'top', ), ('news/admin_content_include.html', 'content', 'above', ) ] ``` In this case, Baton will place the content of the `admin_datetime_include.html` template at the top of the datetime field row, and the content of the `admin_content_include.html` above the content field row. You can specify the following positions: | Position | Description | | --- | --- | | top | the template is placed inside the form row, at the top | | bottom | the template is placed inside the form row, at the bottom | | above | the template is placed above the form row | | below | the template is placed below the form row | | right | the template is placed inline at the field right side | And, of course, you can access the {{ original }} object variable inside your template. It works seamlessly with the tab facility, if you include content related to a field inside one tab, then the content will be placed in the same tab. ### Collapsable StackedInline entries[¶](#collapsable-stackedinline-entries) Baton lets you collapse single stacked inline entries, just add a collapse-entry class to the inline, with or without the entire collapse class ``` class VideosInline(admin.StackedInline): model = Video extra = 1 classes = ('collapse-entry', ) # or ('collapse', 'collapse-entry', ) ``` And if you want the first entry to be initially expanded, add also the expand-first class ``` class VideosInline(admin.StackedInline): model = Video extra = 1 classes = ('collapse-entry', 'expand-first', ) ``` Advanced customization[¶](#advanced-customization) --- ### Customization[¶](#customization) It’s easy to heavily customize the appeareance of baton. All the stuff is compiled from a modern js app which resides in baton/static/baton/app. #### The Baton js app[¶](#the-baton-js-app) The js app which **baton** provides is a modern js app, written using es2015 and stage-0 code features, which are then transpiled to a code browsers can understand using [babel](https://babeljs.io/) and [webpack](https://webpack.github.io/). All css are written using sass on top of bootstrap 4.5.0, and transpiled with babel so that the final output is a single js file ready to be included in the html template. The app entry point is [index.js](https://github.com/otto-torino/django-baton/blob/master/baton/static/baton/app/src/index.js), where the only variable attached to the window object `Baton` is defined. All the js modules used are inside the [core](https://github.com/otto-torino/django-baton/tree/master/baton/static/baton/app/src/core) directory. #### Change the baton appearance[¶](#change-the-baton-appearance) It’s quite easy to change completely the appearance of baton, just overwrite the [sass variables](https://github.com/otto-torino/django-baton/blob/master/baton/static/baton/app/src/styles/_variables.scss) as you like and recompile the app. Then make sure to serve your recompiled app in place of the baton one. Here comes what you have to do: * place one of your django apps before baton in the INSTALLED_APPS settings, I’ll call this app ROOTAPP * clone the repository (or copy the static/baton/app dir from your virtualenv) ``` $ git clone https://github.com/otto-torino/django-baton.git ``` * install the app requirements ``` $ cd django-baton/baton/static/baton/app/ $ npm install ``` * edit the `src/styles/_variables.scss` file as you like * recompile the app ``` $ npm run compile ``` * copy the generated bundle `dist/baton.min.js` in `ROOTAPP/static/baton/app/dist/` You can also perform live development, in this case: * place one of your django apps before baton in the INSTALLED_APPS settings, I’ll call this app ROOTAPP * create an admin base_site template `ROOTAPP/templates/admin/base_site.html` with the following content: ``` {% baton_config as conf %} {{ conf | json_script:"baton-config" }} <script charset="utf-8"> (function () { // immediately set the theme mode to avoid flashes var systemTheme = window.matchMedia("(prefers-color-scheme: dark)"); var theme = JSON.parse(document.getElementById('baton-config').textContent).forceTheme || localStorage.getItem('baton-theme') || (systemTheme.matches ? 'dark' : 'light'); document.getElementsByTagName('html')[0].setAttribute('data-bs-theme', theme); })() </script> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <link rel="stylesheet" href="{% static 'baton/css/theme.css' %}" /> <script src="{% static 'baton/app/dist/baton.min.js' %}"></script> <!-- <script src="http://localhost:8080/static/baton/app/dist/baton.min.js"></script> --> <script src="{% static 'baton/js_snippets/init_baton.js' %}"></script> ``` * or you can edit directly the baton template and switch the comment of the two lines: ``` <!-- <script src="{% static 'baton/app/dist/baton.min.js' %}"></script> comment the compiled src and uncomment the webpack served src --> <script src="http://localhost:8080/static/baton/app/dist/baton.min.js"></script> ``` * start the webpack development server ``` $ npm run dev ``` Now while you make your changes to the js app (css included), webpack will update the bundle automatically, so just refresh the page and you’ll see your changes. Screenshots[¶](#screenshots) ---
Java%20-%20Mattone%20dopo%20mattone.pdf
free_programming_book
Unknown
Versione 0.1.5 Rilascio del 09/03/2001 Titolo Originale Java Enterprise Computing Copyrigth per la prima edizione <NAME> Copyrigth per ledizione corrente <NAME> Coordinamento Editoriale <NAME> Progetto Editoriale <NAME> PRIMA EDIZIONE <NAME> http://www.java-net.tv <EMAIL> 2 Se in un primo momento l'idea non assurda, allora non c' nessuna speranza che si realizzi. <NAME> <NAME> http://www.java-net.tv <EMAIL> 3 Gli sponsor di Java Mattone Dopo Mattone Questo spazio libero Questo spazio libero <NAME> http://www.java-net.tv <EMAIL> 4 Questo spazio libero Questo spazio libero Questo spazio libero Questo spazio libero <NAME> http://www.java-net.tv <EMAIL> 5 Indice Analitico GLI SPONSOR DI JAVA MATTONE DOPO MATTONE ... 4 INDICE ANALITICO ... 6 JAVA MATTONE DOPO MATTONE ... 14 INTRODUZIONE ... 14 PREMESSE... 14 CAPITOLO 1 ... 17 INTRODUZIONE ALLA PROGRAMMAZIONE OBJECT ORIENTED ... 17 INTRODUZIONE ... 17 UNA EVOLUZIONE NECESSARIA... 18 IL PARADIGMA PROCEDURALE ... 18 CORREGGERE GLI ERRORI PROCEDURALI ... 19 IL PARADIGMA OBJECT ORIENTED ... 21 CLASSI DI OGGETTI ... 21 EREDITARIET ... 21 IL CONCETTO DI EREDITARIET NELLA PROGRAMMAZIONE ... 22 VANTAGGI NELLUSO DELLEREDITARIET ... 23 PROGRAMMAZIONE OBJECT ORIENTED ED INCAPSULAMENTO... 23 I VANTAGGI DELLINCAPSULAMENTO ... 24 ALCUNE BUONE REGOLE PER CREARE OGGETTI ... 25 CAPITOLO 2 ... 26 INTRODUZIONE AL LINGUAGGIO JAVA ... 26 INTRODUZIONE ... 26 LA STORIA DI JAVA ... 26 LE CARATTERISTICHE PRINCIPALI DI JAVA INDIPENDENZA DALLA PIATTAFORMA......26 LE CARATTERISTICHE PRINCIPALI DI JAVA USO DELLA MEMORIA E MULTI-THREADING ... 28 MECCANISMO DI CARICAMENTO DELLE CLASSI DA PARTE DELLA JVM... 29 IL JAVA DEVELOPMENT KIT (JDK) ... 29 SCARICARE ED INSTALLARE IL JDK ... 30 IL COMPILATORE JAVA (JAVAC)... 31 IL DEBUGGER JAVA (JDB)... 31 LINTERPRETE JAVA ... 31 CAPITOLO 3 ... 33 INTRODUZIONE ALLA SINTASSI DI JAVA... 33 INTRODUZIONE ... 33 VARIABILI ... 33 Massimiliano Tarquini http://www.java-net.tv <EMAIL> 6 INIZIALIZZAZIONE DI UNA VARIABILE ... 34 VARIABILI FINAL ... 34 OPERATORI ... 34 OPERATORI ARITMETICI ... 36 OPERATORI RELAZIONALI ... 37 OPERATORI CONDIZIONALI ... 38 OPERATORI LOGICI E DI SHIFT BIT A BIT ... 38 OPERATORI DI ASSEGNAMENTO ... 40 ESPRESSIONI ... 41 ISTRUZIONI ... 41 REGOLE SINTATTICHE DI JAVA ... 41 BLOCCHI DI ISTRUZIONI ... 42 METODI ... 42 DEFINIRE UNA CLASSE... 43 VARIABILI REFERENCE ... 44 VISIBILIT DI UNA VARIABILE JAVA ... 46 LOGGETTO NULL ... 47 CREARE ISTANZE ... 47 LOPERATORE PUNTO .... 48 AUTO REFERENZA ED AUTO REFERENZA ESPLICITA ... 49 AUTO REFERENZA IMPLICITA ... 49 STRINGHE ... 51 STATO DI UN OGGETTO JAVA ... 51 COMPARAZIONE DI OGGETTI ... 51 METODI STATICI ... 52 IL METODO MAIN... 53 LOGGETTO SYSTEM ... 53 LABORATORIO 3 ... 55 INTRODUZIONE ALLA SINTASSI DI JAVA... 55 DESCRIZIONE ... 55 ESERCIZIO 1... 55 SOLUZIONE AL PRIMO ESERCIZIO ... 57 CAPITOLO 4 ... 59 CONTROLLO DI FLUSSO E DISTRIBUZIONE DI OGGETTI ... 59 INTRODUZIONE ... 59 ISTRUZIONI PER IL CONTROLLO DI FLUSSO ... 59 LISTRUZIONE IF ... 60 LISTRUZIONE IF-ELSE ... 60 ISTRUZIONI IF, IF-ELSE ANNIDATE ... 61 CATENE IF-ELSE-IF ... 61 LISTRUZIONE SWITCH ... 62 LISTRUZIONE WHILE ... 64 LISTRUZIONE DO-WHILE ... 65 LISTRUZIONE FOR ... 65 ISTRUZIONE FOR NEI DETTAGLI ... 66 <NAME> http://www.java-net.tv <EMAIL> 7 ISTRUZIONI DI RAMIFICAZIONE ... 66 LISTRUZIONE BREAK ... 67 LISTRUZIONE CONTINUE... 67 LISTRUZIONE RETURN ... 68 PACKAGE JAVA ... 68 ASSEGNAMENTO DI NOMI A PACKAGE ... 68 CREAZIONE DEI PACKAGE SU DISCO ... 69 IL MODIFICATORE PUBLIC ... 70 LISTRUZIONE IMPORT ... 71 LABORATORIO 4 ... 72 CONTROLLO DI FLUSSO E DISTRIBUZIONE DI OGGETTI ... 72 ESERCIZIO 1... 72 ESERCIZIO 2... 72 SOLUZIONE AL PRIMO ESERCIZIO ... 73 SOLUZIONE AL SECONDO ESERCIZIO... 73 CAPITOLO 5 ... 74 INCAPSULAMENTO ... 74 INTRODUZIONE ... 74 MODIFICATORI PUBLIC E PRIVATE ... 75 PRIVATE ... 75 PUBLIC ... 75 IL MODIFICATORE PROTECTED ... 76 UN ESEMPIO DI INCAPSULAMENTO ... 77 LOPERATORE NEW ... 77 COSTRUTTORI ... 78 UN ESEMPIO DI COSTRUTTORI ... 79 OVERLOADING DEI COSTRUTTORI ... 80 RESTRIZIONE SULLA CHIAMATA AI COSTRUTTORI ... 81 CROSS CALLING TRA COSTRUTTORI ... 82 LABORATORIO 5 ... 84 INCAPSULAMENTO DI OGGETTI... 84 ESERCIZIO 1... 84 SOLUZIONE DEL PRIMO ESERCIZIO... 85 CAPITOLO 6 ... 86 EREDITARIET ... 86 INTRODUZIONE ... 86 DISEGNARE UNA CLASSE BASE... 86 OVERLOAD DI METODI... 87 ESTENDERE UNA CLASSE BASE... 89 EREDITARIET ED INCAPSULAMENTO... 89 <NAME> http://www.java-net.tv <EMAIL> 8 EREDITARIET E COSTRUTTORI... 90 AGGIUNGERE NUOVI METODI ... 92 OVERRIDING DI METODI ... 92 CHIAMARE METODI DELLA CLASSE BASE ... 93 FLESSIBILIT DELLE VARIABILI REFERENCE ... 94 RUN-TIME E COMPILE-TIME ... 94 ACCESSO A METODI ATTRAVERSO VARIABILI REFERENCE ... 95 CAST DEI TIPI ... 95 LOPERATORE INSTANCEOF ... 96 LOGGETTO OBJECT ... 96 IL METODO EQUALS() ... 97 RILASCIARE RISORSE ESTERNE... 97 RENDERE GLI OGGETTI IN FORMA DI STRINGA... 98 LABORATORIO 6 ... 99 INTRODUZIONE ALLA EREDITARIET ... 99 ESERCIZIO 1... 99 ESERCIZIO 2... 100 SOLUZIONE AL PRIMO ESERCIZIO ... 101 SOLUZIONE AL SECONDO ESERCIZIO... 102 CAPITOLO 7 ... 104 ECCEZIONI... 104 INTRODUZIONE ... 104 ECCEZIONI : PROPAGAZIONE DI OGGETTI ... 104 OGGETTI THROWABLE ... 105 LISTRUZIONE THROW ... 106 ISTRUZIONI TRY / CATCH ... 106 SINGOLI CATCH PER ECCEZIONI MULTIPLE ... 107 LA CLAUSOLA THROWS ... 108 LE ALTRE ISTRUZIONI GUARDIANE. FINALLY... 109 DEFINIRE ECCEZIONI PERSONALIZZATE ... 109 UN ESEMPIO COMPLETO... 110 CAPITOLO 8 ... 113 POLIMORFISMO ED EREDITARIET AVANZATA ... 113 INTRODUZIONE ... 113 POLIMORFISMO : UNINTERFACCIA, MOLTI METODI... 113 INTERFACCE ... 114 DEFINIZIONE DI UNA INTERFACCIA... 114 IMPLEMENTARE UNA INTERFACCIA ... 114 EREDITARIET MULTIPLA IN JAVA ... 115 CLASSI ASTRATTE ... 116 CAPITOLO 9 ... 118 <NAME> http://www.java-net.tv <EMAIL> 9 JAVA THREADS ... 118 INTRODUZIONE ... 118 THREAD DI SISTEMA ... 118 LA CLASSE JAVA.LANG.THREAD ... 119 INTERFACCIA RUNNABLE... 120 SINCRONIZZARE THREAD ... 121 LOCK ... 122 SINCRONIZZAZIONE DI METODI STATICI... 123 BLOCCHI SINCRONIZZATI ... 124 LABORATORIO 9 ... 125 JAVA THREAD ... 125 ESERCIZIO 1... 125 ESERCIZIO 2... 125 SOLUZIONE AL PRIMO ESERCIZIO ... 126 SOLUZIONE AL SECONDO ESERCIZIO... 126 CAPITOLO 11 ... 129 JAVA NETWORKING... 129 INTRODUZIONE ... 129 I PROTOCOLLI DI RETE (INTERNET) ... 129 INDIRIZZI IP... 130 COMUNICAZIONE CONNECTION ORIENTED O CONNECTIONLESS ... 132 DOMAIN NAME SYSTEM : RISOLUZIONE DEI NOMI DI UN HOST ... 133 URL... 135 TRASMISSION CONTROL PROTOCOL : TRASMISSIONE CONNECTION ORIENTED ..........135 USER DATAGRAM PROTOCOL : TRASMISSIONE CONNECTIONLESS ... 137 IDENTIFICAZIONE DI UN PROCESSO : PORTE E SOCKET ... 137 IL PACKAGE JAVA.NET ... 139 UN ESEMPIO COMPLETO DI APPLICAZIONE CLIENT/SERVER... 140 LA CLASSE SERVERSOCKET ... 142 LA CLASSE SOCKET ... 142 UN SEMPLICE THREAD DI SERVIZIO ... 143 TCP SERVER ... 143 IL CLIENT ... 145 CAPITOLO 12 ... 147 JAVA ENTERPRISE COMPUTING... 147 INTRODUZIONE ... 147 ARCHITETTURA DI J2EE... 148 J2EE APPLICATION MODEL... 150 CLIENT TIER ... 151 WEB TIER ... 152 BUSINESS TIER... 153 EIS-TIER ... 155 <NAME> http://www.java-net.tv <EMAIL> 10 LE API DI J2EE ... 156 JDBC : JAVA DATABASE CONNECTIVITY ... 156 RMI : REMOTE METHOD INVOCATION... 158 JAVA IDL ... 159 JNDI ... 159 JMS ... 160 CAPITOLO 13 ... 162 ARCHITETTURA DEL WEB TIER... 162 INTRODUZIONE ... 162 LARCHITETTURA DEL WEB TIER... 162 INVIARE DATI ... 164 SVILUPPARE APPLICAZIONI WEB ... 165 COMMON GATEWAY INTERFACE ... 165 ISAPI ED NSAPI... 166 ASP ACTIVE SERVER PAGES ... 166 JAVA SERVLET E JAVASERVER PAGES ... 167 CAPITOLO 14 ... 168 JAVA SERVLET API ... 168 INTRODUZIONE ... 168 IL PACKAGE JAVAX.SERVLET ... 168 IL PACKAGE JAVAX.SERVLET.HTTP... 169 CICLO DI VITA DI UNA SERVLET ... 170 SERVLET E MULTITHREADING ... 171 LINTERFACCIA SINGLETHREADMODEL ... 172 UN PRIMO ESEMPIO DI CLASSE SERVLET ... 172 IL METODO SERVICE()... 173 CAPITOLO 15 ... 175 SERVLET HTTP... 175 INTRODUZIONE ... 175 IL PROTOCOLLO HTTP 1.1 ... 175 RICHIESTA HTTP... 176 RISPOSTA HTTP ... 178 ENTIT ... 179 I METODI DI REQUEST ... 180 INIZIALIZZAZIONE DI UNA SERVLET ... 180 LOGGETTO HTTPSERVLETRESPONSE ... 181 I METODI SPECIALIZZATI DI HTTPSERVLETRESPONSE ... 183 NOTIFICARE ERRORI UTILIZZANDO JAVA SERVLET ... 184 LOGGETTO HTTPSERVLETREQUEST ... 184 INVIARE DATI MEDIANTE LA QUERY STRING ... 186 QUERY STRING E FORM HTML ... 187 I LIMITI DEL PROTOCOLLO HTTP : COOKIES ... 189 <NAME> http://www.java-net.tv <EMAIL> 11 MANIPOLARE COOKIES CON LE SERVLET ... 189 UN ESEMPIO COMPLETO... 190 SESSIONI UTENTE ... 191 SESSIONI DAL PUNTO DI VISTA DI UNA SERVLET... 191 LA CLASSE HTTPSESSION ... 192 UN ESEMPIO DI GESTIONE DI UNA SESSIONE UTENTE ... 193 DURATA DI UNA SESSIONE UTENTE ... 194 URL REWRITING ... 194 CAPITOLO 16 ... 196 JAVASERVER PAGES ... 196 INTRODUZIONE ... 196 JAVASERVER PAGES ... 196 COMPILAZIONE DI UNA PAGINA JSP... 198 SCRIVERE PAGINE JSP... 198 INVOCARE UNA PAGINA JSP DA UNA SERVLET ... 199 CAPITOLO 17 ... 201 JAVASERVER PAGES NOZIONI AVANZATE... 201 INTRODUZIONE ... 201 DIRETTIVE ... 201 DICHIARAZIONI... 202 SCRIPTLETS ... 202 OGGETTI IMPLICITI : REQUEST ... 203 OGGETTI IMPLICITI : RESPONSE... 203 OGGETTI IMPLICITI : SESSION... 204 CAPITOLO 18 ... 205 JDBC ... 205 INTRODUZIONE ... 205 ARCHITETTURA DI JDBC ... 205 DRIVER DI TIPO 1 ... 206 DRIVER DI TIPO 2 ... 207 DRIVER DI TIPO 3 ... 207 DRIVER DI TIPO 4 ... 209 UNA PRIMA APPLICAZIONE DI ESEMPIO... 209 RICHIEDERE UNA CONNESSIONE AD UN DATABASE ... 211 ESEGUIRE QUERY SUL DATABASE... 212 LOGGETTO RESULTSET ... 212 APPENDICE A ... 216 JAVA TIME-LINE ... 216 1995-1996... 216 1997... 216 <NAME> http://www.java-net.tv <EMAIL> 12 1998... 217 1999... 218 2000... 219 APPENDICE B... 220 GLOSSARIO DEI TERMINI ... 220 BIBLIOGRAFIA... 224 <NAME> http://www.java-net.tv <EMAIL> 13 Java Mattone dopo Mattone Introduzione Premesse La guerra dei desktop ormai persa, ma con Java 2 Enterprise Edition la Sun Microsystem ha trasformato un linguaggio in una piattaforma di sviluppo integrata diventata ormai standard nel mondo del Server Side Computing. Per anni, il mondo della IT ha continuato a spendere soldi ed energie in soluzioni proprietarie tra loro disomogenee dovendo spesso reinvestire in infrastrutture tecnologiche per adattarsi alle necessit emergenti di mercato. Nella ultima decade di questo secolo con la introduzione di tecnologie legate ad Internet e pi in generale alle reti, lindustria del software ha immesso sul mercato circa 30 application server, ognuno con un modello di programmazione specifico. Con la nascita di nuovi modelli di business legati al fenomeno della neweconomy, la divergenza di tali tecnologie diventata in breve tempo un fattore destabilizzante ed il maggior ostacolo alla innovazione tecnologica. Capacit di risposta in tempi brevi e produttivit con lunghi margini temporali sono diventate oggi le chiavi del successo di applicazioni enterprise. Con la introduzione della piattaforma J2EE, la Sun ha proposto non pi una soluzione proprietaria, ma una architettura basata su tecnologie aperte e portabili proponendo un modello in grado di accelerare il processo di implementazione di soluzioni server-sideattraverso lo sviluppo di funzionalit nella forma di Enterprise Java Beans in grado di girare su qualsiasi application server compatibile con lo standard. Oltre a garantire tutte le caratteristiche di portabilit (Write Once Run Everywhere) del linguaggio Java, J2EE fornisce: Un modello di sviluppo semplificato per l enterprise computing - La piattaforma offre ai vendors di sistemi la capacit di fornire una soluzione che lega insieme molti tipi di middleware in un unico ambiente, riducendo tempi di sviluppo e costi necessari alla integrazioni di componenti software di varia natura. J2EE permette di creare ambienti server side contenenti tutti i middletiers di tipo server come connettivit verso database, ambienti transazionale, servizi di naming ecc.; Una architettura altamente scalabile - La piattaforma fornisce la scalabilit necessaria allo sviluppo di soluzione in ambienti dove le applicazioni scalano da prototipo di lavoro ad architetture 24x7 enterprise wide; Legacy Connectivity La piattaforma consente lintegrabilit di soluzioni pre esistenti in ambienti legacy consentendo di non reinvestire in nuove soluzioni; Piattaforme Aperte J2EE uno standard aperto. La Sun in collaborazione con partner tecnologici garantisce ambienti aperti per specifiche e portabilit; Sicurezza La piattaforma fornisce un modello di sicurezza in grado di proteggere dati in applicazioni Internet; Alla luce di queste considerazioni si pu affermare che la soluzione offerta da Sun abbia traghettato lenterprise computingin una nuova era in cui le applicazioni usufruiranno sempre pi di tutti i vantaggi offerti da uno standard aperto. <NAME> http://www.java-net.tv <EMAIL> 14 <NAME> http://www.java-net.tv <EMAIL> 15 Parte Prima La programmazione Object Oriented <NAME> http://www.java-net.tv <EMAIL> 16 Capitolo 1 Introduzione alla programmazione Object Oriented Introduzione Questo capitolo dedicato al paradigma Object Orientede cerca di fornire ai neofiti della programmazione in Java i concetti base necessari allo sviluppo di applicazioni Object Oriented. In realt le problematiche che andremo ad affrontare nei prossimi paragrafi sono estremamente complesse e trattate un gran numero di testi che non fanno alcuna menzione a linguaggi di programmazione, quindi limiter la discussione soltanto ai concetti pi importanti. Procedendo nella comprensione del nuovo modello di programmazione risulter chiara levoluzione che, a partire dallapproccio orientato a procedure e funzioni e quindi alla programmazione dal punto di vista del calcolatore, porta oggi ad un modello di analisi che, partendo dal punto di vista dellutente suddivide lapplicazione in concetti rendendo il codice pi comprensibile e semplice da mantenere. Il modello classico conosciuto come paradigma procedurale, pu essere riassunto in due parole: Divide et Impera ossia dividi e conquista. Difatti secondo il paradigma procedurale, un problema complesso viene suddiviso in problemi pi semplici in modo che siano facilmente risolvibili mediante programmi procedurali. E chiaro che in questo caso, lattenzione del programmatore accentrata al problema. A differenza del primo, il paradigma Object Oriented accentra lattenzione verso dati. Lapplicazione viene suddivisa in un insieme di oggetti in grado di interagire tra di loro e codificati in modo tale che la macchina sia in gradi di comprenderli. Il primo cambiamento evidente quindi a livello di disegno della applicazione. Di fatto lapproccio Object Oriented non limitato a linguaggi come Java o C++ . Molte applicazione basate su questo modello sono state scritte con linguaggi tipo C o Assembler. Un linguaggio Object Oriented semplifica il meccanismo di creazione degli Oggetti allo stesso modo con cui un linguaggio procedurale semplifica la decomposizione in funzioni. Figura 1-1 : Evoluzione del modello di programmazione <NAME> http://www.java-net.tv <EMAIL> 17 Una evoluzione necessaria Quando i programmi erano scritti in assembler, ogni dato era globale e le funzioni andavano disegnate a basso livello. Con lavvento dei linguaggi procedurali come il linguaggio C, i programmi sono diventati pi robusti e semplici da mantenere inquanto il linguaggio forniva regole sintattiche e semantiche che supportate da un compilatore consentivano un maggior livello di astrazione rispetto a quello fornito dallassembler fornendo un ottimo supporto alla decomposizione procedurale della applicazione. Con laumento delle prestazione dei calcolatori e di conseguenza con laumento della complessit delle applicazioni, lapproccio procedurale ha iniziato a mostrare i propri limiti rendendo necessario definire un nuovo modello e nuovi linguaggi di programmazione. Questa evoluzione stata schematizzata nella figura 1-1. I linguaggi come Java e C++ forniscono il supporto ideale al disegno ad oggetti di applicazioni fornendo un insieme di regole sintattiche e semantiche che aiutano nello sviluppo di oggetti. Il paradigma procedurale Secondo il paradigma procedurale il programmatore analizza il problema ponendosi dal punto di vista del computer che solamente istruzioni semplici e, di conseguenza adotta un approccio di tipo divide et impera1. Il programmatore sa perfettamente che una applicazione per quanto complessa pu essere suddivisa in step di piccola entit. Questo approccio stato formalizzato in molti modi ed ben supportato da molti linguaggi che forniscono al programmatore un ambiente in cui siano facilmente definibili procedure e funzioni. Le procedure sono blocchi di codice riutilizzabile che possiedono un proprio insieme di dati e realizzano specifiche funzioni. Le funzioni una volta scritte possono essere richiamate ripetutamente in un programma, possono ricevere parametri che modificano il loro stato e possono tornare valori al codice chiamante. Una volta scritte, le procedure possono essere legate assieme a formare un applicazione. Allinterno della applicazione quindi necessario che i dati vengano condivisi tra loro. Questo meccanismo si risolve mediante luso di variabili globali, passaggio di parametri e ritorno di valori. Una applicazione procedurale tipica ed il suo diagramma di flusso riassunta nella Figura 1-2. Luso di variabili globali genera per problemi di protezione dei dati quando le procedure si richiamano tra di loro. Per esempio nella applicazione mostrata nella Figura 1-2, la procedura outputesegue una chiamata a basso livello verso il terminale e pu essere chiamata soltanto dalla procedura print la quale a sua volta modifica dati globali. Dal momento che le procedure non sono auto-documentanti(self-documenting) ossia non rappresentano entit ben definite, un programmatore dovendo modificare la applicazione e non conoscendone a fondo il codice, potrebbe utilizzare la routine Output senza chiamare la procedura Print dimenticando quindi laggiornamento dei dati globali a carico di Print e producendo di conseguenza effetti indesiderati (side-effects) difficilmente gestibili. 1 Divide et Impera ossia dividi e conquista era la tecnica utilizzata dagli antichi romani che sul campo di battaglia dividevano le truppe avversarie per poi batterle con pochi sforzi. <NAME> http://www.java-net.tv <EMAIL> 18 Figura 1-2 : Diagramma di una applicazione procedurale Per questo motivo, le applicazioni basate sul modello procedurale sono difficili da aggiornare e controllare con meccanismi di debug. I bug derivanti da side-effects possono presentarsi in qualunque punto del codice causando una propagazione incontrollata dellerrore. Ad esempio riprendendo ancora la nostra applicazione, una gestione errata dei dati globali dovuta ad una mancata chiamata a Print potrebbe avere effetto su f4()che a sua volta propagherebbe lerrore ad f2()ed f3()fino al maindel programma causando la terminazione anomala del processo. Correggere gli errori procedurali Per risolvere i problemi presentati nel paragrafo precedente i programmatori hanno fatto sempre pi uso di tecniche mirate a proteggere dati globali o funzioni nascondendone il codice. Un modo sicuramente spartano, ma spesso utilizzato, consisteva nel nascondere il codice di routine sensibili (Outputnel nostro esempio) allinterno di librerie contando sul fatto che la mancanza di documentazione scoraggiasse un nuovo programmatore ad utilizzare impropriamente queste funzioni. Il linguaggio C fornisce strumenti mirati alla circoscrizione del problema come il modificatore static con il fine di delimitare sezioni di codice di una applicazione in grado di accedere a dati globali, eseguire funzioni di basso livello o, evitare direttamente luso di variabili globali. Quando si applica il modificatore static ad una variabile locale, viene allocata per la variabile della memoria permanente in modo molto simile a quanto avviene per le variabili globali. Questo meccanismo consente alla variabile dichiarata static di mantenere il proprio valore tra due chiamate successive ad una funzione. A differenza di una variabile locale non statica il cui ciclo di vita (di conseguenza il valore) limitato al tempo necessario per la esecuzione della funzione, il valore di una variabile dichiarata static non andr perduto tra chiamate successive. La differenza sostanziale tra una variabile globale ed una variabile locale static che la seconda nota solamente al blocco in cui dichiarata ossia una variabile globale con scopo limitato, vengono inizializzate solo una volta allavvio del Massimiliano Tarquini http://www.java-net.tv <EMAIL> 19 programma e non ogni volta che si effettui una chiamata alla funzione in cui sono definite. Supponiamo ad esempio di voler scrivere che calcoli la somma di numeri interi passati ad uno ad uno per parametro. Grazie alluso di variabili static sar possibile risolvere il problema nel modo seguente : int _sum (int i) { static int sum=0; sum=sum+I; return sum; } Usando una variabile static, la funzione in grado di mantenere il valore della variabile tra chiamate successive evitando luso di variabili globali. Il modificatore static pu essere utilizzato anche con variabili globali. Difatti, se applicato ad un dato globale indica al compilatore che la variabile creata dovr essere nota solamente alle funzioni dichiarate nello stesso file contenente la dichiarazione della variabile. Stesso risultato lo otterremmo applicando il modificatore ad una funzione o procedura. Questo meccanismo consente di suddividere applicazioni procedurali in moduli. Un modulo un insieme di dati e procedure logicamente correlate tra di loro in cui le parti sensibili possono essere isolate in modo da poter essere chiamate solo da determinati blocchi di codice. Il processo di limitazione dellaccesso a dati o funzioni conosciuto come incapsulamento. Un esempio tipico di applicazione suddivisa in moduli schematizzato nella figura 1-3 nella quale rappresentata una nuova versione del modello precedentemente proposto. Il modulo di I/O mette a disposizione degli altri moduli la funzione Printincapsulando la routine Outputed i dati sensibili. Figura 1-3 : Diagramma di una applicazione procedurale suddiviso per moduli Questa evoluzione del modello fornisce numerosi vantaggi; i dati ora non sono completamente globali e risultano quindi pi protetti che nel modello precedente, limitando di conseguenza i danni causati da propagazioni anomale dei bug. Inoltre il <NAME> http://www.java-net.tv <EMAIL> 20 numero limitato di procedure pubbliche viene in aiuto ad un programmatore che inizi a studiare il codice della applicazione. Questo nuovo modello si avvicina molto al modello proposto dallapproccio Object Oriented. Il paradigma Object Oriented Il paradigma Object Oriented formalizza la tecnica vista in precedenza di incapsulare e raggruppare parti di un programma. In generale, il programmatore divide le applicazioni in gruppi logici che rappresentano concetti sia a livello di utente che a livello applicativo. I pezzi che vengono poi riuniti a formare una applicazione. Scendendo nei dettagli, il programmatore ora inizia con lanalizzare tutti i singoli aspetti concettuali che compongono un programma. Questi concetti sono chiamati oggetti ed hanno nomi legati a ci che rappresentano. Una volta che gli oggetti sono identificati, il programmatore decide di quali attributi (dati) e funzionalit (metodi) dotare le entit. Lanalisi infine dovr includere le modalit di interazione tra gli oggetti. Proprio grazie a queste interazioni sar possibile riunire gli oggetti a formare un applicazione. A differenza di procedure e funzioni, gli oggetti sono auto-documentanti (selfdocumenting). Una applicazione pu essere scritta a partire da poche informazioni ed in particolar modo il funzionamento interno delle funzionalit di ogni oggetto completamente nascosto al programmatore (Incapsulamento Object Oriented). Classi di Oggetti Concentriamoci per qualche istante su alcuni concetti tralasciando laspetto tecnico del paradigma object oriented e proviamo per un istante a pensare ad un libro. Quando pensiamo ad un libro pensiamo subito ad una classe di oggetti aventi caratteristiche comuni: tutti i libri contengono delle pagine, ogni pagina contiene del testo e le note sono scritte a fondo pagina. Altra cosa che ci viene subito in mente riguarda le azioni che tipicamente compiamo quando utilizziamo un libro: voltare pagina, leggere il testo, guardare le figure etc. E interessante notare che utilizziamo il termine libro per generalizzare un concetto relativo a qualcosa che contiene pagine da sfogliare, da leggere o da strappare ossia ci riferiamo ad un insieme di oggetti con attributi comuni, ma comunque composto da entit aventi ognuna caratteristiche proprie che rendono ognuna differente rispetto allaltra. Pensiamo ora ad un libro scritto in francese. Ovviamente sar comprensibile soltanto a persone in grado di comprendere questa lingua; daltro canto possiamo comunque guardarne i contenuti (anche se privi di senso), sfogliarne le pagine o scriverci dentro. Questo insieme generico di propriet rende un libro utilizzabile da chiunque a prescindere dalle caratteristiche specifiche (nel nostro caso la lingua). Possiamo quindi affermare che un libro un oggetto che contiene pagine e contenuti da guardare e viceversa ogni oggetto contenente pagine e contenuti da guardare pu essere classificato come un libro. Abbiamo quindi definito una categoria di oggetti che chiameremo classe e che, nel nostro caso, fornisce la descrizione generale del concetto di libro. Ogni nuovo libro con caratteristiche proprie apparterr comunque a questa classe base. Ereditariet Con la definizione di una classe, nel paragrafo precedente abbiamo stabilito che un libro contiene pagine che possono essere girate, scarabocchiate, strappate etc. <NAME> http://www.java-net.tv <EMAIL> 21 Figura 1-4 : Diagramma di una applicazione procedurale suddiviso per moduli Stabilita la classe base, possiamo creare tanti libri purch aderiscano alle regole definite (Figura 1-4). Il vantaggio maggiore nellaver stabilito questa classificazione che ogni persona deve conoscere solo le regole base per essere in grado di poter utilizzare qualsiasi libro. Una volta assimilato il concetto di pagina che pu essere sfogliata, si in grado di utilizzare qualsiasi entit classificabile come libro. Il concetto di ereditariet nella programmazione Se estendiamo i concetti illustrati alla programmazione iniziamo ad intravederne i reali vantaggi. Una volta stabilite le categorie di base, possiamo utilizzarle per creare tipi specifici di oggetti ereditando e specializzando le regole base. Figura 1-5 : Diagramma di ereditariet <NAME> http://www.java-net.tv <EMAIL> 22 Per definire questo tipo di relazioni viene utilizzata una forma a diagramma in cui la classe generica riportata come nodo sorgente di un grafo orientato i cui sotto nodi rappresentano categorie pi specifiche e gli archi che uniscono i nodi sono orientati da specifico a generale (Figura 1-5). Un linguaggio orientato ad oggetti fornisce al programmatore strumenti per rappresentare queste relazioni. Una volta definite classi e relazioni, sar possibile mediante il linguaggio implementare applicazioni in termini di classi generiche; questo significa che una applicazione sar in grado di utilizzare ogni oggetto specifico senza essere necessariamente riscritta, ma limitando le modifiche alle funzionalit fornite dalloggetto per manipolare le sue propriet. Vantaggi nelluso dellereditariet Come facile intravedere, lorganizzazione degli oggetti fornita dal meccanismo di ereditariet rende semplici le operazioni di manutenzione di una applicazione. Ogni volta che si renda necessaria una modifica, in genere sufficiente creare un nuovo oggetto allinterno di una classe di oggetti ed utilizzarlo per rimpiazzare uno vecchio ed obsoleto. Un altro vantaggio della ereditariet la re-utilizzabilit del codice. Creare una classe di oggetti per definire entit molto di pi che crearne una semplice rappresentazione: per la maggior parte delle classi limplementazione spesso scritta allinterno della descrizione. In Java ad esempio ogni volta che definiamo un concetto, esso viene definito come una classe allinterno della quale viene scritto il codice necessario ad implementare le funzionalit delloggetto per quanto generico esso sia. Se viene creato un nuovo oggetto (e quindi una nuova classe) a partire da un oggetto (classe) esistente si dice che la nuova classe deriva dalla originale. Quando questo accade, tutte le caratteristiche delloggetto principale diventano parte della nuova classe. Dal momento che la classe derivata eredita le funzionalit della classe predecessore, lammontare del codice da necessario per la nuova classe pesantemente ridotto: il codice della classe di origine stato riutilizzato. A questo punto necessario iniziare a definire formalmente alcuni termini. La relazione di ereditariet tra classi espressa in termini di superclasse e sottoclasse. Una superclasse la classe pi generica utilizzata come punto di partenza per derivare nuove classi. Una sottoclasse rappresenta invece una specializzazione di una superclasse. Euso comune chiamare una superclasse classe basee una sottoclasse classe derivata. Questi termini sono comunque relativi in quanto una classe derivata pu a sua volta essere una classe base per una classe pi specifica. Programmazione object oriented ed incapsulamento Come gi ampiamente discusso, nella programmazione orientata ad oggetti definiamo oggetti creando rappresentazioni di entit o nozioni da utilizzare come parte di unapplicazione. Per assicurarci che il programma lavori correttamente ogni oggetto deve rappresentare in modo corretto il concetto di cui modello senza che lutente possa disgregarne lintegrit. Per fare questo importante che loggetto esponga solo la porzione di codice e dati che il programma deve utilizzare. Ogni altro dato e codice deve essere nascosto affinch sia possibile mantenere loggetto in uno stato consistente. Ad esempio se un <NAME> http://www.java-net.tv <EMAIL> 23 oggetto rappresenta uno stack2 di dati (figura 1-6), lapplicazione dovr poter accedere solo al primo dato dello stack ossia alle funzioni di Push e Pop. Il contenitore ed ogni altra funzionalit necessaria alla sua gestione dovr essere protetta rispetto alla applicazione garantendo cos che lunico errore in cui si pu incorrere quello di inserire un oggetto sbagliato in testa allo stack o estrapolare pi dati del necessario. In qualunque caso lapplicazione non sar mai in grado di creare inconsistenze nello stato del contenitore. Lincapsulamento inoltre localizza tutti i possibili problemi in porzioni ristrette di codice. Una applicazione potrebbe inserire dati sbagliati nello Stack, ma saremo comunque sicuri che lerrore localizzato allesterno delloggetto. Figura 1-6 : Stack di dati I vantaggi dellincapsulamento Una volta che un oggetto stato incapsulato e testato, tutto il codice ed i dati associati sono protetti. Modifiche successive al programma non potranno causare rotture nelle le dipendenze tra gli oggetti inquanto non saranno in grado di vedere i legami tra dati ed entit. Leffetto principale sulla applicazione sar quindi quello di localizzare i bugs evitando la propagazione di errori, dotando la applicazione di grande stabilit. In un programma decomposto per funzioni, le procedure tendono ad essere interdipendenti. Ogni modifica al programma richiede spesso la modifica di funzioni condivise cosa che pu propagare un errore alle componenti del programma che le utilizzano. In un programma object oriented, le dipendenze sono sempre strettamente sotto controllo e sono mascherate allinterno delle entit concettuali. Modifiche a programmi di questo tipo riguardano tipicamente la aggiunta di nuovi oggetti, ed il meccanismo di ereditariet ha leffetto di preservare lintegrit referenziale delle entit componenti la applicazione. Se invece fosse necessario modificare internamente un oggetto, le modifiche sarebbero comunque limitate al corpo dellentit e quindi confinate allinterno delloggetto che impedir la propagazione di errori allesterno del codice. 2 Uno Stack di dati una struttura a pila allinterno della quale possibile inserire dati solo sulla cima ed estrarre solo lultimo dato inserito. <NAME> http://www.java-net.tv <EMAIL> 24 Anche le operazioni di ottimizzazione risultano semplificate. Quando un oggetto risulta avere performance molto basse, si pu cambiare facilmente la sua struttura interna senza dovere riscrivere il resto del programma, purch le modifiche non tocchino le propriet gi definite delloggetto. Alcune buone regole per creare oggetti Un oggetto deve rappresentare un singolo concetto ben definito. Rappresentare piccoli concetti con oggetti ben definiti aiuta ad evitare confusione inutile allinterno della applicazione. Il meccanismo dellereditariet rappresenta uno strumento potente per creare concetti pi complessi a partire da concetti semplici. Un oggetto deve rimanere in uno stato consistente per tutto il tempo che viene utilizzato, dalla sua creazione alla sua distruzione. Qualunque linguaggio di programmazione venga utilizzato, bisogna sempre mascherare limplementazione di un oggetto al resto della applicazione. Lincapsulamento una ottima tecnica per evitare effetti indesiderati e spesso incontrollabili. Fare attenzione nellutilizzo della ereditariet. Esistono delle circostanze in cui la convenienza sintattica della ereditariet porta ad un uso inappropriato della tecnica. Per esempio una lampadina pu essere accesa o spenta. Usando il meccanismo della ereditariet sarebbe possibile estendere queste sue propriet ad un gran numero di concetti come un televisore, un fon etc.. Il modello che ne deriverebbe sarebbe inconsistente e confuso. <NAME> http://www.java-net.tv <EMAIL> 25 Capitolo 2 Introduzione al linguaggio Java Introduzione Java un linguaggio di programmazione object oriented indipendente dalla piattaforma, modellato a partire dai linguaggi C e C++ di cui mantiene caratteristiche. Lindipendenza dalla piattaforma ottenuta grazie alluso di uno strato software chiamato Java Virtual Machine che traduce le istruzioni dei codici binari indipendenti dalla piattaforma generati dal compilatore java, in istruzioni eseguibili dalla macchina locale (Figura 2-1). La natura di linguaggio a oggetti di Java consente di sviluppare applicazioni utilizzando oggetti concettuali piuttosto che procedure e funzioni. La sintassi object oriented di Java supporta la creazione di oggetti concettuali, il che consente al programmatore di scrivere codice stabile e riutilizzabile utilizzando il paradigma object oriented secondo il quale il programma viene scomposto in concetti piuttosto che funzioni o procedure. La sua stretta parentela con il linguaggio C a livello sintattico fa si che un programmatore che abbia gi fatto esperienza con linguaggi come C, C++, Perl sia facilitato nellapprendimento del linguaggio. In fase di sviluppo, lo strato che rappresenta la virtual machine pu essere creato mediante il comando java anche se molti ambienti sono in grado di fornire questo tipo di supporto. Esistono inoltre compilatori specializzati o jit (Just In Time) in grado di generare codice eseguibile dipendente dalla piattaforma. Infine Java contiene alcune caratteristiche che lo rendono particolarmente adatto alla programmazione di applicazioni web (client-side e server-side). La storia di Java Durante laprile del 1991, un gruppo di impiegati della SUN Microsystem, conosciuti come Green Group iniziarono a studiare la possibilit di creare una tecnologia in grado di integrare le allora attuali conoscenze nel campo del software con lelettronica di consumo. Avendo subito focalizzato il problema sulla necessit di avere un linguaggio indipendente dalla piattaforma (il software non doveva essere legato ad un particolare processore) il gruppo inizi i lavori nel tentativo di creare un linguaggio che estendesse il C++. La prima versione del linguaggio fu chiamata Oak e, successivamente per motivi di royalty Java. Attraverso una serie di eventi, quella che era la direzione originale del progetto sub vari cambiamenti ed il target fu spostato dallelettronica di consumo al world wide web. Il 23 Maggio del 1995 la SUN ha annunciato formalmente Java. Da quel momento in poi il linguaggio stato adottato da tutti i maggiori vendorsdi software incluse IBM, Hewlett Packard e Microsoft. In appendice riportata la Time line della storia del linguaggio a partire dal maggio 1995. I dati sono stati recuperati dal sito della SUN Microsystem allindirizzo http://java.sun.com/features/2000/06/time-line.html. Le caratteristiche principali di Java Indipendenza dalla piattaforma Le istruzioni binarie di Java indipendenti dalla piattaforma sono pi comunemente conosciuto come Bytecodes. Il Bytecodes di java prodotto dal compilatore e <NAME> http://www.java-net.tv <EMAIL> 26 necessita di uno strato di software, la Java Virtual Machine (che per semplicit indicheremo con JVM), per essere eseguito (Figura 2-1). La JVM un programma scritto mediante un qualunque linguaggio di programmazione dipendente dalla piattaforma, e traduce le istruzioni Java, nella forma di Bytecodes, in istruzioni native del processore locale. Figura 2-1: architettura di una applicazione Java Non essendo il Bytecodes legato ad una particolare architettura Hardware, questo fa si che per trasferire una applicazione Java da una piattaforma ad unaltra necessario solamente che la nuova piattaforma sia dotata di una apposita JVM. In presenza di un interprete una applicazione Java potr essere eseguita su qualunque piattaforma senza necessit di essere ricompilata. In alternativa, si possono utilizzare strumenti come i Just In Time Compilers, compilatori in grado di tradurre il Bytecodes in un formato eseguibile su una specifica piattaforma al momento della esecuzione del programma Java. I vantaggi nelluso dei compilatori JIT sono molteplici. La tecnologia JIT traduce il bytecodes in un formato eseguibile al momento del caricamento della applicazione. Ci consente di migliorare le performance della applicazione che non dovr pi passare per la virtual machine, e allo stesso tempo preserva la caratteristica di portabilit del codice. Lunico svantaggio nelluso di un JIT sta nella perdita di prestazioni al momento del lancio della applicazione che deve essere prima compilata e poi eseguita. Un ultimo aspetto interessante della tecnologia Java quello legato agli sviluppi che la tecnologia sta avendo. Negli ultimi anni molti produttori di hardware anno iniziato a rilasciare processori in grado di eseguire direttamente il Bytecode di Java a livello di istruzioni macchina senza luso di una virtual machine. <NAME> http://www.java-net.tv <EMAIL> 27 Le caratteristiche principali di Java Uso della memoria e multi-threading Un problema scottante quando si parla di programmazione la gestione luso della memoria. Uno dei problemi pi complessi da affrontare quando si progetta una applicazione di fatto proprio quello legato al mantenimento degli spazi di indirizzamento del programma, con il risultato che spesso necessario sviluppare complesse routine specializzate nella gestione e tracciamento della memoria assegnata alla applicazione. Java risolve il problema alla radice sollevando direttamente il programmatore dallonere della gestione della memoria grazie ad un meccanismo detto Garbage Collector. Il Garbage Collector, tiene traccia degli oggetti utilizzati da una applicazione Java, nonch delle referenze a tali oggetti. Ogni volta che un oggetto non pi referenziato per tutta la durata di una specifica slide di tempo, viene rimosso dalla memoria e la risorsa liberata viene di nuovo messa a disposizione della applicazione che potr continuare a farne uso. Questo meccanismo in grado di funzionare correttamente in quasi tutti i casi anche se molto complessi, ma non si pu dire che completamente esente da problemi. Esistono infatti dei casi documentati di fronte ai quali il Garbage Collector non in grado di intervenire. Un caso tipico quello della referenza circolare in cui un oggetto A referenzia un oggetto B e viceversa, ma la applicazione non sta utilizzando nessuno dei due come schematizzato nella figura 2-2. Figura 2-2: riferimento circolare Java un linguaggio multi-threaded. Il multi-threading consente ad applicazioni Java di sfruttare il meccanismo di concorrenza logica. Parti separate di un programma possono essere eseguite come se fossero (dal punto di vista del programmatore) processate parallelamente. Luso di thread rappresenta un modo semplice di gestire la concorrenza tra processi inquanto gli spazi di indirizzamento della memoria della applicazione sono condivisi con i thread eliminando cos la necessit di sviluppare complesse procedure di comunicazione tra processi. Infine Java supporta il metodo detto di Dynamic Loading and Linking. Secondo questo modello, ogni modulo del programma (classe) memorizzato in un determinato file. Quando un programma Java viene eseguito, le classi vengono caricate e stanziate solo al momento del loro effettivo utilizzo. Una applicazione composta da molte classi caricher solamente quelle porzioni di codice che debbono essere eseguite in un determinato istante. Java prevede un gran numero di classi pre-compilate che forniscono molte funzionalit come strumenti di i/o o di networking. <NAME> http://www.java-net.tv <EMAIL> 28 Meccanismo di caricamento delle classi da parte della JVM Quando la JVM viene avviata, il primo passo che deve compiere quello di caricare le classi necessarie allavvio della applicazione. Questa fase avviene secondo uno schema temporale ben preciso e schematizzato nella figura 2-3, ed a carico di un modulo interno chiamato launcher. Figura 2-3: schema temporale del caricamento delle classi della JVM Le prime ad essere caricate sono le classi di base necessarie alla piattaforma Java per fornire lo strato di supporto alla applicazione a cui fornir lambiente di runtime. Il secondo passo caricare le classi Java appartenenti alle librerie di oggetti messi a disposizione dalla SUN ed utilizzate allinterno della applicazione. Infine vengono caricate le classi componenti lapplicazione e definite dal programmatore. Per consentire al launcher di trovare le librerie e le classi utente, necessario specificare esplicitamente la loro locazione su disco. Per far questo necessario definire una variabile di ambiente chiamata CLASSPATH che viene letta sia in fase di compilazione, sia in fase di esecuzione della applicazione. La variabile di ambiente CLASSPATH contiene una serie di stringhe suddivise dal carattere ; e rappresentanti ognuna il nome completo di una archivio3 di classi (files con estensione .jar e .zip) o di una directory contenete file con estensione .class . Ad esempio, se la classe MiaClasse.java memorizzata su disco nella directory c:\java\mieclassi , la variabile classpath dovr contenere una stringa del tipo: CLASSPATH=.;.\;c:\java\mieclassi\; . I valori . E .\ indicano alla JVM che le classi definite dallutente si trovano allinterno della directory corrente o in un package definito a partire dalla directory corrente. Il Java Development Kit (JDK) Java Development Kit un insieme di strumenti ed utilit ed messo a disposizione gratuitamente da tanti produttori di software. Linsieme base o standard delle funzionalit supportato direttamente da SUN Microsystem ed include un compilatore (javac), una Java Virtual Machine (java), un debugger e tanti altri strumenti necessari allo sviluppo di applicazioni Java. Inoltre il JDK comprende, oltre alle utilit a linea di comando, un completo insieme di classi pre-compilate ed il relativo codice sorgente. La documentazione generalmente distribuita separatamente, rilasciata in formato HTML (Figura2-4) e copre tutto linsieme delle classi rilasciate con il JDK a cui da ora in poi ci riferiremo come alle Java API (Application Program Interface). 3 Gli archivi di classi verranno trattati esaustivamente nei capitoli successivi. <NAME> http://www.java-net.tv <EMAIL> 29 Figura 2-4: Java Doc Scaricare ed installare il JDK Questo testo fa riferimento alla ultima versione del Java Development Kit rilasciata da SUN nel corso del 2000: il JDK 1.3 . JDK pu essere scaricato gratuitamente insieme a tutta la documentazione dal sito della SUN (http://www.javasoft.com), facendo ovviamente attenzione che il prodotto che si sta scaricando sia quello relativo alla piattaforma da utilizzare. Linstallazione del prodotto semplice e, nel caso di piattaforme Microsoft richiede solo la esecuzione di un file auto-installante. Per semplicit da questo momento in poi faremo riferimento a questi ambienti. Al momento della istallazione, a meno di specifiche differenti, il JDK crea allinterno del disco principale la directory jdk1.3allinterno della quale istaller tutto il necessario al programmatore. Sotto questa directory verranno create le seguenti sottodirettori: c:\jdk1.3\bin contenente tutti i comandi java per compilare, le utility di servizio, oltre che ad una quantit di librerie dll di utilit varie. c:\jdk1.3\demo contenente molti esempi comprensivi di eseguibili e codici sorgenti; c:\jdk1.3\include contenente alcune librerie per poter utilizzare chiamate a funzioni scritte in C o C++; c:\jdk1.3\lib contenente alcune file di libreria tra cui tools.jar contenete le API rilasciate da SUN ; <NAME> http://www.java-net.tv <EMAIL> 30 c:\jdk1.3\src contenente il codice sorgente delle classi contenute nellarchivio tools.jar. Il compilatore Java (javac) Il compilatore java (javac) accetta come argomento da linea di comando il nome di un file che deve terminare con la estensione .java. Il file passato come argomento deve essere un normale file ASCII contenente del codice Java valido. Il compilatore processer il contenuto del file e produrr come risultato un file con estensione .class e con nome uguale a quello datogli in pasto contenente il Bytecodes generato dal codice sorgente ed eseguibile tramite virtual machine. I parametri pi comuni che possono essere passati tramite linea di comando al compilatore sono generalmente : -O : questa opzione attiva lottimizzazione del codice -g : questa opzione attiva il supporto per il debug del codice -classpath path : specifica lesatto percorso su disco per trovare le librerie o gli oggetti da utilizzare. Lultima opzione pu essere omessa purch sia definita la variabile di ambiente CLASSPATH. Ad esempio questi sono i passi da compiere per compilare una applicazione Java utilizzando il command promptdi windows: C:\> set CLASSPATH=c:\java\lib\classes.zip C:\> c:\jdk1.3\bin\javac O pippo.java C:\> Il debugger Java (JDB) Il debugger (jdb) uno strumento utilizzato per effettuare le operazioni di debug di applicazioni Java ed molto simile al debugger standard su sistemi Unix (dbx). Per utilizzare il debugger, necessario che le applicazioni siano compilate utilizzando lopzione g C:\> c:\jdk1.3\bin\javac g pippo.java Dopo che il codice stato compilato, il debugger pu essere utilizzato direttamente chiamando attraverso linea di comando. C:\> c:\jdk1.3\bin\jdb pippo Linterprete Java Linterprete Java (java) utilizzato per eseguire applicazioni Java stand-alone ed accetta argomenti tramite linea di comando da trasmettere al metodo main() della applicazione (nei paragrafi successivi spiegheremo nei dettagli il meccanismo di passaggio di parametri ad una applicazione Java). La linea di comando per attivare linterprete prende la forma seguente: C:\> c:\jdk1.3\bin\java ClassName arg1 arg2 .. <NAME> http://www.java-net.tv tar<EMAIL> 31 Linterprete va utilizzato solamente con file contenenti Bytecodes (ovvero con estensione .class) in particolare in grado di eseguire solo file che rappresentano una applicazione ovvero contengono il metodo statico main() (anche questo aspetto verr approfondito nei capitoli successivi). Le informazioni di cui necessita il traduttore sono le stesse del compilatore. E infatti necessario utilizzare la variabile di ambiente CLASSPATH o il parametro a linea di comando classpath per indicare al programma la locazione su disco dei file da caricare. <NAME> http://www.java-net.tv <EMAIL> 32 Capitolo 3 Introduzione alla sintassi di Java Introduzione In questo capitolo verranno trattati gli aspetti specifici del linguaggio Java: le regole sintattiche base per la definizione di classi, linstanziamento di oggetti e la definizione dellentry point di una applicazione. Per tutta la durata del capitolo sar importante ricordare i concetti base discussi nei capitoli precedenti , in particolar modo quelli relativi alla definizione di una classe. Le definizioni di classe rappresentano il punto centrale dei programmi Java. Le classi hanno la funzione di contenitori logici per dati e codice e facilitano la creazione di oggetti che compongono la applicazione. Per completezza il capitolo tratter le caratteristiche del linguaggio necessarie per scrivere piccoli programmi includendo la manipolazione di stringhe e la generazione di output a video. Variabili Per scrivere applicazioni Java un programmatore deve poter creare oggetti, e per creare oggetti necessario poter rappresentarne i dati. Il linguaggio mette a disposizione del programmatore una serie di primitive utili alla definizione di oggetti pi complessi. Per garantire la portabilit del Bytecodes da una piattaforma ad unaltra Java fissa le dimensioni di ogni dato primitivo . Queste dimensioni sono quindi definite e non variano se passiamo da un ambiente ad un altro, cosa che non succede con gli altri linguaggi di programmazione. I tipi numerici sono da considerarsi tutti con segno. La tabella a seguire schematizza i dati primitivi messi a disposizione da Java. Primitiva boolean char byte short int long float double void Dimensione 1-bit 16-bit 8-bit 16-bit 32-bit 64-bit 32-bit 64 -bit - Val. minimo Unicode 0 -128 -2 15 -2 31 -2 63 IEEE754 IEEE754 - Val.Massimo Unicode 2 16 - 1 +127 +2 15 - 1 +2 31 - 1 +2 63 - 1 IEEE754 IEEE754 - La dichiarazione di un dato primitivo in Java ha la seguente forma: identificatore var_name; dove lidentificatore uno tra i tipi descritti nella prima colonna della tabella e var_name rappresenta il nome della variabile, pu contenere caratteri alfanumerici ma deve iniziare necessariamente con una lettera. E possibile creare pi di una variabile dello stesso tipo utilizzando una virgola per separare tra di loro i nomi delle variabili: identificatore var_name, var_name, . ; <NAME> http://www.java-net.tv <EMAIL> 33 Per convenzione lidentificatore di una variabile deve iniziare con una lettera minuscola. Inizializzazione di una variabile Ogni variabile in Java richiede che al momento della dichiarazione le venga assegnato un valore iniziale. Come per il linguaggio c e C++ linizializzazione di una variabile in Java pu essere effettuata direttamente al moneto della sua dichiarazione con la sintassi seguente: identificatore var_name = var_value; dove var_value rappresenta un valore legale per il tipo di variabile dichiarata, ed = rappresenta loperatore di assegnamento. Ad esempio possibile dichiarare ed inizializzare una variale intera con la riga di codice: int mioPrimoIntero = 100; In alternativa, Java assegna ad ogni variabile un valore di default al momento della dichiarazione. La tabella riassume il valore iniziale assegnato dalla JVM nel caso in cui una variabile non venga inizializzata dal programmatore: Tipo primitivo boolean char byte short int long float double Valore assegnato dalla JVM false \u0000 0 0 0 0L 0.0f 0.0 Variabili final A differenza di molti altri linguaggi, Java non consente di definire costanti. Per far fronte alla mancanza possibile utilizzare il modificatore final. Una variabile dichiarata final si comporta come una costante, pertanto le deve essere assegnato il valore iniziale al momento della sua dichiarazione utilizzando loperatore = di assegnamento. final identificatore var_name = var_value; Le variabili di questo tipo vengono inizializzate solo una volta al momento della dichiarazione. Qualsiasi altro tentativo di assegnamento si risolver in un errore di compilazione. Operatori Una volta definito, un oggetto deve poter manipolare i dati. Java mette a disposizione del programmatore una serie di operatori utili allo scopo. Nella tabella a seguire sono stati elencati la maggior parte degli operatori Java ordinati secondo lordine di precedenza; dal pi alto al pi basso. Gran parte degli operatori Java sono stati importati dal set degli operatori del linguaggio C, a cui ne sono stati aggiunti <NAME> http://www.java-net.tv <EMAIL> 34 nuovi allo scopo di supportare le nuove funzionalit messe a disposizione da questo linguaggio. Tutti gli operatori funzionano solamente con dati primitivi a parte gli operatori !=, == e = che hanno effetto anche se gli operandi sono rappresentati da oggetti. Inoltre la classe String utilizza gli operatori + e += per operazioni di concatenazione. Come in C, gli operatori di uguaglianza e disuguaglianza sono == (uguale a) e != (non uguale a). Si nota subito la disuguaglianza con gli stessi operatori come definiti dallalgebra: = e <>. Luso delloperatore digrafo4 == necessario dal momento che = utilizzato esclusivamente come operatore di assegnamento. Loperatore != compare in questa forma per consistenza con la definizione delloperatore logico ! (NOT). Operatori ++ -- + - ? Funzioni Aritmetiche unarie e booleane * Aritmetiche + / % - Addizione, sottrazione e concatenazione << >> >>> Shift di bit < <= > >= instanceof Comparazione == != Uguaglianza e disuguaglianza & (bit a bit) AND ^ (bit a bit) XOR | (bit a bit) OR && AND Logico || OR Logico ! NOT Logico expr ? expr :expr Condizione a tre = *= /+ %= += -= <<= >>>= n &= ^= |= Assegnamento e di combinazione Anche gli operatori bit a bite logici derivano dal C sono completamente separati tra di loro. Ad esempio loperatore & utilizzato per combinare due interi bit per bit e loperatore && utilizzato per eseguire loperazione di AND logico tra due espressioni booleane. Quindi mentre (1011 & 1001) restituir 1001 (a == a && b != b) restituir false. La differenza con C, sta nel fatto che gli operatori logici in Java sono di tipo shortcircuitossia, se il lato sinistro di una espressione fornisce informazioni sufficienti a completare lintera operazione, il lato destro della espressione non verr valutato. Per esempio, si consideri lespressione booleana 4 Gli operatori digrafi sono operatori formati dalla combinazione di due simboli. I due simboli debbono essere adiacenti ed ordinati. <NAME> http://www.java-net.tv <EMAIL> 35 ( a == a ) || ( b == c ) La valutazione del lato sinistro dellespressione fornisce valore true. Dal momento che si tratta di una operazione di OR logico, non c motivo a proseguire nella valutazione del lato sinistro della espressione, cos che b non sar mai comparato con c. Questo meccanismo allapparenza poco utile, si rivela invece estremamente valido nei casi di chiamate a funzioni complesse per controllare la complessit della applicazione. Se infatti scriviamo una chiamata a funzione nel modo seguente : ( A == B ) && ( f() == 2 ) dove f() una funzione arbitrariamente complessa, f() non sar eseguita se A non uguale a B. Sempre dal C Java eredita gli operatori unari di incremento e decremento ++ e --: i++ equivale a i=i+1 e i-- equivale a i=i-1. Infine gli operatori di combinazione, combinano un assegnamento con una operazione aritmetica: i*=2 equivale a i=i*2. Questi operatori anche se semplificano la scrittura del codice lo rendono di difficile comprensione al nuovo programmatore che avesse la necessit di apportare modifiche. Per questo motivo non sono comunemente utilizzati. Operatori aritmetici Java supporta tutti i pi comuni operatori aritmetici (somma, sottrazione, moltiplicazione, divisione e modulo), in aggiunta fornisce una serie di operatori che semplificano la vita al programmatore consentendogli, in alcuni casi, di ridurre la quantit di codice da scrivere. Gli operatori aritmetici sono suddivisi in due classi: operatori binari ed operatori unari. Gli operatori binari (ovvero operatori che necessitano di due operandi) sono cinque e sono schematizzati nella tabella seguente: Operatore + * / % Operatori Aritmetici Binari Utilizzo Descrizione res=sx + dx res = somma algebrica di dx ed sx res= sx - dx res = sottrazione algebrica di dx da sx res= sx * dx res = moltiplicazione algebrica tra sx e dx res= sx / dx res = divisione algebrica di sx con dx res= sx % dx res = resto della divisione tra sx e dx Consideriamo ora le seguenti poche righe di codice: int sx = 1500; long dx = 1.000.000.000 ??? res; res = sx * dx; Nasce il problema di rappresentare correttamente la variabile res affinch le si assegnare il risultato della operazione. Essendo tale risultato 1.500.000.000.000 troppo grande per essere assegnato ad una variabile di tipo int, sar necessario utilizzare una variabile in grado di contenere correttamente il valore prodotto. Il nostro codice funzioner perfettamente se riscritto nel modo seguente: <NAME> http://www.java-net.tv <EMAIL> 36 int sx = 1500; long dx = 1.000.000.000 long res; res = sx * dx; Quello che notiamo che se i due operandi non rappresentano uno stesso tipo, nel nostro caso un tipo int ed un tipo long, Java prima di valutare lespressione trasforma implicitamente il tipo int in long e produce un valore di tipo long. Questo processo di conversione implicita dei tipi viene effettuato da Java secondo alcune regole ben precise. Queste regole possono essere riassunte come segue: Il risultato di una espressione aritmetica di tipo long se almeno un operando di tipo long e, nessun operando di tipo float o double; Il risultato di una espressione aritmetica di tipo int se entrambi gli operandi sono di tipo int; Il risultato di una espressione aritmetica di tipo float se almeno un operando di tipo float e, nessun operando di tipo double; Il risultato di una espressione aritmetica di tipo double se almeno un operando di tipo double; Gli operatori + e -, oltre ad avere una forma binaria hanno una forma unaria il cui significato definito dalle seguenti regole: +op : trasforma loperando op in un tipo int se dichiarato di tipo char, byte o short; -op : restituisce la negazione aritmetica di op; Non resta che parlare degli operatori aritmetici di tipo shortcut . Questo tipo di operatori consente lincremento od il decremento di uno come riassunto nella tabella: Forma shortcut int i=0; int j; j=i++; int i=1; int j; j=i--; int i=0; int j; j=++i; int i=1; int j; j=--i; Forma estesa corrispondente int i=0; int j; j=i; i=i+1; int i=1; int j; j=i; i=i-1; int i=0; int j; i=i+1; j=i; int i=1; int j; i=i-1; j=i; Risultato dopo lesecuzione i=1 j=0 i=0 j=1 i=1 j=1 i=0 j=0 Operatori relazionali Gli operatori relazionali servono ad effettuare un confronto tra valori producendo come risultato di ritorno un valore booleano (true o false) come prodotto del confronto. Nella tabella sono riassunti gli operatori ed il loro significato. <NAME> http://www.java-net.tv <EMAIL> 37 Operatori Relazionali Descrizione res = true se e solo se sx maggiore di dx Operatore > Utilizzo res=sx > dx >= res= sx >= dx < res= sx < dx res = true se e solo se sx maggiore o uguale di dx res = true se e solo se sx minore di dx <= res= sx <= dx res = true se e solo se sx minore o uguale di dx != res= sx != dx res = true se e solo se sx diverso da dx Operatori condizionali Gli operatori condizionali consentono di effettuare operazioni logiche su operandi di tipo booleano, ossia operandi che prendono solo valori true o false. Questi operatori sono quattro e sono riassunti nella tabella: Operatore && Utilizzo res=sx && dx || res= sx || dx ! res= ! sx ^ res= sx ^ dx Operatori Condizionali Descrizione AND : res = true se e solo se sx vale true e dx vale true, false altrimenti. OR : res = true se e solo se almeno uno tra sx e dx vale true, false altrimenti. NOT : res = true se e solo se sx vale false, false altrimenti. XOR : res = true se e solo se uno solo dei due operandi vale true, false altrimenti. Nelle tabelle successive vengono specificati tutti i possibili valori booleani prodotti dagli operatori descritti. sx true true false false sx true false AND ( && ) dx res true true false false true false false false NOT ( ! ) res false true sx true true false false OR ( || ) dx true false true false res true true true false sx true true false false XOR ( ^ ) dx true false true false res false true true false Operatori logici e di shift bit a bit Gli operatori di shift bit a bit consentono di manipolare tipi primitivi spostandone i bit verso sinistra o verso destra secondo le regole definite nella tabella seguente <NAME> http://www.java-net.tv <EMAIL> 38 Operatore >> Utilizzo sx >> dx << sx << dx >>> sx >>> dx Operatori di shift bit a bit Descrizione Sposta i bit di sx verso destra di un numero di posizioni come stabilito da dx. Sposta i bit di sx verso sinistra di un numero di posizioni come stabilito da dx. Sposta i bit di sx verso sinistra di un numero di posizioni come stabilito da dx, ove dx da considerarsi un intero senza segno. Consideriamo ad esempio: byte i = 100; i >> 1; dal momento che la rappresentazione binaria del numero decimale 100 01100100, lo shift verso destra di una posizione dei bit, produrr come risultato il numero binario 00110010 che corrisponde al valore 50 decimale. Oltre ad operatori di shift, Java consente di eseguire operazioni logiche su tipi primitivi operando come nel caso precedente sulla loro rappresentazione binaria. Operatore & | ^ ~ Utilizzo res = sx & dx res = sx | dx res = sx ^ dx res = ~sx Operatori logici bit a bit Descrizione AND bit a bit OR bit a bit XOR bit a bit COMPLEMENTO A UNO bit a bit Nelle tabelle seguenti sono riportati tutti i possibili risultati prodotti dalla applicazione degli operatori nella tabella precedente. Tutte le combinazioni sono state effettuate considerando un singolo bit degli operandi. sx (bit) 1 1 0 0 AND ( & ) dx (bit) 1 0 1 0 res (bit) 1 0 0 0 COMPLEMENTO ( ~ ) sx (bit) res (bit) 1 0 0 1 sx (bit) 1 1 0 0 OR ( | ) dx (bit) 1 0 1 0 res (bit) 1 1 1 0 sx (bit) 1 1 0 0 XOR ( ^ ) dx (bit) 1 0 1 0 res (bit) 0 1 1 0 Il prossimo un esempio di applicazione di operatori logici bit a bit tra variabili di tipo byte: byte sx = 100; byte dx = 125; byte res1 = sx & dx; byte res2 = sx | dx; byte res3 = sx ^ dx; <NAME> http://www.java-net.tv <EMAIL> 39 byte res4 = ~sx; Dal momento che la rappresentazione binaria di sx e dx rispettivamente: variabile sx dx decimale 100 125 binario 01100100 01111101 Lesecuzione del codice produrr i risultati seguenti: operatore & | ^ ~ sx 01100100 01100100 01100100 01100100 dx 01111101 01111101 01111101 ------------- risultato 01100100 01111101 00011001 10011011 decimale 100 125 25 155 Operatori di assegnamento Loperatore di assegnamento = consente al programmatore, una volta definita una variabile, di assegnarle un valore. La sintassi da utilizzare la seguente: result_type res_var = espressione; Espressione rappresenta una qualsiasi espressione che produce un valore del tipo compatibile con il tipo definito da result_type, e res_var rappresenta lidentificatore della variabile che conterr il risultato. Se torniamo alla tabella definita nel paragrafo Operatori, vediamo che loperatore di assegnamento ha la priorit pi bassa rispetto a tutti gli altri. La riga di codice Java produrr quindi la valutazione della espressione ed infine lassegnamento del risultato alla variabile res_var. Ad esempio: int res1 = 5+10; Esegue lespressione alla destra delloperatore e ne assegna il risultato (15) a res1. int res1 = 5; Assegna il valore 5 alla destra delloperatore alla variabile res1. Oltre alloperatore = Java mette a disposizione del programmatore una serie di operatori di assegnamento di tipo shortcut (in italiano scorciatoia), definiti nella prossima tabella. Questi operatori combinano un operatore aritmetico o logico con loperatore di assegnamento. <NAME> http://www.java-net.tv <EMAIL> 40 Operatore += -= *= /= %= &= |= ^= <<= >>= >>>= Operatori di assegnamento shortcut Utilizzo Equivalente a sx +=dx sx = sx + dx; sx -=dx sx = sx - dx; sx *=dx sx = sx * dx; sx /=dx sx = sx / dx; sx %=dx sx = sx % dx; sx &=dx sx = sx & dx; sx |=dx sx = sx | dx; sx ^=dx sx = sx ^ dx; sx <<=dx sx = sx << dx; sx >>=dx sx = sx >> dx; sx >>>=dx sx = sx >>> dx; Espressioni Le espressioni rappresentano il meccanismo per effettuare calcoli allinterno della nostra applicazione, e combinano variabili e operatori producendo un singolo valore di ritorno. Le espressioni vengono utilizzate per assegnare valori a variabili o modificare, come vedremo nel prossimo capitolo, il flusso della esecuzione di una applicazione Java. Una espressione non rappresenta una unit di calcolo completa inquanto non produce assegnamenti o modifiche alle variabili della applicazione. Istruzioni A differenza delle espressioni, le istruzioni sono unit eseguibili complete terminate dal carattere ; e combinano operazioni di assegnamento, valutazione di espressioni o chiamate ad oggetti (questultimo concetto risulter pi chiaro alla fine del capitolo) combinate tra loro a partire dalle regole sintattiche del linguaggio. Regole sintattiche di Java Una istruzione rappresenta il mattone per la costruzione di oggetti. Difatti la sintassi del linguaggio Java pu essere descritta da tre sole regole di espansione: istruzione --> expression OR istruzione --> { istruzione [istruzione] } OR istruzione --> flow_control istruzione Queste tre regole hanno natura ricorsiva e, la freccia deve essere letta come diventa. Sostituendo una qualunque di queste tre definizioni allinterno del lato destro di ogni espansione possono essere generati una infinit di istruzioni. Di seguito un esempio. Prendiamo in considerazione la terza regola. <NAME> http://www.java-net.tv <EMAIL> 41 istruzione --> flow_control Statement E sostituiamo il lato destro utilizzando la seconda espansione ottenendo istruzione --> flow_control --> flow_control istruzione 2 { istruzione } Applicando ora la terza regola di espansione otteniamo : istruzione --> flow_control --> flow_control --> flow_control istruzione 2 { 3 { istruzione flow_control } istruzione } Prendiamo per buona che listruzione if sia uno statement per il controllo del flusso della applicazione (flow_control), e facciamo un ulteriore sforzo accettando che la sua sintassi sia: if(boolean_expression) Ecco che la nostra espansione diventer quindi : istruzione --> --> --> flow_control --> 2 3 { flow_control istruzione } if(i>10) { if(I==5) print(Il valore di I 5); i++; } Blocchi di istruzioni La seconda regola di espansione: istruzione --> { istruzione [istruzione] } definisce la struttura di un blocco di istruzioni, ovvero una sequenza di una o pi istruzioni racchiuse allinterno di parentesi graffe. Metodi Una istruzione rappresenta il mattone per creare le funzionalit di un oggetto. Nasce spontaneo chiedersi: come vengono organizzate le istruzioni allinterno di oggetti? I metodi rappresentano il cemento che tiene assieme tutti i mattoni. I metodi sono gruppi di istruzioni riuniti a fornire una singola funzionalit. Essi hanno una sintassi <NAME> http://www.java-net.tv <EMAIL> 42 molto simile a quella della definizione di funzioni ANSI C e possono essere descritti con la seguente forma: return_type method_name(arg_type name [,arg_type name] ) { istruzioni } return_type e arg_type rappresentano ogni tipo di dato (primitivo o oggetto), name e method_name sono identificatori alfanumerici ed iniziano con una lettera (discuteremo in seguito come avviene il passaggio di parametri). Se il metodo non ritorna valori, dovr essere utilizzata la chiave speciale void al posto di return_type. Se il corpo di un metodo contiene dichiarazioni di variabili, queste saranno visibili solo allinterno del metodo stesso, ed il loro ciclo di vita sar limitato alla esecuzione del metodo. Non manterranno il loro valore tra chiamate differenti e, non saranno accessibili da altri metodi. Per evitare la allocazione di variabili inutilizzate, il compilatore java prevede una forma di controllo secondo la quale un metodo non pu essere compilato se esistono variabili a cui non stato assegnato alcun valore. In questi casi la compilazione verr interrotta con la restituzione di un messaggio di errore. Ad esempio consideriamo il metodo seguente: int moltiplica_per_tre (int number) { int risultato = 0; risultato = number*3; return risultato; } In questo caso la compilazione andr a buon fine ed il compilatore Java produrr come risultato un file contenente Bytecodes. Se invece il metodo avesse la forma: int moltiplica_per_tre (int number) { int risultato; return number*3; } il compilatore produrrebbe un messaggio di errore dal momento che esiste una variabile dichiarata e mai utilizzata. Definire una classe Le istruzioni sono organizzate utilizzando metodi, e i metodi forniscono funzionalit. Daltro canto, Java un linguaggio object oriented, e come tale richiede che le funzionalit (metodi) siano organizzati in classi. Nel primo capitolo, una classe stata paragonata al concetto di categoria. Se trasportato nel contesto del linguaggio di programmazione la definizione non cambia, ma importante chiarire le implicazioni che la cosa comporta. Una classe Java deve rappresentare un oggetto concettuale. Per poterlo fare deve raggruppare dati e metodi assegnando un nome comune. La sintassi la seguente: <NAME> http://www.java-net.tv <EMAIL> 43 class ObjectName { data_declarations method_declarations } I dati ed I metodi contenuti allinterno della classe vengono chiamati membri della classe. Eimportante notare che dati e metodi devono essere rigorosamente definiti allinterno della classe. Non possibile in nessun modo dichiarare variabili globali, funzioni o procedure. Questa restrizione del linguaggio Java, scoraggia il programmatore ad effettuare una decomposizione procedurale, incoraggiando di conseguenza ad utilizzare lapproccio object oriented. Riprendendo la classe libro descritta nel primo capitolo, ricordiamo che avevamo stabilito che un libro tale solo se contiene pagine, le pagine si possono sfogliare, strappare etc.. Utilizzando la sintassi di Java potremmo fornire una grossolana definizione della nostra classe nel modo seguente: class Libro { // dichiarazione dei dati int numero_di_pagine; int pagina_attuale; // dichiarazione dei metodi void strappaUnaPagina(int numero_della_pagina) {} int paginaCorrente(){} void giraLaPagina(){} } Variabili reference Java fa una netta distinzione tra Classi e tipi primitivi. Una delle maggiori differenze che un oggetto non allocato dal linguaggio al momento della dichiarazione. Per chiarire questo punto, consideriamo la seguente dichiarazione: int counter; Questa dichiarazione crea una variabile intera chiamata counter ed alloca subito quattro byte per lo storage del dato. Con le classi lo scenario cambia e la dichiarazione Stack s; crea una variabile che referenzia loggetto, ma non crea loggetto Stack. Una variabile di referenza, quindi una variabile speciale che tiene traccia di istanze di tipi non primitivi. Questo tipo di variabili hanno lunica capacit di tracciare oggetti del tipo compatibile: ad esempio una referenza ad un oggetto di tipo Stack non pu tracciare oggetti di diverso tipo. Oltre che per gli oggetti, Java utilizza lo stesso meccanismo per gli array, che non sono allocati al momento della dichiarazione, ma viene semplicemente creata una variabile per referenziare lentit. Un array pu essere dichiarato utilizzando la sintassi: <NAME> http://www.java-net.tv <EMAIL> 44 int numbers[]; Una dichiarazione cos fatta crea una variabile che tiene traccia di un array di interi di dimensione arbitraria. Le variabili reference sono molto simili concettualmente ai puntatori di C e C++, ma non consentono la conversione intero/indirizzo o le operazioni aritmetiche; tuttavia queste variabili sono uno strumento potente per la creazione di strutture dati dinamiche come liste, alberi binari e array multidimensionali. In questo modo eliminano gli svantaggi derivanti dalluso di puntatori, mentre ne mantengono tutti i vantaggi. Nella Figura 3-1 sono riportati alcuni esempi relativi alla modalit utilizzata da Java per allocare primitive od oggetti. Unultima considerazione da fare riguardo la gestione delle variabili in Java che a differenza di C e C++ in cui un dato rappresenta il corrispondente dato-macchina ossia una variabile intera in C++ occupa 32 bit ed una variabile byte ne occupa 8, ora le variabili si comportano come se. La virtual machine Java difatti alloca per ogni dato primitivo il massimo disponibile in fatto di rappresentazione macchina dei dati. La virtual machine riserver, su una macchina a 32 bit, 32 bit sia per variabili intere che variabili byte, quello che cambia che il programmatore vedr una variabile byte comportarsi come tale ed altrettanto per le altre primitive. Questo, a discapito di un maggior consumo di risorse, fornisce per molti vantaggi: primo consente la portabilit del Bytecodes su ogni piattaforma garantendo che una variabile si comporter sempre allo stesso modo, secondo sfrutta al massimo le capacit della piattaforma che utilizzer le FPU (Floating Point Unit) anche per calcoli su variabili intere di piccole dimensioni. Figura 3-1 : Variabili primitive e variabili reference <NAME> http://www.java-net.tv <EMAIL> 45 Visibilit di una variabile Java Come C e C++ Java consente di dichiarare variabili in qualunque punto del codice della applicazione a differenza di linguaggi come il Pascal che richiedevano che le variabili venissero dichiarate allinterno di un apposito blocco dedicato. Dal momento che secondo questa regola potrebbe risultare possibile dichiarare pi variabili con lo stesso nome in punti differenti del codice, necessario stabilire le regole di visibilit delle variabili. I blocchi di istruzioni ci forniscono il meccanismo necessario per delimitare quello che chiameremo scope di una variabile Java. In generale diremo che una variabile ha scopelimitato al blocco allinterno del quale stata dichiarata. Analizziamo quindi caso per caso lo scope di variabili. Quando definiamo una classe, racchiudiamo allinterno del suo blocco di istruzioni sia dichiarazioni di variabili membro che dichiarazioni di metodi membro. Secondo la regola definita, e come schematizzato nella Figura 3-2, i dati membro di una classe sono visibili a da tutti i metodi dichiarati allinterno della definizione delloggetto. Figura 3-2 : scope dei dati membro di una classe Nel caso di metodi membro vale a sua volta lo schema degli scope come definito nella Figura 3-3. Figura 3-3 : scope delle variabili in una dichiarazione di metodo <NAME> http://www.java-net.tv <EMAIL> 46 Loggetto null Il linguaggio Java prevede un valore speciale per le variabili reference che non referenzia nessuna istanza di un oggetto. Il valore speciale null rappresenta un oggetto inesistente, e viene assegnato di default ad ogni variabile reference. Se la applicazione esegue una chiamata ad un oggetto tramite una variabile reference non inizializzato, il compilatore Java produrr un messaggio di errore di tipo NullPointerException5. Quando ad una variabile reference viene assegnato il valore null, loggetto referenziato verr rilasciato e, se non utilizzato verr dato in pasto alla garbage collection che si occuper di rilasciare la memoria allocata per la entit. Altro uso che pu essere fatto delloggetto null riguarda le operazioni di comparazione come visibile nellesempio seguente. Le poche righe di codice dichiarano un array di interi chiamato numbers. Mediante listruzione per il controllo di flusso if6 controlla se loggetto array sia stato creato o no. Stack s = null; int numbers[]; if (numbers == null) { .. } Facciano attenzione I programmatori C, C++. Il valore null nel nostro caso non equivale al valore 0, ma rappresenta un oggetto nullo. Creare istanze Creata la variabile refence, siamo pronti a creare una istanza di un nuovo oggetto o di un array. Loperatore new fa questo per noi, allocando la memoria necessaria per il nostro oggetto e tornando la locazione in memoria della entit creata. Questa locazione pu quindi essere memorizzata nella variabile reference di tipo appropriato ed utilizzata per accedere alloggetto quando necessario. Quando utilizziamo loperatore new con una classe, la sintassi la seguente: new class_type() ; Le parentesi sono necessarie ed hanno un significato particolare che sveleremo presto. Class_type una classe appartenente alle API di Java oppure definita dal programmatore. Per creare un oggetto Stack utilizzeremo quindi listruzione: Stack s = new Stack(); Che dichiara una variabile s di tipo Stack(), istanzia loggetto utilizzando la definizione di classe e memorizza la locazione della nuova istanza nella variabile. Un risultato analogo pu essere ottenuto anche nel modo seguente: Stack s = null; s = new Stack(); Gli array sono allocati allo stesso modo: 5 6 Le eccezioni verranno discusse in un capitolo a se Le istruzioni per il controllo di flusso verranno trattate nel capitolo successivo <NAME> http://www.java-net.tv <EMAIL> 47 int my_array[] = new int[20]; o, analogamente al caso precedente int my_array[] = null; my_array = new int[20]; In questo caso Java dichiarer una variabile reference intera, allocher memoria per 20 interi e memorizzer la locazione di memoria a my_array. Il nuovo array sar indicizzato a partire da 07. Loperatore punto . Questo operatore utilizzato per accedere ai membri di un oggetto tramite la variabile reference. Le due definizioni di classe a seguire, rappresentano una definizione per la classe Stack ed una per la classe StackElement che rappresentano vicendevolmente il concetto di stack e quello di elemento dello stack. class StackElement { int val; } class Stack { StackElement pop() { .. } void push(StackElement stack_ele) { .. } } La classe StackElement contiene un dato membro chiamato val che rappresenta un numero intero da inserire allinterno dello Stack. Le due classi possono essere legate assieme a formare un breve blocco di codice che realizza una operazione di pop() ed una di push() sullo Stack utilizzando loperatore punto: //Creiamo un oggetto StackElement ed inizializziamo il dato membro StackElement stack_el = new StackElement(); int value = 10; Stack_el.val = value ; //Creiamo un oggetto Stack Stack s = new Stack(); //inseriamo il valore in testa allo stack s.push(Stack_el); 7 In java come in C e C++ gli array di dimensione n indicizzano gli elementi con valori compresi tra 0 e (n-1). Ad esempio my_array[0] torner lindice relativo al primo elemento dellarray. <NAME> http://www.java-net.tv <EMAIL> 48 //Rilasciamo il vecchio valore per StackElement e eseguiamo una operazione di //pop sullo stack Stack_el = null; Stack_el = s.pop(); Auto referenza ed auto referenza esplicita Loperatore punto, oltre a fornire il meccanismo per accedere a dati i metodi di un oggetto attraverso la relativa variabile reference, consente ai metodi di una classe di accedere ai dati membro della classe di appartenenza. Proviamo a fare qualche modifica alla classe StackElement del paragrafo precedente: class StackElement { int val; // questo metodo inizializza il dato membro della classe void setVal(int valore) { ???.val = valore; } } Il metodo setVal prende come parametro un intero ed utilizza loperatore punto per memorizzare il dato allinterno della variabile membro val. Il problema che rimane da risolvere (evidenziato nellesempio dai punti interrogativi ???), riguarda la modalit con cui un oggetto possa referenziare se stesso. Java prevede una modalit di referenziazione speciale identificata da this. Difatti il valore di this viene modificato automaticamente da Java in modo che ad ogni istante sia sempre referenziato alloggetto attivo, intendendo per oggetto attivo listanza delloggetto in esecuzione durante la chiamata al metodo corrente. La nostra classe diventa ora: class StackElement { int val; // questo metodo inizializza il dato membro della classe void setVal(int valore) { this.val = valore; } } Questa modalit di accesso viene detta auto referenza esplicita ed applicabile ad ogni tipo di dato e metodo membro di una classe. Auto referenza implicita Dal momento che, come abbiamo detto, ogni metodo deve essere definito allinterno di una classe, i meccanismo di auto referenza molto comune in applicazioni Java. <NAME> http://www.java-net.tv <EMAIL> 49 Se una referenza non risulta ambigua, Java consente di utilizzare un ulteriore meccanismo detto di auto referenza implicita, mediante il quale possibile accede a dati o metodi membro di una classe senza necessariamente utilizzare this. class StackElement { int val; void setVal(int valore) { val = valore; } } Dal momento che la visibilit di una variabile in Java limitata al blocco ai sottoblocchi di codice in cui stata effettuata la dichiarazione, Java basa su questo meccanismo la auto referenza implicita. Formalmente java ricerca una variabile non qualificata risalendo a ritroso tra i diversi livelli dei blocchi di codice. Prima di tutto Java ricerca la dichiarazione di variabile allinterno del blocco di istruzioni correntemente in esecuzione. Se la variabile non un parametro appartenente al blocco risale tra i vari livelli del codice fino ad arrivare alla lista dei parametri del metodo corrente. Se la lista dei parametri del metodo non soddisfa la ricerca, Java legge il blocco di dichiarazione delloggetto corrente utilizzando quindi implicitamente this. Nel caso in cui la variabile non neanche un dato membro delloggetto viene generato un codice di errore dal compilatore. Anche se luso implicito di variabili facilita la scrittura di codice riducendo la quantit di caratteri da digitare, un abuso della tecnica rischia di provocare ambiguit allinterno del codice. Tipicamente la situazione a cui si va incontro la seguente: class StackElement { int val; void setVal(int valore) { int val ; .. .. val = valore; } } Una assegnazione di questo tipo in assenza di this provocher la perdita del dato passato come parametro al metodo setVal(int), dato che verr memorizzato in una variabile visibile solo allinterno del blocco di istruzioni del metodo e di conseguenza con ciclo di vita limitato al tempo necessario alla esecuzione del metodo. Il codice per funzionare correttamente dovr essere modificato nel modo seguente: class StackElement { int val; void setVal(int valore) { int val ; .. .. this.val = valore; <NAME> http://www.java-net.tv <EMAIL> 50 } } Meno ambiguo invece luso della auto referenza implicita se utilizzata per la chiamata a metodi della classe. In questo caso infatti Java applicher soltanto il terzo passo dellalgoritmo descritto per la determinazione delle variabili. Un metodo infatti non pu essere definito allinterno di un altro, e non pu essere passato come argomento ad unaltro metodo. Stringhe Come abbiamo anticipato, Java ha a disposizione molti tipi gi definiti. String uno di questi, ed dotato di molte caratteristiche particolari. Le stringhe sono oggetti che possono essere inizializzato usando semplicemente una notazione con doppi apici senza lutilizzo delloperatore new: String prima = Hello; String seconda = world; Possono essere concatenate usando loperatore di addizione: String terza = prima + seconda; Hanno un membro che ritorna la lunghezza della stringa rappresentata: int lunghezza = prima.lenght(); Stato di un oggetto Java Gli oggetti Java rappresentano dati molto complessi il cui stato, a differenza di un tipo primitivo, non pu essere definito semplicemente dal valore della variabile reference. In particolare, definiamo stato di un oggetto il valore in un certo istante di tutti i dati membro della classe. Ad esempio lo stato delloggetto StackElement rappresentato dal valore del dato membro val di tipo intero. Comparazione di oggetti In Java la comparazione di oggetti leggermente differente rispetto ad altri linguaggi e ci dipende dal modo in cui Java utilizza gli oggetti. Una applicazione Java non usa oggetti, ma usa variabili reference come oggetti. Una normale comparazione effettuata utilizzando loperatore == comparerebbe il riferimento e non lo stato degli oggetti. Ci significa che == produrr risultato true solo se le due variabili reference puntano allo stesso oggetto e non se i due oggetti distinti di tipo uguale sono nello stesso stato. Stack a = new Stack(); Stack b = new Stack(); (a == b) -> false Molte volte per ad una applicazione Java potrebbe tornare utile sapere se due istanze separate di una stessa classe sono nello stesso stato ovvero, ricordando la definizione data nel paragrafo precedente potremmo formulare la regola secondo la quale due oggetti java dello stesso tipo sono uguali se si trovano nello stesso stato al momento del confronto. <NAME> http://www.java-net.tv <EMAIL> 51 Java prevede un metodo speciale chiamato equals() che confronta lo stato di due oggetti. Di fatto, tutti gli oggetti in Java, anche quelli definiti dal programmatore, possiedono questo metodo inquanto ereditato per default da una classe particolare che analizzeremo in seguito parlando di ereditariet. Stack a = new Stack(); Stack b = new Stack(); a.push(1); b.push(1); a.equals(b) -> true Metodi statici Finora abbiamo mostrato segmenti di codice dando per scontato che siano parte di un processo attivo: in tutto questo c una falla. Per tapparla dobbiamo fare alcune considerazioni: primo, ogni metodo deve essere definito allinterno di una classe (questo incoraggia ad utilizzare il paradigma object oriented). Secondo, i metodi devono essere invocati utilizzando una variabile reference inizializzata in modo che tenga traccia della istanza di un oggetto. Questo meccanismo rende possibile lauto referenziazione inquanto se un metodo viene chiamato senza che loggetto di cui membro sia attivo, this non sarebbe inizializzato. Il problema quindi che in questo scenario un metodo per essere eseguito richiede un oggetto attivo, ma fino a che non c qualcosa in esecuzione un oggetto non pu essere istanziato. Lunica possibile soluzione quindi quella di creare metodi speciali che non richiedano lattivit da parte delloggetto di cui sono membro cos che possano essere utilizzati in qualsiasi momento. La risposta nei metodi statici, ossia metodi che appartengono a classi, ma non richiedono oggetti attivi. Questi metodi possono essere creati utilizzando la parola chiave static a sinistra della dichiarazione di un metodo come mostrato nella dichiarazione di static_method() nellesempio che segue: 1 class esempio 2 { 3 static int static_method() 4 { 5 . 6 } 7 int non_static_method() 8 { 9 return static_method(); 10 } 11 } 12 class altra_classe 13 { 14 void un_metodo_qualunque() 15 { 16 int i = esempio. static_method(); 17 } 18 } Un metodo statico esiste sempre a prescindere dallo stato delloggetto; tuttavia la locazione o classe incapsulante del metodo deve sempre essere ben qualificata. Questa tecnica chiamata scope resolution e pu essere realizzata in svariati Massimiliano Tarquini http://www.java-net.tv <EMAIL> 52 modi. Uno di questi consiste nellutilizzare il nome della classe come se fosse una variabile reference: esempio.static_metod(); Oppure si pu utilizzare una variabile reference nel modo che conosciamo: esempio _ese = new esempio(); _ese.static_metod(); Se il metodo statico viene chiamato da un altro membro della stessa classe non necessario alcun accorgimento. Eimportante tener bene a mente che un metodo statico non inizializza loggetto this; di conseguenza un oggetto statico non pu utilizzare membri non statici della classe di appartenenza. Il metodo main Affinch la Java Virtual Machine possa eseguire una applicazione, necessario che abbia ben chiaro quale debba essere il primo metodo da eseguire. Questo metodo viene detto entry point della applicazione. Come per il linguaggio C, Java riserva allo scopo lidentificatore di membro main. Ogni classe pu avere il suo metodo main(), ma solo il metodo main della classe specificata verr eseguito allavvio del processo. Questo significa che ogni classe di una applicazione pu rappresentare un potenziale entry point che pu quindi essere scelto allavvio del processo scegliendo semplicemente la classe desiderata. Come pi avanti vedremo, una classe pu contenere pi metodi membro aventi lo stesso nome, purch abbiano differenti parametri in input. Affinch il metodo main() possa essere trovato dalla virtual machine, necessario che abbia una lista di argomenti che accetti un array di stringhe. Eproprio grazie a questo array la virtual machine in grado di passare alla applicazioni dei valori da riga di comando. Infine, per il metodo main() necessario utilizzare il modificatore public8 che accorda alla virtual machine il permesso per eseguire il metodo. class prima_applicazione { public static void main(String args[]) { .. } } Tutto questo ci porta ad una importante considerazione finale : tutto un oggetto, anche un applicazione. Loggetto System Unaltra delle classi predefinite in Java la classe System. Questa classe ha una serie di metodi statici e rappresenta il sistema su cui la applicazione Java sta girando. Due dati membro statici di questa classe sono System.out e System.err che rappresentano rispettivamente lo standard output e lo standard error dellinterprete java. Usando il loro metodo statico println(), una applicazione Java in grado di inviare un output sullo standard output o sullo standard error. 8 Capiremo meglio il suo significato successivamente <NAME> http://www.java-net.tv [email protected] 53 System.out.println(Scrivo sullo standard output); System.err.println(Scrivo sullo standard error); Il metodo statico System.exit(int number) causa la terminazione della applicazione Java. <NAME> http://www.java-net.tv <EMAIL> 54 Laboratorio 3 Introduzione alla sintassi di Java Descrizione In questa sezione inizieremo a comprendere la tecnica delluso degli oggetti Java. Prima di proseguire per necessario capire la sintassi di una semplice istruzione if9 La sintassi base di if la seguente: if (expression) { istruzione } Ad esempio: if(x > y) { System.out.println("x is greater than y); } Esercizio 1 Uno Stack o Pila una struttura dati gestita secondo la filosofia LIFO (Last In First Out) ovvero lultimo elemento ad essere inserito il primo ad essere recuperato. Disegnare e realizzare un oggetto Stack. Loggetto Stack deve contenere al massimo 20 numeri interi e deve avere i due metodi: void push(int) int pop() 9 I controlli di flusso verranno descritti in dettaglio nel capitolo successivo. <NAME> http://www.java-net.tv tarqu<EMAIL> 55 Il metodo push che ritorna un tipo void e prende come parametro di input un numero intero inserisce lelemento in cima alla pila. Larray deve essere inizializzato allinterno del metodo push(int). Si pu controllare lo stato dello stack ricordando che una variabile reference non inizializzata punta alloggetto null. <NAME> http://www.java-net.tv <EMAIL>@all-one-mail.net 56 Soluzione al primo esercizio La classe Stack dovrebbe essere qualcosa tipo: c:\esercizi\cap3\Stack.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Stack { int data[]; int first; void push(int i) { if(data == null) { first = 0; data = new int[20]; } if(first < 20) { data[first] = i; first ++; } } int pop() { if(first > 0) { first --; return data[first]; } return 0; // Bisogna tornare qualcosa } } Le righe 3 e 4 contengono la dichiarazione dei dati membro della classe. In particolare utilizziamo un array di numeri interi per contenere i dati ed una variabile intera che mantiene traccia della prima posizione libera allinterno dellarray. Dalla riga 5 alla riga 17 viene dichiarato il metodo void push(int i) allinterno del quale per prima cosa viene controllato se larray stato inizializzato (righe 7-11) ed eventualmente viene allocato come array di 20 numeri interi. if(data == null) { first = 0; data = new int[20]; } Quindi viene effettuato il controllo per verificare se possibile inserire elementi allinterno dellarray. In particolare essendo 20 il numero massimo di interi contenuti, mediante listruzione if il metodo verifica che la posizione puntata dalla variabile first sia minore di 20 (ricordiamo che in un array le posizioni sono identificate a partire da 0). Se lespressione first < 20 produce il valore true, il numero intero passato come parametro di input viene inserito nellarray nella posizione first. La variabile first viene quindi aggiornata in modo che punto alla prima posizione libera nellarray. <NAME> http://www.java-net.tv <EMAIL> 57 if(first < 20) { data[first] = i; first ++; } Le righe da 18 a 26 rappresentano la dichiarazione del metodo int pop() che recupera il primo elemento della pila e lo ritorna allutente. Per prima cosa il metodo controlla allinterno di una istruzione if se first sia maggiore di 0 ovvero che esista almeno un elemento allinterno dello Stack. Se la condizione si verifica first viene modificata in modo da puntare allultimo elemento inserito il cui valore viene restituito mediante il comando return. In caso contrario il metodo ritorna il valore 0. int pop() { if(first > 0) { first --; return data[first]; } return 0; // Bisogna tornare qualcosa } A questo punto possibile salvare il file contenente il codice sorgente e compilarlo. Alla fine del processo di compilazione avremo a disposizione un file contenente il bytecode della definizione di classe. Salviamo il file nella directory c:\esercizi\cap3\ con nome Stack.java. A questo punto possiamo quindi compilare il file: C:\> set CLASSPATH=.;.\;c:\jdk1.3\lib\tools.jar; C:\> set PATH=%PATH%;c:\jdk1.3\bin; C:\> javac Stack.java C:\> <NAME> http://www.java-net.tv <EMAIL> 58 Capitolo 4 Controllo di flusso e distribuzione di oggetti Introduzione Java eredita da C e C++ lintero insieme di istruzioni per il controllo di flusso apportando solo alcune modifiche. In aggiunta Java introduce alcune nuove istruzioni necessarie alla manipolazione di oggetti. Questo capitolo tratta le istruzioni condizionali, le istruzioni di loop, le istruzioni relative alla gestione dei package per lorganizzazione di classi e, listruzione import per risolvere la posizionedelle definizioni di classi in altri file o package. I package Java sono strumenti simili a librerie e servono come meccanismo per raggruppare classi o distribuire oggetti. Listruzione import una istruzione speciale utilizzata dal compilatore per determinare la posizione su disco delle definizioni di classi da utilizzare nella applicazione corrente . Come C e C++ Java indipendente dagli spazi ovvero lindentazione del codice di un programma ed eventualmente luso di pi di una riga di testo sono opzionali. Istruzioni per il controllo di flusso Espressioni ed istruzioni per il controllo di flusso forniscono al programmatore il meccanismo per decidere se e come eseguire blocchi di istruzioni condizionatamente a meccanismo decisionali definiti allinterno della applicazione. Istruzione if if-else switch for while do-while Istruzioni per il controllo di flusso Descrizione Esegue o no un blocco di codice a seconda del valore restituito da una espressione booleana. Esegue permette di selezionare tra due blocchi di codice quello da eseguire a seconda del valore restituito da una espressione booleana. Utile in tutti quei casi in cui sia necessario decidere tra opzioni multiple prese in base al controllo di una sola variabile. Esegue ripetutamente un blocco di codice. Esegue ripetutamente un blocco di codice controllando il valore di una espressione booleana. Esegue ripetutamente un blocco di codice controllando il valore di una espressione booleana. Le istruzioni per il controllo di flusso sono riassunte nella tabella precedente ed hanno sintassi definita dalle regole di espansione definite nel terzo capitolo e riassunte qui di seguito.. istruzione --> { istruzione [istruzione] } OR istruzione --> flow_control istruzione <NAME> http://www.java-net.tv <EMAIL> 59 Listruzione if Listruzione per il controllo di flusso if consente alla applicazione di decidere, in base ad una espressione booleana, se eseguire o no un blocco di codice. Applicando le regole di espansione definite, la sintassi di questa istruzione la seguente: if (boolean_expr) istruzione1 --> if (boolean_expr) { istruzione; [istruzione] } dove boolean_expr rappresenta una istruzione booleana valida. Di fatto, se boolean_expr restituisce il valore true, verr eseguito il blocco di istruzioni successivo, in caso contrario il controllo passer alla prima istruzione successiva al blocco if. Un esempio di istruzione if il seguente: 1 2 3 4 5 6 7 8 9 int x; . if(x>10) { . x=0; .. } x=1; In questo caso, se il valore di x strettamente maggiore di 10, verr eseguito il blocco di istruzioni di if (righe 4-8), in caso contrario il flusso delle istruzioni salter direttamente dalla riga 3 alla riga 9 del codice. Listruzione if-else Una istruzione if pu essere opzionalmente affiancata da una istruzione else. Questa forma particolare dellistruzione if, la cui sintassi descritta qui di seguito, consente di decidere quale blocco di codice eseguire tra due blocchi di codice. if (boolean_expr) istruzione1 else istruzione2 --> if (boolean_expr) { istruzione; [istruzione] } else { istruzione; [istruzione] } Se boolean_expr restituisce il valore true verr eseguito il blocco di istruzioni di if, altrimenti il controllo verr passato ad else e verr eseguito il secondo blocco di istruzioni. Di seguito un esempio: <NAME> http://www.java-net.tv <EMAIL> 60 1 2 3 4 5 6 7 8 if(y==3) { y=12; } else { y=0; } In questo caso, se lespressione booleana sulla riga 3 del codice ritorna valore true, allora verranno eseguite le istruzioni contenute nelle righe 2-4, altrimenti verranno eseguite le istruzioni contenute nelle righe 6-8. Istruzioni if, if-else annidate Una istruzione if annidata rappresenta una forma particolare di controllo di flusso in cui una istruzione if o if-else controllata da unaltra istruzione if o if-else. Utilizzando le regole di espansione, in particolare concatenando ricorsivamente la terza con le definizioni di if e if-else: flow_control ->if(espressione) istruzione istruzione -> flow_control flow_control istruzione flow_control ->if(espressione) istruzione else istruzione otteniamo la regola sintattica per costruire blocchi if annidati: if(espressione) { istruzione if (espressione2) { istruzione if (espressione3) { istruzione . } } } Catene if-else-if La forma pi comune di if annidati rappresentata dalla sequenza o catena ifelse-if. Questo tipo di concatenazione valuta una serie arbitraria di istruzioni booleane precedendo dallalto verso il basso. Se almeno una delle condizioni restituisce il valore true verr eseguito il blocco di istruzioni relativo. Se nessuna delle condizioni si dovesse verificare allora verrebbe eseguito il blocco else finale. <NAME> http://www.java-net.tv <EMAIL> 61 if(espressione) { istruzione } else if (espressione2) { istruzione } else if (espressione3) { istruzione . } else { istruzione . } Nellesempio viene utilizzato un tipico caso in cui utilizzare questa forma di annidamento: .. int i = getUserSelection(); if(i==1) { faiQualcosa(); } else if(i==2) { faiQualcosAltro(); } else { nonFareNulla (); } . Nellesempio, la variabile di tipo int i prende il valore restituito come parametro di ritorno dal metodo getUserSelection(). La catena controlla quindi il valore di i ed esegue il metodo faiQualcosa() nel caso in cui i valga 1, faiQualcosAltro() nel caso in cui valga 2, nonFareNulla() in tutti gli altri casi. Listruzione switch Java mette a disposizione una istruzione di controllo di flusso che, specializzando la catena if-else-if, semplifica la vita al programmatore. Listruzione switch utile in tutti quei casi in cui sia necessario decidere tra opzioni multiple prese in base al controllo di una sola variabile. Questa istruzione pu sembrare sicuramente ridondante rispetto alla forma precedente, ma sicuramente rende la vita del programmatore pi semplice in fase di lettura del codice. La sintassi della istruzione la seguente: <NAME> http://www.java-net.tv tar<EMAIL> 62 switch (espressione) { case espr_costante: istruzione1 break_opzionale case espr_costante: istruzione2 break_opzionale case espr_costante: istruzione3 break_opzionale .. default: istruzione4 } espressione rappresenta ogni espressione valida che produca un intero e espr_costante una espressione che pu essere valutata completamente al momento della compilazione. Questultima per funzionamento pu essere paragonata ad una costante. Istruzione ogni istruzione Java come specificato dalle regole di espansione e break_opzionale rappresenta la inclusione opzionale della parala chiave break seguita da ;. Un esempio pu aiutarci a comprendere il significato di questo costrutto. Consideriamo lesempio del paragrafo precedente: .. int i = getUserSelection(); if(i==1) { faiQualcosa(); } else if(i==2) { faiQualcosAltro(); } else { nonFareNulla (); } . Utilizzando listruzione switch possiamo riscrivere il blocco di codice nel modo seguente: .. int i = getUserSelection(); switch (i) { case 1: faiQualcosa(); break; case 2: faiQualcosAltro(); break; default: <NAME> http://www.java-net.tv <EMAIL> 63 nonFareNulla(); } . Se la variabile intera i valesse 1, il programma eseguirebbe il blocco di codice relativo alla prima istruzione case chiamando il metodo faiQualcosa(), troverrebbe listruzione break ed uscirebbe quindi dal blocco switch passando alla prossima istruzione del bytecode. Se invece i valesse 2, verrebbe eseguito il blocco contente la chiamata al metodo faiQualcosAltro() ed essendoci una istruzione break uscirebbe anche in questo caso dal blocco switch. Infine, per qualunque altro valore di i, lapplicazione eseguirebbe il blocco identificato dalla label default. In generale, dopo che viene valutata lespressione di switch, il controllo della applicazione salta al primo case tale che espressione == espr_costante ed esegue il relativo blocco di codice. Nel caso in cui il blocco sia terminato con una istruzione break, lapplicazione abbandona lesecuzione del blocco switch saltando alla prima istruzione successiva al blocco, altrimenti il controllo viene eseguito sui blocchi case a seguire. Se nessun blocco case soddisfa la condizione ossia espressione != espr_costante la virtual machine controlla lesistenza della label default ed esegue, se presente, solo il blocco di codice relativo ed esce da switch. Listruzione while Una istruzione while permette la esecuzione ripetitiva di una istruzione utilizzando una espressione booleana per determinare se eseguire il blocco di istruzioni, eseguendolo quindi fino a che lespressione booleana non restituisce il valore false. La sintassi per questa istruzione la seguente: while (espressione_booleana){ istruzione } dove espressione_booleana una espressione valida che restituisce un valore booleano. Per prima cosa, una istruzione while controlla il valore della espressione booleana. Se restituisce true verr eseguito il blocco di codice di while. Alla fine della esecuzione viene nuovamente controllato il valore della espressione booleana per decidere se ripetere lesecuzione del blocco di codice o passare il controllo della esecuzione alla prima istruzione successiva al blocco while. Applicando le regole di espansione, anche in questo caso otteniamo la forma annidata: while (espressione_booleana) while (espressione_booleana) istruzione Il codice di esempio utilizza la forma annidata del ciclo while: <NAME> http://www.java-net.tv <EMAIL> 64 1 2 3 4 5 6 7 8 9 10 11 int i=0; while(i<10) { j=10; while(j>0) { System.out.println(i=+i+e j=+j); j--; } i++; } Listruzione do-while Una alternativa alla istruzione while rappresentata dallistruzione do-while a differenza della precedente, controlla il valore della espressione booleana alla fine del blocco di istruzioni. In questo caso quindi il blocco di istruzioni verr eseguito sicuramente almeno una volta. La sintassi di do-while la seguente: do { istruzione; } while (espressione_booleana); Listruzione for Quando scriviamo un ciclo, accade spesso la situazione in cui tre task distinti concorrono alla esecuzione del blocco di istruzioni. Consideriamo il ciclo di 10 iterazioni: i=0; while(i<10) { faiQualcosa(); i++; } Nel codice come prima cosa viene inizializzata una variabile per il controllo del ciclo, quindi viene eseguita una espressione condizionale per decidere sullo stato del ciclo, infine la variabile viene aggiornata in modo tale che possa determinare la fine del ciclo. Per semplificare la vita al programmatore, Java mette a disposizione listruzione for che include tutte queste operazioni nella stessa istruzione condizionale: for(init_statement ; conditional_expr ; iteration_stmt){ istruzione } che ha forma annidata: for(init_statement ; conditional_expr ; iteration_stmt){ for(init_statement ; conditional_expr ; iteration_stmt){ istruzione } } <NAME> http://www.java-net.tv <EMAIL> 65 init_statement rappresenta linizializzazione della variabile per il controllo del ciclo, conditional_expr lespressione condizionale, iteration_stmt laggiornamento della variabile di controllo. In una istruzione for lespressione condizionale viene sempre controllata allinizio del ciclo. Nel caso in cui restituisca un valore false, il blocco di istruzioni non verr mai eseguito. Per esempio, il ciclo realizzato nel primo esempio utilizzando il comando while pu essere riscritto utilizzando il comando for : for (int i=0 ; i<10 ; i++) faiQualcosa(); Istruzione for nei dettagli Listruzione for in Java come in C e C++ una istruzione estremamente versatile inquanto consente di scrivere cicli di esecuzione utilizzando molte varianti alla forma descritta nel paragrafo precedente. In pratica, il ciclo for consente di utilizzare zero o pi variabili di controllo, zero o pi istruzioni di assegnamento ed altrettanto vale per le espressioni booleane. Nella sua forma pi semplice il ciclo for pu essere scritto nella forma: for( ; ; ){ istruzione } Questa forma non utilizza ne variabili di controllo, ne istruzioni di assegnamento ne tanto meno espressioni booleane. In un contesto applicativo realizza un ciclo infinito. Consideriamo ora il seguente esempio: for (int i=0, j=10 ; (i<10 && j>0) ; i++, j--) { faiQualcosa(); } Il ciclo descritto utilizza due variabili di controllo con due operazioni di assegnamento distinte. Sia la dichiarazione ed inizializzazione delle variabili di controllo che le operazioni di assegnamento utilizzando il carattere , come separatore. Per concludere, la sintassi di questa istruzione pu essere quindi descritta della regola generale: for([init_stmt][,init_stmt] ; conditional_expr ; [iteration_stmt] [,iteration_stmt] ) { istruzione } Istruzioni di ramificazione Il linguaggio Java consente luso di tre parole chiave che consentono di modificare in qualunque punto del codice il normale flusso della esecuzione della applicazione con effetto sul blocco di codice in esecuzione o sul metodo corrente. Queste parole chiave sono tre (come schematizzato nella tabella seguente) e sono dette istruzioni di branchingo ramificazione. <NAME> http://www.java-net.tv <EMAIL> 66 Istruzione break continue return Istruzioni di ramificazione Descrizione Interrompe lesecuzione di un ciclo evitando ulteriori controlli sulla espressione condizionale e ritorna il controllo alla istruzione successiva al blocco attuale. Salta un blocco di istruzioni allinterno di un ciclo e ritorna il controllo alla espressione booleana che ne governa lesecuzione. Interrompe lesecuzione del metodo attuale e ritorna il controllo al metodo chiamante. Listruzione break Questa istruzione consente di forzare luscita da un ciclo aggirando il controllo sulla espressione booleana e provocandone luscita immediata in modo del tutto simile a quanto gi visto parlando della istruzione switch. Per comprenderne meglio il funzionamento torniamo per un attimo al ciclo for gi visto nei paragrafi precedenti: for (int i=0; i<10 ; i++) { faiQualcosa(); } Utilizzando listruzione break, possiamo riscrivere il codice evitando di inserire controlli allinterno del ciclo for come segue: for (int i=0; ; i++) { if(i==10) break; faiQualcosa(); } Lesecuzione del codice produrr esattamente gli stessi risultati del caso precedente. Luso di questa istruzione tipicamente legata a casi in cui sia necessario poter terminare lesecuzione di un ciclo a prescindere dai valori delle variabili di controllo utilizzate. Queste situazioni si verificano in quei casi in cui sia impossibile utilizzare un parametro di ritorno come operando allinterno della espressione booleana che controlla lesecuzione del ciclo, ed pertanto necessario implementare allinterno del blocco meccanismi specializzati per la gestione di questi casi. Un esempio tipico quello di chiamate a metodi che possono generare eccezioni10 ovvero notificare errori di esecuzione in forma di oggetti. In questi casi utilizzando il comando break possibile interrompere lesecuzione del ciclo non appena venga catturato lerrore. Listruzione continue A differenza del caso precedente questa istruzione non interrompe lesecuzione del ciclo di istruzioni, ma al momento della chiamata produce un salto alla parentesi graffa che chiude il blocco restituendo il controllo alla espressione booleana che ne determina lesecuzione. Un esempio pu aiutarci a chiarire le idee: 10 Le eccezioni verranno trattate in dettaglio a breve. <NAME> http://www.java-net.tv <EMAIL> 67 1 2 3 4 5 6 7 8 int i=-1; int pairs=0; while(I<20) { i++; if((i%2)!=0) continue; pairs ++; } Le righe di codice descritte calcolano quante occorrenze di interi pari ci sono in una sequenza di interi compresa tra 1 e 20 e memorizzano il valore in una variabile di tipo int chiamata pairs. Il ciclo while controllato dal valore della variabile i inizializzata a 1. La riga 6 effettua una controllo sul valore di i: nel caso in cui i rappresenti un numero intero dispari viene eseguito il comando continue ed il flusso ritorna alla riga 3. In caso contrario viene aggiornato il valore di pairs. Listruzione return Questa istruzione rappresenta lultima istruzione di ramificazione e pu essere utilizzata per terminare lesecuzione del metodo corrente tornando il controllo al metodo chiamante. Return pu essere utilizzata in due forme: return valore; return; La prima forma viene utilizzata per consentire ad un metodo di ritornare valori al metodo chiamante e pertanto deve ritornare un valore compatibile con quello dichiarato nella definizione del metodo. La seconda pu essere utilizzata per interrompere lesecuzione di un metodo qualora il metodo ritorni un tipo void. Package Java I package sono meccanismi per raggruppare definizioni di classe in librerie, similmente ad altri linguaggi di programmazione. Il meccanismo provvisto di una struttura gerarchica per lassegnamento di nomi alle classi in modo da evitare eventuali collisioni in caso in cui alcuni programmatori usino lo stesso nome per differenti definizioni di classe. Oltre a questo, sono molti i benefici nelluso di questo meccanismo: primo, le classi possono essere mascherate allinterno dei package implementando lincapsulamento anche a livello di file. Secondo, le classi di un package possono condividere dati e metodi con classi di altri package. Terzo, i package forniscono un meccanismo efficace per distribuire oggetti. In questo capitolo verr mostrato in dettaglio solamente il meccanismo di raggruppamento. Gli altri aspetti verranno trattati nei capitoli successivi. Assegnamento di nomi a package I package combinano definizioni di classi in un unico archivio la cui struttura gerarchica rispetta quella del file system. I nomi dei package sono separati tra loro da punto. La classe Vector ad esempio fa parte del package java.util archiviato nel file tools.jar . Secondo le specifiche, il linguaggio riserva tutti i package che iniziano con java per le classi che sono parte del linguaggio. Questo significa che nuove classi definite da un utente devono essere raggruppate in package con nomi differenti da questo. <NAME> http://www.java-net.tv <EMAIL> 68 Le specifiche suggeriscono inoltre che package generati con classi di uso generale debbano iniziare con il nome della azienda proprietaria del codice. Ad esempio se la pippo corporation avesse generato un insieme di classi dedicate al calcolo statistico, le classi dovrebbero essere contenute in un package chiamato ad esempio pippo.stat . Una volta definito il nome di un package, affinch una classe possa essere archiviata al suo interno, necessario aggiungere una istruzione package allinizio del codice sorgente che definisce la classe. Per esempio allinizio di ogni file contenente i sorgenti del package pippo.stat necessario aggiungere la riga: package pippo.stat; Questa istruzione non deve assolutamente essere preceduta da nessuna linea di codice. In generale, se una classe non viene definita come appartenente ad un package, il linguaggio per definizione assegna la classe ad un particolare package senza nome. Creazione dei package su disco Una volta definito il nome di un package, deve essere creata su disco la struttura a directory che rappresenti la gerarchia definita dai nomi. Ad esempio, le classi appartenenti al package java.util devono essere memorizzate in una gerarchia di directory che termina con java/util localizzata in qualunque punto del disco (ex. C:/classes/java/util/ schematizzato nella Figura 4-1). Per trovare le classi contenute in un package, Java utilizza la variabile di ambiente CLASSPATH che contiene le informazioni per puntare alla root del nome del package e non direttamente alle classi allinterno del package. Per esempio se il nome del package java.util e le classi sono memorizzate nella directory C:/classes/java/util/*, allora CLASSPATH dovr includere la directory C:/classes/. Sotto sistemi microsoft, una variabile CLASSPATH ha tipicamente una forma del tipo: CLASSPATH = c:\java\lib\tools.jar;d:\java\import;.;.\; Figura 4-1 : Struttura di un package Java Massimiliano Tarquini http://www.java-net.tv <EMAIL> 69 Il modificatore public Di default, la definizione di una classe Java pu essere utilizzata solo dalle classi allinterno del suo stesso package. Per esempio, assumiamo di aver scritto una applicazione in un file Appo.java non appartenente a nessun package e, supponiamo che esista una classe Stack appartenente al package app.stack . Per definizione, Appo.java non potr accedere alla definizione di classe di Stack. package app.stack; class Stack { int data[]; int ndata; void push(int i) { } int pop() { .. } } Java richiede al programmatore di esplicitare quali classi e quali membri possano essere utilizzati allesterno del package. A questo scopo Java riserva il modificatore public da utilizzare prima della dichiarazione della classe o di un membro come mostrato nella nuova versione della classe Stack detta ora classe pubblica. package app.stack; public class Stack { int data[]; int ndata; public void push(int i) { } public int pop() { .. } } Le specifiche del linguaggio richiedono che il codice sorgente di classe pubblica sia memorizzata in un file avente lo stesso nome della classe (incluse maiuscole e minuscole), ma con estensione .java. Come conseguenza alla regola, pu esistere solo una classe pubblica per ogni file di sorgente. Questa regola rinforzata dal compilatore che scrive il bytecode di ogni classe in un file avente lo stesso nome della classe (incluse maiuscole e minuscole), ma con estensione .class. Lo scopo di questa regola quello di semplificare la ricerca di sorgenti e bytecode da parte del programmatore. Per esempio supponiamo di avere tre classi A, B e C in un file unico. Se A fosse la classe pubblica (solo una lo pu essere), il codice sorgente di tutte e tre le classi dovrebbe trovarsi allinterno di un file A.java . <NAME> http://www.java-net.tv <EMAIL> 70 Quando A.java verr compilato, il compilatore creer una classe per ogni classe nel file: A.class, B.class e C.class . Questa organizzazione per quanto contorta, ha un senso logico. Se come detto la classe pubblica lunica a poter essere eseguita da altre classi allesterno del package, le altre classi rappresentano solo limplementazione di dettagli non necessarie al di fuori del package. Per concludere non mi resta che ricordare che, anche se una classe non pubblica pu essere definita nello stesso file di una classe pubblica, questo non strettamente necessario e sar compito del programmatore scegliere in che modo memorizzare le definizioni delle classi allinterno di un package. Listruzione import Il runtime di Java fornisce un ambiente completamente dinamico. Le classi non vengono caricate fino a che non sono referenziate per la prima volta durante lesecuzione della applicazione. Questo consente di ricompilare singole classi senza dover ricaricare grandi applicazioni. Dal momento che ogni classe Java memorizzata in un suo file, la virtual machine pu trovare i file binari .class appropriati cercando nelle directory specificate nelle directory definite nella variabile dambiente CLASSPATH. Inoltre, dal momento che le classi possono essere organizzate in package, necessario specificare a quale package una classe appartenga pena lincapacit della virtual machine di trovarla. Un modo per indicare il package a cui una classe appartiene quello di specificare il package ad ogni chiamata alla classe ossia utilizzando nomi qualificati11. Riprendendo la nostra classe Stack appartenente al package app.stack, il suo nome qualificato sar app.stack.Stack . Luso di nomi qualificati non sempre comodo soprattutto per package organizzati con gerarchie a molti livelli. Per venire in contro al programmatore,Java consente di specificare una volta per tutte il nome qualificato di una classe allinizio del file utilizzando la parola chiave import. Listruzione import ha come unico effetto quello di identificare univocamente una classe e quindi di consentire al compilatore di risolvere nomi di classe senza ricorrere ogni volta a nomi qualificati. Grazie allistruzione import app.stack.Stack; una applicazione sar in grado di risolvere il nome di Stack ogni volta che sia necessario semplicemente utilizzando il nome di classe Stack. Capita spesso di dover per utilizzare un gran numero di classi appartenenti ad un unico package. Per questi casi listruzione import supporta luso di un carattere fantasma : import app.stack.*; che risolve il nome di tutte le classi pubbliche di un package (app.stack nellesempio). Questa sintassi non consente altre forme e non pu essere utilizzata per caricare solo porzioni di package. Per esempio la forma import app.stack.S* non consentita. 11 Tecnicamente, in Java un nome qualificato un nome formato da una serie di identificatori separati da punto per identificare univocamente una classe. <NAME> http://www.java-net.tv <EMAIL> 71 Laboratorio 4 Controllo di flusso e distribuzione di oggetti Esercizio 1 Utilizzando le API Java, scrivere un semplice programma che utilizzando la classe Date stampi a video una stringa del tipo: Oggi : giorno_della_settimana e sono le ore hh:mm Esercizio 2 Utilizzando la classe stack definita in precedenza, scrivere un ciclo while che stampi tutti gli interi pari da 1 a 13 inserendoli nello stack. La definizione di classe di stack dovr essere memorizzato nel package esempi.lab4. <NAME> http://www.java-net.tv <EMAIL> 72 Soluzione al primo esercizio import java.util.Date; class esercizio1 { public static void main(String args[]) { Date d = new Date() ; String giorni[] = new String[7]; giorni [0] = Luned; giorni [1] = Marted; giorni [2] = Mercoled; giorni [3] = Gioved; giorni [4] = Venerd; giorni [5] = Sabato; giorni [6] = Domenica; System.out.println(Oggi : + giorni[d.getDay()] + e sono le ore + d.getHours() + : + d.getMinutes()); } } Soluzione al secondo esercizio import esempi.lab4.*; class esercizio2 { public static void main(String args[]) { Stack a = new Stack(); int i; i=1; while(i<=13) { if(i % 2 !=0) { System.out.println(i); a.push(i); } i++; } } } <NAME> http://www.java-net.tv <EMAIL> 73 Capitolo 5 Incapsulamento Introduzione Lincapsulamento di oggetti il processo di mascheramento dei dettagli dellimplementazione ad altri oggetti per evitare riferimenti incrociati. I programmi scritti con questa tecnica risultano molto pi leggibili e limitano i danni dovuto alla propagazione di un bug. Una analogia con il mondo reale rappresentata dalle carte di credito. Chiunque sia dotato di carta di credito pu eseguire una serie di operazioni bancarie attraverso lo sportello elettronico. Una carta di credito, non mostra allutente le modalit con cui si messa in comunicazione con lente bancario o ha effettuato transazioni sul conto corrente, semplicemente si limita a farci prelevare la somma richiesta tramite una interfaccia utente semplice e ben definita. In altre parole, una carta di credito maschera il sistema allutente che potr prelevare denaro semplicemente conoscendo luso di pochi strumenti come la tastiera numerica ed il codice pin. Limitando luso della carta di credito ad un insieme limitato di operazioni si pu: primo, proteggere il nostro conto corrente. Secondo, impedire allutente di modificare in modo irreparabile dati o stati interni della carta di credito. Uno degli scopi primari di un disegno object oriented, dovrebbe essere proprio quello di fornire allutente un insieme di dati e metodi che danno il senso delloggetto in questione. Questo possibile farlo senza esporre le modalit con cui loggetto tiene traccia dei dati ed implementa il corpo (metodi) delloggetto. Nascondendo i dettagli, possiamo assicurare a chi utilizza loggetto che ci che sta utilizzando sempre in uno stato consistente a meno di bug delloggetto stesso. Uno stato consistente uno stato permesso dal disegno di un oggetto. E per importante notare che uno stato consistente non corrisponde sempre allo stato spettato dallutente delloggetto. Se infatti lutente trasmette alloggetto parametri errati, loggetto si trover in uno stato consistente, ma non nello stato desiderato. Figura 5-1 : Modificatori public e private Massimiliano Tarquini http://www.java-net.tv <EMAIL> 74 Modificatori public e private Java fornisce supporto per lincapsulamento a livello di linguaggio mediante i modificatori public e private da utilizzare al momento della dichiarazione di variabili e metodi. I membri di una classe o lintera classe, definiti public, sono liberamente accessibili da ogni classe utilizzata nella applicazione. I membri di una classe definiti private possono essere utilizzati sono dai membri della stessa classe. I membri privati mascherano i dettagli della implementazione di una classe. Membri di una classe non dichiarati n public, n private saranno per definizione accessibili a tutte le classi dello stesso package. Questi membri o classi sono comunemente detti package friendly. La regola stata schematizzata nella Figura 5-1. Private Il modificatore private realizza incapsulamento a livello di definizione di classe e serve a definire membri che devono essere utilizzati solo da altri membri della stessa classe di definizione. Lintento di fatto quello di nascondere porzioni di codice della classe che non devono essere utilizzati da altre classi. Un membro privato pu essere utilizzato da di qualsiasi membro statico, e non, della stessa classe di definizione con laccorgimento che i membri statici possono solo utilizzare membri (dati od oggetti) statici o entit di qualunque tipo purch esplicitamente passate per parametro. Per dichiarare un membro privato si utilizza la parola chiave private anteposta alla dichiarazione di un metodo o di un dato: private identificatore var_name; oppure nel caso di metodi: private return_type method_name(arg_type name [,arg_type name] ) { istruzioni } Public Il modificatore public consente di definire classi o membri di una classe visibili da qualsiasi classe allinterno dello stesso package e non. Public deve essere utilizzato per definire linterfaccia che loggetto mette a disposizione dellutente. Tipicamente metodi membro public utilizzano membri private per implementare le funzionalit delloggetto. Per dichiarare una classe od un membro pubblico si utilizza la parola chiave public anteposta alla dichiarazione : public identificatore var_name; nel caso di metodi: public return_type method_name(arg_type name [,arg_type name] ) { istruzioni } <NAME> http://www.java-net.tv tar<EMAIL>-one-mail.net 75 infine nel caso di classi: public class ObjectName { data_declarations method_declarations } Il modificatore protected Un altro modificatore messo a disposizione dal linguaggio Java protected. Membri di una classe dichiarati protected possono essere utilizzati sia dai membri della stessa classe che da altre classi purch appartenenti allo stesso package (Figura 5-2). Figura 5-2 : Modificatore protected Per dichiarare un membro protected si utilizza la parola chiave protected anteposta alla dichiarazione : protected identificatore var_name; nel caso di metodi: protected return_type method_name(arg_type name [,arg_type name] ) { istruzioni } Di questo modificatore torneremo a parlarne nei dettagli nel prossimo capitolo dove affronteremo il problema della ereditariet. <NAME> http://www.java-net.tv <EMAIL> 76 Un esempio di incapsulamento Nellesempio mostrato di seguito, i dati della classe Impiegato (nome, e affamato) sono tutti dichiarati privati. Questo previene la lettura o peggio la modifica del valore dei dati da parte di DatoreDiLavoro. Daltra parte, la classe dotata di metodi pubblici (haiFame() e nome()), che consentono ad altre classi di accedere al valore dei dati privati. Nel codice sorgente, luso dei modificatori crea una simulazione ancora pi realistica limitando lazione di DatoreDiLavoro nella interazione DatoreDiLavoro / Impiegato. Ad esempio, DatoreDiLavoro non pu cambiare il nome di Impiegato. ../javanet/mattone/cap5/Impiegato.java package javanet.mattone.cap5; public class Impiegato { private String nome; private boolean affamato=true; public boolean haiFame() { return affamato; } public String nome() { return nome; } public void vaiAPranzo(String luogo) { // mangia affamato = false; } } ../javanet/mattone/cap5/DatoreDiLavoro.java package javanet.mattone.cap5; public class DatoreDiLavoro { public void siiCorrettoConImpiegato(Impiegato impiegato) { // if (person.Hungry) una chiamata illegale perch Hungry private // person.Hyngry = true un assegnamento illegale if (impiegato.haiFame()) { impiegato.vaiAPranzo("Ristorante sotto l''ufficio"); } } } Loperatore new Per creare un oggetto attivo dalla sua definizione di classe, Java mette a disposizione loperatore new. Questo operatore paragonabile alla malloc in C, ed identico allo stesso operatore in C++. <NAME> http://www.java-net.tv <EMAIL> 77 New oltre a generare un oggetto, consente di assegnargli lo stato iniziale ritornando un riferimento (indirizzo di memoria) al nuovo oggetto che pu essere memorizzata in una variabile reference di tipo compatibile mediante loperatore di assegnamento =. La responsabilit della gestione della liberazione della memoria allocata per loggetto non pi in uso del il garbage collector. Per questo motivo, a differenza di C++ Java non prevede nessun meccanismo esplicito per distruggere un oggetto creato. La sintassi delloperatore new prevede un tipo seguito da un insieme di parentesi. Le parentesi indicano che per creare loggetto verr chiamata un metodo chiamato costruttore, responsabile della inizializzazione dello stato delloggetto (Figura 5-3). Figura 5-3 : Loperatore new Costruttori Tutti i programmatori, esperti e non, conoscono il pericolo che costituisce una variabile non inizializzata. Fare un calcolo matematico con una variabile intera non inizializzata pu generare risultati errati. In una applicazione object oriented, un oggetto una entit molto pi complessa di un tipo primitivo come int e, lerrata inizializzazione dello stato delloggetto pu essere causa della terminazione prematura della applicazione o della generazione di bug intermittenti difficilmente controllabili. In molti altri linguaggi di programmazione, il responsabile della inizializzazione delle variabili il programmatore. In Java questo impossibile dal momento che potrebbero essere dati membro privati delloggetto e quindi inaccessibili alloggetto utente. I costruttori sono metodi speciali chiamati quando viene creata una nuova istanza di classe e servono ad inizializzare lo stato iniziale delloggetto. Questi metodi hanno lo stesso nome della classe di cui sono membro e non restituiscono nessun tipo. Se una classe non provvista di costruttore, Java ne utilizza uno speciale di default che <NAME> http://www.java-net.tv [email protected] 78 non fa nulla. Dal momento che il linguaggio garantisce la chiamata al costruttore ad ogni instanziamento di un oggetto, un costruttore scritto intelligentemente garantisce che tutti i dati membro vengano inizializzati. Nella nuova versione della classe Impiegato, il costruttore viene dichiarato esplicitamente dal programmatore e si occupa di impostare lo stato iniziale dei dati membro privati: ../javanet/mattone/cap5/second/Impiegato.java package javanet.mattone.cap5.second; public class Impiegato { private String nome; private boolean affamato; public Impiegato haiFame() { affamato=true; nome=Massimiliano; } public boolean haiFame() { return affamato; } public String nome() { return nome; } public void vaiAPranzo(String luogo) { // mangia affamato = false; } } Java supporta molte caratteristiche per i costruttori, ed esistono molte regole per la loro creazione. Un esempio di costruttori In questo esempio, la definizione delloggetto Stack contiene un solo costruttore che non prende argomenti ed imposta la dimensione massima dello stack a 10 elementi. ../javanet/mattone/cap5/Stack.java package javanet.mattone.cap5; public class Stack { private int maxsize; private int data[]; private int first; <NAME> http://www.java-net.tv <EMAIL> 79 public Stack) { maxsize = 10; data = new int[10]; first=0; } int pop() { if (first > 0) { first--; return data[first]; } return 0; // Bisogna tornare qualcosa } void push(int i) { if (first < maxsize) { data[first] = i; first++; } } } Luso dei costruttori ci consente di inizializzare, al momento della creazione delloggetto tutti i dati membro (ora dichiarati privati), compreso larray che conterr i dati dello stack. Rispetto alla prima definizione della classe Stack fatta nel laboratorio 3, non sar pi necessario creare lo stack al momento della chiamata al metodo push(int) rendendo di conseguenza inutile il controllo sullo stato dellarray ad ogni sua chiamata: if (data == null) { first = 0; data = new int[20]; } Di fatto, utilizzando il costruttore saremo sempre sicuri che lo stato iniziale della classe correttamente impostato. Overloading dei costruttori Al programmatore consentito scrivere pi di un costruttore per una data classe a seconda delle necessit di disegno delloggetto, permettendogli di passare diversi insiemi di dati di inizializzazione. Ad esempio, un oggetto Stack potrebbe di default contenere al massimo 10 elementi. Un modo per generalizzare loggetto quello di scrivere un costruttore che prendendo come parametro di input un intero, inizializza la dimensione massima dello Stack a seconda delle necessit della applicazione. ../javanet/mattone/cap5/Stack.java package javanet.mattone.cap5; public class Stack { <NAME> http://www.java-net.tv <EMAIL> 80 private int maxsize; private int data[]; private int first; public Stack) { maxsize = 10; data = new int[10]; first=0; } public Stack (int size) { maxsize=size; data = new int[size]; first= 0; } int pop() { if (first > 0) { first--; return data[first]; } return 0; // Bisogna tornare qualcosa } void push(int i) { if (first < maxsize) { data[first] = i; first++; } } } Lutilizzo dei due costruttori della classe Stack ci consente di creare oggetti Stack di dimensioni variabili chiamando il costruttore che prende come parametro di input un intero che rappresenta le dimensioni dello stack: public Stack (int size) { maxsize=size; data = new int[size]; first= 0; } Per creare una istanza della classe Stack invocando il costruttore Stack(int) baster utilizzare loperatore new come segue: int dimensioni=10; Stack s = new Stack(dimensioni); Restrizione sulla chiamata ai costruttori Java permette una sola chiamata a costruttore al momento della referenziazione delloggetto. Questo significa che nessun costruttore pu essere eseguito Massimiliano Tarquini http://www.java-net.tv <EMAIL> 81 nuovamente dopo la creazione delloggetto. Di fatto, il codice Java descritto di seguito produrr un errore di compilazione sulla riga 3: 1 2 3 int dimensioni=10; Stack s = new Stack(dimensioni); s.Stack(20); Cross Calling tra costruttori Java consente ad un costruttore di chiamare altri costruttori appartenenti alla stessa defnizione di classe. Questo meccanismo utile inquanto i costruttori generalmente hanno funzionalit simili e, un costruttore che assume uno stato di default, potrebbe chiamarne uno che prevede che lo stato sia passato come parametro, chiamandolo e passando i dati di default. Guardando la definizione di Stack, notiamo che i due costruttori fanno esattamente la stessa cosa. Per ridurre la quantit di codice, possiamo chiamare un costruttore da un altro. Per chiamare un costruttore da un altro, necessario utilizzare una sintassi speciale: this(parameter_list); Nella chiamata, parameter_list rappresenta la lista di parametri del costruttore che si intende chiamare. Una chiamata cross-call tra costruttori, deve essere la prima riga di codice del costruttore chiamante. Qualsiasi altra cosa venga fatta prima, compresa la definizione di variabili, Java non consente di effettuare tale chiamata. Il costruttore corretto viene determinato in base alla lista dei parametri paragonando parameter_list con la lista dei parametri di tutti i costruttori della classe. ../javanet/mattone/cap5/Stack.java package javanet.mattone.cap5; class Stack { private int data[]; private int max; //Dimensione massima private int size; //Dimensione Corrente public Stack () { this(10); } public Stack (int max_size) { data = new int[max_size]; size = 0; max = max_size; } void push(int n) { if(size<max) { data[size]=n; size++; } else <NAME> http://www.java-net.tv <EMAIL> 82 return; } int pop() { if(size > 0) { size--; return data[size]; } return 0; // Bisogna tornare qualcosa } } <NAME> http://www.java-net.tv <EMAIL> 83 Laboratorio 5 Incapsulamento di oggetti Esercizio 1 Definire un oggetto chiamato Set che rappresenta un insieme di interi. Linsieme deve avere al massimo tre metodi: boolean isMember(int); //Ritorna true se il numero nellinsieme void addMember(int); //Aggiunge un numero allinsieme void showSet(); //stampa a video il contenuto dellinsieme nel formato: // {1, 4, 5, 12} Assicurarsi di incapsulare loggetto utilizzando i modificatori public/private appropriati. <NAME> http://www.java-net.tv <EMAIL> 84 Soluzione del primo esercizio class Set { private int numbers[]; private int cur_size; public Set() { cur_size=0; numbers = new int[100]; } public boolean isMember(int n) { int i; i=0; while(i < cur_size) { if(numbers[i]==n) return true; i++; } return false; } public void addMember(int n) { if(isMember(n)) return; if(cur_size == numbers.length) return; numbers[cur_size++] = n; } public void showSet() { int i; i=0; System.out.println({); while(i < cur_size) { System.out.println(numbers[i] + , ); i++; } System.out.println(}); } } <NAME> http://www.java-net.tv <EMAIL> 85 Capitolo 6 Ereditariet Introduzione Lereditariet la caratteristica dei linguaggi object oriented che consente di utilizzare classi come base per la definizione di nuove entit che specializzano il concetto. Lereditariet fornisce inoltre un ottimo meccanismo per aggiungere funzionalit ad un programma con rischi minimi per le funzionalit esistenti, nonch un modello concettuale che rende un programma object oriented auto-documentante rispetto ad un analogo scritto con linguaggi procedurali. Per utilizzare correttamente lereditariet, il programmatore deve conoscere a fondo gli strumenti forniti dal linguaggio in supporto. Questo capitolo introduce al concetto di ereditariet in Java, alla sintassi per estendere classi, alloverloading e overriding di metodi e ad una caratteristica molto importante di Java che include per default la classe Object nella gerarchia delle classi. Disegnare una classe base Quando disegniamo una classe, dobbiamo sempre tenere a mente che con molta probabilit ci sar qualcuno che in seguito potrebbe aver bisogno di utilizzarla tramite il meccanismo di ereditariet. Ogni colta che si utilizza una classe per ereditariet ci si riferisce a questa come alla classe baseo superclasse. Il termine ha come significato che la classe stata utilizzata come fondamenta per una nuova definizione. Utilizzando lereditariet, tutte le funzionalit della classe base sono trasferite alla nuova classe comunemente detta classe derivatao sottoclasse. Quando si fa uso della ereditariet, bisogna sempre tener ben presente alcuni concetti. Lereditariet consente di utilizzare una classe come punto di partenza per la scrittura di nuove classi. Questa caratteristica pu essere vista come una forma di riutilizzazione del codice: i membri della classe base sono concettualmente copiati nella nuova classe. Come conseguenza diretta, lereditariet consente alla classe base di modificare la superclasse. In altre parole, ogni aggiunta o modifica ai metodi della superclasse sar applicata solo alle classe derivata. La classe base risulter quindi protetta dalla generazione di nuovi eventuali bug, che rimarranno circoscritti alla classe derivata. La classe derivata per ereditariet, supporter tutte le caratteristiche della classe base. In definitiva, tramite questa metodologia sar possibile creare nuove variet di entit gi definite mantenendone tutte le caratteristiche e le funzionalit. Questo significa che se una applicazione in grado di utilizzare una classe base, sar in grado di utilizzarne la derivata allo stesso modo. Per questi motivi, importante che una classe base rappresenti le funzionalit generiche delle varie specializzazioni che andremo a definire. Proviamo a pensare ad un veicolo generico: questo potr muoversi, svoltare a sinistra o a destra o fermarsi. Di seguito la definizione della classe della classe contenete lentry point della applicazione. <NAME> http://www.java-net.tv <EMAIL> 86 public class Driver { public static void main(String args[]) { Veicolo v = new Veicolo(); v.go(); v.left(); v.diritto(); v.stop(); } } public class Veicolo { String nome; int velocita; //in Km/h int direzione; final static int STRAIGHT=0; final static int LEFT = -1; final static int RIGHT = 1; public Veicolo() { velocita=0; direzione = STRAIGHT; nome = Veicolo; } public void go() { velocita=1; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } public void stop() { velocita=0; System.out.println(nome + si fermato); } public void left() { direzione =LEFT; System.out.println(nome + ha sterzato a sinistra); } public void right() { direzione =RIGHT; System.out.println(nome + ha sterzato a destra); } public void diritto() { direzione = STRAIGHT; System.out.println(nome + ha sterzato a sinistra); } } Overload di metodi Per utilizzare a fondo lereditariet, introdurre unaltra importante caratteristica di Java: quella di consentire loverloading di metodi. Fare loverloading di un metodo significa dotare una classe di metodi aventi stesso nome ma con parametri differenti. <NAME> http://www.java-net.tv <EMAIL>-one-mail.net 87 Consideriamo ad esempio il metodo go() della classe Veicolo nellesempio precedente: il metodo simula la messa in moto del veicolo e la mette in moto alla velocit di 1 Km/h. Apportiamo quindi qualche modifica alla definizione di classe: public class Veicolo { String nome; int velocita; //in Km/h int direzione; final static int STRAIGHT=0; final static int LEFT = -1; final static int RIGHT = 1; public Veicolo() { velocita=0; direzione = STRAIGHT; nome = Veicolo; } public void go() { velocita=1; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } public void go(int quale_velocita) { velocita= quale_velocita; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } public void stop() { velocita=0; System.out.println(nome + si fermato); } public void left() { direzione =LEFT; System.out.println(nome + ha sterzato a sinistra); } public void right() { direzione =RIGHT; System.out.println(nome + ha sterzato a destra); } public void diritto() { direzione = STRAIGHT; System.out.println(nome + ha sterzato a sinistra); } } Avendo a disposizione anche il metodo go(int quale_velocita) potremo migliorare la nostra simulazione facendo in modo che il veicolo possa accelerare o decelerare ad una determinata velocit. Prima di terminare il paragrafo, ecco alcune linee guida per utilizzare loverloading di metodi. Primo, non possono esistere due metodi aventi nomi e lista dei parametri contemporaneamente uguali. Secondo, i metodi di cui si fatto loverloading devono implementare vari aspetti di una medesima funzionalit. <NAME> http://www.java-net.tv <EMAIL> 88 Nellesempio, aggiungere un metodo go() che provochi la svolta della macchina non avrebbe senso. Estendere una classe base Definita la classe Veicolo, sar possibile definire nuovi veicoli estendendo la classe base. La nuova classe, manterr tutti i dati ed i metodi membro della superclasse con la possibilit di aggiungerne di nuovi o modificare quelli esistenti. La sintassi per estendere una classe a partire dalla classe base la seguente: class nome_classe extends nome_super_classe Lesempio seguente mostra come creare un oggetto Macchina a partire dalla classe base Veicolo. public class Macchina extends Veicolo { public Macchina() { velocita=0; direzione = STRAIGHT; nome = Macchina; } } public class Driver { public static void main(String args[]) { Macchina fiat = new Macchina (); fiat.go(); fiat.left(); fiat.diritto(); fiat.stop(); } } Estendendo la classe Veicolo, ne ereditiamo tutti i dati membro ed I metodi. Lunico cambiamento che abbiamo dovuto apportare quello di creare un costruttore ad hoc. Il nuovo costruttore semplicemente modifca il contenuto della variabile nome affinch lapplicazione stampi I messaggi corretti. Come mostrato nel nuovo codice della classe Driver, utilizzare il nuovo veicolo equivale ad utilizzare il Veicolo generico. Ereditariet ed incapsulamento Nellesempi precedente si nota facilmente che il codice del metodo costruttore della classe Veicolo molto simile a quello del costruttore della classe Macchina di conseguenza potrebbe tornare utile utilizzare il costruttore della classe base per effettuare almeno una parte delle operazioni di inizializzazione. Facciamo qualche considerazione: Cosa potrebbe succedere se sbagliassimo nella definizione del costruttore della classe derivata? Nella classe base potrebbero esserci dei dati privati che il costruttore della classe derivata non potrebbe aggiornare. Cosa fare? <NAME> http://www.java-net.tv <EMAIL> 89 class A { private int stato; public A() { stato=10; } public int f() { //ritorna valori basati sullo stato impostato a 10 } } class B extends A { private int var; public B() { var=20; // stato = 20; ISTRUZIONE ILLEGALE } public int g() { return f(); // Problemi di runtime dal momento che A.stato // non stato inizializzato correttamente } } Per assicurare che un oggetto venga inizializzato ad uno stato corretto, i dati della classe devono essere inizializzati con i valori corretti, ma questo esattamente il compito di un costruttore. In altre parole, Java applica lincapsulamento anche a livello di ereditariet e ci significa che non solo Java deve consentire luso del costruttore della classe derivata, ma anzi deve forzare il programmatore affinch lo utilizzi. Tornando al nostro esempio con Macchina e Veicolo, la seconda condivide tutti i dati membro con la prima, ed quindi possibile modificarne lo stato dei dati membro mediante accesso diretto ai dati. Se la classe Veicolo avesse per avuto dei dati privati, lunico modo per modificarne lo state sarebbe stato attraverso i metodi pubblici della classe. In questo modo la classe base gode di tutti i benefici dellincapsulamento (isolamento dei bug, facilit di tuning ecc.). Ereditariet e costruttori Il meccanismo utilizzato da Java per assicurare la chiamata di un costruttore per ogni classe di una gerarchia il seguente. Primo, ogni classe deve avere un costruttore. Se il programmatore non ne implementa alcuno, Java assegner alla classe un costruttore di default con blocco del codice vuoto e senza lista di parametri: public Some_Costructor() { } <NAME> http://www.java-net.tv [email protected] 90 Il costruttore di default viene utilizzato solamente in questo caso. Se il programmatore implementa un costruttore specializzato con lista di parametri di input non vuota, Java elimina completamente il costruttore di default. Secondo, se una classe derivata da unaltra lutente pu chiamare il costruttore della classe base immediatamente precedente nella gerarchia utilizzando la sintassi: super(argument_list) dove argument_list la lista dei parametri del costruttore da chiamare. Una chiamata esplicita al costruttore della classe base deve essere effettuata prima di ogni altra operazione incluso la dichiarazione di variabili. Public user_defined_costructor() { super(23); //Chiama il costruttore della classe base che accetta un intero //come parametro int i; } Infine, se lutente non effettua una chiamata esplicita al costruttore della classe base, Java esegue implicitamente la chiamata. In questo caso, Java non passa argomenti al costruttore della classe base cosa che generer un errore in fase di compilazione se non esiste un costruttore senza argomenti. Se avessimo compilato il codice dellesempio precedente class A { private int stato; public A() { stato=10; } public int f() { //ritorna valori basati sullo stato impostato a 10 } } class B extends A { private int var; public B() { //Chiamata implicita a super(); var=20; } public int g() { return f(); //Lavora correttamente } } Avremmo notato subito che il codice funziona correttamente ed i due oggetti sarebbero stati sempre in uno stato consistente proprio grazie alla chiamata implicita che Java effettua nel costruttore di B sul costruttore della super classe A. <NAME> http://www.java-net.tv <EMAIL> 91 Aggiungere nuovi metodi Quando estendiamo una classe, possiamo aggiungere nuovi metodi alla classe derivata. Per esempio, una Macchina generalmente possiede un clacson. Aggiungendo il metodo honk(), continueremo a mantenere tutte le vecchie funzionalit, ma ora la macchina in grado di suonare il clacson. public class Macchina extends Veicolo { public Macchina() { velocita=0; direzione = STRAIGHT; nome = Macchina; } public void honk() { System.out.println(nome + ha attivato il clacson); } } public class Driver { public static void main(String args[]) { Macchina fiat = new Macchina (); fiat.go(); fiat.left(); fiat.diritto(); fiat.stop(); fiat.honk(); } } Overriding di metodi Se un metodo ereditato non lavorasse come ci aspettiamo, possiamo sovrascrivere il metodo originale. Questo semplicemente significa riscrivere il metodo coinvolto allinterno della classe derivata. Anche in questo caso, riscrivendo nuovamente il metodo solo nella nuova classe, non c pericolo che la vecchia venga rovinata. Il nuovo metodo verr quindi chiamato al posto del vecchio anche se la chiamata venisse effettuata da un metodo ereditato dalla classe base. public class Macchina extends Veicolo { public Macchina() { velocita=0; direzione = STRAIGHT; nome = Macchina; } public void go(int quale_velocita) { if(quale_velocita<120) velocita= quale_velocita; else <NAME> http://www.java-net.tv <EMAIL> 92 speed = 120; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } public void honk() { System.out.println(nome + ha attivato il clacson); } } public class Driver { public static void main(String args[]) { Macchina fiat = new Macchina (); fiat.go(300); fiat.left(); fiat.diritto(); fiat.stop(); fiat.honk(); } } Chiamare metodi della classe base La parola chiave super() pu essere utilizzata anche nel caso in cui sia necessario richiamare un metodo della super classe ridefinito nella classe derivata con il meccanismo di overriding. Ritorniamo ancore sul codice della classe Macchina: public class Macchina extends Veicolo { public void go(int quale_velocita) { if(quale_velocita<120) velocita= quale_velocita; else speed = 120; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } . } il metodo go() della classe effettua un check della variabile di input per limitare la velocit massima della macchina, quindi effettua un assegnamento identico a quello effettuato nel metodo ridefinito della superclasse: public void go(int quale_velocita) { velocita= quale_velocita; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } Il metodo go() della classe macchina pu quindi essere riscritto nel modo seguente: <NAME> http://www.java-net.tv <EMAIL> 93 public class Macchina extends Veicolo { public void go(int quale_velocita) { if(quale_velocita<120) velocita= quale_velocita; else super.go(quale_velocita); System.out.println(nome + si sta movendo a: + velocita+ Kmh); } . } Eimportante notare che a differenza della chiamata a costruttori che richiedeva solo luso della parola chiave super ed eventualmente la lista dei parametri, ora necessario utilizzare loperatore .specificando il nome del metodo da chiamare. Flessibilit delle variabili reference Una volta che una classe Java stata derivata, Java consente alle variabili reference che rappresentano il tipo della classe base di referenziare ogni istanza di un oggetto derivato da essa nella gerarchia definita dalla ereditariet. Veicolo v = new Macchina(); v.go(10); //Chiama il metodo go()dichiarato in Macchina Il motivo alla base di questa funzionalit che tutti gli oggetti derivati hanno sicuramente almeno tutti i metodi della classe base (li hanno ereditati), e quindi non ci dovrebbero essere problemi nellutilizzarli. Nel caso in cui un metodo sia stato ridefinito mediante overriding, queste tipo di referenziamento comunque effettuer una chiamata al nuovo metodo. Run-time e compile-time Questo paragrafo introduce i due concetti di run-time e compile-time. Il tipo rappresentato a compile-time di una espressione, il tipo dellespressione come dichiarato formalmente nel codice sorgente. Il tipo rappresentato a run-time invece quello determinato quando il programma in esecuzione. Il tipo a compile-time sempre costante, mentre quello a run-time pu variare. Nel nostro esempio del Veicolo e della Macchina, una variabile reference di tipo Veicolo rappresenta il tipo Veicolo a compile-time uguale, e il tipo Macchina a runtime. Veicolo v = new Macchina(); Volendo fornire una regola generale, diremo che il tipo rappresentato al compiletime da una variabile specificato nella sua dichiarazione, mentre quello a run-time il tipo attualmente rappresentato. I tipi primitivi a run-time (int, float, double etc. ) invece rappresentano lo stesso tipo del compile-time. // v ha tipo a compile-time di Veicolo ed al run-time di Macchina Veicolo v = new Macchina(); <NAME> http://www.java-net.tv <EMAIL> 94 //Il tipo a run-time di v cambia in Veicolo v = new Veicolo(); //b rappresenta al compile-time il tipo Libro, al run-time il tipo LibroDiMatematica Libro b = new LibroDiMatematica() // i rappresenta un tipo int sia a run-time che a compile-time int i; // i sempre un intero (4.0 viene convertito in intero) i = 4.0; E comunque importante sottolineare che, una variabile reference potr referenziare solo qualcosa il cui tipo sia in qualche modo compatibile con il tipo rappresentato al compile-time. Questa compatibilit rappresentata dalla relazione di ereditariet: tipi derivati sono sempre compatibili con le variabili reference dei predecessori. Accesso a metodi attraverso variabili reference Consideriamo ora le linee di codice: Macchina c = new Macchina (); Veicolo v = c; c.honk(); v.honk(); Se proviamo a compilare il codice, il compilatore ci ritorner un errore sulla quarta riga del sorgente. Questo perch, dal momento che il tipo rappresentato da una variabile al run-time pu cambiare, il compilatore assumer per definizione che la variabile reference sta referenziando loggetto del tipo rappresentato al compiletime. In altre parole, anche se una classe Macchina possiede un metodo honk(), questo non sar utilizzabile tramite una variabile reference di tipo veicolo. Cast dei tipi Java fornisce un modo per girare intorno a questa limitazione. Il cast di un tipo consente di dichiarare che una variabile reference temporaneamente rappresenter un tipo differente da quello rappresentato al compile-time. La sintassi di una cast di tipo la seguente: (new_type) variable Dove new_type il tipo desiderato, e variable la variabile che vogliamo convertire temporaneamente. Riscrivendo lesempio precedente come segue: Macchina c = new Macchina (); Veicolo v = c; c.honk(); ((Macchina) v).honk(); <NAME> http://www.java-net.tv <EMAIL> 95 Il codice verr compilato ed eseguito correttamente. Loperazione di cast possibile su tutti i tipi purch la variabile reference ed il nuovo tipo siano compatibili. Il cast di tipo di una variabile reference, cambia realmente il tipo rappresentato al compile-time della espressione, ma non loggetto in se stesso. Il cast su un tipo provocher la terminazione della applicazione se, il tipo rappresentato al run-time dalloggetto non rappresenta il tipo desiderato al momento della esecuzione. Loperatore instanceof Dal momento che in una applicazione Java esistono variabili reference in gran numero, a volte utile determinare al run-time, che tipo di oggetto la variabile sta referenziando. A tal fine Java supporta loperatore booleano instanceof che controlla il tipo di oggetto referenziato al run-time da una variabile reference. La sintassi formale la seguente: A instanceof B Dove A rappresenta una variabile reference, e B un tipo referenziabile. Il tipo rappresentato al run-time dalla variabile reference A verr confrontato con il tipo definito da B. Loperatore torner uno tra i due possibili valori true o false. Nel primo caso (true) saremo sicuri che il tipo rappresentato da A al run-time consente di rappresentare il tipo rappresentato da B. False, indica che A referenzia loggetto null oppure che non rappresenta il tipo definito da B. In poche parole, se possibile effettuare il cast di A in B, instanceof ritorner true. Veicolo v = new Macchina(); v.honk(); //errore di compilazione -------------------------if(v instanceof Macchina) ((Macchina)v).honk(); //Compila ed esegue correttamente -------------------------v = new Veicolo; if(v instanceof Macchina) ((Macchina)v).honk(); //Compila ed esegue correttamente inquanto if //previene lesecuzione Loggetto Object Quando in Java viene creato un nuovo oggetto che non estende nessuna classe base, Java ne causer lestensione automatica delloggetto Object. Questo meccanismo implementato per garantire alcune funzionalit base comuni a tutte le classi. Queste funzionalit includono la possibilit di esprimere lo stato di un oggetto in forma di String (tramite il metodo ereditato toString()), la possibilit di comparare due oggetti tramite il metodo equals() e terminare loggetto tramite il metodo finalize(). Questultimo metodo utilizzato dal garbage collector nel momento in cui elimina loggetto rilasciando la memoria, e pu essere modificato per poter gestire situazioni non gestibili dal garbage collector quali referenze circolari. <NAME> http://www.java-net.tv <EMAIL> 96 Il metodo equals() Il metodo equals() ereditato dalla classe Object, necessario dal momento che le classi istanziate vengono referenziate ossia le variabili reference si comportano come se. Questo significa che loperatore di comparazione == insufficiente inquanto opererebbe a livello di reference e non a livello di stato delloggetto. Per capire meglio il funzionamento di questo metodo, definiamo una classe Punto che rappresenta un punto in uno spazio a due dimensioni ed effettua loverriding di equals(Object) public class Punto { public int x,y; public Punto(int xc, int yc) { x=xc; y=yc; } public boolean equals(Object o) { if (o instanceof Punto) { Punto p = (Punto)o; if (p.x == x && p.y==y) return true; } return false; } } . public static void main(String args[]) { Point a,b; a= new Point(1,2); b= new Point(1,2); if (a==b) . //restituisce false if (a.equals(b)) . //restituisce false Rilasciare risorse esterne Il metodo finalize() di una classe Java viene chiamato dal garbage collector prima di rilasciare loggetto e liberare la memoria allocata. Tipicamente questo metodo utilizzato in quei casi in cui sia necessario gestire situazioni di referenza circolare, oppure situazione in cui loggetto utilizzi metodi nativi (metodi esterni a Java e nativi rispetto alla macchina locale) che utilizzano funzioni scritte in altri linguaggi. Dal momento che situazioni di questo tipo coinvolgono risorse al di fuori del controllo del garbage collector12, finalize() viene chiamato per consentire al programmatore di implementare meccanismi di gestione esplicita della memoria. Di default questo metodo non fa nulla. 12 Ad esempio nel caso in cui si utilizzi una funzione C che fa uso della malloc() per allocare memoria <NAME> http://www.java-net.tv <EMAIL> 97 Rendere gli oggetti in forma di stringa Il metodi toString() utilizzato per implementare la conversione in String di una classe. Tutti gli oggetti definiti dal programmatore, dovrebbero contenere questo metodo che ritorna una stringa rappresentante loggetto. Tipicamente questo metodo viene riscritto in modo che ritorni informazioni relative alla versione delloggetto ed al programmatore che lo ha disegnato. <NAME> http://www.java-net.tv <EMAIL> 98 Laboratorio 6 Introduzione alla ereditariet d Esercizio 1 Creare, a partire dalla classe Veicolo, nuovi tipi di veicolo mediante il meccanismo della ereditariet: Cavallo, Nave, Aeroplano. public class Veicolo { String nome; int velocita; //in Km/h int direzione; final static int STRAIGHT=0; final static int LEFT = -1; final static int RIGHT = 1; public Veicolo() { velocita=0; direzione = STRAIGHT; nome = Veicolo; } public void go() { velocita=1; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } public void go(int quale_velocita) { velocita= quale_velocita; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } public void stop() { velocita=0; System.out.println(nome + si fermato); } public void left() { direzione =LEFT; System.out.println(nome + ha sterzato a sinistra); } public void right() { direzione =RIGHT; System.out.println(nome + ha sterzato a destra); } public void diritto() { direzione = STRAIGHT; System.out.println(nome + ha sterzato a sinistra); } } <NAME> http://www.java-net.tv <EMAIL> 99 Esercizio 2 Trasformare la classe Driver in una definizione di classe completa (non pi contenente solo il metodo main). La nuova definizione deve contenere un costruttore che richiede un Veicolo come parametro di input e sia in grado di riconoscere le limitazioni in fatto di velocit massima del veicolo preso in input. Aggiungere alla classe Driver il metodo sorpassa(Veicolo) e spostare il metodo main in una nuova classe. Creare alcuni autisti e veicoli ed effettuate la simulazione. <NAME> http://www.java-net.tv <EMAIL> 100 Soluzione al primo esercizio public class Macchina extends Veicolo { public Macchina() { velocita=0; direzione = STRAIGHT; nome = Macchina; } public void go(int quale_velocita) { if(quale_velocita<120) velocita= quale_velocita; else speed = 120; System.out.println(nome + si sta movendo a: + velocita+ Kmh); } public void honk() { System.out.println(nome + ha attivato il clacson); } } public class Cavallo extends Veicolo { int stanchezza; // range da 0 a 10 public Cavallo (String n) { name = n + il cavallo; velocita=0; direzione = STRAIGHT; stanchezza = 0; } public void go(int velocita) { int velocita_massima = 20 stanchezza; if(velocita > velocita_massima) velocita= velocita_massima super.go(velocita); if(velocita > 10 && stanchezza <10) stanchezza++; } public void stop() { stanchezza = stanchezza /2; super.stop(); } } public class Driver { public static void main(String args[]) { Macchina fiat = new Macchina (); <NAME> http://www.java-net.tv <EMAIL> 101 fiat.go(); fiat.left(); fiat.diritto(); fiat.stop(); Cavallo furia = new Cavallo(Furia); furia.go(30); furia.left(); furia.right(); furia.go(15); furia.go(9); furia.go(12); furia.go(20); } } Soluzione al secondo esercizio class Driver { String nome; Veicolo trasporto; public Driver(String nome, Veicolo v) { this.nome=nome; trasporto = v; } public void sorpassa(Driver altro_autista) { int velocita_sorpasso = altro_autista.trasporto.velocita+1; System.out.println(nome + sta sorpassando un + altro_autista.trasporto.nome + con + trasporto.nome); trasporto.go(velocita_sorpasso); if(trasporto.velocita < velocita_sorpasso) System.out.println(Questo trasporto troppo lento per superare); else System.out.println(Lautista +altro_autista.nome+ha mangiato la mia polvere); } public void viaggia(int velocita_di_marcia) { trasporto.diritto(); trasporto.go(velocita_di_marcia); } } class Simulazione { public static void main(String args[]) { Driver max = new Driver(Max, new Cavallo(Furia)); Driver catia = new Driver(Catia, new Macchina()); Driver franco = new Driver(Franco, new Macchina()); <NAME> http://www.java-net.tv <EMAIL> 102 max.viaggia(15); franco.viaggia(30); catia.viaggia(40); max.sorpassa(franco); franco.sorpassa(catia); catia.sorpassa(max); } } <NAME> http://www.java-net.tv <EMAIL> 103 Capitolo 7 Eccezioni Introduzione Le eccezioni sono utilizzate in Java in quelle situazioni in cui sia necessario gestire condizioni di errore, ma i normali meccanismi sono insufficienti ad indicare lerrore. Queste situazioni sono molte frequenti; molto frequentemente sono legate ai costruttori di classe. I costruttori sono chiamati dalloperatore new dopo aver allocato lo spazio di memoria appropriato alloggetto da istanziare. I costruttori non hanno valori di ritorno (dal momento che non c nessuno che possa catturarli) e quindi risulta molto difficile controllare casi in cui siano occorsi errori al momento della inizializzazione dei dati membro della classe (ricordiamo che non esistono variabili globali). Consideriamo ancora una volta la classe Stack definita nel capitolo 3. Dal momento che il metodo push() non prevede parametri di ritorno, necessario un meccanismo alternativo per gestire un eventuale errore causato da un overflow dellarray che pu contenere solo 20 elementi. Il metodo pop() a sua volta costretto a utilizzare il valore 0 come parametro di ritorno nel caso in cui lo stack non contenga pi elementi. Questo ovviamente costringere ad escludere il numero intero 0 dai valori che potr contenere lo Stack e dovr essere riservato alla gestione della eccezione. class Stack { int data[]; int ndata; void push(int i) { if(data == null) { ndata = 0; data = new int[20]; } if(ndata < 20) { data[ndata] = i; ndata++; } } int pop() { if(ndata > 0) { ndata--; return data[ndata]; } return 0; // Bisogna tornare qualcosa } } Eccezioni : propagazione di oggetti Il punto di forza delle Eccezioni consiste nel consentire la propagazione di un oggetto a ritroso attraverso la sequenza corrente di chiamate tra metodi. Opzionalmente, ogni metodo pu fermare la propagazione, gestire la condizione di Massimiliano Tarquini http://www.java-net.tv <EMAIL> 104 errore utilizzando le informazioni trasportate, oppure continuare la propagazione ai metodi subito adiacenti nella sequenza di chiamate. Ogni metodo che non sia in grado di gestire leccezione viene interrotto nel punto in cui aveva chiamato il metodo che sta propagando lerrore (es. vedi codice sottostante). Se la propagazione raggiunge lentry point della applicazione e non viene arrestata, lapplicazione viene terminata. class Example { double metodo1() { double d; d=4.0 / metodo2(); System.out.println(d) ; } float metodo2() { float f ; f = metodo3(); //Le prossime righe di codice non vengono eseguite //se il metodo 3 fallisce f = f*f; return f; } int metodo3() { if(condizione) return espressione ; else // genera una eccezione e propaga loggetto a ritroso // al metodo2() } } Propagare un oggetto detto exception throwinge fermarne la propagazione exception catching. Gli oggetti da propagare devono derivare dalla classe base java.lang.Exception. A partire da questa possibile creare nuovi tipi di eccezioni specializzando il codice a seconda del caso da gestire. Oggetti throwable Come abbiamo detto, Java consente di propagare solo alcuni tipi di oggetti. Di fatto, tecnicamente Java richiede che tutti gli oggetti da propagare siano derivati da java.lang.Throwable, e questo sembra smentire quanto affermato nel paragrafo precedente in cui affermavamo che devono derivare dalla classe base java.lang.Exception. In realt entrambe le affermazioni sono vere: vediamo perch. La classe Throwable contiene dei metodi necessari a gestire lo stack tracing13 per la propagazione delloggetto a ritroso, ed ha due costruttori: Throwable(); Throwable(String); 13 Al fine garantire la propagazione a ritroso, java utilizza uno stack (LIFO) per determinare la catena dei metodi chiamanti e risalire nella gerarchia. <NAME> http://www.java-net.tv <EMAIL>-one-<EMAIL> 105 Entrambi i costruttori di Throwable avviano lo stack tracing, il secondo in pi inizializza un dato membro String con un messaggio di stato dettagliato e, accessibile attraverso il metodo toString() ereditato da Object. Per convenzione invece, ogni eccezione definita dal programmatore deve derivare da java.lang.Exception che a sua volta deriva da Throwable (Figura 5-1). Anche questa classe ha due costruttori che coincidono con i costruttori della superclasse. Figura 5-0-1 Listruzione throw Le eccezioni vengono propagate a ritroso attraverso la sequenza dei metodi chiamanti tramite listruzione throw che ha sintassi: throw Object_Instance ; Dove Object_Instance una istanza delloggetto Throwable. Eimportante tener presente che Object_Instance una istanza creata mediante loperatore new e non semplicemente un tipo di dato. Questo metodo causa la terminazione del metodo corrente (come se fosse stata utilizzata listruzione return), ed invia loggetto specificato al chiamante. Non c modo da parte del chiamante di riesumare il metodo senza richiamarlo. Istruzioni try / catch Una volta generata una eccezione, una applicazione destinata alla terminazione a meno che loggetto propagato non venga catturato prima di raggiungere lentry-point del programma o direttamente al suo interno. Questo compito spetta alla istruzione catch. Questa istruzione fa parte di un insieme di istruzioni dette istruzioni guardiane deputate alla gestione delle eccezioni ed utilizzate per racchiudere e gestire le chiamate a metodi che le generano. <NAME> http://www.java-net.tv <EMAIL> 106 Listruzione catch non pu gestire da sola una eccezione, ma deve essere sempre accompagnata da un blocco try. Il blocco try utilizzato come guardiano per il controllo di un blocco di istruzioni, potenziali sorgenti di eccezioni. Try ha la sintassi seguente: try { istruzioni } catch (Exception var1) { istruzioni } catch (Exception var2) { istruzioni } .. Listruzione catch cattura solamente le eccezioni di tipo compatibile con il suo argomento e solamente quelle generate dalle chiamate a metodi racchiuse allinterno del blocco try. Se una istruzione nel blocco try genera una eccezione, le rimanenti istruzioni nel blocco vengono saltate (es. vedi codice a seguire). try { f1(); //Una eccezione in questo punto fa saltare f2() e f3() f2(); //Una eccezione in questo punto fa saltare f3() f3(); } catch (IOException _e) { System.out.println(_e.toString()) } catch (NullPointerException _npe) { System.out.println(_npe.toString()) } Lesecuzione di un blocco catch esclude automaticamente tutti gli altri. Singoli catch per eccezioni multiple Ogni istruzione catch, cattura solo le eccezioni compatibili con il tipo definito dal suo argomento. Ricordando quanto abbiamo detto parlando di oggetti compatibili, tutto questo significa che una istruzione catch cattura ogni eccezione dello stesso tipo definito dal suo argomento o derivata dal tipo dichiarato. Nellesempio a seguire, la classe base Exception catturer ogni tipo di eccezione rendendo inutile ogni altro blocco catch a seguire. try { f1(); //Una eccezione in questo punto fa saltare f2() e f3() f2(); //Una eccezione in questo punto fa saltare f3() f3(); } catch (java.lang.Exception _e) { System.out.println(_e.toString()) } catch (NullPointerException _npe) { <NAME> http://www.java-net.tv <EMAIL> 107 //Questo codice non verr mai eseguito } Utilizzare un tipo base con un istruzione catch, pu essere utilizzato per implementare un meccanismo di catch di default. try { f1(); //Una eccezione in questo punto fa saltare f2() e f3() f2(); //Una eccezione in questo punto fa saltare f3() f3(); } catch (NullPointerException _npe) { //Questo blocco cattura NullPointerException } catch (java.lang.Exception _e) { //Questo blocco cattura tutte le altre eccezioni System.out.println(_e.toString()) } Questo meccanismo ricorda molto listruzione per il controllo di flusso switch, ed in particola modo il funzionamento del blocco identificato dalla label default. Nellesempio, una eccezione di tipo NullPointerException verr catturata da una apposita istruzione catch. Tutte le altre eccezioni saranno catturate dal blocco successivo. Questa forma utile in quei casi in cui esista un insieme di eccezioni che richiedono ognuna un trattamento specifico, ed altre che possono invece essere trattate allo stesso modo. La clausola throws Le eccezioni possono essere propagate solo dai metodi che ne dichiarano la possibilit. Tentare di generare una eccezione allinterno un metodo che non ha precedentemente dichiarato di avere la capacit di propagare tali oggetti, causer un errore in fase di compilazione. Per far questo, necessario utilizzare la clausola throws che indica al metodo chiamante che un oggetto eccezione potrebbe essere generato o propagato dal metodo chiamato. La clausola throws ha sintassi: return_type method_name (param_list) throws Throwable_type { Method Body } Un metodo con una clausola throws pu generare un oggetto di tipo Throwable_type oppure ogni tipo derivato esso. Se un metodo contenente una clausola throws viene ridefinito (overrided) attraverso lereditariet, il nuovo metodo pu scegliere se avere o no la clausola throws. Nel caso in cui scelga di avere una clausola throws, sar costretto a dichiarare lo stesso tipo del metodo originale, o al massimo un tipo derivato. <NAME> http://www.java-net.tv <EMAIL> 108 Le altre istruzioni guardiane. Finally Di seguito ad ogni blocco catch, pu essere utilizzato opzionalmente un blocco finally, che sar sempre eseguito prima di uscire dal blocco try/catch. Questo blocco vuole fornire ad un metodo la possibilit di eseguire sempre un certo insieme di istruzioni a prescindere da come il metodo manipola le eccezioni. I blocchi finally non possono essere evitati dal controllo di flusso della applicazione. Le istruzioni break, continue o return allinterno del blocco try o allinterno di un qualunque blocco catch verranno eseguito solo dopo lesecuzione del codice nel blocco finally. try { f1(); //Una eccezione in questo punto fa saltare f2() e f3() f2(); //Una eccezione in questo punto fa saltare f3() f3(); } catch (java.lang.Exception _e) { //Questo blocco cattura tutte le eccezioni System.out.println(_e.toString()) return; } finally { //Questo blocco cattura tutte le altre eccezioni System.out.println(Questo blocco viene comunque eseguito) } Solo una chiamata del tipo System.exit() ha la capacit di evitare lesecuzione del blocco di istruzioni in questione. La sintassi completa per il blocco guardiano diventa quindi: try { istruzioni } catch (Exception var1) { istruzioni } catch (Exception var2) { istruzioni } finally { istruzioni } Definire eccezioni personalizzate Quando definiamo nuovi tipi di oggetti, spesso desiderabile disegnare nuovi tipi di eccezioni che li accompagnino. Un nuovo tipo di eccezione deve essere derivata da java.lang.Exception. Il funzionamento interno della nuova eccezione non ristretto da nessuna limitazione. <NAME> http://www.java-net.tv <EMAIL> 109 class OutOfDataException extends Exception { String errormessage; public OutOfDataException(String s) { super(s); errormessage = s; } public OutOfDataException(s) { super(); errormessage = OutOfDataException; } public String toString() { return errormessage; } } Un esempio completo In questo paragrafo mostrato un esempio completo di uso di eccezioni a partire dalla definizione di un oggetto Set gi definito nel laboratorio del capitolo 5. Lesempio mostra come definire una nuova eccezione (Duplicate-exception) generata dal metodo addMember() quando si cerca di inserire un elemento gi esistente allinterno dellinsieme. Il programma di test infine, utilizza blocchi try/catch per la gestione della eccezione generata. DuplicateException.java import java.lang.Exception; public class DuplicateException extends Exception { String errormessage; public DuplicateException (String s) { super(s); errormessage = s; } public DuplicateException () { super(); errormessage = DuplicateException; } public String toString() { return errormessage; } } <NAME> http://www.java-net.tv tarquini<EMAIL> 110 Set.java class Set { private int numbers[]; private int cur_size; public Set() { cur_size=0; numbers = new int[100]; } public boolean isMember(int n) { int i; i=0; while(i < cur_size) { if(numbers[i]==n) return true; i++; } return false; } public void addMember(int n) throws DuplicateException { if(isMember(n)) throw new DuplicateException(Loggetto non pu essere duplicato); if(cur_size == numbers.length) return; numbers[cur_size++] = n; } public void showSet() { int i; i=0; System.out.println({); while(i < cur_size) { System.out.println(numbers[i] + , ); i++; } System.out.println(}); } } <NAME> http://www.java-net.tv tarquini<EMAIL> 111 SetTest.java class SetTest { public static void main(String args[]) { Set s = new Set(); try { s.addMemeber(10); //duplico lelemento s.addMemeber(10); } catch(DuplicateException _de) { System.err.println(_de.toString()); } } } <NAME> http://www.java-net.tv <EMAIL> 112 Capitolo 8 Polimorfismo ed ereditariet avanzata Introduzione Lereditariet rappresenta uno strumento di programmazione molto potente; daltra parte il semplice modello di ereditariet presentato nel capitolo 6 non risolve alcuni problemi di ereditariet molto comuni e, se non bastasse, crea alcuni problemi potenziali che possono essere risolti solo scrivendo codice aggiuntivo. Uno dei limiti pi comuni della ereditariet singola che non prevede lutilizzo di una classe base come modello puramente concettuale, ossia priva della implementazione delle funzioni base. Se facciamo un passo indietro, ricordiamo che abbiamo definito uno Stack (pila) come un contenitore allinterno del quale inserire dati da recuperare secondo il criterio primo ad entrare, ultimo ad uscire. Potrebbe esserci per una applicazione che richiede vari tipi differenti di Stack: uno utilizzato per contenere valori interi ed un altro utilizzato per contenere valori reali a virgola mobile. In questo caso, le modalit utilizzate per manipolare lo Stack sono le stesse, quello che cambia sono i tipi di dato contenuti. Anche se utilizzassimo la classe Stack definita nel codice seguente come classe base, sarebbe impossibile per mezzo della semplice ereditariet creare specializzazioni dellentit rappresentata a meno di riscrivere una parte sostanziale del codice del nostro modello in grado di contenere solo valori interi. class Stack { int data[]; int ndata; void push(int i) { } int pop() { .. } } Un altro problema che non viene risolto dal nostro modello di ereditariet quello di non consentire ereditariet multipla, ossia la possibilit di derivare una classe da due o pi classi base; la parola chiave extends prevede solamente un singolo argomento. Java risolve tutti questi problemi con due variazioni al modello di ereditariet definito in precedenza: interfacce e classi astratte. Le interfacce sono entit simili a classi, ma non contengono implementazioni delle funzionalit descritte. Le classi astratte, anchesse del tutto simili a classi normali, consentono di non implementare tutte le caratteristiche delloggetto rappresentato. Interfacce e classi astratte, assieme, permettono di definire un concetto senza dover conoscere i dettagli di una classe posponendone limplementazione attraverso il meccanismo della ereditariet. Polimorfismo : uninterfaccia, molti metodi Polimorfismo la terza parola chiave del paradigma ad oggetti. Derivato dal greco, significa pluralit di forme ed la caratteristica che ci consente di utilizzare ununica interfaccia per una moltitudine di azioni. Quale sia la particolare azione eseguita dipende solamente dalla situazione in cui ci si trova. <NAME> http://www.java-net.tv <EMAIL> 113 Per questo motivo, parlando di programmazione, il polimorfismo viene riassunto nellespressione uninterfaccia, molti metodi. Ci significa che possiamo definire una interfaccia unica da utilizzare in molti casi collegati logicamente tra di loro. Oltre a risolvere i limiti del modello di ereditariet proposto, Java per mezzo delle interfacce fornisce al programmatore lo strumento per implementare il polimorfismo. Interfacce Formalmente, una interfaccia Java rappresenta un prototipo e consente al programmatore di definire lo scheletro di una classe: nomi dei metodi, tipi ritornati, lista dei parametri. Al suo interno il programmatore pu definire dati membro purch di tipo primitivo con ununica restrizione: Java considerer implicitamente questi dati come static e final (costanti). Quello che una interfaccia non consente, la implementazione del corpo dei metodi. Una interfaccia stabilisce il protocollo di una classe senza preoccuparsi dei dettagli di implementazione. Definizione di una interfaccia La sintassi per implementare una interfaccia la seguente: interface identificatore { corpo_dell_interfaccia } Interface la parola chiave riservata da Java per lo scopo, identificatore il nome interfaccia e corpo_dell_interfaccia una lista di definizioni di metodi e dati membro separati da ;. Ad esempio, linterfaccia per la nostra classe Stack sar: interface Stack { public void push( int i ); public int pop(); } Implementare una interfaccia Dal momento che una interfaccia rappresenta solo il prototipo di una classe, affinch possa essere utilizzata necessario che ne esista una implementazione che rappresenti una classe istanziabile. Per implementare una interfaccia, Java mette a disposizione la parola chiave implements con sintassi: class nome_classe implements interface { corpo_dell_interfaccia } La nostra classe Stack potr quindi essere definita a partire da un modello nel modo seguente: <NAME> http://www.java-net.tv <EMAIL> 114 StackDef.java public interface StackDef { public void push( int i ); public int pop(); } Stack.java class Stack implements Stack { public void push( int i ) { .. } public int pop() { .. } } Quando una classe implementa una interfaccia obbligata ad implementarne i prototipi dei metodi definiti nel corpo. In caso contrario il compilatore generer un messaggio di errore. Di fatto, possiamo pensare ad una interfaccia come ad una specie di contratto che il run-time di Java stipula con una classe. Implementando una interfaccia la classe non solo definir un concetto a partire da un modello logico (molto utile al momento del disegno della applicazione), ma assicurer limplementazione di almeno i metodi definiti nellinterfaccia. Conseguenza diretta sar la possibilit di utilizzare le interfacce come tipi per definire variabili reference in grado di referenziare oggetti costruiti mediante implementazione di una interfaccia. StackDef s = new Stack(); Varranno in questo caso tutte le regole gi discusse nel capitolo sesto parlando di variabili reference ed ereditariet. Ereditariet multipla in Java Se loperatore extends limitava la derivazione di una classe a partire da una sola classe base, loperatore implements ci consente di implementare una classe a partire da quante interfacce desideriamo semplicemente esplicitando lelenco delle interfacce implementate separate tra loro con una virgola. class nome_classe implements interface1, interface2, .interfacen { corpo_dell_interfaccia } Questa caratteristica permette al programmatore di creare gerarchie di classi molto complesse in cui una classe eredit la natura concettuale di molte entit. Se una classe implementa interfacce multiple, la classe dovr fornire tutte le funzionalit per i metodi definiti in tutte le interfacce. <NAME> http://www.java-net.tv <EMAIL> 115 Classi astratte Capitano casi in cui questa astrazione deve essere implementata solo parzialmente allinterno della classe base. In questi casi le interfacce sono restrittive (non si possono implementare funzionalit alcune). Per risolvere questo problema, Java fornisce un metodo per creare classi base astratte ossia classi solo parzialmente implementate. Le classi astratte possono essere utilizzate come classi base tramite il meccanismo della ereditariet e per creare variabili reference; tuttavia queste classi non sono complete e, come le interfacce, non possono essere istanziate. Per estendere le classi astratte si utilizza come nel caso di classi normali listruzione extends e di conseguenza solo una classe astratta pu essere utilizzata per creare nuove definizioni di classe. Questo meccanismo fornisce una alternativa alla costrizione di dover implementare tutte le funzionalit di una interfaccia allinterno di una nuova classe aumentando la flessibilit nella creazione delle gerarchie di derivazione. Per definire una classe astratta Java mette a disposizione la parola chiave abstract. Questa clausola informa il compilatore che alcuni metodi della classe potrebbero essere semplicemente prototipi o astratti. abstract class nome_classe { data_members abstract_methods non_abstract_methods } Ogni metodo che rappresenta semplicemente un prototipo deve essere dichiarato abstract. Quando una nuova classe viene derivata a partire dalla classe astratta, il compilatore richiede che tutti i metodi astratti vengano definiti. Se la necessit del momento costringe a non definire questi metodi, la nuova classe dovr a sua volta essere definita abstract . Un esempio semplice potrebbe essere rappresentato da un oggetto Terminale. Questo oggetto avr dei metodi per muovere il cursore, per inserire testo, ecc. Inoltre Terminale dovr utilizzare dei dati per rappresentare la posizione del cursore e le dimensioni dello schermo (in caratteri). public abstract class Terminal { private int cur_row, cur_col, nrows, ncols; public Terminal(int rows, int cols) { nrows = rows; ncols = cols; cur_row=0; cur_col=0; } public abstract void move_cursor(int rows, int col); public abstract void insert_string(int rows, int col); . public void clear() { int r,c; for(r=0 ; r<nrows ;r++) for(c=0 ; c<ncols ;c++) { move_cursor(r , c); <NAME> http://www.java-net.tv <EMAIL> 116 insert_string( ); } } } Il metodo che pulisce lo schermo (clear()) potrebbe essere scritto in termini di altri metodi prima che siano implementati. Quando viene implementato un terminale reale i metodi astratti saranno tutti implementati, ma non sar necessario implementare nuovamente il metodo clear(). <NAME> http://www.java-net.tv <EMAIL> 117 Capitolo 9 Java Threads Introduzione Java un linguaggio multi-thread, cosa che sta a significare che un programma pu essere eseguito logicamente in molti luoghi nello stesso momento. Ovvero, il multithreading consente di creare applicazioni in grado di utilizzare la concorrenza logica tra i processi, continuando a condividere tra i thread lo spazio in memoria riservato ai dati. Figura 8-1 Nel diagramma nella Figura 8-1, viene schematizzato lipotetico funzionamento della concorrenza logica. Dal punto di vista dellutente, i thread logici appaiono come una serie di processi che eseguono parallelamente le loro funzioni. Dal punto di vista della applicazione rappresentano una serie di processi logici che, da una parte condividono la stessa memoria della applicazione che li ha creati, dallaltra concorrono con il processo principale al meccanismo di assegnazione della CPU del computer su cui lapplicazione sta girando. Thread di sistema In Java, esistono un certo numero di thread che vengono avviati dalla virtual machine in modo del tutto trasparente allutente. Esiste un thread per la gestione delle interfacce grafiche responsabile della cattura di eventi da passare alle componenti o dellaggiornamento dei contenuti dellinterfaccia grafica. Il garbage collection un thread responsabile di trovare gli oggetti non pi referenziati e quindi da eliminare dallo spazio di memoria della applicazione. Lo stesso metodo main() di una applicazione viene avviato come un thread sotto il controllo della java virtual machine. <NAME> http://www.java-net.tv <EMAIL> 118 Figura 8-2 Nella figura 8-2 viene schematizzata la struttura dei principali thread di sistema della virtual machine Java. La classe java.lang.Thread In Java, un modo per definire un oggetto thread quello di utilizzare lereditariet derivando il nuovo oggetto dalla classe base java.lang.Thread mediante listruzione extends (questo meccanismo schematizzato nella figura 8-3). Figura 8-3 La classe java.lang.Thread fornita dei metodi necessari alla esecuzione, gestione e interruzione di un thread. I tre principali: <NAME> http://www.java-net.tv <EMAIL> 119 run() : il metodo utilizzato per implementare le funzionalit eseguite thread. In genere lunico metodo su cui effettuare overriding. Nel caso in cui il metodo non venga soprascritto, al momento della esecuzione eseguir una funzione nulla; start() : causa lesecuzione del thread. La Java Virtual Machine chiama il metodo run() avviando il processo concorrente; destroy() : distrugge il thread e rilascia le risorse allocate. Un esempio di thread definito per ereditariet dalla classe Thread il seguente: class MioPrimoThread extends Thread { int secondi ; MioPrimoThread (int secondi) { this. secondi = secondi; } public void run() { // ogni slice di tempo definito da secondi //stampa a video una frase } Interfaccia Runnable Ricordando i capitoli sulla ereditariet in Java, eravamo arrivati alla conclusione che lereditariet singola insufficiente a rappresentare casi in cui necessario creare gerarchie di derivazione pi complesse, e che grazie alle interfacce possibile implementare lereditariet multipla a livello di prototipi di classe. Supponiamo ora che la nostra classe MioPrimoThread sia stata definita a partire da una classe generale diversa da java.lang.Thread. A causa dei limiti stabiliti dalla ereditariet singola, sar impossibile creare un thread utilizzando lo stesso meccanismo definito nel paragrafo precedente. Sappiamo per che mediante listruzione implements possiamo implementare pi di una interfaccia. Lalternativa al caso precedente quindi quella di definire un oggetto thread utilizzando linterfaccia Runnable di java.lang (Figura 8-4). Linterfaccia Runnable contiene il prototipo di un solo metodo: public interface Runnable { public void run(); } necessario ad indicare lentry-point del nuovo thread (esattamente come definito nel paragrafo precedente). La nuova versione di MioPrimoThread sar quindi: class MiaClasseBase{ MiaClasseBase () { . } public void faiQualcosa() { . } } <NAME> http://www.java-net.tv <EMAIL> 120 class MioPrimoThread extends MiaClasseBase implements Runnable{ int secondi ; MioPrimoThread (int secondi) { this. secondi = secondi; } public void run() { // ogni slice di tempo definito da secondi //stampa a video una frase } } In questo caso, affinch il threads sia attivato, sar necessario creare esplicitamente una istanza della classe Thread utilizzando il costruttore Thread(Runnable r). MioPrimoThread miothread = new MioPrimoThread(5); Thread nthread = new Thread(miothread); nthread.start() //provoca la chiamata al metodi run di MioPrimoThread ; Figura 8-4 Sincronizzare thread Quando due o pi thread possono accedere ad un oggetto contemporaneamente per modificarlo, il rischio a cui si va incontro quello della corruzione dei dati rappresentati dalloggetto utilizzato tra i thread in regime di concorrenza. Immaginiamo ad esempio che una classe rappresenti il conto in banca della famiglia Tizioecaio e che il conto sia intestato ad entrambi i signori Tizioecaio. Supponiamo ora che loggetto utilizzi un dato membro intero per il saldo del conto pari a lire 1.200.000. Se i due intestatari del conto (thread) accedessero contemporaneamente per ritirare dei soldi, si rischierebbe una situazione simile alla seguente: <NAME> http://www.java-net.tv tarquini@all-<EMAIL> 121 Il signor Tizioecaio accede al conto chiedendo di ritirare 600.000 lire. Un metodo membro delloggetto conto controlla il saldo trovando 1.200.000 lire. La signora Tizioecaio accede al conto chiedendo di ritirare 800.000 lire. Un metodo membro delloggetto conto controlla il saldo trovando 1.200.000 lire. Il metodo membro delloggetto conto controlla il saldo trovando 1.200.000 lire. Vengono addebitate 600.000 del signor Tizioecaio. Vengono addebitate 800.000 della signora Tizioecaio. Il conto va in scoperto di 200.000 ed i due non lo sanno. In questi casi quindi necessario che i due thread vengano sincronizzati ovvero che mentre uno esegue loperazione, laltro deve rimanere in attesa. Java fornisce un metodo per gestire la sincronizzazione tra thread mediante la parola chiave synchronized. Questo modificatore deve essere aggiunto alla dichiarazione del metodo per assicurare che solo un thread alla volta sia in grado di utilizzare dati sensibili. Di fatto, indipendentemente dal numero di thread che tenteranno di accedere la metodo, solo uno alla volta potr eseguirlo. Gli altri rimarranno in coda in attesa di ricevere il controllo. Metodi di questo tipo sono detti Thread Safe. Nellesempio successivo riportiamo due versioni della classe Set di cui, la prima non utilizza il modificatore, la seconda invece thread safe. class Set // Versione non thread safe { private int data[]; .. boolean isMember(int n) { //controlla se lintero appartiene allinsieme } void add(int n) { //aggiunge n allinsieme } } class Set // Versione thread safe { private int data[]; .. synchronized boolean isMember(int n) { //controlla se lintero appartiene allinsieme } void add(int n) { //aggiunge n allinsieme } } Lock Il meccanismo descritto nel paragrafo precedente non ha come solo effetto quello di impedire che due thread accedano ad uno stesso metodo contemporaneamente, ma impedisce il verificarsi di situazioni anomale tipiche della programmazione concorrente. Consideriamo lesempio seguente: <NAME> http://www.java-net.tv <EMAIL> 122 class A { .. synchronized int a() { return b() } synchronized b(int n) { .. return a(); } } Supponiamo ora che un thread T1 chiami il metodo b() della classe A contemporaneamente ad un secondo thread T2 che effettua una chiamata al metodo a() della stessa istanza di classe. Ovviamente, essendo i due metodi sincronizzati, il primo thread avrebbe il controllo sul metodo b() ed il secondo su a(). Lo scenario che si verrebbe a delineare disastroso inquanto T1 rimarrebbe in attesa sulla chiamata al metodo a() sotto il controllo di T2 e, viceversa T2 rimarrebbe bloccato sulla chiamata al metodo b() sotto il controllo di T1. Questa situazione si definisce deadlock e necessit di algoritmi molto complessi e poco efficienti per essere gestita o prevenuta. Java fornisce il programmatore la certezza che casi di questo tipo non avverranno mai. Di fatto, quando un thread entra allinterno di un metodo sincronizzato ottiene il lock sulla istanza dell oggetto (non solo sul controllo del metodo). Il thread che ha ottenuto il lock sulla istanza potr quindi richiamare altri metodi sincronizzati senza entrare in deadlock. Ogni altro thread che prover ad utilizzare listanza in lock delloggetto si metter in coda in attesa di essere risvegliato al momento del rilascio della istanza da parte del thread proprietario. Quando il primo thread avr terminato le sue operazioni, il secondo otterr il lock e di conseguenza luso privato delloggetto. Sincronizzazione di metodi statici Metodi statici accedono a dati membro statici. Dal momento che ogni classe pu accedere a dati membro statici i quali non richiedono che la classe di cui sono membri sia attiva, allora un thread che effettui una chiamata ad un metodo statico sincronizzato non pu ottenere il lock sulla istanza delloggetto. Daltra parte necessaria una forma di prevenzione del deadlock anche in questo caso. Java prevede luso di una seconda forma di lock. Quando un thread accede ad un metodo statico sincronizzato, ottiene un lock su classe, ovvero su tutte le istanza della stessa classe di cui sta chiamando il metodo. In questo scenario, nessun thread pu accedere a metodi statici sincronizzati di ogni istanza di una stessa classe fino a che un thread detiene il lock sulla classe. Questa seconda forma di lock nonostante riguardi tutte le istanze di un oggetto, comunque meno restrittiva della precedente inquanto metodi sincronizzati non statici della classe in lock possono essere eseguiti durante lesecuzione del metodo statico sincronizzato. <NAME> http://www.java-net.tv <EMAIL> 123 Blocchi sincronizzati Alcune volte pu essere comodo ottenere il lock su una istanza direttamente allinterno di un metodo e ristretto al tempo necessario per eseguire solo alcune istruzioni di codice. Java gestisce queste situazioni utilizzando blocchi di codice sincronizzati. Nellesempio a seguire, il blocco sincronizzato ottiene il controllo sulloggetto QualcheOggetto e modifica il dato membro pubblico v. class UnaClasseACaso { public void a(QualcheOggetto unaistanza) { .. synchronized (unaistanza); //ottiene il lock su una istanza { unaistanza.v=23; } } } Questa tecnica pu essere utilizzata anche utilizzando la parola chiave this come parametro della dichiarazione del blocco sincronizzato. Nel nuovo esempio, durante tutta la esecuzione del blocco sincronizzato, nessun altro thread potr accedere alla classe attiva. class UnaClasseACaso { public void a(QualcheOggetto unaistanza) { .. synchronized (this); //ottiene il lock su se stessa { unaistanza.v=23; } } } <NAME> http://www.java-net.tv <EMAIL> 124 Laboratorio 9 Java Thread d Esercizio 1 Creare una applicazione che genera tre thread. Utilizzando il metodo sleep() di java.lang.Thread, il primo deve stampare I am thread one una volta al secondo, il secondo I am thread twouna volta ogni due secondi, ed il terzo I am thread three una volta ogni tre secondi. Esercizio 2 Creare una applicazione che testi il funzionamento della sincronizzazione. Usando i tre thread dellesercizio precedente, fare in modo che rimangano in attesa un tempo random da 1 a 3 secondi (non pi un tempo prefissato) ed utilizzino un metodo sincronizzato statico e uno sincronizzato non statico stampando un messaggio di avviso ogni volta. <NAME> http://www.java-net.tv <EMAIL> 125 Soluzione al primo esercizio import java.lang.*; public class three_threads implements Runnable { String message; int how_long; Thread me; public three_threads (String msg, int sleep_time) { message = msg; how_long= sleep_time * 1000; me = new Thread(this); me.start(); } public void run () { while (true) { try { me. Sleep (how_long); System.out.println(message); } catch(Exception e) {} } } public static void main (String g[]) { three_threads tmp; tmp= new three_threads(I am thread one,1); tmp= new three_threads(I am thread two,2); tmp= new three_threads(I am thread three,3); } } Soluzione al secondo esercizio Import java.lang.*; class shared_thing { public static synchronized void stat_f(locks who) { System.out.println(who.name + Locked static); try { Who.me.sleep (who.how_long); } catch(Exception e) {} System.out.println(who.name + Unlocked static); } public synchronized void a (locks who) { System.out.println(who.name + Locked a); try { who.me.sleep (who.how_long); } catch(Exception e) {} System.out.println(who.name + Unlocked a); <NAME> http://www.java-net.tv <EMAIL> 126 } public synchronized void b (locks who) { System.out.println(who.name + Locked b); try { Who.me.sleep (who.how_long); } catch(Exception e) {} System.out.println(who.name + Unlocked b); } } public class locks implements Runnable { String name; int how_long; Shared_thing thing; Thread me; public locks(String n, shared_thing st) { Name = n ; Thing = st; } public static void main (String a[a]) { locks lk; shared_thing t = new shared_thing(); 1k=new locks (Thread one: ,t ); 1k.me =new Thread(1k); 1k.me.start(); 1k=new locks (Thread two: ,t ); 1k.me =new Thread(1k); 1k.me.start(); 1k=new locks (Thread three: ,t ); 1k.me =new Thread(1k); 1k.me.start(); } public void run () { int which_func; while(true) { which_func; while(true) { which_func =(int) (Math.random() * 2.5 + 1); how_long = (int) (Mayh.random() * 2000.0 + 1000.0); switch (which_func) { case 1: System.out.println(name + Trying a()); Thing.a(this); Break; case 2: System.out.println(name + Trying b()); Thing.b(this); Break; case 3: System.out.println(name + Trying static()); Thing.stat_f(this); Break; <NAME> http://www.java-net.tv <EMAIL> 127 } } } } <NAME> http://www.java-net.tv tar<EMAIL> 128 Capitolo 11 Java Networking Introduzione La programmazione di rete un tema di primaria importanza inquanto spesso utile creare applicazioni che forniscano di servizi di rete. Per ogni piattaforma supportata, Java supporta sia il protocollo TCP che il protocollo UDP. In questo capitolo introdurremo alla programmazione client/server utilizzando Java non prima per di aver introdotto le nozioni basilari su reti e TCP/IP. I protocolli di rete (Internet) Descrivere i protocolli di rete e pi in generale il funzionamento di una rete probabilmente cosa impossibile se fatto, come in questo caso, in poche pagine. Cercher quindi di limitare i danni facendo solo una breve introduzione a tutto ci che utilizziamo e non vediamo quando parliamo di strutture di rete, ai protocolli che pi comunemente vengono utilizzati ed alle modalit di connessione che ognuno di essi utilizza per realizzare la trasmissione dei dati tra client e server o viceversa. Due applicazioni client/server in rete comunicano tra di loro scambiandosi pacchetti di dati costruiti secondo un comune protocollo di comunicazione che definisce quella serie di regole sintattiche e semantiche utili alla comprensione dei dati contenuti nel pacchetto. I dati trasportati allinterno di questi flussi di informazioni possono essere suddivisi in due categorie principali : i dati necessari alla comunicazione tra le applicazioni ovvero i dati che non sono a carico dellapplicativo che invia il messaggio (esempio: lindirizzo della macchina che invia il messaggio e quello della macchina destinataria) ed i dati contenenti informazioni strettamente legate alla comunicazione tra le applicazioni ovvero tutti i dati a carico della applicazione che trasmette il messaggio. Risulta chiaro che possiamo identificare, parlando di protocolli, due macro insiemi : Protocolli di rete e Protocolli applicativi. Appartengono ai protocolli di rete i protocolli dipendenti dalla implementazione della rete necessari alla trasmissione di dati tra una applicazione ed un'altra. Appartengono invece ai protocolli applicativitutti i protocolli che contengono dati dipendenti dalla applicazione e utilizzano i protocolli di rete come supporto per la trasmissione. Nelle tabelle 1 e 2 vengono riportati i pi comuni protocolli appartenenti ai due insiemi. Descrizione TCP Trasmission Control Protocol / Internet Protocol UDP User Datagram Protocol IP Internet Protocol ICMP Internet Control Message Protocol Tabella 1 I pi comuni protocolli di rete Protocollo <NAME> http://www.java-net.tv <EMAIL> 129 Descrizione http Hyper Text Trasfer Protocol Telnet Protocollo per la gestione remota via terminale TP Time Protocol Smtp Simple message trasfer protocollo Ftp File trasfer protocol Tabella 2 I pi comuni protocolli applicativi in Internet Protocollo Il primo insieme, pu essere a sua volta suddiviso in due sottoinsiemi: Protocolli di trasmissione e Protocolli di instradamento. Per semplicit faremo comunque sempre riferimento a questi come protocolli di rete. Lunione dei due insiemi suddetti viene comunemente chiamata TCP/IP essendo TCP ed IP i due protocolli pi noti ed utilizzati. Nella Figura 10-1 viene riportato lo schema architetturale del TCP/IP dal quale risulter pi comprensibile la suddivisione nei due insiemi suddetti. In pratica, possiamo ridurre internet ad un gestore di indirizzi il cui compito quello di far comunicare tra di loro due o pi sistemi appartenenti o no alla stessa rete. Figura 10-1 TCP/IP Indirizzi IP Per inviare pacchetti da una applicazione allaltra necessario specificare lindirizzo della macchina mittente e quello della macchina destinataria. Tutti i Mass<NAME> http://www.java-net.tv [email protected] 130 computer collegati ad internet sono identificati da uno o pi indirizzi numerici detti IP. Tali indirizzi sono rappresentati da numeri di 32 bit e possono essere scritti informato decimale, esadecimale o in altri formati. Il formato di uso comune quello che usa la notazione decimale separata da punti mediante il quale lindirizzo numerico a 32 bit viene suddiviso in quattro sequenze di 1 byte ognuna separate da punto ed ogni byte viene scritto mediante numero intero senza segno. Ad esempio consideriamo lindirizzo IP 0xCCD499C1 (in notazione esadecimale). Dal momento che: 0xCC 0xD4 0x99 0xC1 204 212 153 193 Lindirizzo IP secondo la notazione decimale separata da punti sar 204.212.153.193. Gli indirizzi IP contengono due informazioni utilizzate dal protocollo IP per linstradamento di un pacchetto dal mittente al destinatario, informazioni che rappresentano lindirizzo della rete del destinatario e lindirizzo del computer destinatario allinterno della rete e sono suddivisi in quattro classi differenti : A, B, C, D. INDIRIZZO IP = INDIRIZZO RETE | INDIRIZZO HOST Gli indirizzi di Classe Asono tutti gli indirizzi il cui primo byte compreso tra 0 e 127 (ad esempio, appartiene alla classe A lindirizzo IP 10.10.2.11) ed hanno la seguente struttura: Bit: 0 Id. Rete 0-127 7,8 Identificativo di Host 0-255 0-255 0-255 15,16 23,24 31 Dal momento che gli indirizzi di rete 0 e 127 sono indirizzi riservati, un IP di classe A fornisce 126 possibili indirizzi di rete e 224 = 16.777.219 indirizzi di host per ogni rete. Appartengono alla Classe B gli indirizzi IP in cui il primo numero compreso tra 128 e 191 (esempio : 129.100.1.32) ed utilizzano i primi due byte per identificare lindirizzo di rete. In questo caso, lindirizzo IP assume quindi la seguente struttura : Id. Rete 128-191 Bit: 0 0-255 7,8 Identificativo di Host 0-255 0-255 15,16 23,24 31 Notiamo che lindirizzo IP fornisce 214 = 16.384 reti ognuna delle quali con 216 = 65.536 possibili host. Gli indirizzi di Classe C hanno il primo numero compreso tra 192 e 223 (esempio: 192.243.233.4) ed hanno la seguente struttura : Id. Rete 192-223 Bit: 0 <NAME> 0-255 7,8 0-255 15,16 http://www.java-net.tv Id. di Host 0-255 23,24 31 <EMAIL> 131 Questi indirizzi forniscono identificatori per 222 = 4.194.304 reti e 28 = 256 computer che, si riducono a 254 dal momento che gli indirizzi 0 e 255 sono indirizzi riservati. Gli indirizzi di Classe D, sono invece indirizzi riservati per attivit di multicasting. Indirizzo Multicast 1110 . Bit: 0 7,8 15,16 23,24 31 In una trasmissione Multicast, un indirizzo non fa riferimento ad un singolo host allinterno di una rete bens a pi host in attesa di ricevere i dati trasmessi. Esistono infatti applicazioni in cui necessario inviare uno stesso pacchetto IP a pi host destinatari in simultanea. Ad esempio, applicazioni che forniscono servizi di streaming video privilegiano comunicazioni multicast a unicast potendo in questo caso inviare pacchetti a gruppi di host contemporaneamente, utilizzando un solo indirizzo IP di destinazione. Quanto descritto in questo paragrafo schematizzato nella prossima figura (Figura 10-2) da cui appare chiaro che possibile effettuare la suddivisione degli indirizzi IP nelle quattro classi suddette applicando al primo byte in formato binario la seguente regola : 1) un indirizzo IP appartiene alla Classe Ase il primo bit uguale a 0; 2) un indirizzo IP appartiene alla Classe Bse i primi due bit sono uguali a 10; 3) un indirizzo IP appartiene alla Classe Cse i primi tre bit sono uguali a 110; 4) un indirizzo IP appartiene alla Classe Dse i primi 4 bit sono uguali a 1110. Classe A 0 Indirizzo di rete Indirizzo di host Classe B 1 0 Indirizzo di rete Indirizzo di host Classe C 1 1 0 Indirizzo di rete Indirizzo di host Classe D 1 1 1 0 Bit: 2 3 0 1 Indirizzo multicast 31 Figura 10-2 : Le quattro forme di un indirizzo IP Comunicazione Connection Orientedo Connectionless I protocolli di trasporto appartenenti al primo insieme descritto nei paragrafi precedenti si occupano della trasmissione delle informazioni tra server e client (o viceversa). Per far questo utilizzano due modalit di trasmissione dei dati rispettivamente con connessione (Connection Oriented) o senza (Connectionless). In modalit con connessioneil TCP/IP stabilisce un canale logico tra il computer server ed il computer client, canale che rimane attivo sino alla fine della trasmissione dei dati o sino alla chiusura da parte del server o del client. Questo tipo di Massimiliano Tarquini http://www.java-net.tv <EMAIL> 132 comunicazione necessaria in tutti i casi in cui la rete debba garantire la avvenuta trasmissione dei dati e la loro integrit. Con una serie di messaggi detti di Acknowledge server e client verificano lo stato della trasmissione ripetendola se necessario. Un esempio di comunicazione con connessione la posta elettronica in cui il client di posta elettronica stabilisce un canale logico di comunicazione con il server tramite il quale effettua tutte lo operazione di scarico od invio di messaggi di posta. Solo alla fine delle operazione il client si occuper di notificare al server la fine della trasmissione e quindi la chiusura della comunicazione. Nel secondo caso (Connectionless) il TCP/IP non si preoccupa della integrit dei dati inviati ne della avvenuta ricezione da parte del client. Per fare un paragone con situazioni reali, un esempio di protocollo connectionless ci fornito dalla trasmissione del normale segnale televisivo via etere. In questo caso infatti il trasmettitore (o ripetitore) trasmette il suo messaggio senza preoccuparsi se il destinatario lo abbia ricevuto. Domain Name System : risoluzione dei nomi di un host Ricordarsi a memoria un indirizzo IP non cosa semplicissima, proviamo infatti ad immaginare quanto potrebbe essere complicato navigare in Internet dovendo utilizzare la rappresentazione in notazione decimale separata da punto dellindirizzo del sito internet che vogliamo visitare. Lo standard prevede che oltre ad un indirizzo IP un host abbia associato uno o pi nomi Host Name che ci consentono di referenziare un computer in rete utilizzando una forma pi semplice e mnemonica della precedente. Ecco perch generalmente utilizziamo nomi piuttosto che indirizzi per collegarci ad un computer sulla rete. Per poter fornire questa forma di indirizzamento esistono delle applicazioni che traducono i nomi in indirizzi (o viceversa) comunemente chiamate Server DNS o nameserver. Analizziamo in breve come funziona la risoluzione di un nome mediante nameserver, ossia la determinazione dellindirizzo IP a partire dall Host Name. Figura 10-3: Gerarchia dei server DNS Tipicamente un nome di host ha la seguente forma : myhost.mynet.net <NAME> http://www.java-net.tv [email protected] 133 Dal punto di vista dellutente il nome va letto da sinistra verso destra ossia dal nome locale (myhost) al nome globale (net) ed ha diversi significati : myhost.mynet.net si riferisce ad un singolo host allinterno di una rete ed per questo motivo detto fully qualified; mynet.net si riferisce al dominio degli host collegati alla rete dellorganizzazione mynet. Net si riferisce ai sistemi amministrativi nella rete mondiale Internet ed detto nome di alto livello Un nome quindi definisce una struttura gerarchica, e proprio su questa gerarchia si basa il funzionamento della risoluzione di un nome. Nella Figura 10-3 illustrata la struttura gerarchica utilizzata dai server DNS per risolvere i nomi. Dal punto di vista di un server DNS il nome non viene letto da sinistra verso destra, ma al contrario da destra verso sinistra ed il processo di risoluzione pu essere schematizzato nel modo seguente: 1. Il nostro browser richiede al proprio server DNS lindirizzo IP corrispondente al nome myhost.mynet.net; 2. Il DNS interroga il proprio database dei nomi per verificare se in grado di risolvere da solo il nome richiesto. Nel caso in cui il nome esista allinterno della propria base dati ritorna lindirizzo IP corrispondente, altrimenti deve tentare unaltra strada per ottenere quanto richiesto. 3. Ogni nameserver deve sapere come contattare un almeno un server radice, ossia un server DNS che conosca i nomi di alto livello e sappia quale DNS in grado di risolverli. Il nostro DNS contatter quindi il server radice a lui conosciuto e chieder quale DNS server in grado di risolvere i nomi di tipo net; 4. Il DNS server interrogher quindi il nuovo sistema chiedendogli quale DNS Server a lui conosciuto in grado di risolvere i nomi appartenenti al dominio mynet.net il quale verr a sua volta interrogato per risolvere infine il nome completo myhost.mynet.net Nella Figura 10-4 schematizzato il percorso descritto affinch il nostro DNS ci restituisca la corretta risposta. Figura 10-4: flusso di ricerca allinterno della gerarchia dei server DNS <NAME> http://www.java-net.tv [email protected] 134 URL Parlando di referenziazione di un computer sulla rete, il nome di un Host non rappresenta ancora il nostro punto di arrivo. Con le nostre conoscenze siamo ora in grado di reperire e referenziare un computer host sulla rete, ma non siamo ancora in grado di accedere ad una risorsa di qualunque tipo essa sia. Navigando in Internet avrete sentito spesso nominare il termine URL. URL acronimo di Uniform Resource Locator e rappresenta lindirizzo di una risorsa sulla rete e fornisce informazioni relative al protocollo necessario alla gestione della risorsa indirizzata. Un esempio di URL il seguente: http://www.java-net.tv/index.html Http indica il protocollo (in questo caso Hyper Text Trasfer Protocol) e //www.java-net.tv/index.html il nome completo della risorsa richiesta. In definitiva un URL ha la seguente struttura : URL = Identificatore del Protocollo : Nome della Risorsa Il Nome della risorsapu contenere una o pi componenti tra le seguenti : 1) Host Name : Nome del computer host su cui la risorsa risiede; 2) File Name : Il path completo alla risorsa sul computer puntato da Host Name; 3) Port Number : Il numero della porta a cui connettersi (vedremo in seguito il significato di porta); 4) Reference : un puntatore ad una locazione specifica allinterno di una risorsa. Trasmission Control Protocol : trasmissione Connection Oriented Il protocollo TCP appartenente allo strato di trasporto del TCP/IP (Figura 10-1) trasmette dati da server a client suddividendo un messaggio di dimensioni arbitrarie in frammenti o datagrammi da spedire separatamente e non necessariamente sequenzialmente, per poi ricomporli nellordine corretto. Una eventuale nuova trasmissione pu essere richiesta per leventuale pacchetto non arrivato a destinazione o contenenti dati affetti da errori. Tutto questo in maniera del tutto trasparente rispetto alle applicazioni che trasmettono e ricevono il dato. A tal fine, TCP stabilisce un collegamento logico o connessione tra il computer mittente ed il computer destinatario, creando una sorta di canale attraverso il quale le due applicazioni possono inviarsi dati in forma di pacchetti di lunghezza arbitraria. Per questo motivo TCP fornisce un servizio di trasporto affidabile garantendo una corretta trasmissione dei dati tra applicazioni. Nella Figura 10-5 riportato in maniera schematica il flusso di attivit che il TCP/IP deve eseguire in caso di trasmissioni di questo tipo. Queste operazioni, soprattutto su reti di grandi dimensioni, risultano essere molto complicate ed estremamente gravose in quanto comportano che per assolvere al suo compito il TCP debba tener traccia di tutti i possibili percorsi tra mittente e destinatario. Unaltra capacit del TCP garantita dalla trasmissione in presenza di una connessione quella di poter bilanciare la velocit di trasmissione tra mittente e destinatario, capacit che risulta molto utile soprattutto nel caso in cui la trasmissione avvenga in presenza di reti eterogenee. In generale quando due sistemi comunicano tra di loro, necessario stabilire le dimensioni massime che un datagramma pu raggiungere affinch possa esservi Massimiliano Tarquini http://www.java-net.tv <EMAIL> 135 trasferimento di dati. Tali dimensioni sono dipendenti dalla infrastruttura di rete, dal sistema operativo della macchina host e, possono quindi variare anche per macchine appartenenti alla stessa rete. Figura 10-5: Time-Line di una trasmissione Connection Oriented Quando viene stabilita una connessione tra due host, il TCP/IP negozia le dimensioni massime per la trasmissione in ogni direzione dei dati. Mediante il meccanismo di accettazione di un datagramma (acknowledge) viene trasmesso di volta in volta un nuovo valore di dimensione detto finestra che il mittente potr utilizzare nellinvio del datagramma successivo. Questo valore pu variare in maniera crescente o decrescente a seconda dello stato della infrastruttura di rete. Figura 10-6 : I primi 16 ottetti di un segmento TCP Massimiliano Tarquini http://www.java-net.tv <EMAIL> 136 Nonostante le sue caratteristiche, il TCP/IP non risulta sempre essere la scelta migliore relativamente al metodo di trasmissione di dati. Dovendo fornire tanti servizi, il protocollo in questione oltre ai dati relativi al messaggio da trasmettere deve trasportare una quantit informazioni a volte non necessarie e, che spesso possono diventare causa di sovraccarico sulla rete. In questi casi a discapito della qualit della trasmissione necessario favorirne la velocit adottando trasmissioni di tipo Connectionless. User Datagram Protocol : trasmissione Connectionless User Datagram Protocol si limita ad eseguire operazioni di trasmissione di un pacchetto di dati tra macchina mittente e macchina destinataria con il minimo sovraccarico di rete senza garanzia di consegna: il protocollo in assenza di connessione non invia pacchetti di controllo della trasmissione perdendo di conseguenza la capacit di rilevare perdite o duplicazioni di dati. Figura 10-7 : Datagramma User Datagram Protocol Nella Figura 10-8 viene mostrato il formato del datagramma UDP. Dal confronto con limmagine 7, appare chiaro quanto siano ridotte le dimensioni dell header del datagramma UDP rispetto al datagramma TCP. Altro limite di UDP rispetto al precedente sta nella mancata capacit di calcolare la finestraper la trasmissione dei dati, calcolo che sar completamente a carico del programmatore. Una applicazione che utilizza questo protocollo ha generalmente a disposizione un buffer di scrittura di dimensioni prefissate su cui scrivere i dati da inviare. Nel caso di messaggi che superino queste dimensioni sar necessario spezzare il messaggio gestendo manualmente la trasmissione dei vari segmenti che lo compongono. Sempre a carico del programmatore sar quindi la definizione delle politiche di gestione per la ricostruzione dei vari segmenti nel pacchetto originario e per il recupero di dati eventualmente persi nella trasmissione. Identificazione di un processo : Porte e Socket Sino ad ora abbiamo sottointeso il fatto che parlando di rete, esistano allinterno di ogni computer host uno o pi processi che devono comunicare tra di loro tramite il TCP/IP con processi esistenti su altri computer host. Viene spontaneo domandarsi come un processo possa usufruire dei servizi messi a disposizione dal TCP/IP. Il primo passo che un processo deve compiere per poter trasmettere o ricevere dati quello di identificarsi rispetto al TCP/IP affinch possa essere riconosciuto dallo strato di gestione della rete. Tale identificazione viene effettuata tramite un numero detto Port o Port Address. Questo numero non per in grado di descrivere in maniera univoca una connessione (n processi su n host differenti potrebbero avere medesima Port). Le specifiche del protocollo definiscono una Massimiliano Tarquini http://www.java-net.tv <EMAIL> 137 struttura chiamata Association, nientaltro che una quintupla di informazioni necessarie a descrivere univocamente una connessione : Association = (Protocollo, Indirizzo Locale, Processo Locale, Indirizzo Remoto, Processo Remoto) Ad esempio una Associationla seguente quintupla : (TCP, 195.233.121.14, 1500, 194.243.233.4, 21) in cui TCP il protocollo da utilizzare, 195.233.121.14 lindirizzo locale ovvero lindirizzo IP del computer mittente, 1500 lidentificativo o Port Address del processo locale, 194.243.233.4 lindirizzo remoto ovvero lindirizzo IP del computer destinatario ed infine 21 lidentificativo o Port Address del processo remoto.Come fanno quindi due applicazioni che debbano comunicare tra di loro a creare una Association? Proviamo a pensare ad una Association come ad un insieme contenente solamente i 5 elementi della quintupla. Come si vede dalla Immagine 9, tale insieme pi essere costruito mediante unione a partire da due sottoinsiemi che chiameremo rispettivamente Local Half Association e Remote Half Association: Figura 10-8 : Association = Local Half Association U Remote Half Association Due processi (mittente o locale e destinatario o remoto) definiscono una Association, stabilendo in modo univoco una trasmissione mediante la creazione di due Half Association. Le Half Associationsono chiamate Socket. Un Socket rappresenta quindi il meccanismo attraverso il quale una applicazione invia e riceve dati tramite rete con unaltra. Consideriamo ad esempio la precedente Half Association (TCP, 195.233.121.14, 1500, 194.243.233.4, 21). La quintupla rappresenta in modo univoco una trasmissione TCP tra due applicazioni che comunicano tramite i due Socket : 1 : (TCP, 195.233.121.14, 1500) 2 : (TCP, 194.243.233.4, 21) <NAME> http://www.java-net.tv <EMAIL> 138 Il package java.net E il package Java che mette a disposizione del programmatore le API necessarie per lo sviluppo di applicazioni Client/Server basata su socket. Vedremo ora come le classi appartenenti a questo package implementino quanto finora descritto solo concettualmente e come utilizzare gli oggetti messi a disposizione dal package per realizzare trasmissione di dati via rete tra applicazioni. La Figura 10.9 rappresenta la gerarchia delle classi ed interfacce appartenenti a questo package. Scorrendo velocemente i loro nomi notiamo subito le loro analogie con la nomenclatura utilizzata nei paragrafi precedenti. Analizziamole brevemente. Gerarchia delle classi o class java.lang.Object o class java.net.Authenticator o class java.lang.ClassLoader o class java.security.SecureClassLoader o class java.net.URLClassLoader o class java.net.ContentHandler o class java.net.DatagramPacket o class java.net.DatagramSocket o class java.net.MulticastSocket o class java.net.DatagramSocketImpl (implements java.net.SocketOptions) o class java.net.InetAddress (implements java.io.Serializable) o class java.net.PasswordAuthentication o class java.security.Permission (implements java.security.Guard, java.io.Serializable) o class java.security.BasicPermission (implements java.io.Serializable) o class java.net.NetPermission o class java.net.SocketPermission (implements java.io.Serializable) o class java.net.ServerSocket o class java.net.Socket o class java.net.SocketImpl (implements java.net.SocketOptions) o class java.lang.Throwable (implements java.io.Serializable) o class java.lang.Exception o class java.io.IOException o class java.net.MalformedURLException o class java.net.ProtocolException o class java.net.SocketException o class java.net.BindException o class java.net.ConnectException o class java.net.NoRouteToHostException o class java.net.UnknownHostException o class java.net.UnknownServiceException o class java.net.URL (implements java.io.Serializable) o class java.net.URLConnection o class java.net.HttpURLConnection o class java.net.JarURLConnection o class java.net.URLDecoder o class java.net.URLEncoder o class java.net.URLStreamHandler o o o o o o Gerarchia delle Interfacce interface java.net.ContentHandlerFactory interface java.net.DatagramSocketImplFactory interface java.net.FileNameMap interface java.net.SocketImplFactory interface java.net.SocketOptions interface java.net.URLStreamHandlerFactory Figura 10-9 : Gerarchie tra le classi di Java.net Un indirizzo IP rappresentato dalla classe InetAddress che fornisce tutti i metodi necessari a manipolare un indirizzo internet necessario allinstradamento dei dati sulla rete e consente la trasformazione di un indirizzo nelle sue varie forme : <NAME> http://www.java-net.tv [email protected] 139 getAllByName(String host) ritorna tutti gli indirizzi internet di un host dato il suo nome in forma estesa (esempio: getAllByName(www.javasoft.com)); getByName(String host) ritorna lindirizzo internet di un host dato il suo nome in forma estesa; getHostAddress() ritorna una stringa rappresentante lindirizzo IP dellhost nella forma decimale separata da punto "%d.%d.%d.%d"; getHostName() ritorna una stringa rappresentante il nome dellhost. Le classi Socket e ServerSocket implementano rispettivamente un socket client e server per la comunicazione orientata alla connessione, la classe DatagramSocket implementa i socket per la trasmissione senza connessione ed infine la classe MulticastSocket fornisce supporto per i socket di tipo multicast. Rimangono da menzionare le classi URL, URLConnection, HttpURLConnection e URLEencoder che implementano i meccanismi di connessione tra un browser ed un Web Server. Un esempio completo di applicazione client/server Nei prossimi paragrafi analizzeremo in dettaglio una applicazione client/server basata su modello di trasmissione con connessione. Prima di entrare nei dettagli della applicazione necessario per porci una domanda: cosa accade tra due applicazioni che comunichino con trasmissione orientata a connessione? Il server ospitato su un computer host in ascolto tramite socket su una determinata porta in attesa di richiesta di connessione da parte di un client (Figura 10-10). Il client invia la sua richiesta al server tentando la connessione tramite la porta su cui il server in ascolto. Figura 10-11: Richiesta di connessione Client/Server <NAME> http://www.java-net.tv [email protected] 140 Dobbiamo a questo punto distinguere due casi: nel primo caso il server comunica con un solo client alla volta accettando una richiesta di connessione solo se nessunaltro client gi connesso (trasmissione unicast); nel secondo caso il server in grado di comunicare con pi client contemporaneamente (trasmissione multicast). Nel caso di trasmissione unicast, se la richiesta di connessione tra client e server va a buon fine, il server accetta la connessione stabilendo il canale di comunicazione con il client che, a sua volta, ricevuta la conferma alloca un socket su una porta locale tramite il quale trasmettere e ricevere pacchetti (Figura 10-12). Figura 10-12: Connessione Unicast Nel caso di trasmissione multicast, se la richiesta di connessione tra client e server va a buon fine, il server prima di creare il canale di connessione alloca un nuovo socket associato ad una nuova porta (tipicamente avvia un nuovo thread per ogni connessione) a cui cede in gestione la gestione del canale di trasmissione con il client. Il socket principale torna quindi ad essere libero di rimanere in ascolto per una nuova richiesta di connessione (Figura 10-13). Un buon esempio di applicazione client/server che implementano trasmissioni multicast dono browser e Web Server. A fronte di n client (browser) connessi, il server deve essere in grado di fornire servizi a tutti gli utenti continuando ad ascoltare sulla porta 80 (porta standard per il servizio) in attesa di nuove connessioni. Figura 10-13 : Connessione Multicast Massimiliano Tarquini http://www.java-net.tv <EMAIL> 141 La classe ServerSocket La classe ServerSocket rappresenta quella porzione del server che pu accettare richieste di connessioni da parte del client. Questa classe deve essere istanziata passando come parametro il numero della porta su cui il server sar in ascolto. Il codice di seguito rappresenta un prototipo semplificato della classe ServerSocket. public final class ServerSocket { public ServerSocket(int port) throws IOException .. public ServerSocket(int port, int count) throws IOException .. public Socket accept() throws IOException public void close()throws IOException public String toString() } Lunico metodo realmente necessario alla classe il metodo accept(). Questo metodo mette il thread in attesa di richiesta di connessioni da parte di un client sulla porta specificata nel costruttore. Quando una richiesta di connessione va a buon fine, viene creato il canale di collegamento e il metodo ritorna un oggetto Socket connesso con il client. Nel caso di comunicazione multicast, sar necessario creare un nuovo thread a cui passare il socket connesso al client. La classe Socket La classe Socket rappresenta una connessione client/server via TCP su entrambi i lati: client e server. La differenza tra server e client sta nella modalit di creazione di un oggetto di questo tipo. A differenza del server in cui un oggetto Socket viene creato dal metodo accept() della classe ServerSocket, il client dovr provvedere a creare una istanza di Socket manualmente. public final class Socket { public Socket (String host, int port) public int getPort() public int getLocalPort() public InputStream getInputStream() throws IOException public OutputStream getOutputStream() throws IOException public synchronized void close () throws IOException public String toString(); } Quando si crea una istanza manuale della classe Socket, il costruttore messo a disposizione dalla classe accetta due parametri: il primo, rappresenta il nome dell host a cui ci si vuole connettere; il secondo, la porta su cui il server in ascolto. Il costruttore una volta chiamato tenter di effettuare la connessione generando una eccezione nel caso in cui il tentativo non sia andato a buon fine. Notiamo inoltre che questa classe ha un metodo getInputStream() e un metodo getOutputStream(). Questo perch un Socket accetta la modalit di trasmissione in entrambi i sensi (entrata ed uscita). I metodi getPort() e getLocalPort() possono essere utilizzati per ottenere informazioni relative alla connessione, mentre il metodo close() chiude la connessione rilasciando la porta libera di essere utilizzata per altre connessioni. <NAME> http://www.java-net.tv <EMAIL> 142 Un semplice thread di servizio Abbiamo detto che quando implementiamo un server di rete che gestisce pi client simultaneamente, importante creare dei thread separati per comunicare con ogni client. Questi thread sono detti thread di servizio. Nel nostro esempio, utilizzeremo una classe chiamata Xfer per definire i servizi erogati dalla nostra applicazione client/server . 1. import java.net.* ; 2. import java.lang.* ; 3. import java.io.* ; 4. 5. class Xfer implements Runnable 6. { 7. private Socket connection; 8. private PrintStream o; 9. private Thread me; 10. 11. public Xfer(socket s) 12. { 13. connection = s; 14. me = new Thread(this); 15. me.start(); 16. } 17. 18. public void run() 19. { 20. try 21. { 22. //converte loutput del socket in un printstream 23. o = new PrintStream(connection.getOutPutStream()); 24. } catch(Exception e) {} 25. while (true) 26. { 27. o.println(Questo un messaggio dal server); 28. try 29. { 30. ma.sleep(1000); 31. } catch(Exception e) {} 32. } 33. } 34. } Xfer pu essere creata solo passandogli un oggetto Socket che deve essere gi connesso ad un client. Una volta istanziato, Xfer crea ed avvia un thread associato a se stesso (linee 11-16). Il metodo run() di Xfer converte lOutputStream del Socket in un PrintStream che utilizza per inviare un semplice messaggio al client ogni secondo. TCP Server La classe NetServ rappresenta il thread primario del server. Equesto il thread che accetter connessioni e creer tutti gli alti thread del server. <NAME> http://www.java-net.tv <EMAIL> 143 1. import java.io.* ; 2. import java.net.* ; 3. import java.lang.* ; 4. 5. public class NetServ implements Runnable 6. { 7. private ServerSocket server; 8. public NetServ () throws Exception 9. { 10. server = new ServerSocket(2000); 11. } 12. public void run() 13. { 14. Socket s = null; 15. Xfer x; 16. 17. while (true) 18. { 19. try { 20. //aspetta la richiesta da parte del client 21. s = server.accept(); 22. } catch (IOException e) { 23. System.out.println(e.toString()); 24. System.exit(1); 25. } 26. //crea un nuovo thread per servire la richiesta 27. x = new xfer(s); 28. } 29. } 30. } 31. 32. public class ServerProgram 33. { 34. public static void main(String args[]) 35. { 36. NetServ n = new NetServ(); 37. (new Thread(n)).start(); 38. } 39. } Il costruttore alla linea 8 crea una istanza di un oggetto ServerSocket associandolo alla porta 2000. Ogni eccezione viene propagata al metodo chiamante. Loggetto NetServ implementa Runnable, ma non crea il proprio thread. Sar responsabilit dellutente di questa classe creare e lanciare il thread associato a questo oggetto. Il metodo run() estremamente semplice. Alla linea 21 viene accettata la connessione da parte del client. La chiamata server.accept() ritorna un oggetto socket connesso con il client. A questo punto, NetServ crea una istanza di Xfer utilizzando il Socket (linea 27) generando un nuovo thread che gestisca la comunicazione con il client. La seconda classe semplicemente rappresenta il programma con il suo metodo main(). Nelle righe 36 e 37 viene creato un oggetto NetServ, viene generato il thread associato e quindi avviato. <NAME> http://www.java-net.tv <EMAIL> 144 Il client Loggetto NetClient effettua una connessione ad un host specifico su una porta specifica,e legge i dati in arrivo dal server linea per linea. Per convertire i dati di input viene utilizzato un oggetto DataInputStream, ed il client utilizza un thread per leggere i dati in arrivo. 1. import java.net.* ; 2. import java.lang.* ; 3. import java.io.* ; 4. 5. public class NetClient implements Runnable 6. { 7. private Socket s; 8. private DataInputStream input; 9. public NetClient(String host, int port) throws Exception 10. { 11. s = new Socket(host, port); 12. } 13. public String read() throws Exception 14. { 15. if (input == null) 16. input = new DataInputStream(s.getInputStream()); 17. return input.readLine(); 18. } 19. public void run() 20. { 40. while (true) 41. { 42. try { 43. System.out.println(nc.read()); 44. } catch (Exception e) { 45. System.out.println(e.toString()); 46. } 21. } 22. } 23. } 24. 25. class ClientProgram 26. { 27. public static void main(String args[]) 28. { 29. if(args.length<1) System.exit(1); 30. NetClient nc = new NetClient(args[0], 2000); 31. (new Thread(nc)).start(); 32. } 33. } <NAME> http://www.java-net.tv <EMAIL> 145 Parte Seconda Applicazioni Server Side Versione 0.1 <NAME> http://www.java-net.tv <EMAIL>-one-mail.net 146 Capitolo 12 Java Enterprise Computing Introduzione Il termine Enterprise Computing (che per semplicit in futuro indicheremo con EC) sinonimo di Distributed Computing ovvero calcolo eseguito da un gruppo di programmi interagenti attraverso una rete. La figura 11-1 mostra schematicamente un ipotetico scenario di Enterprise Computing evidenziando alcune possibili integrazioni tra componenti server-side. Appare chiara la disomogeneit tra le componenti e di conseguenza la complessit strutturale di questi sistemi. Figura 11-1 Dalla figura appaiono chiari alcuni aspetti. Primo, lEC generalmente legato ad architetture di rete eterogenee in cui la potenza di calcolo distribuita tra Main Frame, Super Computer e semplici PC. Lunico denominatore comune tra le componenti il protocollo di rete utilizzato, in genere il TCP/IP. Secondo, applicazioni server di vario tipo girano allinterno delle varie tipologie di hardware. Ed infine lEC comporta spesso luso di molti protocolli di rete e altrettanti standard differenti, alcuni dei quali vengono implementati dallindustria del software con componenti specifiche della piattaforma. E quindi evidente la complessit di tali sistemi e di conseguenza le problematiche che un analista od un programmatore sono costretti ad affrontare. Java tende a semplificare tali aspetti fornendo un ambiente di sviluppo completo di API e metodologie di approccio al problem-solving. La soluzione composta da Sun di Mass<NAME> http://www.java-net.tv [email protected] 147 compone di quattro elementi principali: specifiche, Reference Implementation, test di compatibilit e Application Programming Model. Le specifiche elencano gli elementi necessari alla piattaforma e le procedure da seguire per una corretta implementazione con J2EE. La reference implementation contiene prototipi che rappresentano istanze semanticamente corrette di J2EE al fine di fornire allindustria del software modelli completi per test. Include tool per il deployment e lamministrazione di sistema, EJBs, JSPs, un container per il supporto a runtime e con supporto verso le transazioni, Java Messaging Service e altri prodotti di terzi. L Application Programming Model un modello per la progettazione e programmazione di applicazioni basato sulla metodologia best-practiceper favorire un approccio ottimale alla piattaforma. Guida il programmatore analizzando quanto va fatto e quanto no con J2EE, e fornisce le basi della metodologia legata allo sviluppo di sistemi multi-tier con J2EE. Figura 11-2 Nella figura 11-2 viene illustrato un modello di EC alternativo al precedente in cui viene illustrato con maggior dettaglio il modello precedente con una particolare attenzione ad alcune delle tecnologie di Sun e le loro modalit di interconnessione. Architettura di J2EE Larchitettura proposta dalla piattaforma J2EE divide le applicazioni enterprise in tre strati applicativi fondamentali (figura 11-3): componenti, contenitori e connettori. Il modello di programmazione prevede lo sviluppo di soluzioni utilizzando componenti a supporto delle quali fornisce quattro tecnologie fondamentali: Enterprise Java Beans; Servelet ; <NAME> http://www.java-net.tv [email protected] 148 Java Server Pages ; Applet. La prima delle tre che per semplicit denoteremo con EJB fornisce supporto per la creazione di componenti server-side che possono essere generate indipendentemente da uno specifico database, da uno specifico transaction server o dalla piattaforma su cui gireranno. La seconda, servlet, consente la costruzione di servizi web altamente performanti ed in grado di funzionare sulla maggior parte dei web server ad oggi sul mercato. La terza, JavaServer Pages o JSP, permette di costruire pagine web dai contenuti dinamici utilizzando tutta la potenza del linguaggio java. Le applet, anche se sono componenti client-side rappresentano comunque tecnologie appartenenti allo strato delle componenti. In realt esiste una quinta alternativa alle quattro riportate per la quale per non si pu parlare di tecnologia dedicate, ed rappresentata dalle componenti serverside sviluppate utilizzando java. Figura 11-3 In realt esiste una quinta alternativa alle quattro riportate per la quale per non si pu parlare di tecnologia dedicate, ed rappresentata dalle componenti serverside sviluppate utilizzando java. Il secondo strato rappresentato dai contenitori ovvero supporti tecnologici alle tecnologie appartenenti al primo strato logico della architettura. La possibilit di costruire contenitori rappresenta la caratteristica fondamentale del sistema in quanto fornisce ambienti scalari con alte performance. Infine i connettori consentono alle soluzioni basate sulla tecnologia J2EE di preservare e proteggere investimenti in tecnologie gi esistenti fornendo uno strato di connessione verso applicazioni-server o middleware di varia natura: dai database relazionali con JDBC fino ai server LDAP con JNDI. Gli application-server compatibili con questa tecnologia riuniscono tutti e tre gli strati in un una unica piattaforma standard e quindi indipendente dal codice Massimiliano Tarquini http://www.java-net.tv [email protected] 149 proprietario, consentendo lo sviluppo di componenti server-centricin grado di girare in qualunque container compatibile con J2EE indipendentemente dal fornitore di software, e di interagire con una vasta gamma di servizi pre-esistenti tramite i connettori. Ad appoggio di questa soluzione, la Sun mette a disposizione dello sviluppatore un numero elevato di tecnologie specializzate nella soluzione di singoli problemi. Gli EJBs forniscono un modello a componenti per il server-side computing, Servlet offrono un efficiente meccanismo per sviluppare estensioni ai Web Server in grado di girare in qualunque sistema purch implementi il relativo container. Infine Java Server Pages consente di scrivere pagine web dai contenuti dinamici sfruttando a pieno le caratteristiche di java. Un ultima considerazione, non di secondaria importanza, va fatta sul modello di approccio al problem-solving: la suddivisione netta che la soluzione introduce tra logiche di business, logiche di client, e logiche di presentazione consente un approccio per strati al problema garantendo ordine nella progettazione e nello sviluppo di una soluzione. J2EE Application Model Date le caratteristiche della piattaforma, laspetto pi interessante legato a quello che le applicazioni non devono fare; la complessit intrinseca delle applicazioni enterprise quali gestione delle transazioni, ciclo di vita delle componenti, pooling delle risorse viene inglobata allinterno della piattaforma che provvede autonomamente alle componenti ed al loro supporto. Figura 11-4 Programmatori e analisti sono quindi liberi di concentrarsi su aspetti specifici della applicazione come presentazione o logiche di business non dovendosi <NAME> http://www.java-net.tv <EMAIL> 150 occupare di aspetti la cui complessit non irrilevante e, in ambito progettuale ha un impatto notevolissimo su costi e tempi di sviluppo. A supporto di questo, lApplication Model descrive la stratificazione orizzontale tipica di una applicazione J2EE. Tale stratificazione identifica quattro settori principali (figura 11-4) : Client Tier, Web Tier, Business-Tier, EIS-Tier. Client Tier Appartengono allo strato client le applicazioni che forniscono allutente una interfaccia semplificata verso il mondo enterprise e rappresentano quindi la percezione che lutente ha della applicazione J2EE. Tali applicazioni si suddividono in due classi di appartenenza : le applicazioni web-based e le applicazioni non-webbased. Figura 11-5 Le prime sono quelle applicazioni che utilizzano il browser come strato di supporto alla interfaccia verso lutente ed i cui contenuti vengono generati dinamicamente da Servlet o Java Server Pages o staticamente in HTML. Le seconde (non-web-based) sono invece tutte quelle basate su applicazioni stand-alone che sfruttano lo strato di rete disponibile sul client per interfacciarsi direttamente con la applicazione J2EE senza passare per il Web-Tier. Nella figura 11-5 vengono illustrate schematicamente le applicazioni appartenenti a questo strato e le modalit di interconnessione verso gli strati componenti la architettura del sistema. <NAME> http://www.java-net.tv <EMAIL> 151 Web Tier Le componenti web-tier di J2EE sono rappresentate da pagine JSP, server-side applet e Servlet. Le pagine HTML che invocano Servlet o JSP secondo lo standard J2EE non sono considerate web-components, ed il motivo il seguente : come illustrato nei paragrafi precedenti si considerano componenti, oggetti caricabili e gestibili allinterno di un contenitore in grado di sfruttarne i servizi messi a disposizione. Nel nostro caso, Servlet e JSP hanno il loro ambiente runtime allinterno del Servlet-Container che provvede al loro ciclo di vita, nonch alla fornitura di servizi quali client-request e client-response ovvero come un client appartenente allo strato client-tier rappresenta la percezione che lutente ha della applicazione J2EE, il contenitore rappresenta la percezione che una componente al suo interno ha della interazione verso lesterno (Figura 11-6). Figura 11-6 La piattaforma J2EE prevede quattro tipi di applicazioni web : basic HTML, HTML with base JSP and Servlet, Servlet and JSP with JavaBeans components, High Structured Application con componenti modulari, Servlet ed Enterprise Beans. Di queste, le prime tre sono dette applicazioni web-centric, quelle appartenenti al quarto tipo sono dette applicazioni EJB Centric. La scelta di un tipo di applicazione piuttosto che di un altro dipende ovviamente da vari fattori tra cui: Complessit del problema; Risorse del Team di sviluppo; Longevit della applicazione; Dinamismo dei contenuti da gestire e proporre. <NAME> http://www.java-net.tv <EMAIL> 152 Figura 11-7 Nella figura 11-77 viene presentata in modo schematico tutta la gamma di applicazioni web ed il loro uso in relazione a due fattori principali : complessit e robustezza. Business Tier Nellambito di una applicazione enterprise, questo lo strato che fornisce servizi specifici: gestione delle transazioni, controllo della concorrenza, gestione della sicurezza, ed implementa inoltre logiche specifiche circoscritte allambito applicativo ed alla manipolazione dei dati. Mediante un approccio di tipo Object Oriented possibile decomporre tali logiche o logiche di business in un insieme di componenti ed elementi chiamati business object. La tecnologia fornita da Sun per implementare i business object quella che in precedenza abbiamo indicato come EJBs (Enterprise Java Beans). Tali componenti si occupano di: Ricevere dati da un client, processare tali dati (se necessario), inviare i dati allo strato EIS per la loro memorizzazione su base dati; (Viceversa) Acquisire dati da un database appartenente allo strato EIS, processare tali dati (se necessario), inviare tali dati al programma client che ne abbia fatto richiesta. Esistono due tipi principali di EJBs : entity beans e session beans. Per session bean si intende un oggetto di business che rappresenta una risorsa privatarispetto al client che lo ha creato. Un entity bean al contrario rappresenta in modo univoco un Massimiliano Tarquini http://www.java-net.tv <EMAIL> 153 dato esistente allinterno dello strato EIS ed ha quindi una sua precisa identit rappresentata da una chiave primaria (figura 11-8). Figura 11-8 Oltre alle componenti, la architettura EJB definisce altre 3 entit fondamentali: servers, containers e client. Un Enterprise Bean vive allinterno del container che provvede al ciclo vitale della componente e ad una variet di latri servizi quali gestione della concorrenza e scalabilit. LEJB Container a sua volta parte di un EJB server che fornisce tutti i servizi di naming e di directory (tali problematiche verranno affrontate negli articoli successivi). Quando un client invoca una operazione su un EJB, la chiamata viene intergettata dal container. Questa intercessione del container tra client ed EJB a livello di chiamata a metodo consente al container la gestione di quei servizi di cui si parlato allinizio del paragrafo oppure della propagazione della chiamata ad altre componenti (Load Balancing) o ad altri container (Scalabilit) su altri server sparsi per la rete su differenti macchine. Nella implementazione di una architettura enterprise, oltre a decidere che tipo di enterprise beans utilizzare, un programmatore deve effettuare altre scelte strategiche nella definizione del modello a componenti : Che tipo di oggetto debba rappresentare un Enterprise Bean; Che ruolo tale oggetto deve avere allinterno di un gruppo di componenti che collaborino tra di loro. Dal momento che gli enterprise beans sono oggetti che necessitano di abbondanti risorse di sistema e di banda di rete, non sempre soluzione ottima modellare tutti i business object come EJBs. In generale una soluzione consigliabile <NAME> http://www.java-net.tv <EMAIL> 154 quella di adottare tale modello solo per quelle componenti che necessitino un accesso diretto da parte di un client. EIS-Tier Le applicazioni enterprise implicano per definizione laccesso ad altre applicazioni, dati o servizi sparsi allinterno delle infrastrutture informatiche del fornitore di servizi. Le informazioni gestite ed i dati contenuti allinterno di tali infrastrutture rappresentano la ricchezza del fornitore, e come tale vanno trattati con estrema cura garantendone la integrit. Figura 11-9 Al modello bidimensionale delle vecchie forme di business legato ai sistemi informativi (figura 11-9) stato oggi sostituito da un nuovo modello (e-business) che introduce una terza dimensione che rappresenta la necessit da parte del fornitore di garantire accesso ai dati contenuti nella infrastruttura enterprise via web a: partner commerciali, consumatori, impiegati e altri sistemi informativi. Gli scenari di riferimento sono quindi svariati e comprendono vari modelli di configurazione che le architetture enterprise vanno ad assumere per soddisfare le necessit della new-economy. Un modello classico quello rappresentato da sistemi di commercio elettronico (figura 11-10) . Nei negozi virtuali o E-Store lutente web interagisce tramite browser con i cataloghi on-line del fornitore, seleziona i prodotti, inserisce i prodotti selezionati nel carrello virtuale, avvia una transazione di pagamento con protocolli sicuri. <NAME> http://www.java-net.tv <EMAIL> 155 Figura 11-10 Le API di J2EE Le API di J2EE forniscono supporto al programmatore per lavorare con le pi comuni tecnologie utilizzate nellambito della programmazione distribuita e dei servizi di J2EE Technologies interconnessione via rete. I prossimi paragrafi forniranno una breve introduzione alle API Java IDL RMI/IIOP componenti lo strato tecnologico fornito con la JDBC piattaforma definendo volta per volta la filosofia alla JDBC 2.0 Client Parts base di ognuna di esse e tralasciando le API relative JNDI Servlet a Servlet, EJBs e JavaServer Pages gi introdotte Javaserver Pages nei paragrafi precedenti. Javamail, JavaBeans Activation Framework JTS EJB JTA JMS Connector/Resource Mgmt. Comp. JDBC : Java DataBase Connectivity Rappresentano le API di J2EE per poter lavorare con database relazionali. Esse consentono al programmatore di inviare query ad un database relazionale, di effettuare dolete o update dei dati allinterno di tabelle, di lanciare stored-procedure o di ottenere meta-informazioni relativamente al database o le entit che lo compongono. <NAME> http://www.java-net.tv <EMAIL> 156 Figura 11-11 Architetturalmente JDBC sono suddivisi in due strati principali : il primo che fornisce una interfaccia verso il programmatore, il secondo di livello pi basso che fornisce invece una serie di API per i produttori di drivers verso database relazionali e nasconde allutente i dettagli del driver in uso.Questa caratteristica rende la tecnologia indipendente rispetto al motore relazionale che il programmatore deve interfacciare. I driver JDBC possono essere suddivisi in 4 tipi fondamentali come da tabella: Tipo 4 Tipo 3 Tipo 2 Tipo 1 Direct-to-Database Pure Java Driver Pure Java Driver for Database Middleware; JDBC-ODBC Bridge plus ODBC Driver; A native-API partly Java technology-enabled driver. I driver di tipo 4 e 3 appartengono a quella gamma di drivers che convertono le chiamate JDBC nel protocollo di rete utilizzato direttamente da un server relazionale o un middleware che fornisca connettivit attraverso la rete verso uno o pi database (figura 11-11) e sono scritti completamente in Java. <NAME> http://www.java-net.tv <EMAIL> 157 Figura 11-12 I driver di tipo 2 sono driver scritti parzialmente in Java e funzionano da interfaccia verso API native di specifici prodotti. I driver di tipo 1, anchessi scritti parzialmente in java hanno funzioni di bridge verso il protocollo ODBC rilasciato da Microsoft. Questi driver sono anche detti JDBC/ODBC Bridge (Figura 11-12) e rappresentano una buona alternativa in situazioni in cui non siano disponibili driver di tipo 3 o 4. RMI : Remote Method Invocation Remote Method Invocation fornisce il supporto per sviluppare applicazioni java in grado di invocare metodi di oggetti distribuiti su virtual-machine differenti sparse per la rete. Grazie a questa tecnologia possibile realizzare architetture distribuite in cui un client invoca metodi di oggetti residenti su un server che a sua volta pu essere client nei confronti di un altro server. Oltre a garantire tutte i vantaggi tipici di una architettura distribuita, essendo fortemente incentrato su Java RMI consente di trasportare in ambiente distribuito tutte le caratteristiche di portabilit e semplicit legata allo sviluppo di componenti Object Oriented apportando nuovi e significativi vantaggi rispetto alle ormai datate tecnologie distribuite (vd. CORBA). Primo, RMI in grado di passare oggetti e ritornare valori durante una chiamata a metodo oltre che a tipi di dati predefiniti. Questo significa che dati strutturati e complessi come le Hashtable possono essere passati come un singolo argomento senza dover decomporre loggetto in tipi di dati primitivi. In poche parole RMI <NAME> http://www.java-net.tv <EMAIL> 158 permette di trasportare oggetti attraverso le infrastrutture di una architettura enterprise senza necessitare di codice aggiuntivo. Secondo, RMI consente di delegare limplementazione di una classe dal client al server o viceversa. Questo fornisce una enorme flessibilit al programmatore che scriver solo una volta il codice per implementare un oggetto che sar immediatamente visibile sia a client che al server. Terzo, RMI estende le architetture distribuite consentendo luso di thread da parte di un server RMI per garantire la gestione ottimale della concorrenza tra oggetti distribuiti. Infine RMI abbraccia completamente la filosofia Write Once Run Anywhere di Java. Ogni sistema RMI portabile al 100% su ogni Java Virtual Machine. Java IDL RMI fornisce una soluzione ottima come supporto ad oggetti distribuiti con la limitazione che tali oggetti debbano essere scritti con Java. Tale soluzione non si adatta invece alle architetture in cui gli oggetti distribuiti siano scritti con linguaggi arbitrari. Per far fronte a tali situazioni, la Sun offre anche la soluzione basata su CORBA per la chiamata ad oggetti remoti. CORBA (Common Object Request Broker Architecture) uno standard largamente utilizzato introdotto dallOMG (Object Managment Group) e prevede la definizione delle interfacce verso oggetti remoti mediante un IDL (Interface Definition Language) indipendente dalla piattaforma e dal linguaggio di riferimento con cui loggetto stato implementato. Limplementazione di questa tecnologia rilasciata da Sun comprende un ORB (Object Request Broker) in grado di interagire con altri ORB presenti sul mercato, nonch di un pre-compilatore IDL che traduce una descrizione IDL di una interfaccia remota in una classe Java che ne rappresenti il dato. JNDI Java Naming and Directory Interface quellinsieme di API che forniscono laccesso a servizi generici di Naming o Directory attraverso la rete. Consentono, alla applicazione che ne abbia bisogno, di ottenere oggetti o dati tramite il loro nome o di ricercare oggetti o dati mediante luso di attributi a loro associati. Adesempio tramite JNDI possibile accedere ad informazioni relative ad utenti di rete, server o workstation, sottoreti o servizi generici (figura 11-13). Come per JDBC le API JNDI non nascono per fornire accesso in modo specifico ad un particolare servizio, ma costituiscono un set generico di strumenti in grado di interfacciarsi a servizi mediante driver rilasciati dal produttore del servizio e che mappano le API JNDI nel protocollo proprietario di ogni specifico servizio. Tali driver vengono detti Service Providers e forniscono accesso a protocolli come LDAP, NIS, Novell NDS oltre che ad una gran quantit di servizi come DNS, RMI o CORBA Registry. <NAME> http://www.java-net.tv <EMAIL> 159 Figura 11-13 JMS Java Message Service o Enterprise Messaging rappresentano le API forniscono supporto alle applicazioni enterprise nella gestione asincrona della comunicazione verso servizi di messaging o nella creazione di nuovi MOM (Message Oriented Middleware). Nonostante JMS non sia cos largamente diffuso come le altre tecnologie, svolge un ruolo importantissimo nellambito di sistemi enterprise. Per meglio comprenderne il motivo necessario comprendere il significato della parola messaggio che in ambito JMS rappresenta tutto linsieme di messaggi asincroni utilizzati dalle applicazioni enterprise, non dagli utenti umani, contenenti dati relativi a richieste, report o eventi che si verificano allinterno del sistema fornendo informazioni vitali per il coordinamento delle attivit tra i processi. Essi contengono informazioni impacchettate secondo specifici formati relativi a particolari eventi di business. Grazie a JMS possibile scrivere applicazioni di business message-based altamente portabili fornendo una alternativa a RMI che risulta necessaria in determinati ambiti applicativi. Nella figura 11-14 schematizzata una soluzione tipo di applicazioni basate su messaggi. Una applicazione di Home Banking deve interfacciarsi con il sistema di messagistica bancaria ed interbancaria da cui trarre tutte le informazioni relative alla gestione economica dellutente. <NAME> http://www.java-net.tv <EMAIL> 160 Figura 11-14 Nel modello proposto da J2EE laccesso alle informazioni contenute allinterno di questo strato possibile tramite oggetti chiamati connettoriche rappresentano una architettura standard per integrare applicazioni e componenti enterprise eterogenee con sistemi informativi enterprise anche loro eterogenei. I connettori sono messi a disposizione della applicazione enterprise grazie al server J2EE che li contiene sotto forma di servizi di varia natura (es. Pool di connessioni) e che tramite questi collabora con i sistemi informativi appartenenti allo strato EIS in modo da rendere ogni meccanismo a livello di sistema completamente trasparente alle applicazioni enterprise. Lo stato attuale dellarte prevede che la piattaforma J2EE consenta pieno supporto per la connettivit verso database relazionali tramite le API JDBC, le prossime versioni della architettura J2EE prevedono invece pieno supporto transazionale verso i pi disparati sistemi enterprise oltre che a database relazionali. <NAME> http://www.java-net.tv <EMAIL> 161 Capitolo 13 Architettura del Web Tier Introduzione Chi ha potuto accedere ad internet a partire dagli inizi degli anni 90, quando ancora la diffusione della tecnologia non aveva raggiunto la massa ed i costi erano eccessivi (ricordo che nel 1991 pagai un modem interno usato da 9600 bps la cifra incredibile di 200.000 lire), ha assistito alla incredibile evoluzione che ci ha portato oggi ad una diversa concezione del computer. A partire dai primi siti internet dai contenuti statici, siamo oggi in grado di poter effettuare qualsiasi operazione tramite Web da remoto. Questa enorme crescita, come una vera rivoluzione, ha voluto le sua vittime. Nel corso degli anni sono nate e poi completamente scomparse un gran numero di tecnologie a supporto di un sistema in continua evoluzione. Servlet e JavaServer Pages rappresentano oggi lo stato dellarte delle tecnologie web. Raccogliendo la pesante eredit lasciata dai suoi predecessori, la soluzione proposta da SUN rappresenta quanto di pi potente e flessibile possa essere utilizzato per sviluppare applicazioni web. Larchitettura del Web Tier Prima di affrontare il tema dello sviluppo di applicazioni web con Servlet e JavaServer Pages importante fissare alcuni concetti. Il web-server gioca un ruolo fondamentale allinterno di questo strato. In ascolto su un server, riceve richieste da parte del browser (client), le processa, quindi restituisce al client una entit o un eventuale codice di errore come prodotto della richiesta (Figura 0-12). Figura 0-12 Nei Box 1 e 2 sono riportati i dati relativi alla distribuzione dei web-server sul mercato negli ultimi anni (i dati sono disponibili nella forma completa allindirizzo internet http://www.netcraft.com/survey). <NAME> http://www.java-net.tv [email protected] 162 Box 1 : Grafici di distribuzione dei web server Market Share for Top Servers Across All Domains August 1995 - December 2000 Box 2 : Distribuzione dei web server Top Developers Developer Apache Microsoft iPlanet November 2000 14193854 4776220 1643977 Percent 59.69 20.09 6.91 December 2000 15414726 5027023 1722228 Percent Change 60.04 19.58 6.71 0.35 -0.51 -0.20 Top Servers Server Apache MicrosoftIIS NetscapeEnterprise WebLogic Zeus Rapidsite thttpd tigershark AOLserver WebSitePro November 2000 14193854 Percent Change 59.69 December 2000 15414726 60.04 0.35 4774050 20.08 5025017 19.57 -0.51 1605438 6.75 1682737 6.55 -0.20 789953 640386 347307 226867 120213 136326 106618 3.32 2.69 1.46 0.95 0.51 0.57 0.45 890791 676526 365807 321944 139300 125513 110681 3.47 2.63 1.42 1.25 0.54 0.49 0.43 0.15 -0.06 -0.04 0.30 0.03 -0.08 -0.02 <NAME> Percent http://www.java-net.tv Server Apache MicrosoftIIS NetscapeEnterprise WebLogic Zeus Rapidsite thttpd tigershark AOLserver WebSitePro <EMAIL> 163 Le entit prodotte da un web-server possono essere entit statiche o entit dinamiche. Una entit statica ad esempio un file html residente sul file-system del server. Rispetto alle entit statiche, unico compito del web-server quello di recuperare la risorsa dal file-system ed inviarla al browser che si occuper della visualizzazione dei contenuti. Quello che pi ci interessa sono invece le entit dinamiche, ossia entit prodotte dalla esecuzione di applicazioni eseguite dal web-server su richiesta del client. Il modello proposto nella immagine 1 ora si complica in quanto viene introdotto un nuovo grado di complessit (Figura 2-12) nella architettura del sistema che, oltre a fornire accesso a risorse statiche dovr fornire un modo per accedere a contenuti e dati memorizzati su una Base Dati, dati con i quali un utente internet potr interagire da remoto. Figura 2-12 Inviare dati Mediante form HTML possibile inviare dati ad un web-server. Tipicamente lutente riempie alcuni campi il cui contenuto, una volta premuto il pulsante submit viene inviato al server con il messaggio di richiesta. La modalit con cui questi dati vengono inviati dipende dal metodo specificato nella richiesta. Utilizzando il metodo GET, i dati vengono appesi alla request-URI nella forma di coppie chiave=valore separati tra di loro dal carattere &. La stringa seguente un esempio di campo request-URI per una richiesta di tipo GET. http://www.java-net.tv/servelt/Hello?nome=Massimo&cognome=Rossi http://www.java-net.tv rappresenta lindirizzo del web-server a cui inviare la richiesta. I campi /servlet/Hello rappresenta la locazione della applicazione web da <NAME> http://www.java-net.tv <EMAIL> 164 eseguire. Il carattere ? separa lindirizzo dai dati e il carattere & separa ogni coppia chiave=valore. Questo metodo utilizzato per default dai browser a meno di specifiche differenti, viene utilizzato nei casi in cui si richieda al server il recupero di informazioni mediante query su un database. Il metodo POST pur producendo gli stessi effetti del precedente, utilizza una modalit di trasmissione dei dati differente impacchettando i contenuti dei campi di un form allinterno di un message-header. Rispetto al precedente, il metodo POST consente di inviare una quantit maggiore di dati ed quindi utilizzato quando necessario inviare al server nuovi dati affinch possano essere memorizzati allinterno della Base Dati. Sviluppare applicazioni web A meno di qualche eccezione una applicazione web paragonabile ad una qualsiasi applicazione con la differenza che deve essere accessibile al web-server che fornir lambiente di runtime per lesecuzione. Affinch ci sia possibile necessario che esista un modo affinch il web-server possa trasmettergli i dati inviati dal client, che esista un modo univoco per laccesso alle funzioni fornite dalla applicazione (entry-point), che lapplicazione sia in grado di restituire al web-server i dati prodotti in formato HTML da inviare al client nel messaggio di risposta. Esistono molte tecnologie per scrivere applicazioni web che vanno dalla pi comune CGI a soluzioni proprietarie come ISAPI di Microsoft o NSAPI della Netscape. Common Gateway Interface CGI sicuramente la pi comune e datata tra le tecnologie server-side per lo sviluppo di applicazioni web. Scopo principale di un CGI quello di fornire funzioni di gatewaytra il web-server e la base dati del sistema. I CGI possono essere scritti praticamente con tutti i linguaggi di programmazione. Questa caratteristica classifica i CGI in due categorie: CGI sviluppati mediante linguaggi script e CGI sviluppati con linguaggi compilati. I primi, per i quali viene generalmente utilizzato il linguaggio PERL, sono semplici da implementare, ma hanno lo svantaggio di essere molto lenti e per essere eseguiti richiedono lintervento di un traduttore che trasformi le chiamate al linguaggio script in chiamate di sistema. I secondi a differenza dei primi sono molto veloci, ma risultano difficili da programmare (generalmente sono scritti mediante linguaggio C). Figura 3-12 <NAME> http://www.java-net.tv [email protected] 165 Nella Figura 3-12 schematizzato il ciclo di vita di un CGI. Il pi grande svantaggio nelluso dei CGI sta nella scarsa scalabilit della tecnologia infatti, ogni volta che il web-server riceve una richiesta deve creare una nuova istanza del CGI (Figura 4-12). Il dover stanziare un processo per ogni richiesta ha come conseguenza enormi carichi in fatto di risorse macchina e tempi di esecuzione (per ogni richiesta devono essere ripetuti i passi come nella Figura 3-12). A meno di non utilizzare strumenti di altro tipo inoltre impossibile riuscire ad ottimizzare gli accessi al database. Ogni istanza del CGI sar difatti costretta ad aprire e chiudere una propria connessione verso il DBMS. Questi problemi sono stati affrontati ed in parte risolti dai Fast-CGI grazie ai quali possibile condividere una stessa istanza tra pi richieste http. Figura 3-12: Un CGI non una tecnologia scalabile ISAPI ed NSAPI Per far fronte ai limiti tecnologici imposti dai CGI, Microsoft e Netscape hanno sviluppato API proprietarie mediante le quali creare librerie ed applicazioni che possono essere caricate dal web-server al suo avvio ed utilizzate come proprie estensioni. Linsuccesso di queste tecnologie stato per segnato proprio dalla loro natura di tecnologie proprietarie e quindi non portabili tra le varie piattaforme sul mercato. Essendo utilizzate come moduli del web-server era inoltre caso frequente che un loro accesso errato alla memoria causasse il crash dellintero web-server provocando enormi danni al sistema che doveva ogni volta essere riavviato. ASP Active Server Pages Active Server Pages stata lultima tecnologia web rilasciata da Microsoft. Una applicazione ASP tipicamente un misto tra HTML e linguaggi script come VBScript o JavaScript mediante i quali si pu accedere ad oggetti del server. Una pagina ASP, a differenza di ISAPI, non viene eseguita come estensione del web-server, ma viene compilata alla prima chiamata, ed il codice compilato pu quindi essere utilizzato ad ogni richiesta HTTP. Nonostante sia oggi largamente diffusa, ASP come ISAPI rimane una tecnologia proprietaria e quindi in grado di funzionare solamente su piattaforma Microsoft, ma il Massimiliano Tarquini http://www.java-net.tv [email protected] 166 reale svantaggio di ASP per legato alla sua natura di mix tra linguaggi script ed HTML. Questa sua caratteristica ha come effetto secondario quello di riunire in un unico contenitore sia le logiche applicative che le logiche di presentazione rendendo estremamente complicate le normali operazioni di manutenzione delle pagine. Java Servlet e JavaServer Pages Sun cerca di risolvere i problemi legati alle varie tecnologie illustrate, mettendo a disposizione del programmatore due tecnologie che raccogliendo leredit dei predecessori, ne abbattono i limiti mantenendo e migliorando gli aspetti positivi di ognuna. In aggiunta Servlet e JavaServer Pages ereditano tutte quelle caratteristiche che rendono le applicazioni Java potenti, flessibili e semplici da mantenere: portabilit del codice, paradigma object oriented. Rispetto ai CGI, Servlet forniscono un ambiente ideale per quelle applicazioni per cui sia richiesta una massiccia scalabilit e di conseguenza lottimizzazione degli accessi alle basi dati di sistema. Rispetto ad ISAPI ed NSAPI, pur rappresentando una estensione al web server, mediante il meccanismo delle eccezioni risolvono a priori tutti gli errori che potrebbero causare la terminazione prematura del sistema. Rispetto ad ASP, Servlet e JavaServer Pages separano completamente le logiche di business dalle logiche di presentazione dotando il programmatore di un ambiente semplice da modificare o mantenere. <NAME> http://www.java-net.tv <EMAIL> 167 Capitolo 14 Java Servlet API Introduzione Java Servlet sono oggetti Java con propriet particolari che vengono caricati ed eseguiti dal web server che le utilizzer come proprie estensioni. Il web server di fatto mette a disposizione delle Servlet il container che si occuper della gestione del loro ciclo di vita, delle gestione dellambiente allinterno delle quali le servlet girano, dei servizi di sicurezza. Il container ha anche funzione passare i dati dal client verso le servlet e viceversa ritornare al client i dati prodotti dalla loro esecuzione. Dal momento che una servlet un oggetto server-side, pu accedere a tutte le risorse messe a disposizione dal server per generare pagine dai contenuti dinamici come prodotto della esecuzione delle logiche di business. Eovvio che sar cura del programmatore implementare tali oggetti affinch gestiscano le risorse del server in modo appropriato evitando di causare danni al sistema che le ospita. Il package javax.servlet Questo package il package di base delle Servlet API, e contiene le classi per definire Servlet standard indipendenti dal protocollo. Tecnicamente una Servlet generica una classe definita a partire dallinterfaccia Servlet contenuta allinterno del package javax.servlet. Questa interfaccia contiene i prototipi di tutti i metodi necessari alla esecuzione delle logiche di business, nonch alla gestione del ciclo di vita delloggetto dal momento del suo istanziamento, sino al momento della sua terminazione. package javax.servlet; import java.io.*; public interface Servlet { public abstract void destroy(); public ServletConfig getServletConfig(); public String getServletInfo(); public void service (ServletRequest req, ServletResponse res) throws IOException, ServletException; } I metodi definiti in questa interfaccia devono essere supportati da tutte le servlet o possono essere ereditati attraverso la classe astratta GenericServlet che rappresenta una implementazione base di una servlet generica. Nella Figura 14-1 viene schematizzata la gerarchia di classi di questo package. Il package include inoltre una serie di classi utili alla comunicazione tra client e server, nonch alcune interfacce che definiscono i prototipi di oggetti utilizzati per tipizzare le classi che saranno necessarie alla specializzazione della servlet generica in servlet dipendenti da un particolare protocollo. <NAME> http://www.java-net.tv <EMAIL> 168 InputStream InputStream ServletInputStream ServletInputStream OutputStream OutputStream OutputStream OutputStream Servlet Servlet ServletConfig ServletConfig ServletContext ServletContext Seriaizable Seriaizable ServletRequest ServletRequest ServletResponse ServletResponse Object Object GenericServlet GenericServlet Exception Exception ServletException ServletException SingleThreadModel SingleThreadModel UnavoidableException UnavoidableException RequestDispatcher RequestDispatcher Estende Classi Astratte Classi Astratte Interfacce Interfacce Classi Classi Implementa Figura 14-1: il package javax.servlet Il package javax.servlet.http Questo package supporta lo sviluppo di Servlet che specializzando la classe base astratta GenericServlet definita nel package javax.servlet utilizzano il protocollo http. Le classi di questo package estendono le funzionalit di base di una servlet supportando tutte le caratteristiche della trasmissione di dati con protocollo http compresi cookies, richieste e risposte http nonch metodi http (get, post head, put ecc. ecc.). Nella Figura 14-2 schematizzata la gerarchia del package in questione. Formalmente quindi, una servlet specializzata per generare contenuti specifici per il mondo web sar ottenibile estendendo la classe base astratta javax.servlet.http.HttpServlet. <NAME> http://www.java-net.tv <EMAIL> 169 EventObject EventObject HTTPSessionBindingEvent HTTPSessionBindingEvent EventListener EventListener HTTPSessionBindingListener HTTPSessionBindingListener Cookie Cookie HTTPSession HTTPSession HttpUtils HttpUtils Seriaizable Seriaizable HTTPSessionContext HTTPSessionContext Object Object GenericServlet GenericServlet Cloneable Cloneable HttpServlet HttpServlet Servlet Servlet ServletRequest ServletRequest HttpServletRequest HttpServletRequest ServletResponse ServletResponse HttpServletResponse HttpServletResponse Estende Classi Astratte Classi Astratte Interfacce Interfacce Classi Classi Implementa Figura 14-2 : il package javax.servlet Ciclo di vita di una servlet Il ciclo di vita di una servlet definisce come una servlet sar caricata ed inizializzata, come ricever e risponder a richieste dal client ed infine come sar terminata prima di passare sotto la responsabilit del garbage collector. Il ciclo di vita di una servlet schematizzato nel diagramma seguente (Figura 14- 3). Figura 14-3: Ciclo di vita di una servlet Il caricamento e listanziamento di una o pi servlet a carico del web server ed avviene al momento della prima richiesta http da parte di un client, o se specificato direttamente, al momento dellavvio del servizio. Questa fase viene eseguita dal web server utilizzando loggetto Class di java.lang . <NAME> http://www.java-net.tv <EMAIL> 170 Dopo che stata caricata, necessario che la servlet venga inizializzata. Durante questa fase, la servlet generalmente carica dati persistenti, apre connessioni verso il database o stabilisce legami con altre entit esterne. Linizializzazione della servlet avviene mediante la chiamata al metodo init(), definito nella interfaccia javax.servlet.Servlet ed ereditato dalla classe base astratta javax.servlet.http.HttpServlet. Nel caso in cui il metodo non venga riscritto, il metodo ereditato non eseguir nessuna operazione. Il metodo init di una servlet prende come parametro di input un oggetto di tipo ServletConfig che consente di accedere a parametri di inizializzazione passati attraverso il web server nella forma di coppie chiave-valore. Dopo che la nostra servlet stata inizializzata, pronta ad eseguire richieste da parte di un client. Le richieste da parte di un client vengono inoltrate alla servlet dal container nella forma di oggetti di tipo HttpServletRequest e HttpServletResponse mediante passaggio di parametri al momento della chiamata del metodo service(). Come per init(), il metodo service() viene ereditato di default dalla classe base astratta HttpServlet. In questo caso per il metodo ereditato a meno che non venga ridefinito eseguir alcune istruzioni di default come vedremo tra qualche paragrafo. Ecomunque importante ricordare che allinterno di questo metodo vengono definite le logiche di business della nostra applicazione. Mediante loggetto HttpServletRequest saremo in grado di accedere ai parametri passati in input dal client, processarli e rispondere con un oggetto di tipo HttpServletResponse. Infine, quando una servlet deve essere distrutta (tipicamente quando viene terminata lesecuzione del web server), il container chiama di default il metodo destroy(). LOverriding di questo metodo ci consentir di rilasciare tutte le risorse utilizzate dalla servlet, ad esempio le connessioni a basi dati, garantendo che il sistema non rimanga in uno stato inconsistente a causa di una gestione malsana da parte della applicazione web. Servlet e multithreading Tipicamente quando n richieste da parte del client arrivano al web server, vengono creati n thread differenti in grado di accedere ad una particolare servlet in maniera concorrente (Figura 14-4). Figura 14-4 : Accessi concorrenti a servlet Come tutti gli oggetti Java, servlet non sono oggetti thread-safe, ovvero necessario che il programmatore definisca le politiche di accesso alla istanza della classe da parte del thread. Inoltre, lo standard definito da SUN Microsystem prevede <NAME> http://www.java-net.tv [email protected] 171 che un server possa utilizzare una sola istanza di questi oggetti (questa limitazione anche se tale aiuta alla ottimizzazione della gestione delle risorse percui ad esempio una connessione ad un database sar condivisa tra tante richieste da parte di client). Mediante lutilizzo delloperatore synchronized, possibile sincronizzare laccesso alla classe da parte dei thread dichiarando il metodo service() di tipo sincronizzato o limitando lutilizzo del modificatore a singoli blocci di codice che contengono dati sensibili (vd. Capitolo 9). Linterfaccia SingleThreadModel Quando un thread accede al metodo sincronizzato di una servlet, ottiene il lock sulla istanza delloggetto. Abbiamo inoltre detto che un web server per definizione utilizza una sola istanza di servlet condividendola tra le varie richieste da parte dei client. Stiamo creando un collo di bottiglia che in caso di sistemi con grossi carichi di richieste potrebbe ridurre significativamente le prestazioni del sistema. Se il sistema dispone di abbondanti risorse, le Servlet API ci mettono a disposizione un metodo per risolvere il problema a scapito delle risorse della macchina rendendo le servlet classi thread-safe. Formalmente, una servlet viene considerata thread-safe se implementa linterfaccia javax.servlet.SingleThreadModel . In questo modo saremo sicuri che solamente un thread avr accesso ad una istanza della classe in un determinato istante. A differenza dellutilizzo del modificatore synchronized, in questo caso il web server creer pi istanze di una stessa servlet (tipicamente in numero limitato e definito) al momento del caricamento delloggetto, e utilizzer le varie istanze assegnando al thread che ne faccia richiesta, la prima istanza libera (Figura 14-5). Figura 14-5 : SingleThreadModel Un primo esempio di classe Servlet Questa prima servlet di esempio fornisce la versione web della applicazione Java HelloWorld. La nostra servlet una volta chiamata ci restituir una pagina HTML contenente semplicemente la stringa HelloWorld. HelloWorldServlet.java import javax.servlet.* ; import javax.servlet.http.* ; public class HelloWorldServlet extends HttpServlet { <NAME> http://www.java-net.tv <EMAIL> 172 public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); ServletOutputStream out = res.getOutputStream(); out.println(<html>); out.println(<head><title>Hello World</title></head>); out.println(<body>); out.println(<h1>Hello World</h1>); out.println(</body></html>); } } Il metodo service() Se il metodo service() di una servlet non viene modificato, la nostra classe eredita di default il metodo service definito allinterno della classe astratta HttpServlet (Figura 14-6). Essendo il metodo chiamato in causa al momento dellarrivo di una richiesta da parte di un client, nella sua forma originale questo metodo ha funzioni di dispatchertra altri metodi basati sul tipo di richiesta http in arrivo dal client. Figura 14-6: La classe HttpServlet Come abbiamo gi introdotto nel capitolo precedente, il protocollo http ha una variet di tipi differenti di richieste che possono essere avanzate da parte di un client. Comunemente quelle di uso pi frequente sono le richieste di tipo GET e POST. Nel caso di richiesta di tipo GET o POST, il metodo service definito allinterno della classe astratta HttpServlet chiamer i metodi rispettivamente doGet() o doPost() che conterranno ognuno il codice per gestire la particolare richiesta. In questo caso quindi, non avendo applicato la tecnica di Overriding sul metodo service() , sar necessario implementare uno di questi metodi allinterno della nostra nuova classe a seconda del tipo di richieste che dovr esaudire (Figura 13-7). <NAME> http://www.java-net.tv <EMAIL> 173 Figura 14-7 : service() ha funzioni di bridge Massimil<NAME> http://www.java-net.tv <EMAIL> 174 Capitolo 15 Servlet HTTP Introduzione Http servlet rappresentano una specializzazione di servlet generiche e sono specializzate per comunicare mediante protocollo http. Il package javax.servlet.http mette a disposizione una serie di definizioni di classe che rappresentano strumenti utili alla comunicazione tra client e server con questo protocollo, nonch forniscono uno strumento flessibile per accedere alle strutture definite nel protocollo, al tipo di richieste inviate ai dati trasportati. Le interfacce ServletRequest e ServletResponse rappresentano rispettivamente richieste e risposte http. In questo capitolo le analizzeremo in dettaglio con lo scopo di comprendere i meccanismi di ricezione e manipolazione dei dati di input nonch di trasmissione delle entit dinamiche prodotte. Il protocollo HTTP 1.1 Rispetto alla classificazione fornita nei paragrafi precedenti riguardo i protocolli di rete, http (HyperText Trasfer Protocol) appartiene allinsieme dei protocolli applicativi e, nella sua ultima versione, fornisce un meccanismo di comunicazione tra applicazioni estremamente flessibile dotato di capacit praticamente infinita nel descrivere possibili richieste nonch i possibili scopi per cui la richiesta stata inviata. Grazie a queste caratteristiche http largamente utilizzato per la comunicazione tra applicazioni in cui sia necessaria la possibilit di negoziare dati e risorse, ecco perch luso del protocollo come standard per i web server. Il protocollo fu adottato nel 1990 dalla World Wide Web Global Information Initiativea partire dalla versione 0.9 come schematizzato nella tabella sottostante: HTTP 0.9 HTTP 1.0 Semplice protocollo per la trasmissione dei dati via internet. Introduzione rispetto alla versione precedente del concetto di Mime-Type. Il protocollo ora in grado di trasportare meta-informazioni relative ai dati trasferiti. HTTP 1.1 Estende la versione precedente affinch il protocollo contenga informazioni che tengono in considerazione problematiche a livello applicativo come ad esempio quelle legate alla gestione della cache. Scendendo nei dettagli, http un protocollo di tipo Request/Response: ovvero un client invia una richiesta al server e rimane in attesa di una sua risposta. Entrambe richiesta e risposta http hanno una struttura che identifica due sezioni principali: un message-header ed un message-body come schematizzato nella figura 15-1. Il message-header contiene tutte le informazioni relative alla richiesta o risposta, mentre il message-body contiene eventuali entit trasportate dal pacchetto (intendendo per entit i contenuti dinamici del protocollo come pagine html) e tutte le informazioni relative: ad esempio mime-type, dimensioni ecc. Le entit trasportate allinterno del message-body vengono inserite allinterno dellentity-body. Le informazioni contenute allinterno di un messaggio http sono separate tra di loro dalla sequenza di caratteri CRLF dove CR il carattere Carriage Return(US ASCII 13) e LF il carattere Line Feed(US ASCII 10). Tale regola non applicabile ai contenuti dellentity-body che rispettano il formato come definito dal rispettivo MIME. <NAME> http://www.java-net.tv [email protected] 175 Figura 15-1 : pacchetti http Per dare una definizione formale del protocollo http utilizzeremo la sintassi della forma estesa di Backup Nauer che per semplicit indicheremo con lacronimo BNF. Secondala BNF, un messaggio http generico definito dalla seguente regola: HTTP-Message = Request | Response Request = generic-message Response = generic-message generic-message = start-line *(message-header CRLF) CRLF [message-body] start-line = Request-line | Response-line Richiesta HTTP Scendendo nei dettagli, una richiesta http da un client ad un server definita dalla seguente regola BNF: Request = Request-line *((general-header | request-header | entity-header) CRLF) CRLF [message-body] La Request-line formata da tre token separati dal carattere SP o Spazio (US ASCII 32) che rappresentano rispettivamente: metodo, indirizzo della risorsa o URI, versione del protocollo. Request-line = Method SP Request-URI SP http-version CRLF SP = <US-ASCII Space (32) > Method = OPTIONS| GET| HEAD| POST| PUT | DELETE| TRACE| CONNECT| extension-method extension-method = token Request-URI = *| absoluteURI | abs-path | authority HTTP-version = HTTP/1*DIGIT .1*DIGIT <NAME> http://www.java-net.tv <EMAIL> 176 DIGIT = <any US ASCII digit 0....9> Un esempio di Request-line inviata da client ha server potrebbe essere : GET /lavora.html HTTP/1.1 Il campo General-header ha valore generale per entrambi I messagi di richiesta o risposta e non contiene dati applicabili alla entit trasportata con il messaggio: General-header = Cache-Control | Connection | Date | Pragma | Trailer | Trasfer-Encoding | Upgrade | Via | Warning Senza scendere nei dettagli di ogni singolo campo contenuto nel Generalheader, importante comprenderne lutilizzo. Questo campo infatti estremamente importante in quanto trasporta le informazioni necessarie alla negoziazione tra le applicazioni. Ad esempio, il campo Connection pu essere utilizzato da un server proxy per determinare lo stato della connessione tra client e server e decidere su eventuali misura da applicare. I campi di request-header consentono al client di inviare informazioni relative alla richiesta in corso ed al client stesso. Request-header = Accept | Accept-Charset | Accept-Encoding | Accept-Language | Authorization | Expect | From | Host | If-Match | If-Modified-Since | If-None-Match | If-Range | If-Unmodified-Since | Max-Forwards | Proxy-Authorization | Range | Referer | TE | User-Agent Entity-header e Message-Body verranno trattati nei paragrafi seguenti. <NAME> http://www.java-net.tv <EMAIL> 177 Risposta HTTP Dopo aver ricevuto un messaggio di richiesta, il server risponde con un messaggio di risposta definito dalla regola BNF: Response = Status-line *((general-header | response-header | entity-header) CRLF) CRLF [message-body] La Status-line la prima linea di un messaggio di risposta http e consiste di tre token separati da spazio contenenti rispettivamente informazioni sulla versione del protocollo, un codice di stato che indica un errore o leventuale buon fine della richiesta, una breve descrizione del codice di stato. Status-line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF SP = <US-ASCII Space (32) > Status-Code = "100" : Continue | "101 : Switching Protocols | "200" : OK | "201" : Created | "202" : Accepted | "203" : Non-Authoritative Information | "204" : No Content | "205" : Reset Content | "206" : Partial Content | "300" : Multiple Choices | "301" : Moved Permanently | "302" : Found | "303" : See Other | "304" : Not Modified | "305" : Use Proxy | "307" : Temporary Redirect | "400" : Bad Request | "401" : Unauthorized | "402" : Payment Required | "403" : Forbidden | "404" : Not Found | "405" : Method Not Allowed | "406" : Not Acceptable | "407" : Proxy Authentication Required | "408" : Request Time-out | "409" : Conflict | "410" : Gone | "411" : Length Required | "412" : Precondition Failed | "413" : Request Entity Too Large | "414" : Request-URI Too Large | "415" : Unsupported Media Type | "416" : Requested range not satisfiable | "417" : Expectation Failed | "500" : Internal Server Error Massimiliano Tarquini http://www.java-net.tv tar<EMAIL> 178 | "501" : Not Implemented | "502" : Bad Gateway | "503" : Service Unavailable | "504" : Gateway Time-out | "505" : HTTP Version not supported | extension-code extension-code = 3DIGIT Reason-Phrase = *<TEXT, excluding CR, LF> Un codice di stato un intero a 3 cifre ed il risultato della processazione da parte del server della richiesta mentre la Reason-Phrase intende fornire una breve descrizione del codice di stato. La prima cifra di un codice di stato definisce la regola per suddividere i vari codici: 1xx : Informativo Richiesta ricevuta, continua la processazione dei dati; 2xx : Successo Lazione stata ricevuta con successo, compresa ed accettata; 3xx : Ridirezione Ulteriori azioni devono essere compiute al fine di completare la richiesta; 4xx : Client-Error La richiesta sintatticamente errata e non pu essere soddisfatta; 5xx : Server-Error Il server non ha soddisfatto la richiesta apparentemente valida. Come per il Request-Header, il Response-Header contiene campi utili alla trasmissione di informazioni aggiuntive relative alla risposta e quindi anchesse utili alla eventuale negoziazione : response-header = Accept-Ranges | Age | Etag | Location | Proxy-Authenticate | Retry-After | Server | www-autheticate Entit Come abbiamo visto, richiesta e risposta http possono trasportare entit a meno che non sia previsto diversamente dallo status-code della risposta o dal requestmethod della richiesta (cosa che vedremo nel paragrafo successivo). In alcuni casi un messaggio di risposta pu contenere solamente il campo entity-header (ossia il campo descrittore della risorsa trasportata). Come regola generale, entity-header trasporta meta-informazioni relative alla risorsa identificata dalla richiesta. entity-header = Allow | Content-Encoding | Content-Language | Content-Length | Content-Location | Content-MD5 | Content-Range | Content-Type | Expires <NAME> http://www.java-net.tv tarquini<EMAIL>-one-mail.net 179 | Last-Modified | extension-header extension-header = message-header Queste informazioni, a seconda dei casi possono essere necessarie od opzionali. Il campo extension-header consente laggiunta di una nuove informazioni non previste, ma necessarie, senza apportare modifiche al protocollo. I metodi di request I metodi definiti dal campo request-method sono necessari al server per poter prendere decisioni sulle modalit di processazione della richiesta. Le specifiche del protocollo http prevedono nove metodi, tuttavia, tratteremo brevemente i tre pi comuni: HEAD, GET, POST. Il metodo GET significa voler ottenere dal server qualsiasi informazione (nella forma di entit) come definita nel campo request-URI. Se utilizzato per trasferire dati mediante form HTML, una richiesta di tipo GET invier i dati contenuti nel form scrivendoli in chiaro nella request-URI. Simile al metodo GET il metodo HEAD che ha come effetto quello di indicare al server che non necessario includere nella risposta un message-body contenente la entit richiesta in request-URI. Tale metodo ha lo scopo di ridurre i carichi di rete in quei casi in cui non sia necessario linvio di una risorsa: ad esempio nel caso in cui il client disponga di un meccanismo di caching. Il metodo POST quello generalmente utilizzato l dove siano necessarie operazioni in cui richiesto il trasferimento di dati al server affinch siano processati. Una richiesta di tipo POST non utilizza il campo Request-URI per trasferire i parametri, bens invia un pacchetto nella forma di message-header con relativo entity-header. Il risultato di una operazione POST non produce necessariamente entit. In questo caso uno status-code 204 inviato dal server indicher al client che la processazione andata a buon fine senza che per abbia prodotto entit. Inizializzazione di una Servlet Linterfaccia ServletConfig rappresenta la configurazione iniziale di una servlet. Oggetti definiti per implementazione di questa interfaccia, contengono i parametri di inizializzazione della servlet (se esistenti) nonch permettono alla servlet di comunicare con il servlet container restituendo un oggetto di tipo ServletContext. public interface ServletConfig { public ServletContext getServletContext(); public String getInitParameter(String name); public Enumeration getInitParameterNames(); } I parametri di inizializzazione di una servlet devono essere definiti allinterno dei file di configurazione del web server che si occuper di comunicarli alla servlet in forma di coppie chiave=valore. I metodi messi a disposizione da oggetti di tipo ServletConfig per accedere a questi parametri sono due: il metodo getInitParametrNames() che restituisce un elenco (enumerazione) dei nomi dei parametri, ed il metodo getInitParameter(String) che preso in input il nome del parametro in forma di oggetto String, restituisce a sua volta una stringa contenente il valore del parametro di inizializzazione. Nellesempio di seguito, utilizziamo il met<NAME> http://www.java-net.tv <EMAIL> 180 getInitParameter(String) per ottenere il valore del parametro di input con chiave CHIAVEPARAMETRO: String key = CHIAVE_PARAMETRO; String val = config.getInitParameter(key); Dove config rappresenta un oggetto di tipo ServletConfig passato come parametro di input al metodo init(ServletConfig) della servlet. Il metodo getServletContext(), restituisce invece un oggetto di tipo ServletContext tramite il quale possibile richiedere al container lo stato dellambiente allinterno del quale le servlet stanno girando. Un metodo alternativo per accedere ai parametri di configurazione della servlet messo a disposizione dal metodo getServletConfig() definito allinterno della interfaccia servlet di javax.servlet. Utilizzando questo metodo sar di fatto possibile accedere ai parametri di configurazione anche allinterno del metodo service(). Nel prossimo esempio viene definita una servlet che legge un parametro di input con chiave INPUTPARAMS, lo memorizza in un dato membro della classe e ne utilizza il valore per stampare una stringa alla esecuzione del metodo service(). import javax.servlet.* ; import javax.servlet.http.* ; import java.io ; public class Test extends HttpServlet { String initparameter=null; public void init(ServletConfig config) { initparameter = config.getInitParameter(INPUTPARAMS); } public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); ServletOutputStream out = res.getOutputStream(); out.println(<html>); out.println(<head><title>Test</title></head>); out.println(<body>); out.println(<h1>Il parametro di input vale + initparameter +</h1>); out.println(</body></html>); } } Loggetto HttpServletResponse Questo oggetto definisce il canale di comunicazione tra la servlet ed il client che ha inviato la richiesta (browser). Questo oggetto mette a disposizione della servlet i metodi necessari per inviare al client le entit prodotte dalla manipolazione dei dati di input. Una istanza delloggetto ServletResponse viene definita per implementazione della interfaccia HttpServletResponse definita allinterno del package javax.servlet.http che definisce una specializzazione della interfaccia derivata rispetto al protocollo http. package javax.servlet; import java.io.*; <NAME> http://www.java-net.tv <EMAIL> 181 public interface ServletResponse extends RequestDispatcher { public String getCharacterEncoding(); public ServletOutputStream getOutputStream() throws IOException; public PrintWriter getWriter() throws IOException; public void setContentLength(int length); public void setContentType(String type); } package javax.servlet.http; import java.util.*; import java.io.*; public interface HttpServletResponse extends javax.servlet.ServletResponse { public static final int SC_CONTINUE = 100; public static final int SC_SWITCHING_PROTOCOLS = 101; public static final int SC_OK = 200; public static final int SC_CREATED = 201; public static final int SC_ACCEPTED = 202; public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; public static final int SC_NO_CONTENT = 204; public static final int SC_RESET_CONTENT = 205; public static final int SC_PARTIAL_CONTENT = 206; public static final int SC_MULTIPLE_CHOICES = 300; public static final int SC_MOVED_PERMANENTLY = 301; public static final int SC_MOVED_TEMPORARILY = 302; public static final int SC_SEE_OTHER = 303; public static final int SC_NOT_MODIFIED = 304; public static final int SC_USE_PROXY = 305; public static final int SC_BAD_REQUEST = 400; public static final int SC_UNAUTHORIZED = 401; public static final int SC_PAYMENT_REQUIRED = 402; public static final int SC_FORBIDDEN = 403; public static final int SC_NOT_FOUND = 404; public static final int SC_METHOD_NOT_ALLOWED = 405; public static final int SC_NOT_ACCEPTABLE = 406; public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; public static final int SC_REQUEST_TIMEOUT = 408; public static final int SC_CONFLICT = 409; public static final int SC_GONE = 410; public static final int SC_LENGTH_REQUIRED = 411; public static final int SC_PRECONDITION_FAILED = 412; public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413; public static final int SC_REQUEST_URI_TOO_LONG = 414; public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; public static final int SC_INTERNAL_SERVER_ERROR = 500; public static final int SC_NOT_IMPLEMENTED = 501; public static final int SC_BAD_GATEWAY = 502; public static final int SC_SERVICE_UNAVAILABLE = 503; public static final int SC_GATEWAY_TIMEOUT = 504; public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; void addCookie(Cookie cookie); boolean containsHeader(String name); String encodeRedirectUrl(String url); //deprecated String encodeRedirectURL(String url); String encodeUrl(String url); String encodeURL(String url); void sendError(int statusCode) throws java.io.IOException; <NAME> http://www.java-net.tv <EMAIL> 182 void sendError(int statusCode, String message) throws java.io.IOException; void sendRedirect(String location) throws java.io.IOException; void setDateHeader(String name, long date); void setHeader(String name, String value); void setIntHeader(String name, int value); void setStatus(int statusCode); void setStatus(int statusCode, String message); } Questa interfaccia definisce i metodi per impostare dati relativi alla entit inviata nella risposta (lunghezza e tipo mime), fornisce informazioni relativamente al set di caratteri utilizzato dal browser (in http questo valore viene trasmesso nell header Accept-Charset del protocollo) infine fornisce alla servlet laccesso al canale di comunicazione per inviare lentit al client. I due metodi deputati alla trasmissione sono quelli definiti nella interfaccia ServletResponse. Il primo, ServletOutputStream getOutputStream(), restituisce un oggetto di tipo ServletOutputStream e consente di inviare dati al client in forma binaria (ad esempio il browser richiede il download di un file) . Il secondo PrintWriter getWriter() restituisce un oggetto di tipo PrintWriter e quindi consente di trasmettere entit allo stesso modo di una System.out. Utilizzando questo secondo metodo, il codice della servlet mostrato nel paragrafo precedente diventa quindi: import javax.servlet.* ; import javax.servlet.http.* ; import java.io ; public class Test extends HttpServlet { String initparameter=null; public void init(ServletConfig config) { initparameter = config.getInitParameter(INPUTPARAMS); } public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res. getWriter (); out.println(<html>); out.println(<head><title>Test</title></head>); out.println(<body>); out.println(<h1>Il parametro di input vale + initparameter +</h1>); out.println(</body></html>); } } Nel caso in cui sia necessario utilizzare il metodo setContentType, sar obbligatorio effettuarne la chiamata prima di utilizzare il canale di output. I metodi specializzati di HttpServletResponse Nel paragrafo precedente abbiamo analizzato i metodi di HttpServletResponse ereditati a partire dalla interfaccia ServletResponse. Come si vede dal codice riportato nel paragrafo precedente, HttpServletResponse specializza un oggetto <NAME> http://www.java-net.tv <EMAIL> 183 response affinch possa utilizzare gli strumenti tipici del protocollo http mediante metodi specializzati e legati alla definizione del protocollo. I metodi definiti allinterno di questa interfaccia coprono la possibilit di modificare o aggiungere campi allinterno dellheader del protocollo http, metodi per lavorare utilizzando i cookie, metodi per effettuare url encoding o per manipolare errori http. E inoltre possibile mediante il metodo sendRedirect() provocare il reindirizzamento della connessione verso un altro server sulla rete. Notificare errori utilizzando Java Servlet Allinterno della interfaccia HttpServletResponse, oltre ai prototipi dei metodi vengono dichiarate tutta una serie di costanti che rappresentano i codici di errore come definiti dallo standard http. Il valore di queste variabili costanti pu essere utilizzato con i metodi sendError(..) e setStatus( ) per inviare al browser particolari messaggi con relativi codici di errore. Un esempio realizzato nella servlet seguente: import javax.servlet.* ; import javax.servlet.http.* ; import java.io ; public class TestStatus extends HttpServlet { String initparameter=null; public void init(ServletConfig config) { } public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); ServletOutputStream out = res.getOutputStream(); out.println(<html>); out.println(<head><title>Test Status Code</title></head>); out.println(<body>); res.sendError(HttpServletResponse. SC_OK, Il sito e stato temporaneamente sospeso); out.println(</body></html>); } } Loggetto HttpServletRequest Come oggetti di tipo HttpServletResponse rappresentano una risposta http, oggetti di tipo HttpServletRequest rappresentano una richiesta http. package javax.servlet; import java.net.*; import java.io.*; import java.util.*; public interface ServletRequest { public Object getAttribute(String name); public Enumeration getAttributeNames(); <NAME> http://www.java-net.tv <EMAIL> 184 public String getCharacterEncoding(); public int getContentLength(); public String getContentType(); public ServletInputStream getInputStream() throws IOException; public String getParameter(String name); public Enumeration getParameterNames(); public String[] getParameterValues(String name); public String getProtocol(); public BufferedReader getReader() throws IOException; public String getRealPath(String path); public String getRemoteAddr(); public String getRemoteHost(); public String getScheme(); public String getServerName(); public int getServerPort(); public Object setAttribute(String name, Object attribute); } package javax.servlet.http; import java.util.*; import java.io.*; public interface HttpServletRequest extends javax.servlet.ServletRequest { String getAuthType(); Cookie[] getCookies(); long getDateHeader(String name); String getHeader(String name); Enumeration getHeaderNames(); int getIntHeader(String name); String getMethod(); String getPathInfo(); String getPathTranslated(); String getQueryString(); String getRemoteUser(); String getRequestedSessionId(); String getRequestURI(); String getServletPath(); HttpSession getSession(); HttpSession getSession(boolean create); boolean isRequestedSessionIdFromCookie(); boolean isRequestedSessionIdFromUrl(); boolean isRequestedSessionIdFromURL(); boolean isRequestedSessionIdValid(); } Mediante i metodi messi a disposizione da questa interfaccia, possibile accedere ai contenuti della richiesta http inviata dal client compreso eventuali parametri o entit trasportate allinterno del pacchetto http. I metodi ServletInputStream getInputStream() e BufferedReader getReader() ci permettono di accedere ai dati trasportati dal protocollo. Il metodo getParameter(String) ci consente di ricavare i valori dei parametri contenuti allinterno della query string della richiesta referenziandoli tramite il loro nome. Esistono inoltre altri metodi che consentono di ottenere meta informazioni relative alla richiesta: ad esempio i metodi .. public String getRealPath(String path); public String getRemoteAddr(); <NAME> http://www.java-net.tv <EMAIL> 185 public String getRemoteHost(); public String getScheme(); public String getServerName(); public int getServerPort(); . Nel prossimo esempio utilizzeremo questi metodi per implementare una servlet che stampa a video tutte le informazioni relative alla richiesta da parte del client: import javax.servlet.* ; import javax.servlet.http.* ; import java.io ; public class Test extends HttpServlet { String initparameter=null; public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(text/html); PrintWriter out = res. getWriter (); out.println(<html>); out.println(<head><title>Test</title></head>); out.println(<body>); out.println(<b>Carachter encoding</b> +req.getCharacterEncoding()+<BR>); out.println(<b>Mime tipe dei contenuti</b> +req.getContentType()+<BR>); out.println(<b>Protocollo</b> +req.getProtocol()+<BR>); out.println(<b>Posizione fisica:</b> +req.getRealPath()+<BR>); out.println(<b>Schema:</b> +req.getScheme()+<BR>); out.println(<b>Nome del server:</b> +req.getServerName()+<BR>); out.println(<b>Porta del server:</b> +req.getServerPort()+<BR>); out.println(</body></html>); out.close(); } } Altri metodi di questa interfaccia ci consentono di utilizzare i cookie esistenti sul client oppure ottenere meta informazioni relative al client che ha inviato la richiesta. Inviare dati mediante la query string Nel capitolo 13 abbiamo introdotto la trasmissione di dati tra client e applicazione web. Ricordando quanto detto, utilizzando il metodo GET del protocollo http i dati vengono appesi alla URL che identifica la richiesta nella forma di coppie nome=valore separate tra loro dal carattere &. Questa concatenazione di coppie detta query string ed separata dallindirizzo della risorsa dal carattere ?. Ad esempio la URL http://www.java-net.tv/servelt/Hello?nome=Massimo&cognome=Rossi <NAME> http://www.java-net.tv <EMAIL> 186 contiene la query string ?nome=Massimo&cognome=Rossi. Abbiamo inoltre accennato al fatto che se il metodo utilizzato il metodo POST, i dati non vengono trasmessi in forma di query string ma vengono accodati nella sezione dati del protocollo http. Le regole utilizzare in automatiche dal browser e necessarie al programmatore per comporre la query string sono le seguenti: La query string inizia con il carattere ?. Utilizza coppie nome=valore per trasferire i dati. Ogni coppia deve essere separata dal carattere &. Ogni carattere spazio deve essere sostituito dalla sequenza %20. Ogni carattere % deve essere sostituito dalla sequenza %33. I valori di una query string possono essere recuperati da una servlet utilizzando i metodi messi a disposizione da oggetti di tipo HttpServletRequest. In particolare nellinterfaccia HttpServletRequest vengono definiti quattro metodi utili alla manipolazione dei parametri inviati dal browser. public String getQueryString (); public Enumeration getParameterNames(); public String getParameter(String name); public String[] getParameterValues(String name); Il primo di questi metodi ritorna una stringa contenente la query string se inviata dal client (null in caso contrario), il secondo ritorna una Enumerazione dei nomi dei parametri contenuti nella query string, il terzo il valore di un parametro a partire dal suo nome ed infine il quarto ritorna un array di valori del parametro il cui nome viene passato in input. Questultimo metodo viene utilizzato quando il client utilizza oggetti di tipo checkboxche possono prendere pi valori contemporaneamente. Nel caso in cui venga utilizzato il metodo POST il metodo getQueryString risulter inutile dal momento che questo metodo non produce la query string. Query String e Form Html Il linguaggio HTML pu produrre URL contenenti query string definendo allinterno della pagina HTML dei form. La sintassi per costruire form HTML la seguente: <FORM method=[GET/POST] action=URL> <INPUT type=[text|textarea|select|hidden|option] name=nomedelvalore [value= valoreiniziale1]> <INPUT type=[text|textarea|select|hidden|option] name=nomedelvalore2 [value= valoreiniziale2]> . <INPUT type=[text|textarea|select|hidden|option] name=nomedelvaloreN [value= valoreinizialeN]> <INPUT type=SUBMIT value=labeldelpulsante> </FORM> Nellistante in cui lutente preme il pulsante SUBMIT, il browser crea una query string contenente le coppie nome=valore che identificano i dati nel form e la appende alla URL che punter alla risorsa puntata dal campo action del tag <FORM>. Vediamo un form di esempio: esempio.html <NAME> http://www.java-net.tv [email protected] 187 <html> <body> <FORM method=GET action=http://www.javanet.tv/Prova> <INPUT type=hidden name=param value="nascosto"><br> Nome:<br><INPUT type=text name=nome value=""><br> Cognome:<br><INPUT type=text name=cognome value=""><br> Et:<br><INPUT type=text name=eta value=""><br> <INPUT type=SUBMIT value="Invia I dati"> </FORM> </body> </html> Nella Figura 15-1 viene riportato il form cos come il browser lo presenta allutente: Figura 15-1 : form html Dopo aver inserito i valori nei tre campi di testo, la pressione del pulsante provocher linvio da parte del client di una richiesta http identificata dalla URL seguente: http://www.javanet.tv/Prova?param=nasconto&nome=nomeutente&cognome=cogno meutente&eta=etautente <NAME> http://www.java-net.tv <EMAIL> 188 I limiti del protocollo http : cookies Il limite maggiore del protocollo http legato alla sua natura di protocollo non transazionale ovvero non in grado di mantenere dati persistenti tra i vari pacchetti http. Fortunatamente esistono due tecniche per aggirare il problema: i cookies e la gestione di sessioni utente. I cookies sono piccoli file contenenti una informazione scritta allinterno secondo un certo formato che vengono depositati dal server sul client e contengono informazioni specifiche relative alla applicazione che li genera. Se utilizzati correttamente consentono di memorizzare dati utili alla gestione del flusso di informazioni creando delle entit persistenti in grado di fornire un punto di appoggio per garantire un minimo di transazionalit alla applicazione web Formalmente i cookie contengono al loro interno una singola informazione nella forma nome=valore pi una serie di informazioni aggiuntive che rappresentano: Il dominio applicativo del cookie; Il path della applicazione; La durata della validit del file; Un valore booleano che identifica se il cookie criptato o no. Il dominio applicativo del cookie consente al browser di determinare se, al momento di inviare una richiesta http dovr associarle il cookie da inviare al server. Un valore del tipo www.java-web.tv indicher al browser che il cookie sar valido solo per la macchina www allinterno del dominio java-web.tv . Il path della applicazione rappresenta il percorso virtuale della applicazione per la quale il cookie valido. Un valore del tipo / indica al browser che qualunque richiesta http da inviare al dominio definito nel campo precedente dovr essere associata al cookie. Un valore del tipo /servlet/ServletProvaindicher invece al browser che il cookie dovr essere inviato in allegato a richieste http del tipo http://www.java-net.tv/servlt/ServletProva. La terza propriet comunemente detta expirationindica il tempo di durata della validit del cookie in secondi prima che il browser lo cancelli definitivamente. Mediante questo campo possibile definire cookie persistenti ossia senza data di scadenza. Manipolare cookies con le Servlet Una servlet pu inviare uno o pi cookie ad un browser mediante il metodo addCookie(Cookie) definito nellinterfaccia HttpServletResponse che consente di appendere lentit ad un messaggio di risposta al browser. Viceversa, i cookie associati ad una richiesta http possono essere recuperati da una servlet utilizzando il metodo getCookie() definito nella interfaccia HttpServletRequest che ritona un array di oggetti. Il cookie in Java viene rappresentato dalla classe javax.servlet.http.Cookie il cui prototipo riportato nel codice seguente. Cookie.java package javax.servlet.http; public class Cookie implements Cloneable { public Cookie(String name, String value); public String getComment() ; public String getDomain() ; public int getMaxAge(); public String getName(); public String getPath(); <NAME> http://www.java-net.tv <EMAIL> 189 public boolean getSecure(); public String getValue(); public int getVersion(); public void setComment(String purpose); public void setDomain(String pattern); public void setMaxAge(int expiry); public void setPath(String uri); public void setSecure(boolean flag); public void setValue(String newValue); public void setVersion(int v); } Un esempio completo Nellesempio implementeremo una servlet che alla prima chiamata invia al server una serie di cookie mentre per ogni chiamata successiva ne stampa semplicemente il valore contenuto. import javax.servlet.* ; import javax.servlet.http.* ; import java.io.* ; public class TestCookie extends HttpServlet { private int numrichiesta=0; public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Cookie cookies = null; res.setContentType("text/html"); PrintWriter out = res. getWriter (); out.println("<html>"); out.println("<head><title>Cookie Test</title></head>"); out.println("<body>"); switch(numrichiesta) { case 0: //Appende 10 cookie alla risposta http for (int i=0; i<10; i++) { String nome="cookie"+i; String valore="valore"+i; cookies = new Cookie(nome,valore); cookies.setMaxAge(1000); res.addCookie(cookies); } out.println("<h1>I cookie sono stati appesi a questa risposta<h1>"); numrichiesta++; break; default : //ricavo l'array dei cookie e stampo le //coppie nome=valore Cookie cookies[] = req.getCookies(); for (int j=0; j<cookies.length; j++) { <NAME> http://www.java-net.tv <EMAIL> 190 Cookie appo = cookies[j]; out.println("<h1>"+appo.getName()+" = "+appo.getValue()+"<h1>"); } } out.println("</body></html>"); out.close(); } } Sessioni utente I cookie non sono uno strumento completo per memorizzare lo stato di una applicazione web. Di fatto i cookie sono spesso considerati dallutente poco sicuri e pertanto non accettati dal browser che li rifiuter al momento dellinvio con un messaggio di risposta. Come se non bastasse il cookie ha un tempo massimo di durata prima di essere cancellato dalla macchina dellutente. Servlet risolvono questo problema mettendo a disposizione del programmatore la possibilit di racchiudere lattivit di un client per tutta la sua durata allinterno di sessioni utente. Una servlet pu utilizzare una sessione per memorizzare dati persistenti, dati specifici relativi alla applicazione e recuperarli in qualsiasi istante sia necessario. Questi dati possono essere inviati al client allinterno dellentit prodotta. Ogni volta che un client effettua una richiesta http, se in precedenza stata definita una sessione utente legata al particolare client, il servlet container identifica il client e determina quale sessione stata associata ad esso. Nel cosa in cui la servlet la richieda, il container gli mette disposizione tutti gli strumenti per utilizzala. Ogni sessione creata dal container associata in modo univoco ad un identificativo o ID. Due sessioni non possono essere associate ad uno stesso ID. Sessioni dal punto di vista di una servlet Il servlet container contiene le istanze delle sessioni utente rendendole disponibili ad ogni servlet che ne faccia richiesta (Figura 15-2). <NAME> http://www.java-net.tv <EMAIL> 191 Figura 15-2 : le sessioni sono accessibili da tutte le servlet Ricevendo un identificativo dal client, una servlet pu accedere alla sessione associata allutente. Esistono molti modi per consentire al client di tracciare lidentificativo di una sessione, tipicamente viene utilizzato il meccanismo dei cookie persistenti. Ogni volta che un client esegue una richiesta http, il cookie contenente lidentificativo della richiesta viene trasmesso al server che ne ricava il valore contenuto e lo mette a disposizione delle servlet. Nel caso in cui il browser non consenta lutilizzo di cookies esistono tecniche alternative che risolvono il problema. Tipicamente una sessione utente deve essere avviata da una servlet dopo aver verificato se gi non ne esista una utilizzando il metodo getSession(boolean) di HttpServletRequest. Se il valore boolean passato al metodo vale true ed esiste gi una sessione associata allutente il metodo semplicemente ritorner un oggetto che la rappresenta, altrimenti ne creer una ritornandola come oggetto di ritorno del metodo. Al contrario se il parametro di input vale false, il metodo torner la sessione se gi esistente null altrimenti. Quando una servlet crea una nuova sessione, il container genera automaticamente lidentificativo ed appende un cookie contenente lID alla risposta http in modo del tutto trasparente alla servlet. La classe HttpSession Un oggetto di tipo httpSession viene restituito alla servlet come parametro di ritorno del metodo getSession(boolean) e viene definito dallinterfaccia javax.servlet.http.HttpSession . HttpSession.java package javax.servlet.http; public interface HttpSession { long getCreationTime(); <NAME> http://www.java-net.tv <EMAIL> 192 String getId(); long getLastAccessedTime(); int getMaxInactiveInterval(); HttpSessionContext getSessionContext(); Object getValue(String name); String[] getValueNames(); void invalidate(); boolean isNew(); void putValue(String name, Object value); void removeValue(String name); int setMaxInactiveInterval(int interval); } Utilizzando i metodi getId() long getCreationTime() long getLastAccessedTime() int getMaxInactiveInterval() boolean isNew() possiamo ottenere le meta informazioni relative alla sessione che stiamo manipolando. E importante notare che i metodi che ritornano un valore che rappresenta un tempo rappresentano il dato in secondi. Sar quindi necessario operare le necessarie conversioni per determinare informazioni tipo date ed ore. Il significato dei metodi descritti risulta chiaro leggendo il nome del metodo. Il primo ritorna lidentificativo della sessione, il secondo il tempo in secondi trascorso dalla creazione della sessione, il terzo il tempo in secondi trascorso dallultimo accesso alla sezione, infine il quarto lintervallo massimo di tempo di inattivit della sessione. Quando creiamo una sessione utente, loggetto generato verr messo in uno stato di NEW che sta ad indicare che la sessione stata creata ma non attiva. Dal un punto di vista puramente formale ovvio che per essere attiva la sessione deve essere accettata dal client ovvero una sessione viene accettata dal client solo nel momento in cui invia al server per la prima volta lidentificativo della sessione. Il metodo isNew() restituisce un valore booleano che indica lo stato della sessione. I metodi void putValue(String name, Object value) void removeValue(String name) String[] getValueNames(String name) Object getValue(String name) Consentono di memorizzare o rimuovere oggetti nella forma di coppie nome=oggetto allinterno della sessione consentendo ad una servlet di memorizzare dati (in forma di oggetti) allinterno della sessione per poi utilizzarli ad ogni richiesta http da parte dellutente associato alla sessione. Questi oggetti saranno inoltre accessibili ad ogni servlet che utilizzi la stessa sessione utente potendoli recuperare conoscendo il nome associato. Un esempio di gestione di una sessione utente Nel nostro esempio creeremo una servlet che conta il numero di accessi che un determinato utente ha effettuato sul sistema utilizzando il meccanismo delle sessioni. import javax.servlet.* ; import javax.servlet.http.* ; <NAME> http://www.java-net.tv <EMAIL> 193 import java.io.* ; public class TestSession extends HttpServlet { public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res. getWriter (); out.println("<html>"); out.println("<head><title>Test di una sessione servlet</title></head>"); out.println("<body>"); HttpSession sessione = req.getSession(true); if(session.isNew()) { out.println("<strong>Id della sessione: </strong>" +session.getId()+"<br>"); out.println("<strong>Creata al tempo: </strong>" +session.creationTime()+"<br>"); out.println("<strong>Questa la tua prima +connessione al server </strong>"); session.putValue("ACCESSI", new Integer(1)); }else { int accessi = ((Integer)session.getValue("ACCESSI")).intValue(); accessi++; session.putValue("ACCESSI", new Integer(accessi)); out.println("<strong>Questa la tua connessione numero: </strong>" +accessi); } out.println("</body></html>"); out.close(); } } Durata di una sessione utente Una sessione utente rappresenta un oggetto transiente la cui durata deve essere limitata al periodi di attivit dellutente sul server. Utilizzando i metodi void invalidate(); int setMaxInactiveInterval(int interval) possibile invalidare una sessione o disporre che una volta superato lintervallo massimo di inattivit la servlet venga automaticamente resa inattiva dal container. URL rewriting Il browser ha la facolt di accettare o no cookies da parte di un server web. Quando ci accade impossibile per il server tracciare lidentificativo della sessione e di conseguenza mettere in grado una servlet di accederle. Un metodo alternativo quello di codificare lidentificativo della sessione allinterno della URL che il browser invia al server allinterno di una richiesta http. <NAME> http://www.java-net.tv [email protected] 194 Questa metodologia deve necessariamente essere supportata dal server che dovr prevedere lutilizzo di caratteri speciali allinterno della URL. Server differenti potrebbero utilizzare metodi differenti. Linterfaccia HttpServletResponse ci mette a disposizione il metodo encodeURL(String) che prende come parametro di input una URL, determina se necessario riscriverla ed eventualmente codifica allinterno della URL lidentificativo della sessione. <NAME> http://www.java-net.tv <EMAIL> 195 Capitolo 16 JavaServer Pages Introduzione La tecnologia JavaServer Pages rappresenta un ottimo strumento per scrivere pagine web dinamiche ed insieme a servlet consente di separare le logiche di business della applicazione web (servlet) dalle logiche di presentazione. Basato su Java, JavaServer Pages sposano il modello write once run anywhere, consentono facilmente luso di classi Java, di JavaBeans o laccesso ad Enterprise JavaBeans. JavaServer Pages Una pagina JSP un semplice file di testo che fonde codice html a codice Java a formare una pagina dai contenuti dinamici. La possibilit di fondere codice html con codice Java senza che nessuno interferisca con laltro consente di isolare la rappresentazione dei contenuti dinamici dalle logiche di presentazione. Il disegnatore potr concentrarsi solo sulla impaginazione dei contenuti che saranno inseriti dal programmatore che non dovr preoccuparsi dellaspetto puramente grafico. Da sole, JavaServer Pages consentono di realizzare applicazioni web dinamiche (Figura 16-1) accedendo a componenti Java contenenti logiche di business o alla base dati del sistema. In questo modello il browser accede direttamente ad una pagina JSP che riceve i dati di input, li processa utilizzando eventualmente oggetti Java, si connette alla base dati effettuando le operazioni necessarie e ritorna al client la pagina html prodotta come risultato della processazione dei dati. <NAME> http://www.java-net.tv <EMAIL> 196 Figura 16-1 : primo modello di accesso Il secondo modello, e forse il pi comune, utilizza JavaServer Pages come strumento per sviluppare template demandando completamente a servlet la processazione dei dati di input (Figura 16-2). Figura 16-2 : secondo modello di accesso In questo nuovo modello, il browser invia la sua richiesta ad una servlet che si preoccuper di processare i dati di input utilizzando eventualmente via JDBC la base dati del sistema. La servlet ora generer alcuni oggetti (non pi pagine html) come prodotto della esecuzione del metodo service( ). Utilizzando gli strumenti messi a disposizione dal container, la servlet potr inviare gli oggetti prodotti ad una pagina JavaServer Pages che si preoccuper solamente di ricavare il contenuto di questi Massimiliano Tarquini http://www.java-net.tv <EMAIL> 197 oggetti inserendoli allinterno del codice html. Sara infine la pagina JSP ad inviare al client la pagina prodotta. Compilazione di una pagina JSP Se dal punto di vista del programmatore una pagina JSP un documento di testo contenente tag html e codice Java, dal punto di vista del server una pagina JSP utilizzata allo stesso modo di una servlet. Di fatto, nel momento del primo accesso da parte dellutente, la pagina JSP richiesta viene trasformata in un file Java e compilata dal compilatore interno della virtual machine. Come prodotto della compilazione otterremo una classe Java che rappresenta una servlet di tipo HttpServlet che crea una pagina html e la invia al client. Tipicamente il web server memorizza su disco tutte le definizioni di classe ottenute dal processo di compilazione appena descritto per poter riutilizzare il codice gi compilato. Lunica volta che una pagina JSP viene compilata al momento del suo primo accesso da parte di un client o dopo modifiche apportate dal programmatore affinch il client acceda sempre alla ultima versione prodotta. Scrivere pagine JSP Una pagina JSP deve essere memorizzata allinterno di un file di testo con estensione .jsp . Equesta lestensione che il web server riconosce per decidere se compilare o no il documento. Tutte le altre estensioni verranno ignorate. Ecco quindi un primo esempio di pagina JSP: esempio1.jsp <html> <body> <h1> Informazioni sulla richiesta http </h1> <br> Metodo richiesto : <%= request.getMethod() %> <br> URI : <%= request.getRequestURI() %> <br> Protocollo : <%= request.getProtocol() %> <br> <body> </html> Una pagina JSP come si vede chiaramente dallesempio per la maggior parte formata da codice html con in pi un piccolo insieme di tag addizionali. Nel momento in cui avviene la compilazione della pagina il codice html viene racchiuso in istruzioni di tipo out.println(codicehtml) mentre il codice contenuto allinterno dei tag aggiuntivi viene utilizzato come codice eseguibile. Leffetto prodotto sar comunque quello di inserire allinterno del codice html valori prodotti dalla esecuzione di codice Java. I tag aggiuntivi rispetto a quelli definiti da html per scrivere pagine jsp sono tre: espressioni, scriptlet, dichiarazioni. Le espressioni iniziano con la sequenza di caratteri <%= e terminano con la sequenza %>, le istruzioni contenute non devono terminare con il carattere ; e devono ritornare un valore che pu essere promosso a stringa. Ad esempio una espressione JSP la riga di codice: <%= new Integer(5).toString() %> <NAME> http://www.java-net.tv <EMAIL> 198 Le scriptlet iniziano con la sequenza <%, terminano con la sequenza %> e devono contenere codice Java valido. Allinterno di questi tag non si possono scrivere definizioni di classi o di metodi, ma consentono di dichiarare variabili visibili allinterno di tutta la pagina JSP. Una caratteristica importante di questi tag che il codice Java scritto allinterno non deve essere completo ovvero possibile fondere blocchi di codice Java allinterno di questi tag con blocchi di codice html. Ad esempio: <% for(int i=0; i<10; i++) { %> <strong> Il valore di I : <%= new Integer(i).toString() %> </strong> <% } %> Infine le dichiarazioni iniziano con la sequenza <%! e terminano con la sequenza %> e possono contenere dichiarazioni di classi o di metodi utilizzabili solo allinterno della pagina, e a differenza del caso precedente, devono essere completi. Nellesempio utilizziamo questi tag per definire un metodo StampaData() che ritorna la data attuale in formato di stringa: <%! String StampaData() { return new Date().toString(); } %> Nel prossimo esempio di pagina jsp, allinterno di un loop di dieci cicli effettuiamo un controllo sulla variabile intera che definisce il contatore del ciclo. Se la variabile pari stampiamo il messaggio Pari, altrimenti il messaggio Dispari. Esempio2.jsp <html> <body> <% for(int i=0; i<10; i++) { if(i%2==0) { %> <h1>Pari</h1> <% } else { %> <h2>Dispari</h2> <% } } %> <body> </html> Laspetto pi interessante del codice nellesempio proprio quello relativo alla possibilit si spezzare il codice Java contenuto allinterno delle scriptlets per dar modo al programmatore di non dover fondere tag html allinterno sorgente Java. Invocare una pagina JSP da una servlet Nel secondo modello di accesso ad una applicazione web trattato nel paragrafo 2 di questo capitolo abbiamo definito una pagina jsp come template ossia meccanismo di presentazione dei contenuti generati mediante una servlet. Affinch sia possibile implementare quanto detto, necessario che esista un meccanismo che consenta ad una servlet di trasmettere dati prodotti alla pagina JSP. Sono necessarie alcune considerazioni: primo, una pagina JSP viene tradotta <NAME> http://www.java-net.tv <EMAIL> 199 una in classe Java di tipo HttpServlet e di conseguenza compilata ed eseguita allinterno dello stesso container che fornisce lambiente alle servlet. Secondo, JSP ereditano quindi tutti i meccanismi che il container mette a disposizione delle servlet compresso quello delle sessioni utente. Lo strumento messo a disposizione dal container per rigirare una chiamata da una servlet ad una JavaServer Pages passando eventualmente parametri loggetto RequestDispatcher restituito dal metodo public ServletContext getRequestDispatcher(String Servlet_or_JSP_RelativeUrl) definito nella interfaccia javax.servlet.ServletContext. RequestDispatcher.java package javax.servlet; public interface RequestDispatcher { public void forward(ServletRequest req, ServletResponse res); public void include(ServletRequest req, ServletResponse res); } tramite il metodo forward(ServletRequest req, ServletResponse res) possibile reindirizzare la chiamata alla Servlet o JavaServer Page come indicato dalla URL definita dal parametro di input di getRequestDispatcher. Il metodo public void include(ServletRequest req, ServletResponse res), pur producendo a sua volta un reindirizzamento, inserisce il risultato prodotto dalla entit richiamata allinterno del risultato prodotto dalla servlet che ha richiamato il metodo. Nellesempio viene definita una servlet che trasferisce tramite requestDispatcher la richiesta http alla pagina jsp /appo.jspmemorizzata nella root del web server. public class Redirect extends HttpServlet { public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletContext contesto = getServletContext(); RequestDispatcher rd = contesto.getRequestDispatcher(/appo.jsp); try { rd.forward(req, res); } catch(ServletException e) { System.out.println(e.toString()); } } } <NAME> http://www.java-net.tv <EMAIL> 200 Capitolo 17 JavaServer Pages Nozioni Avanzate Introduzione I tag JSP possono essere rappresentati in due modi differenti: Short-Hand ed XML equivalent. Ogni forma delle due prevede i seguenti tag aggiuntivi rispetto ad html: Tipo Scriptlet Short Hand <% codice java %> Direttive <%@ tipo attributo %> Dichiarazione <%! Dichiarazione %> Espressione <%= espressione %> Azione NA XML <jsp :scriptlet> codice java </jsp :scriptlet> <jsp:directive.tipo attributo /> <jsp:decl> dichiarazione; </jsp:decl> <jsp:expr> espressione; </jsp:expr > <jsp:useBean .> <jsp:include .> <jsp:getProperty .> ecc. Direttive Le direttive forniscono informazioni aggiuntive sulla allambiente allinterno della quale la JavaServer Page in esecuzione. Le possibili direttive sono due: Page : informazioni sulla pagina Include File da includere nel documento e possono contenere gli attributi seguenti: Attributo e possibili valori language=Java extends=package.class import=package.*, package.class session=true|false buffer=none|8kb|dimensione Massimiliano Tarquini Descrizione Dichiara al server il linguaggio utilizzato allinterno della pagina JSP Definisce la classe base a partire dalla quale viene definita la servlet al momento della compilazione. Generalmente non viene utilizzato. Simile alla direttiva import di una definizione di classe Java. Deve essere una delle prime direttive e comunque comparire prima di altri tag JSP. Di default session vale true e significa che i dati appartenenti alla sessione utente sono disponibili dalla pagina JSP Determina se loutput strema della JavaServer Pages utilizza o no un buffer http://www.java-net.tv [email protected] 201 autoFlush=true|false isThreadSafe=true|false info=info_text errorPage=error_url isErrorPage=true|false contentType=ctinfo di scrittura dei dati. Di default la dimensione di 8k. Questa direttiva va utilizzata affiancata dalla direttiva autoflush Se impostato a true svuota il buffer di output quando risulta pieno invece di generare una eccezione Di default lattributo impostato a true e indica allambiente che il programmatore si preoccuper di gestire gli accessi concorrenti mediante blocchi sincronizzati. Se impostato a false viene utilizzata di default linterfaccia SinglkeThreadModel in fase di compilazione. Fornisce informazioni sulla pagina che si sta accedendo attraverso il metodo Servlet.getServletInfo(). Fornisce il path alla pagina jsp che verr richiamata in automatico per gestire eccezioni che non vengono controllate allinterno della pagina attuale. Definisce la pagina come una una pagina di errore. Definisce il mime tipe della pagina prodotta dalla esecuzione. Un esempio di blocco di direttive allinterno di una pagina JSP il seguente: <%@ page language=Java session=true errorPage=/err.jsp %> <%@ page import= java.lang.*, java.io.*%> <%@ include file=headers/intestazione.html %> Dichiarazioni Una dichiarazione rappresenta dal punto di vista del web server che compila la JavaServer Page il blocco di dichiarazione dei dati membro o dei metodi della classe Servlet generata. Per definire un blocco di dichiarazioni si utilizza il tag <%! Dichiarazione %>. Un esempio: <%! String nome =mionome; int tipointero=1; private String stampaNome() { return nome; } %> Scriptlets Come gi definito nel capitolo precedente, le scriptlets rappresentano blocchi di codice java incompleti e consentono di fondere codice Java con codice html. Oltre a poter accedere a dati e metodi dichiarati allinterno di tag di dichiarazione consente di accedere ad alcuni oggetti impliciti ereditati dallambiente servlet. <NAME> http://www.java-net.tv <EMAIL> 202 Gli oggetti in questione sono otto e sono i seguenti: request : rappresenta la richiesta del client response : rappresenta la risposta del client out : rappresenta lo strema di output html inviato come risposta al client session : rappresenta la sessione utente page : rappresenta la pagina JSP attuale config : rappresenta i dettagli della configurazione del server pageContext : rappresenta un container per i metodi relativi alle servlet Oggetti impliciti : request Questo oggetto messo a disposizione della pagina JSP in maniera implicita e rappresenta la richiesta http inviata dallutente ovvero implementa linterfaccia javax.servlet.http.HttpServletRequest. Come tale questo oggetto mette e disposizione di una pagina JSP gli stessi metodi utilizzati allinterno di una servlet. Nellesempio seguente i metodi messi a disposizione vengono utilizzati implicitamente per generare una pagina http che ritorna le informazioni relative alla richiesta: TestAmbiente.jsp <%@ page language=Java session=true %> <%@ page import= java.lang.*, java.io.*, javax.servlet.* , javax.servlet.http.*%> <html> <head><title>Test</title></head> <body> <b>Carachter encoding</b> <%=request.getCharacterEncoding() %> <BR> <b>Mime tipe dei contenuti</b> <%=request.getContentType()%> <BR> <b>Protocollo</b> <%=request.getProtocol()%> <BR> <b>Posizione fisica:</b> <%=request.getRealPath()%> <BR> <b>Schema:</b> <%=request.getScheme()%> <BR> <b>Nome del server:</b> <%=request.getServerName()%> <BR> <b>Porta del server:</b> <%=request.getServerPort()%> <BR> </body></html> Oggetti impliciti : response Rappresenta la risposta http che la pagina JSP invia al client ed implementa javax.servlet.http.HttpServletResponse. Compito dei metodi messi a disposizione da <NAME> http://www.java-net.tv <EMAIL> 203 questo oggetto quello di inviare dati di risposta, aggiungere cookies, impostare headers http e ridirezionare chiamate. Oggetti impliciti : session Rappresenta la sessione utente come definito per servlet. Anche questo metodo mette a disposizione gli stessi metodi di servlet e consente di accedere ai dati della sessione utente allinterno della pagina JSP. <NAME> http://www.java-net.tv <EMAIL> 204 Capitolo 18 JDBC Introduzione JDBC rappresentano le API di J2EE per poter lavorare con database relazionali. Esse consentono al programmatore di inviare query ad un database relazionale, di effettuare delete o update dei dati allinterno di tabelle, di lanciare stored-procedure o di ottenere meta-informazioni relativamente al database o le entit che lo compongono. JDBC sono modellati a partire dallo standard ODBC di Microsoft basato a sua volta sulle specifiche X/Open CLI. La differenza tra le due tecnologie sta nel fatto che mentre ODBC rappresenta una serie di C-Level API, JDBC fornisce uno strato di accesso verso database completo e soprattutto completamente ad oggetti. Architettura di JDBC Figura 18-1: Architettura JDBC Architetturalmente JDBC sono suddivisi in due strati principali : il primo che fornisce una interfaccia verso il programmatore, il secondo di livello pi basso che fornisce invece una serie di API per i produttori di drivers verso database relazionali e nasconde allutente i dettagli del driver in uso. Questa caratteristica rende la tecnologia indipendente rispetto al motore relazionale con cui il programmatore deve comunicare. I driver utilizzabili con JDBC sono di quattro tipi: il primo rappresentato dal bridge jdbc/odbc che utilizzano linterfaccia ODBC del client per connettersi alla base Mass<NAME> http://www.java-net.tv tarquini<EMAIL>-<EMAIL> 205 dati. Il secondo tipo ha sempre funzioni di bridge (ponte), ma traduce le chiamate JDBC in chiamate di driver nativi gi esistenti sulla macchina. Il terzo tipo ha una architettura multi-tier ossia si connette ad un RDBMS tramite un middleware connesso fisicamente al database e con funzioni di proxy. Infine il quarto tipo rappresenta un driver nativo verso il database scritto in Java e compatibile con il modello definito da JDBC. I driver JDBC di qualsiasi tipo siano vengono caricati dalla applicazione in modo dinamico mediante una istruzione del tipo Class.forName(package.class). Una volta che il driver (classe java) viene caricato possibile connettersi al database tramite il driver manager utilizzando il metodo getConnection() che richiede in input la URL della base dati ed una serie di informazioni necessarie ad effettuare la connessione. Il formato con cui devono essere passate queste informazioni dipende dal produttore dei driver. Driver di tipo 1 Rappresentati dal bridge jdbc/odbc di SUN, utilizzano linterfaccia ODBC del client per connettersi alla base dati (Figura 18-2). Figura 18-2 : driver JDBC tipo 1 Questo tipo di driver sono difficili da amministrare e dipendono dalle piattaforme Microsoft. Il fatto di utilizzare meccanismi intermedi per connettersi alla base dati (lo strato ODBC) fa si che non rappresentano la soluzione ottima per tutte le piattaforme in cui le prestazioni del sistema rappresentano laspetto critico. <NAME> http://www.java-net.tv <EMAIL> 206 Driver di tipo 2 I driver di tipo 2 richiedono che sulla macchina client siano installati i driver nativi del database con cui lutente intende dialogare (Figura 18-3). Il driver JDBC convertir quindi le chiamate JDBC in chiamate compatibili con le API native del server. Luso di API scritte in codice nativo rende poco portabili le soluzioni basate su questo tipo di driver. I driver JDBC/ODBC possono essere visti come un caso specifico dei driver di tipo 2. Figura 18-3 : driver JDBC di tipo 2 Driver di tipo 3 I driver di tipo 3 consentono di non utilizzare codice nativo sulla macchina client e quindi consentono di costruire applicazioni Java portabili. Formalmente i driver di tipo 3 sono rappresentati da oggetti che convertono le chiamate JDBC in un protocollo di rete e comunicano con una applicazione middleware chiamata server di rete. Compito del server di rete quello di rigirare le chiamate da JDBC instradandole verso il server database (Immagine 4). Utilizzare architetture di questo tipo dette multi-tier comporta molti vantaggi soprattutto in quelle situazioni in cui un numero imprecisato di client deve connettersi ad una moltitudine di server database. In questi casi infatti tutti i client potranno parlare un unico protocollo di rete, quello conosciuto dal middleware, sar compito del server di rete tradurre i pacchetti nel protocollo nativo del database con cui il client sta cercando di comunicare. Lutilizzo di server di rete consente inoltre di utilizzare politiche di tipo caching e pooling oppure di load balancing del carico. <NAME> http://www.java-net.tv [email protected] 207 Figura 18-4 : driver JDBC di tipo 3 <NAME> http://www.java-net.tv [email protected] 208 Figura 18-5 : driver JDBC di tipo 4 Driver di tipo 4 Un driver di tipo quattro fornisce accesso diretto ad un database ed un oggetto Java completamente serializzabile (Immagine 4).Questo tipo di driver possono funzionare su tutte le piattaforme e, dal momento che sono serializzabili possono essere scaricati dal server. Una prima applicazione di esempio Prima di scendere nei dettagli della tecnologia JDBC soffermiamoci su una prima applicazione di esempio. La applicazione usa driver JDBC di tipo 1 per connettersi ad un database access contenente una sola tabella chiamata impiegati come mostrata nella Figura 18-6. <NAME> http://www.java-net.tv [email protected] 209 Figura 18-6 : tabella access EsempioJDBC.java import java.sql.* ; public class EsempioJDBC { public static void main(String args[]) { try { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver); } catch(ClassNotFoundException e) { System.out.println(e.toString()); System.out.println(Il driver non pu essere caricato); System.exit(1); } try { Connection conn = DriverManager.getConnection(jdbc:odbc:impiegati,,); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SELECT NOME FROM IMPIEGATI); while(rs.next()) { System.out.println(rs.getString(NOME)); } rs.close(); stmt.close(); conn.close(); } catch(SQLException _sql) { System.out.println(se.getMessage()); Se.printStackTrace(System.out); System.exit(1); } } <NAME> http://www.java-net.tv <EMAIL> 210 } Dopo aver caricato il driver JDBC utilizzando il metodo statico forname(String) della classe java.lang.Class Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); lapplicazione tenta la connessione al database utilizzando il metodo statico getConnection(String,String,String) delloggetto DriverManager definito nel package passando come parametro una di tipo Stringa che rappresenta la URL della base dati con una serie di informazioni aggiuntive. Connection conn = DriverManager.getConnection(jdbc:odbc:impiegati,,) Nel caso in cui la connessione vada a buon fine la chiamata al metodo di DriverManager ci ritorna un oggetto di tipo Connection definito nellinterfaccia java.sql.Connection. Mediante loggetto Connection creiamo quindi un oggetto di tipo java.sql.Statement che rappresenta la definizione uno statement SQL tramite il quale effettueremo la nostra query sul database. Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SELECT NOME FROM IMPIEGATI); La nostra applicazione visualizzer infine il risultato della query mediante un ciclo while che scorre gli elementi di un oggetto ResultSet definito in java.sql.ResultSet e ritornato come parametro dalla esecuzione del metodo executeQuery(String) di java.sql.Statement. Richiedere una connessione ad un database Il primo passo da compiere quando utilizziamo un driver JDBC quello di tentare la connessione al database, sar quindi necessario che il driver sia caricato allinterno della virtual machine utilizzando il metodo statico forName(String) delloggetto Class definito nel package java.lang. Una volta caricato il driver si registrer sul sistema come driver JDBC disponibile chiamando implicitamente il metodo statico registerDriver(Driver driver) della classe DriverManager. Questo meccanismo consente di caricare allinterno del gestore dei driver JDBC pi di un driver per poi utilizzare quello necessario al momento della connessione che rappresenta il passo successivo da compiere. Per connetterci al database la classe DriverManager ci mette a disposizione il metodo statico getConnection() che prende in input tre stringhe e ritorna un oggetto di tipo java.sql.Connection che da questo momento in poi rappresenter la connessione ad uno specifico database a seconda del driver JDBC richiamato: Connection conn = DriverManager.getConnection(String URL, String user, String password); Una URL JDBC identifica un database dal punto di vista del driver JDBC. Di fatto URL per driver differenti possono contenere informazioni differenti, tipicamente iniziano con la string jdbc, contengono indicazioni sul protocollo e informazioni aggiuntive per connettersi al database. JDBC URL = jdbc:protocollo:other_info <NAME> http://www.java-net.tv <EMAIL> 211 Per driver JDBC di tipo 1 (bridge JDBC/ODBC) la JDBC URL diventa JDBC/ODBC URL = jdbc:odbc:id_odbc Dove id_odbc il nome ODBC definito dallutente ed associato ad una particolare connessione ODBC. Eseguire query sul database Dopo aver ottenuto la nostra sezione vorremmo poter eseguire delle query sulla base dati. Equindi necessario avere un meccanismo che ci consenta di effettuare operazioni di select, delete, update sulle tabelle della base dati. La via pi breve quella che utilizza loggetto java.sql.Statement che rappresenta una istruzione SQL da eseguire ed ritornato dal metodo createStatement() delloggetto java.sql.Connection. Statement stmt = conn.createStatement(); I due metodi principali delloggetto statement sono I metodi: javax.sql.ResultSet executeQuery(String sql); int executeUpdate(String sql); Il primo viene utilizzato per tutte quelle query che ritornano valori multipli (select) il secondo per tutte quelle query che non ritornano valori (update o delete). In particolar modo lesecuzione del primo metodo produce come parametro di ritorno un oggetto di tipo java.sql.ResultSet che rappresenta il risultato della query riga dopo riga. Questo oggetto legato allo statement che lo ha generato; se loggetto statement viene rilasciato mediante il metodo close() anche il ResultSet generato non sar pi utilizzabile e viceversa fino a che un oggetto ResultSet non viene rilasciato mediante il suo metodo close() non sar possibile utilizzare Statement per inviare al database nuove query. Loggetto ResultSet Loggetto ResultSet rappresenta il risultato di una query come sequenza di record aventi colonne rappresentati dai nomi definiti allinterno della query. Ad esempio la query SELECT NOME, COGNOME FROM DIPENDENTI produrr un ResultSet contenente due colonne identificate rispettivamente dalla stringa NOME e dalla stringa COGNOME (Figura 18-6). Questi identificativi possono essere utilizzati con i metodi delloggetto per recuperare i valori trasportati come risultato della select. Nel caso in cui la query compaia nella forma SELECT * FROM DIPENDENTIle colonne del ResultSet saranno identificato de un numero intero a partire da 1 da sinistra verso destra (Figura 18-7). <NAME> http://www.java-net.tv <EMAIL> 212 Figura 18-6 : SELECT NOME, COGNOME . Esempio2JDBC.java import java.sql.* ; public class Esempio2JDBC { public static void main(String args[]) { try { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver); } catch(ClassNotFoundException e) { System.out.println(e.toString()); System.out.println(Il driver non pu essere caricato); System.exit(1); } try { Connection conn = DriverManager.getConnection(jdbc:odbc:impiegati,,); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SELECT NOME, COGNOME FROM IMPIEGATI); while(rs.next()) { System.out.println(rs.getString(NOME)); System.out.println(rs.getString(COGNOME)); <NAME> http://www.java-net.tv <EMAIL> 213 } rs.close(); stmt.close(); conn.close(); } catch(SQLException _sql) { System.out.println(se.getMessage()); Se.printStackTrace(System.out); System.exit(1); } } } Figura 18-76 : SELECT * FROM . Esempio3JDBC.java import java.sql.* ; public class Esempio3JDBC { public static void main(String args[]) { try { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver); } catch(ClassNotFoundException e) { System.out.println(e.toString()); <NAME> http://www.java-net.tv <EMAIL> 214 System.out.println(Il driver non pu essere caricato); System.exit(1); } try { Connection conn = DriverManager.getConnection(jdbc:odbc:impiegati,,); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SELECT * FROM IMPIEGATI); while(rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); System.out.println(rs.getInt(3)); } rs.close(); stmt.close(); conn.close(); } catch(SQLException _sql) { System.out.println(se.getMessage()); Se.printStackTrace(System.out); System.exit(1); } } } <NAME> http://www.java-net.tv <EMAIL> 215 Appendice A Java Time-line 1995-1996 23 Maggio 1995 Lancio della tecnologia Java 23 Gennaio 1996 Giorno del rilascio del Java Development Kit 1.0 30 Aprile 1996 I 10 maggiori vendors di software annunciano la loro intenzione di includere la tecnologia Java allinterno dei loro prodotti 29 Maggio 1996 Prima versione di JavaOne, convegno dedicato ai programmatori Java. Annunciata la tecnologia JavaBeans basata su componenti, le librerie multimediali, Java Servlet ed altre tecnologie. 10 Giugno 1996 50.000 programmatori in attesa del Sun Java Day in Tokio. 16 Agosto 1996 Sun Microsystem e Addison-Wesley pubblicano i Java Tutorial e la prima versione del Java Language Specification Settembre 1996 83.000 pagine web utilizzano tecnologia Java. Settembre 1996 Lancio del sito Java Developer Connection. 16 Ottobre 1996 Completate le specifiche JavaBeans. 25 Ottobre 1996 La Sun Microsystem annuncia il primo compilatore JIT (Just In Time) per la piattaforma Java. 29 Ottobre 1996 Annuncio delle API JavaCard. 9 Dicembre 1996 Rilasciata la versione beta del JDK 1.1 11 Dicembre 1996 Lancio della prima iniziativa 100% Java a cui aderiscono 100 compagnie. 11 Dicembre 1996 SUN IBM e Netscape iniziano il Java Education World Tour in oltre 40 citt. 1997 11 Gennaio 1997 SUN rilascia il JavaBeans development kit 18 Febbraio 1997 SUN rilascia il JDK 1.1 28 Febbraio 1997 Netscape annuncia che Communicator supporter tutte le Api e le applicazioni Java. <NAME> http://www.java-net.tv <EMAIL> 216 4 Marzo 1997 Rilasciata la versione beta di Java Web Server e il Java Servlet Development Kit. 10 Marzo 1997 Introduzione della API Java JNDI : Java Naming and Directory Interface. 11 Marzo 1997 Raggiunti pi di 220.000 download del JDK 1.1 in tre settimane. 2 Aprile 1997 JavaOne diventa la pi grande conferenza per sviluppatori del mondo con pi di 10.000 persone in attesa dellevento. 2 Aprile 1997 SUN annuncia JavaBeans. la tecnologia Enterprise 2 Aprile 1997 SUN annuncia che la tecnologia Java Foundation Classes sar inclusa nelle revisioni successive della piattaforma Java. 6 Maggio 1997 Glasgow, software per JavaBeans viene rilasciato in visione al pubblico. 5 Giugno 1997 Java Web Server 1.0 viene rilasciato nella sua versione definitiva. 23 Luglio 1997 Annunciate le Java Accessibility API. 23 Luglio 1997 Rilasciata la piattaforma Java Card 2.0 5 Agosto 1997 Rilasciate le Communication. 5 Agosto 1997 Raggiunti oltre 100.000 download JavaBeans Development Kit. API Java Media e del 12 Agosto 1997 Pi di 600 applicazioni commerciali basate sulla tecnologia Java. 23 Settembre 1997 Java Developers Connection 100.000 utenti. supera i 1998 20 Gennaio 1998 2 milioni di download del JDK 1.1 Marzo 1998 Rilascio del progetto Swing. 24 Marzo 1998 JavaOne attesa da oltre programmatori in tutto il mondo. 15.000 24 Marzo 1998 Annunciato il prodotto Java Junpstart 31 Marzo 1998 Ericcson, Sony, Siemens, BEA, Open TV ed altri vendors licenziano la tecnologia Java. 31 Marzo 1998 <NAME> http://www.java-net.tv <EMAIL> 217 SUN annuncia il porting della tecnologia Java su piattaforma WinCE. 20 Aprile 1998 Rilascio dei prodotti Java Plug-In. 3 Giugno 1998 Visa rilascia la prima smart card basata su Visa Open Platform e Java Card Technology. 16 Settembre 1998 Motorola annuncia tecnologia Java. lintroduzione della 21 Ottobre 1998 Oltre 500.000 download JFC/Swing. del software 5 Novembre 1998 Sun inizia a lavorare con Linux Community al porting della tecnologia Java sotto piattaforma Linux. 5 Novembre 1998 Completate le specifiche di EmbeddedJava. 8 Dicembre 1998 Rilascio della piattaforma Java 2. 8 Dicembre 1998 Formalizzazione del programma JCP : Java Community Process. 1999 13 Gennaio 1999 La tecnologia Java viene supportata perla produzione di televisioni digitali. 25 Gennaio 1999 Annunciata la tecnologia Jini. 1 Febbraio 1999 Rilascio della piattaforma PersonalJava 3.0. 24 Febbraio 1999 Rilascio dei codici sorgenti della piattaforma Java 2. Febbraio 1999 Rilascio delle specifiche Java Card 2.1 4 Marzo 1999 Annunciato il supporto XML per Java. 27 Marzo 1999 Rilascio del motore Java HotSpot. 2 Giugno 1999 Rilascio della tecnologia JavaServer Pages. 15 Giugno 1999 SUN annuncia tre edizioni della piattaforma Java: J2SE, J2EE, J2ME. 29 Giugno 1999 Rilascio della Reference Implementation di J2EE in versione Alfa. 30 Settembre 1999 Rilascio del software J2EE in beta version. 22 Novembre 1999 Rilascio della piattaforma J2EE. 22 Novembre 1999 Rilascio della piattaforma J2SE per Linux. <NAME> http://www.java-net.tv tar<EMAIL>-one-mail.net 218 2000 8 Febbraio 2000 Proposta alla comunit la futura versione di J2EE e J2SE. 29 Febbraio 2000 Rilascio delle API per XML. Maggio 2000 Superato il 1.500.000 di utenti su Java Developer Connection. 8 Maggio 2000 Rilascio della piattaforma J2SE 1.3 26 Maggio 2000 Oltre 400 Java User Group in tutto il mondo. <NAME> http://www.java-net.tv <EMAIL> 219 Appendice B Glossario dei termini AGE - "Et" parlando di protocollo HTTP 1.1 indica la data di invio di una Richiesta da parte del client verso il server. ANSI - "American National Standard Institute" stabilisce e diffonde le specifiche su sistemi e standard di vario tipo. L'istituto ANSI attualmente formato da pi di 1000 aziende pubbliche e private. Applet - Componenti Java caricate da un browser come parte di una pagina HTML. ARPANET - le prime quattro lettere significano: "Advanced Research Projet Agency", agenzia del Ministero della difesa U.S.A. nata nel 1969 e progenitrice dell'attuale Internet. ADSL - Asimmetrical Digital Subscriber Line, nuova tecnologia di trasmissione dati per il collegamento ad internet. E' possibile raggiungere velocit di circa 6Mb al secondo per ricevere e 640Kb al secondo per inviare dati. B2B - Con la sigla B2B si identificano tutte quelle iniziative tese ad integrare le attivit commerciali di un'azienda con quella dei propri clienti o dei propri fornitori, dove per il cliente non sia anche il consumatore finale del bene o del servizio venduti ma sia un partner attraverso il quale si raggiungono, appunto, i consumatori finali. B2C - B2C l'acronimo di Business to Consumer e, contrariamente a quanto detto per il B2B, questo identifica tutte quelle iniziative tese a raggiungere il consumatore finale dei beni o dei servizi venduti. B2E - B2E l'acronimo di Business to Employee e riguarda un settore particolare delle attivit commerciali di un'azienda, quelle rivolte alla vendita di beni ai dipendenti. Backbone - definizione attribuita ad uno o pi nodi vitali nella distribuzione e nello smistamento del traffico telematico in Internet. Cache - "Contenitore" gestito localmente da una applicazione con lo scopo di mantenere copie di entit o documenti da utilizzare su richiesta. Generalmente il termine largamente usato in ambito internet per indicare la capacit di un browser di mantenere copia di documenti scaricati in precedenza senza doverli scaricare nuovamente riducendo cos i tempi di connessione con il server. CGI - (Common Gateway Interface), si tratta di programmi sviluppati in linguaggio C++ o simile, per consentire alle pagine web di diventare interattive. Viene usato soprattutto in funzioni come l'interazione con database e nei motori di ricerca. Chat - "chiacchiera" in inglese; permette il dialogo tra due o pi persone in tempo reale, raggruppate o non in appositi canali, comunicando attraverso diversi protocolli tra cui il pi diffuso IRC (Internet Relay Chat). Client - Applicazione che stabilisce una connessione con un server allo scopo di trasmettere dati. Connessione - Canale logico stabilito tra due applicazioni allo scopo di comunicare tra loro. CORBA - Acronimo di Common Object Request Broker identifica la architettura proposta da Object Management Group per la comunicazione tra oggetti distribuiti. Datagram - Pacchetto di dati trasmesso via rete mediante protocolli di tipo "Connectionless". DNS - Acronimo di "Domain Name System" un programma eseguito all'interno di un computer Host e si occupa della traduzione di indirizzi IP in nomi o viceversa. <NAME> http://www.java-net.tv <EMAIL> 220 Dominio - Sistema attualmente in vigore per la suddivisione e gerarchizzazione delle reti in Internet. eCommerce - quel "complesso di attivit che permettono ad un'impresa di condurre affari on line", di qualunque genere di affari si tratti. Se, invece di porre l'accento sull'attivit svolta, si vuole porre l'accento sul destinatario dei beni o dei servizi offerti, allora la definizione pu diventare pi specifica, come nelle voci B2C e B2E . B2B, EJB - Enterprise Java Beans rappresentano nella architettura J2EE lo standard per lo sviluppo di Oggetti di Business distribuiti. Email - o posta elettronica il sistema per l'invio di messagistica tra utenti collegati alla rete. Entit - Informazione trasferita da un client ad un server mediante protocollo HTTP come prodotto di una richiesta o come informazione trasferita da client a server. Una entit formata da meta-informazioni nella forma di entity-header e contenuti nella forma di entity-body come descritto nel capitolo 2. Extranet - rete basata su tecnologia internet, estende una Intranet al di fuori della azienda proprietaria. FAQ - "Frequently Asked Questions" ovvero " domande pi frequenti". FTP - "File Transfer Potocol" protocollo di comunicazione precedente all' HTTP, permette il trasferimento di file tra due computer. Gateway - periferica per collegare computer diversi in una rete. Possiede un proprio microprocessore e una propria memoria di elaborazione per gestire conversioni di protocolli di comunicazione diversi. HDML - Handless Device Markup Language Il linguaggio per sistemi Wireless, attraverso il quale creare pagine Web navigabili dai telefoni cellulari dotati di tecnologia WAP. Host - uno qualsiasi dei computer raggiungibili in rete. Nella architettura TCP/IP sinonimo di End-System. Hosting - Servizio che ospita pi siti Web su una singola macchina, assegnando a ognuno di essi un IP differente. In altri termini con il servizio di hosting il sito condivide hard disk e banda disponibile con altri Website ospitati. HTML - "Hyper Text Markup Language" (Linguaggio di Marcatura per il Testo) il linguaggio per scrivere pagine web. Standardizzato dal W3C deriva da SGML ed composto da elementi di contrassegno, tag e attributi. HTTP - "Hyper Text Trasfer Protocol" protocollo di comunicazione ampiamente diffuso nel Web. HTTP utilizza TCP/IP per il trasferimento di file su Internet. Hub - o concentratore periferica per collegare e smistare i cavi ai computer di una rete locale, utilizzati una volta solo dalle grandi e medie aziende, oggi pare che stiano facendo la loro comparsa anche nelle piccole aziende e persino nel mondo domestico. Hyperlink - collegamento tra parti di una stessa pagina o di documenti presenti sul Web. IDSL -il termine indica la possibilit di fornire la tecnologia DSL a linee ISDN gi esistenti. Anche se la quantit di dati trasferiti (Transfer rate) pi o meno la stessa dell'ISDN (144 Kbps contro i 128 Kbps) e l'ISDL pu trasmettere solamente dati (e non anche la voce), i maggiori benefici consistono: nel poter usufruire di connessioni sempre attive, eliminando quindi i ritardi dovuti alla configurazione della chiamata, nel pagamento con tariffe che vengono definite Flat rate (cio forfetarie, un tanto al mese, quindi non in base agli scatti effettivi) e nella trasmissione di dati su una linea dedicata solo ad essi, piuttosto che sulla normale linea telefonica. IMAP - "Internet Message Access Protocol", protocollo anch'esso utilizzato per la ricezione delle email. L'ultima versione (IMAP4) simile al POP3, ma supporta alcune funzioni in pi. Per esempio: con IMAP4 possibile effettuare Massimiliano Tarquini http://www.java-net.tv <EMAIL> 221 una ricerca per Keyword tra i diversi messaggi, quando ancora questi si trovano sul Server di email; in base all'esito della ricerca quindi possibile scegliere quali messaggi scaricare e quali no. Come POP, anche IMAP utilizza SMTP per la comunicazioni tra il client di email ed il server. Intranet - rete di computer (LAN) per comunicare all'interno di una medesima azienda; si basa sullo stesso protocollo di Internet (TCP/IP): utilizza i medesimi sistemi di comunicazione, di rappresentazione (pagine web) e di gestione delle informazioni. Una serie di software di protezione evita che le informazioni siano accessibili al di fuori di tale rete. IP - un indirizzo formato da quattro gruppi di numeri che vanno da 0,0,0,0 a 255,255,255,255; esso indica in maniera univoca un determinato computer connesso ad Internet o in alcuni casi gruppi di computer all'interno di una rete. ISDN - "Integrated Services Digital Network", rete di linee telefoniche digitali per la trasmissione di dati ad alta velocit, che si aggira sui 64KBps; attualmente possibile utilizzare due linee in contemporanea e raggiungere i 128KBps. J2EE Java 2 Enterprise Edition. JAF - servizio necessario all'instanziamento di una componente JavaBeans. JDBC - Java DataBase Connectivity. JMS - (Java Message Service): API Java di Sun che fornisce una piattaforma comune per lo scambio di messaggi fra computer collegati nello stesso network, utilizzando uno dei tanti sistemi diversi di messagistica, come MQSeries, SonicMQ od altri. E' inoltre possibile utilizzare Java e XML. JNDI - Java Naming & Directory Interface. LAN - Acronimo di Local Area Network, una rete che connette due o pi computer all'interno di piccola un'area. LINK - alla base degli ipertesti, si tratta di un collegamento sotto forma di immagine o testo a un'altra pagina o file MAIL SERVER - Computer che fornisce i servizi di Posta Elettronica. MAN - Acronimo di Metropolitan Area Network. Messaggio - Unit base della comunicazione con protocollo HTTP costituita da una sequenza di ottetti legati tra loro secondo lo standard come definito nel capitolo 2. NBS - Acronimo di National Bureau of Standards ribattezzato recentemente in NIST. NETIQUETTE Galateo della rete. network number - Porzione dell'indirizzo IP indicante la rete. Per le reti di classe A, l'indirizzo di rete il primo byte dell'indirizzo IP; per le reti di classe B, sono i primi due byte dell'indirizzo IP; per quelle di classe C, sono i primi 3 byte dell'indirizzo IP. In tutti e tre i casi, il resto l'indirizzo dell'host. In Internet, gli indirizzi di rete assegnati sono unici a livello globale. NFS Network File System - Protocollo sviluppato da Sun Microsystems e definito in RFC 1094, che consente a un sistema di elaborazione di accedere ai file dispersi in una rete come se fossero sull'unit a disco locale. NIC - Network Information Center : organismo che fornisce informazioni, assistenza e servizi agli utenti di una rete. Pacchetto - E' il termine generico utilizzato per indicare le unit di dati a tutti i livelli di un protocollo, ma l'impiego corretto nella indicazione delle unit di dati delle applicazioni. Porta - Meccanismo di identificazione di un processo su un computer nei confronti del TCP/IP o punto di ingresso/uscita su internet. PPP Point-to-Point Protocol - Il Point-to-Point Protocol, definito in RFC 1548, fornisce il metodo per la trasmissione di pacchetti nei collegamenti di tipo seriale da-punto-a-punto. Protocollo - Descrizione formale del formato dei messaggi e delle regole che due elaboratori devono adottare per lo scambio di messaggi. I protocolli possono <NAME> http://www.java-net.tv <EMAIL> 222 descrivere i particolari low-level delle interfaccia macchina-macchina (cio l'ordine secondo il quale i bit e i bytes vengono trasmessi su una linea) oppure gli scambi high level tra i programmi di allocazione (cio il modo in cui due programmi trasmettono un file su Internet). RA - Registration Authority italiana. Autorit con competenze per l'assegnazione di domini con suffisso .it. RFC - Request for Comments. richiesta di osservazioni. Serie di documenti iniziata nel 1969 che descrive la famiglia di protocolli Internet e relativi esperimenti. Non tutte le RFC (anzi, molto poche, in realt) descrivono gli standard Internet, ma tutti gli standard Internet vengono diffusi sotto forma di RFC. RIP Routing Information Protocol. Router - Dispositivo che serve all'inoltro del traffico tra le reti. La decisione di inoltro basata su informazioni relative allo stato della rete e sulle tabelle di instradamento (routing tables). RPC - Remote Procedure Call: Paradigma facile e diffuso per la realizzazione del modello di elaborazione distribuita client-server. In generale, a un sistema remoto viene inviata una richiesta di svolgere una certa procedura, utilizzando argomenti forniti, restituendo poi il risultato al chiamante. Varianti e sottigliezze distinguono le varie realizzazioni, il che ha dato origine a una variet di protocolli RPC tra loro incompatibili. SERVER - Computer o software che fornisce servizi o informazioni ad utenti o computer che si collegano. SMTP - Acronimo di "Simple Mail Transfer Protocol" il Protocollo standard di Internet per l'invio e la ricezione della posta elettronica tra computer. TCP/IP - standard sviluppato per le comunicazioni tra calcolatori. E' diventato il protocollo pi usato per la trasmissione dei dati in Internet. <NAME> http://www.java-net.tv <EMAIL> 223 Bibliografia ??<NAME>, <NAME>, <NAME>, <NAME> - "Java Enterprise in a nutshell", OReilly, 1999; ??<NAME> - " Java 2 Enterprise Edition has turned the language into a total app-development environment ", INFORMATION WEEK On Line, 22 Maggio 2000 Sun Microsystem -"J2EE Blueprints", Sun Microsystem, 1999; ??<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME> Professional Java Server Programming, Wrox Press, 1999; ??<NAME> - "Reti di Computer", McGraw-Hill, 1999; ??<NAME> - "LAN Architetture e implementazioni delle reti locali", <NAME>, 1999; <NAME> http://www.java-net.tv <EMAIL> 224
pygtrie
readthedoc
Python
pygtrie documentation ### Navigation * [pygtrie documentation](index.html#document-index) » pygtrie[¶](#module-pygtrie) === Pure Python implementation of a trie data structure compatible with Python 2.x and Python 3.x. [Trie data structure](http://en.wikipedia.org/wiki/Trie), also known as radix or prefix tree, is a tree associating keys to values where all the descendants of a node have a common prefix (associated with that node). The trie module contains [`pygtrie.Trie`](#pygtrie.Trie), [`pygtrie.CharTrie`](#pygtrie.CharTrie) and [`pygtrie.StringTrie`](#pygtrie.StringTrie) classes each implementing a mutable mapping interface, i.e. [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) interface. As such, in most circumstances, [`pygtrie.Trie`](#pygtrie.Trie) could be used as a drop-in replacement for a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict), but the prefix nature of the data structure is trie’s real strength. The module also contains [`pygtrie.PrefixSet`](#pygtrie.PrefixSet) class which uses a trie to store a set of prefixes such that a key is contained in the set if it or its prefix is stored in the set. Features[¶](#features) --- * A full mutable mapping implementation. * Supports iterating over as well as deleting of a branch of a trie (i.e. subtrie) * Supports prefix checking as well as shortest and longest prefix look-up. * Extensible for any kind of user-defined keys. * A PrefixSet supports “all keys starting with given prefix” logic. * Can store any value including None. For a few simple examples see `example.py` file. Installation[¶](#installation) --- To install pygtrie, simply run: ``` pip install pygtrie ``` or by adding line such as: ``` pygtrie == 2.* ``` to project’s [requirements file](https://pip.pypa.io/en/latest/user_guide/#requirements-files). Trie classes[¶](#trie-classes) --- *class* `Trie`(**args*, ***kwargs*)[[source]](_modules/pygtrie.html#Trie)[¶](#pygtrie.Trie) A trie implementation with dict interface plus some extensions. Keys used with the [`pygtrie.Trie`](#pygtrie.Trie) class must be iterable which each component being a hashable objects. In other words, for a given key, `dict.fromkeys(key)` must be valid expression. In particular, strings work well as trie keys, however when getting them back (for example via [`Trie.iterkeys`](#pygtrie.Trie.iterkeys) method), instead of strings, tuples of characters are produced. For that reason, [`pygtrie.CharTrie`](#pygtrie.CharTrie) or [`pygtrie.StringTrie`](#pygtrie.StringTrie) classes may be preferred when using string keys. `__delitem__`(*key_or_slice*)[[source]](_modules/pygtrie.html#Trie.__delitem__)[¶](#pygtrie.Trie.__delitem__) Deletes value associated with given key or raises KeyError. If argument is a key, value associated with it is deleted. If the key is also a prefix, its descendents are not affected. On the other hand, if the argument is a slice (in which case it must have only start set), the whole subtrie is removed. For example: ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo'] = 'Foo' >>> t['foo/bar'] = 'Bar' >>> t['foo/bar/baz'] = 'Baz' >>> del t['foo/bar'] >>> t.keys() ['foo', 'foo/bar/baz'] >>> del t['foo':] >>> t.keys() [] ``` | Parameters: | **key_or_slice** – A key to look for or a slice. If key is a slice, the whole subtrie will be removed. | | Raises: | * [`ShortKeyError`](#pygtrie.ShortKeyError) – If the key has no value associated with it but is a prefix of some key with a value. This is not thrown if key_or_slice is a slice – in such cases, the whole subtrie is removed. Note that [`ShortKeyError`](#pygtrie.ShortKeyError) is subclass of [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError). * [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If key has no value associated with it nor is a prefix of an existing key. * [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) – If key is a slice whose stop or step are not `None`. | `__eq__`(*other*)[[source]](_modules/pygtrie.html#Trie.__eq__)[¶](#pygtrie.Trie.__eq__) Compares this trie’s mapping with another mapping. Note that this method doesn’t take trie’s structure into consideration. What matters is whether keys and values in both mappings are the same. This may lead to unexpected results, for example: ``` >>> import pygtrie >>> t0 = StringTrie({'foo/bar': 42}, separator='/') >>> t1 = StringTrie({'foo.bar': 42}, separator='.') >>> t0 == t1 False ``` ``` >>> t0 = StringTrie({'foo/bar.baz': 42}, separator='/') >>> t1 = StringTrie({'foo/bar.baz': 42}, separator='.') >>> t0 == t1 True ``` ``` >>> t0 = Trie({'foo': 42}) >>> t1 = CharTrie({'foo': 42}) >>> t0 == t1 False ``` This behaviour is required to maintain consistency with Mapping interface and its __eq__ method. For example, this implementation maintains transitivity of the comparison: ``` >>> t0 = StringTrie({'foo/bar.baz': 42}, separator='/') >>> d = {'foo/bar.baz': 42} >>> t1 = StringTrie({'foo/bar.baz': 42}, separator='.') >>> t0 == d True >>> d == t1 True >>> t0 == t1 True ``` ``` >>> t0 = Trie({'foo': 42}) >>> d = {'foo': 42} >>> t1 = CharTrie({'foo': 42}) >>> t0 == d False >>> d == t1 True >>> t0 == t1 False ``` | Parameters: | **other** – Other object to compare to. | | Returns: | `NotImplemented` if this method does not know how to perform the comparison or a `bool` denoting whether the two objects are equal or not. | `__getitem__`(*key_or_slice*)[[source]](_modules/pygtrie.html#Trie.__getitem__)[¶](#pygtrie.Trie.__getitem__) Returns value associated with given key or raises KeyError. When argument is a single key, value for that key is returned (or [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) exception is thrown if the node does not exist or has no value associated with it). When argument is a slice, it must be one with only start set in which case the access is identical to [`Trie.itervalues`](#pygtrie.Trie.itervalues) invocation with prefix argument. Example ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo/bar'] = 'Bar' >>> t['foo/baz'] = 'Baz' >>> t['qux'] = 'Qux' >>> t['foo/bar'] 'Bar' >>> sorted(t['foo':]) ['Bar', 'Baz'] >>> t['foo'] # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ShortKeyError: 'foo' ``` | Parameters: | **key_or_slice** – A key or a slice to look for. | | Returns: | If a single key is passed, a value associated with given key. If a slice is passed, a generator of values in specified subtrie. | | Raises: | * [`ShortKeyError`](#pygtrie.ShortKeyError) – If the key has no value associated with it but is a prefix of some key with a value. Note that [`ShortKeyError`](#pygtrie.ShortKeyError) is subclass of [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError). * [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If key has no value associated with it nor is a prefix of an existing key. * [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) – If `key_or_slice` is a slice but it’s stop or step are not `None`. | `__init__`(**args*, ***kwargs*)[[source]](_modules/pygtrie.html#Trie.__init__)[¶](#pygtrie.Trie.__init__) Initialises the trie. Arguments are interpreted the same way [`Trie.update`](#pygtrie.Trie.update) interprets them. `__len__`()[[source]](_modules/pygtrie.html#Trie.__len__)[¶](#pygtrie.Trie.__len__) Returns number of values in a trie. Note that this method is expensive as it iterates over the whole trie. `__setitem__`(*key_or_slice*, *value*)[[source]](_modules/pygtrie.html#Trie.__setitem__)[¶](#pygtrie.Trie.__setitem__) Sets value associated with given key. If key_or_slice is a key, simply associate it with given value. If it is a slice (which must have start set only), it in addition clears any subtrie that might have been attached to particular key. For example: ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo/bar'] = 'Bar' >>> t['foo/baz'] = 'Baz' >>> sorted(t.keys()) ['foo/bar', 'foo/baz'] >>> t['foo':] = 'Foo' >>> t.keys() ['foo'] ``` | Parameters: | * **key_or_slice** – A key to look for or a slice. If it is a slice, the whole subtrie (if present) will be replaced by a single node with given value set. * **value** – Value to set. | | Raises: | [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) – If key is a slice whose stop or step are not None. | `clear`()[[source]](_modules/pygtrie.html#Trie.clear)[¶](#pygtrie.Trie.clear) Removes all the values from the trie. `copy`(*_Trie__make_copy=<function <lambda>>*)[[source]](_modules/pygtrie.html#Trie.copy)[¶](#pygtrie.Trie.copy) Returns a shallow copy of the object. `enable_sorting`(*enable=True*)[[source]](_modules/pygtrie.html#Trie.enable_sorting)[¶](#pygtrie.Trie.enable_sorting) Enables sorting of child nodes when iterating and traversing. Normally, child nodes are not sorted when iterating or traversing over the trie (just like dict elements are not sorted). This method allows sorting to be enabled (which was the behaviour prior to pygtrie 2.0 release). For Trie class, enabling sorting of children is identical to simply sorting the list of items since Trie returns keys as tuples. However, for other implementations such as StringTrie the two may behave subtly different. For example, sorting items might produce: ``` root/foo-bar root/foo/baz ``` even though foo comes before foo-bar. | Parameters: | **enable** – Whether to enable sorting of child nodes. | *classmethod* `fromkeys`(*keys*, *value=None*)[[source]](_modules/pygtrie.html#Trie.fromkeys)[¶](#pygtrie.Trie.fromkeys) Creates a new trie with given keys set. This is roughly equivalent to calling the constructor with a `(key, value) for key in keys` generator. | Parameters: | * **keys** – An iterable of keys that should be set in the new trie. * **value** – Value to associate with given keys. | | Returns: | A new trie where each key from `keys` has been set to the given value. | `has_key`(*key*)[[source]](_modules/pygtrie.html#Trie.has_key)[¶](#pygtrie.Trie.has_key) Indicates whether given key has value associated with it. See [`Trie.has_node`](#pygtrie.Trie.has_node) for more detailed documentation. `has_node`(*key*)[[source]](_modules/pygtrie.html#Trie.has_node)[¶](#pygtrie.Trie.has_node) Returns whether given node is in the trie. Return value is a bitwise or of `HAS_VALUE` and `HAS_SUBTRIE` constants indicating node has a value associated with it and that it is a prefix of another existing key respectively. Both of those are independent of each other and all of the four combinations are possible. For example: ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo/bar'] = 'Bar' >>> t['foo/bar/baz'] = 'Baz' >>> t.has_node('qux') == 0 True >>> t.has_node('foo/bar/baz') == pygtrie.Trie.HAS_VALUE True >>> t.has_node('foo') == pygtrie.Trie.HAS_SUBTRIE True >>> t.has_node('foo/bar') == (pygtrie.Trie.HAS_VALUE | ... pygtrie.Trie.HAS_SUBTRIE) True ``` There are two higher level methods built on top of this one which give easier interface for the information. [`Trie.has_key`](#pygtrie.Trie.has_key) returns whether node has a value associated with it and [`Trie.has_subtrie`](#pygtrie.Trie.has_subtrie) checks whether node is a prefix. Continuing previous example: ``` >>> t.has_key('qux'), t.has_subtrie('qux') (False, False) >>> t.has_key('foo/bar/baz'), t.has_subtrie('foo/bar/baz') (True, False) >>> t.has_key('foo'), t.has_subtrie('foo') (False, True) >>> t.has_key('foo/bar'), t.has_subtrie('foo/bar') (True, True) ``` | Parameters: | **key** – A key to look for. | | Returns: | Non-zero if node exists and if it does a bit-field denoting whether it has a value associated with it and whether it has a subtrie. | `has_subtrie`(*key*)[[source]](_modules/pygtrie.html#Trie.has_subtrie)[¶](#pygtrie.Trie.has_subtrie) Returns whether given key is a prefix of another key in the trie. See [`Trie.has_node`](#pygtrie.Trie.has_node) for more detailed documentation. `items`(*prefix=<pygtrie._NoChildren object>*, *shallow=False*)[[source]](_modules/pygtrie.html#Trie.items)[¶](#pygtrie.Trie.items) Returns a list of `(key, value)` pairs in given subtrie. This is equivalent to constructing a list from generator returned by [`Trie.iteritems`](#pygtrie.Trie.iteritems) which see for more detailed documentation. `iteritems`(*prefix=<pygtrie._NoChildren object>*, *shallow=False*)[[source]](_modules/pygtrie.html#Trie.iteritems)[¶](#pygtrie.Trie.iteritems) Yields all nodes with associated values with given prefix. Only nodes with values are output. For example: ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo'] = 'Foo' >>> t['foo/bar/baz'] = 'Baz' >>> t['qux'] = 'Qux' >>> sorted(t.items()) [('foo', 'Foo'), ('foo/bar/baz', 'Baz'), ('qux', 'Qux')] ``` Items are generated in topological order (i.e. parents before child nodes) but the order of siblings is unspecified. At an expense of efficiency, [`Trie.enable_sorting`](#pygtrie.Trie.enable_sorting) method can turn deterministic ordering of siblings. With `prefix` argument, only items with specified prefix are generated (i.e. only given subtrie is traversed) as demonstrated by: ``` >>> t.items(prefix='foo') [('foo', 'Foo'), ('foo/bar/baz', 'Baz')] ``` With `shallow` argument, if a node has value associated with it, it’s children are not traversed even if they exist which can be seen in: ``` >>> sorted(t.items(shallow=True)) [('foo', 'Foo'), ('qux', 'Qux')] ``` | Parameters: | * **prefix** – Prefix to limit iteration to. * **shallow** – Perform a shallow traversal, i.e. do not yield items if their prefix has been yielded. | | Yields: | `(key, value)` tuples. | | Raises: | [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If `prefix` does not match any node. | `iterkeys`(*prefix=<pygtrie._NoChildren object>*, *shallow=False*)[[source]](_modules/pygtrie.html#Trie.iterkeys)[¶](#pygtrie.Trie.iterkeys) Yields all keys having associated values with given prefix. This is equivalent to taking first element of tuples generated by [`Trie.iteritems`](#pygtrie.Trie.iteritems) which see for more detailed documentation. | Parameters: | * **prefix** – Prefix to limit iteration to. * **shallow** – Perform a shallow traversal, i.e. do not yield keys if their prefix has been yielded. | | Yields: | All the keys (with given prefix) with associated values in the trie. | | Raises: | [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If `prefix` does not match any node. | `itervalues`(*prefix=<pygtrie._NoChildren object>*, *shallow=False*)[[source]](_modules/pygtrie.html#Trie.itervalues)[¶](#pygtrie.Trie.itervalues) Yields all values associated with keys with given prefix. This is equivalent to taking second element of tuples generated by [`Trie.iteritems`](#pygtrie.Trie.iteritems) which see for more detailed documentation. | Parameters: | * **prefix** – Prefix to limit iteration to. * **shallow** – Perform a shallow traversal, i.e. do not yield values if their prefix has been yielded. | | Yields: | All the values associated with keys (with given prefix) in the trie. | | Raises: | [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If `prefix` does not match any node. | `keys`(*prefix=<pygtrie._NoChildren object>*, *shallow=False*)[[source]](_modules/pygtrie.html#Trie.keys)[¶](#pygtrie.Trie.keys) Returns a list of all the keys, with given prefix, in the trie. This is equivalent to constructing a list from generator returned by [`Trie.iterkeys`](#pygtrie.Trie.iterkeys) which see for more detailed documentation. `longest_prefix`(*key*)[[source]](_modules/pygtrie.html#Trie.longest_prefix)[¶](#pygtrie.Trie.longest_prefix) Finds the longest prefix of a key with a value. This is roughly equivalent to taking the last object yielded by [`Trie.prefixes`](#pygtrie.Trie.prefixes) with additional handling for situations when no prefixes are found. Example ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo'] = 'Foo' >>> t['foo/bar/baz'] = 'Baz' >>> t.longest_prefix('foo/bar/baz/qux') ('foo/bar/baz': 'Baz') >>> t.longest_prefix('foo/bar/baz/qux').key 'foo/bar/baz' >>> t.longest_prefix('foo/bar/baz/qux').value 'Baz' >>> t.longest_prefix('does/not/exist') (None Step) >>> bool(t.longest_prefix('does/not/exist')) False ``` | Parameters: | **key** – Key to look for. | | Returns: | `pygtrie.Trie._Step` object (which can be used to extract or set node’s value as well as get node’s key), or a `pygtrie.Trie._NoneStep` object (which is falsy value simulating a _Step with `None` key and value) if no prefix is found.The object can be treated as `(key, value)` pair denoting key with associated value of the prefix. This is deprecated, prefer using `key` and `value` properties of the object. | `merge`(*other*, *overwrite=False*)[[source]](_modules/pygtrie.html#Trie.merge)[¶](#pygtrie.Trie.merge) Moves nodes from other trie into this one. The merging happens at trie structure level and as such is different than iterating over items of one trie and setting them in the other trie. The merging may happen between different types of tries resulting in different (key, value) pairs in the destination trie compared to the source. For example, merging two [`pygtrie.StringTrie`](#pygtrie.StringTrie) objects each using different separators will work as if the other trie had separator of this trie. Similarly, a [`pygtrie.CharTrie`](#pygtrie.CharTrie) may be merged into a [`pygtrie.StringTrie`](#pygtrie.StringTrie) but when keys are read those will be joined by the separator. For example: ``` >>> import pygtrie >>> st = pygtrie.StringTrie(separator='.') >>> st.merge(pygtrie.StringTrie({'foo/bar': 42})) >>> list(st.items()) [('foo.bar', 42)] >>> st.merge(pygtrie.CharTrie({'baz': 24})) >>> sorted(st.items()) [('b.a.z', 24), ('foo.bar', 42)] ``` Not all tries can be merged into other tries. For example, a [`pygtrie.StringTrie`](#pygtrie.StringTrie) may not be merged into a [`pygtrie.CharTrie`](#pygtrie.CharTrie) because the latter imposes a requirement for each component in the key to be exactly one character while in the former components may be arbitrary length. Note that the other trie is cleared and any references or iterators over it are invalidated. To preserve other’s value it needs to be copied first. | Parameters: | * **other** – Other trie to move nodes from. * **overwrite** – Whether to overwrite existing values in this trie. | `pop`(*key*, *default=<pygtrie._NoChildren object>*)[[source]](_modules/pygtrie.html#Trie.pop)[¶](#pygtrie.Trie.pop) Deletes value associated with given key and returns it. | Parameters: | * **key** – A key to look for. * **default** – If specified, value that will be returned if given key has no value associated with it. If not specified, method will throw KeyError in such cases. | | Returns: | Removed value, if key had value associated with it, or `default` (if given). | | Raises: | * [`ShortKeyError`](#pygtrie.ShortKeyError) – If `default` has not been specified and the key has no value associated with it but is a prefix of some key with a value. Note that [`ShortKeyError`](#pygtrie.ShortKeyError) is subclass of [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError). * [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If default has not been specified and key has no value associated with it nor is a prefix of an existing key. | `popitem`()[[source]](_modules/pygtrie.html#Trie.popitem)[¶](#pygtrie.Trie.popitem) Deletes an arbitrary value from the trie and returns it. There is no guarantee as to which item is deleted and returned. Neither in respect to its lexicographical nor topological order. | Returns: | `(key, value)` tuple indicating deleted key. | | Raises: | [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If the trie is empty. | `prefixes`(*key*)[[source]](_modules/pygtrie.html#Trie.prefixes)[¶](#pygtrie.Trie.prefixes) Walks towards the node specified by key and yields all found items. Example ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo'] = 'Foo' >>> t['foo/bar/baz'] = 'Baz' >>> list(t.prefixes('foo/bar/baz/qux')) [('foo': 'Foo'), ('foo/bar/baz': 'Baz')] >>> list(t.prefixes('does/not/exist')) [] ``` | Parameters: | **key** – Key to look for. | | Yields: | `pygtrie.Trie._Step` objects which can be used to extract or set node’s value as well as get node’s key. The objects can be treated as `(k, value)` pairs denoting keys with associated values encountered on the way towards the specified key. This is deprecated, prefer using `key` and `value` properties of the object. | `setdefault`(*key*, *default=None*)[[source]](_modules/pygtrie.html#Trie.setdefault)[¶](#pygtrie.Trie.setdefault) Sets value of a given node if not set already. Also returns it. In contrast to [`Trie.__setitem__`](#pygtrie.Trie.__setitem__), this method does not accept slice as a key. `shortest_prefix`(*key*)[[source]](_modules/pygtrie.html#Trie.shortest_prefix)[¶](#pygtrie.Trie.shortest_prefix) Finds the shortest prefix of a key with a value. This is roughly equivalent to taking the first object yielded by [`Trie.prefixes`](#pygtrie.Trie.prefixes) with additional handling for situations when no prefixes are found. Example ``` >>> import pygtrie >>> t = pygtrie.StringTrie() >>> t['foo'] = 'Foo' >>> t['foo/bar/baz'] = 'Baz' >>> t.shortest_prefix('foo/bar/baz/qux') ('foo': 'Foo') >>> t.shortest_prefix('foo/bar/baz/qux').key 'foo' >>> t.shortest_prefix('foo/bar/baz/qux').value 'Foo' >>> t.shortest_prefix('does/not/exist') (None Step) >>> bool(t.shortest_prefix('does/not/exist')) False ``` | Parameters: | **key** – Key to look for. | | Returns: | `pygtrie.Trie._Step` object (which can be used to extract or set node’s value as well as get node’s key), or a `pygtrie.Trie._NoneStep` object (which is falsy value simulating a _Step with `None` key and value) if no prefix is found.The object can be treated as `(key, value)` pair denoting key with associated value of the prefix. This is deprecated, prefer using `key` and `value` properties of the object. | `strictly_equals`(*other*)[[source]](_modules/pygtrie.html#Trie.strictly_equals)[¶](#pygtrie.Trie.strictly_equals) Checks whether tries are equal with the same structure. This is stricter comparison than the one performed by equality operator. It not only requires for keys and values to be equal but also for the two tries to be of the same type and have the same structure. For example, for two [`pygtrie.StringTrie`](#pygtrie.StringTrie) objects to be equal, they need to have the same structure as well as the same separator as seen below: ``` >>> import pygtrie >>> t0 = StringTrie({'foo/bar': 42}, separator='/') >>> t1 = StringTrie({'foo.bar': 42}, separator='.') >>> t0.strictly_equals(t1) False ``` ``` >>> t0 = StringTrie({'foo/bar.baz': 42}, separator='/') >>> t1 = StringTrie({'foo/bar.baz': 42}, separator='.') >>> t0 == t1 True >>> t0.strictly_equals(t1) False ``` | Parameters: | **other** – Other trie to compare to. | | Returns: | Whether the two tries are the same type and have the same structure. | `traverse`(*node_factory*, *prefix=<pygtrie._NoChildren object>*)[[source]](_modules/pygtrie.html#Trie.traverse)[¶](#pygtrie.Trie.traverse) Traverses the tree using node_factory object. node_factory is a callable which accepts (path_conv, path, children, value=…) arguments, where path_conv is a lambda converting path representation to key, path is the path to this node, children is an iterable of children nodes constructed by node_factory, optional value is the value associated with the path. node_factory’s children argument is an iterator which has a few consequences: * To traverse into node’s children, the object must be iterated over. This can by accomplished by a simple `children = list(children)` statement. * Ignoring the argument allows node_factory to stop the traversal from going into the children of the node. In other words, whole subtries can be removed from traversal if node_factory chooses so. * If children is stored as is (i.e. as a iterator) when it is iterated over later on it may see an inconsistent state of the trie if it has changed between invocation of this method and the iteration. However, to allow constant-time determination whether the node has children or not, the iterator implements bool conversion such that `has_children = bool(children)` will tell whether node has children without iterating over them. (Note that `bool(children)` will continue returning `True` even if the iterator has been iterated over). [`Trie.traverse`](#pygtrie.Trie.traverse) has two advantages over [`Trie.iteritems`](#pygtrie.Trie.iteritems) and similar methods: 1. it allows subtries to be skipped completely when going through the list of nodes based on the property of the parent node; and 2. it represents structure of the trie directly making it easy to convert structure into a different representation. For example, the below snippet prints all files in current directory counting how many HTML files were found but ignores hidden files and directories (i.e. those whose names start with a dot): ``` import os import pygtrie t = pygtrie.StringTrie(separator=os.sep) # Construct a trie with all files in current directory and all # of its sub-directories. Files get set a True value. # Directories are represented implicitly by being prefixes of # files. for root, _, files in os.walk('.'): for name in files: t[os.path.join(root, name)] = True def traverse_callback(path_conv, path, children, is_file=False): if path and path[-1] != '.' and path[-1][0] == '.': # Ignore hidden directory (but accept root node and '.') return 0 elif is_file: print path_conv(path) return int(path[-1].endswith('.html')) else: # Otherwise, it's a directory. Traverse into children. return sum(children) print t.traverse(traverse_callback) ``` As documented, ignoring the children argument causes subtrie to be omitted and not walked into. In the next example, the trie is converted to a tree representation where child nodes include a pointer to their parent. As before, hidden files and directories are ignored: ``` import os import pygtrie t = pygtrie.StringTrie(separator=os.sep) for root, _, files in os.walk('.'): for name in files: t[os.path.join(root, name)] = True class File(object): def __init__(self, name): self.name = name self.parent = None class Directory(File): def __init__(self, name, children): super(Directory, self).__init__(name) self._children = children for child in children: child.parent = self def traverse_callback(path_conv, path, children, is_file=False): if not path or path[-1] == '.' or path[-1][0] != '.': if is_file: return File(path[-1]) children = filter(None, children) return Directory(path[-1] if path else '', children) root = t.traverse(traverse_callback) ``` Note: Unlike iterators, when used on a deep trie, traverse method is prone to rising a RuntimeError exception when Python’s maximum recursion depth is reached. This can be addressed by not iterating over children inside of the node_factory. For example, the below code converts a trie into an undirected graph using adjacency list representation: ``` def undirected_graph_from_trie(t): '''Converts trie into a graph and returns its nodes.''' Node = collections.namedtuple('Node', 'path neighbours') class Builder(object): def __init__(self, path_conv, path, children, _=None): self.node = Node(path_conv(path), []) self.children = children self.parent = None def build(self, queue): for builder in self.children: builder.parent = self.node queue.append(builder) if self.parent: self.parent.neighbours.append(self.node) self.node.neighbours.append(self.parent) return self.node nodes = [t.traverse(Builder)] i = 0 while i < len(nodes): nodes[i] = nodes[i].build(nodes) i += 1 return nodes ``` | Parameters: | * **node_factory** – Makes opaque objects from the keys and values of the trie. * **prefix** – Prefix for node to start traversal, by default starts at root. | | Returns: | Node object constructed by node_factory corresponding to the root node. | `update`(**args*, ***kwargs*)[[source]](_modules/pygtrie.html#Trie.update)[¶](#pygtrie.Trie.update) Updates stored values. Works like [`dict.update`](https://docs.python.org/3/library/stdtypes.html#dict.update). `values`(*prefix=<pygtrie._NoChildren object>*, *shallow=False*)[[source]](_modules/pygtrie.html#Trie.values)[¶](#pygtrie.Trie.values) Returns a list of values in given subtrie. This is equivalent to constructing a list from generator returned by [`Trie.itervalues`](#pygtrie.Trie.itervalues) which see for more detailed documentation. `walk_towards`(*key*)[[source]](_modules/pygtrie.html#Trie.walk_towards)[¶](#pygtrie.Trie.walk_towards) Yields nodes on the path to given node. | Parameters: | **key** – Key of the node to look for. | | Yields: | `pygtrie.Trie._Step` objects which can be used to extract or set node’s value as well as get node’s key. When representing nodes with assigned values, the objects can be treated as `(k, value)` pairs denoting keys with associated values encountered on the way towards the specified key. This is deprecated, prefer using `key` and `value` properties or `get` method of the object. | | Raises: | [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) – If node with given key does not exist. It’s all right if they value is not assigned to the node provided it has a child node. Because the method is a generator, the exception is raised only once a missing node is encountered. | *class* `CharTrie`(**args*, ***kwargs*)[[source]](_modules/pygtrie.html#CharTrie)[¶](#pygtrie.CharTrie) A variant of a [`pygtrie.Trie`](#pygtrie.Trie) which accepts strings as keys. The only difference between [`pygtrie.CharTrie`](#pygtrie.CharTrie) and [`pygtrie.Trie`](#pygtrie.Trie) is that when [`pygtrie.CharTrie`](#pygtrie.CharTrie) returns keys back to the client (for instance when [`Trie.keys`](#pygtrie.Trie.keys) method is called), those keys are returned as strings. Common example where this class can be used is a dictionary of words in a natural language. For example: ``` >>> import pygtrie >>> t = pygtrie.CharTrie() >>> t['wombat'] = True >>> t['woman'] = True >>> t['man'] = True >>> t['manhole'] = True >>> t.has_subtrie('wo') True >>> t.has_key('man') True >>> t.has_subtrie('man') True >>> t.has_subtrie('manhole') False ``` *class* `StringTrie`(**args*, ***kwargs*)[[source]](_modules/pygtrie.html#StringTrie)[¶](#pygtrie.StringTrie) [`pygtrie.Trie`](#pygtrie.Trie) variant accepting strings with a separator as keys. The trie accepts strings as keys which are split into components using a separator specified during initialisation (forward slash, i.e. `/`, by default). Common example where this class can be used is when keys are paths. For example, it could map from a path to a request handler: ``` import pygtrie def handle_root(): pass def handle_admin(): pass def handle_admin_images(): pass handlers = pygtrie.StringTrie() handlers[''] = handle_root handlers['/admin'] = handle_admin handlers['/admin/images'] = handle_admin_images request_path = '/admin/images/foo' handler = handlers.longest_prefix(request_path) ``` `__init__`(**args*, ***kwargs*)[[source]](_modules/pygtrie.html#StringTrie.__init__)[¶](#pygtrie.StringTrie.__init__) Initialises the trie. Except for a `separator` named argument, all other arguments are interpreted the same way [`Trie.update`](#pygtrie.Trie.update) interprets them. | Parameters: | * ***args** – Passed to super class initialiser. * ****kwargs** – Passed to super class initialiser. * **separator** – A separator to use when splitting keys into paths used by the trie. “/” is used if this argument is not specified. This named argument is not specified on the function’s prototype because of Python’s limitations. | | Raises: | * [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) – If `separator` is not a string. * [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) – If `separator` is empty. | *classmethod* `fromkeys`(*keys*, *value=None*, *separator='/'*)[[source]](_modules/pygtrie.html#StringTrie.fromkeys)[¶](#pygtrie.StringTrie.fromkeys) Creates a new trie with given keys set. This is roughly equivalent to calling the constructor with a `(key, value) for key in keys` generator. | Parameters: | * **keys** – An iterable of keys that should be set in the new trie. * **value** – Value to associate with given keys. | | Returns: | A new trie where each key from `keys` has been set to the given value. | PrefixSet class[¶](#prefixset-class) --- *class* `PrefixSet`(*iterable=()*, *factory=<class 'pygtrie.Trie'>*, ***kwargs*)[[source]](_modules/pygtrie.html#PrefixSet)[¶](#pygtrie.PrefixSet) A set of prefixes. [`pygtrie.PrefixSet`](#pygtrie.PrefixSet) works similar to a normal set except it is said to contain a key if the key or it’s prefix is stored in the set. For instance, if “foo” is added to the set, the set contains “foo” as well as “foobar”. The set supports addition of elements but does *not* support removal of elements. This is because there’s no obvious consistent and intuitive behaviour for element deletion. `__contains__`(*key*)[[source]](_modules/pygtrie.html#PrefixSet.__contains__)[¶](#pygtrie.PrefixSet.__contains__) Checks whether set contains key or its prefix. `__init__`(*iterable=()*, *factory=<class 'pygtrie.Trie'>*, ***kwargs*)[[source]](_modules/pygtrie.html#PrefixSet.__init__)[¶](#pygtrie.PrefixSet.__init__) Initialises the prefix set. | Parameters: | * **iterable** – A sequence of keys to add to the set. * **factory** – A function used to create a trie used by the [`pygtrie.PrefixSet`](#pygtrie.PrefixSet). * **kwargs** – Additional keyword arguments passed to the factory function. | `__iter__`()[[source]](_modules/pygtrie.html#PrefixSet.__iter__)[¶](#pygtrie.PrefixSet.__iter__) Return iterator over all prefixes in the set. See [`PrefixSet.iter`](#pygtrie.PrefixSet.iter) method for more info. `__len__`()[[source]](_modules/pygtrie.html#PrefixSet.__len__)[¶](#pygtrie.PrefixSet.__len__) Returns number of keys stored in the set. Since a key does not have to be explicitly added to the set to be an element of the set, this method does not count over all possible keys that the set contains (since that would be infinity), but only over the shortest set of prefixes of all the keys the set contains. For example, if “foo” has been added to the set, the set contains also “foobar”, but this method will *not* count “foobar”. `add`(*value*)[[source]](_modules/pygtrie.html#PrefixSet.add)[¶](#pygtrie.PrefixSet.add) Adds given value to the set. If the set already contains prefix of the value being added, this operation has no effect. If the value being added is a prefix of some existing values in the set, those values are deleted and replaced by a single entry for the value being added. For example, if the set contains value “foo” adding a value “foobar” does not change anything. On the other hand, if the set contains values “foobar” and “foobaz”, adding a value “foo” will replace those two values with a single value “foo”. This makes a difference when iterating over the values or counting number of values. Counter intuitively, adding of a value can *decrease* size of the set. | Parameters: | **value** – Value to add. | `clear`()[[source]](_modules/pygtrie.html#PrefixSet.clear)[¶](#pygtrie.PrefixSet.clear) Removes all keys from the set. `copy`()[[source]](_modules/pygtrie.html#PrefixSet.copy)[¶](#pygtrie.PrefixSet.copy) Returns a shallow copy of the object. `discard`(*value*)[[source]](_modules/pygtrie.html#PrefixSet.discard)[¶](#pygtrie.PrefixSet.discard) Raises NotImplementedError. `iter`(*prefix=<pygtrie._NoChildren object>*)[[source]](_modules/pygtrie.html#PrefixSet.iter)[¶](#pygtrie.PrefixSet.iter) Iterates over all keys in the set optionally starting with a prefix. Since a key does not have to be explicitly added to the set to be an element of the set, this method does not iterate over all possible keys that the set contains, but only over the shortest set of prefixes of all the keys the set contains. For example, if “foo” has been added to the set, the set contains also “foobar”, but this method will *not* iterate over “foobar”. If `prefix` argument is given, method will iterate over keys with given prefix only. The keys yielded from the function if prefix is given does not have to be a subset (in mathematical sense) of the keys yielded when there is not prefix. This happens, if the set contains a prefix of the given prefix. For example, if only “foo” has been added to the set, iter method called with no arguments will yield “foo” only. However, when called with “foobar” argument, it will yield “foobar” only. `pop`()[[source]](_modules/pygtrie.html#PrefixSet.pop)[¶](#pygtrie.PrefixSet.pop) Raises NotImplementedError. `remove`(*value*)[[source]](_modules/pygtrie.html#PrefixSet.remove)[¶](#pygtrie.PrefixSet.remove) Raises NotImplementedError. Custom exceptions[¶](#custom-exceptions) --- *class* `ShortKeyError`[[source]](_modules/pygtrie.html#ShortKeyError)[¶](#pygtrie.ShortKeyError) Raised when given key is a prefix of an existing longer key but does not have a value associated with itself. Version History[¶](#version-history) --- 2.5: 2022/07/16 * Add [`pygtrie.Trie.merge`](#pygtrie.Trie.merge) method which merges structures of two tries. * Add [`pygtrie.Trie.strictly_equals`](#pygtrie.Trie.strictly_equals) method which compares two tries with stricter rules than regular equality operator. It’s not sufficient that keys and values are the same but the structure of the tries must be the same as well. For example: ``` >>> t0 = StringTrie({'foo/bar.baz': 42}, separator='/') >>> t1 = StringTrie({'foo/bar.baz': 42}, separator='.') >>> t0 == t1 True >>> t0.strictly_equals(t1) False ``` * Fix [`pygtrie.Trie.__eq__`](#pygtrie.Trie.__eq__) implementation such that key values are taken into consideration rather than just looking at trie structure. To see what this means it’s best to look at a few examples. Firstly: ``` >>> t0 = StringTrie({'foo/bar': 42}, separator='/') >>> t1 = StringTrie({'foo.bar': 42}, separator='.') >>> t0 == t1 False ``` This used to be true since the two tries have the same node structure. However, as far as Mapping interface is concerned, they use different keys, i.e. ``set(t0) != set(t1)`. Secondly: ``` >>> t0 = StringTrie({'foo/bar.baz': 42}, separator='/') >>> t1 = StringTrie({'foo/bar.baz': 42}, separator='.') >>> t0 == t1 True ``` This used to be false since the two tries have different node structures (the first one splits key into `('foo', 'bar.baz')` while the second into `('foo/bar', 'baz')`). However, their keys are the same, i.e. ``set(t0) == set(t1)`. And lastly: ``` >>> t0 = Trie({'foo': 42}) >>> t1 = CharTrie({'foo': 42}) >>> t0 == t1 False ``` This used to be true since the two tries have the same node structure. However, the two classes return key as different values. [`pygtrie.Trie`](#pygtrie.Trie) returns keys as tuples while [`pygtrie.CharTrie`](#pygtrie.CharTrie) returns them as strings. 2.4.2: 2021/01/03 * Remove use of ‘super’ in `setup.py` to fix compatibility with Python 2.7. This changes build code only; no changes to the library itself. 2.4.1: 2020/11/20 * Remove dependency on `packaging` module from `setup.py` to fix installation on systems without that package. This changes build code only; no changes to the library itself. [Thanks to <NAME> for reporting] 2.4.0: 2020/11/19 [pulled back from PyPi] * Change `children` argument of the `node_factory` passed to [`pygtrie.Trie.traverse`](#pygtrie.Trie.traverse) from a generator to an iterator with a custom bool conversion. This allows checking whether node has children without having to iterate over them (`bool(children)`) To test whether this feature is available, one can check whether Trie.traverse.uses_bool_convertible_children property is true, e.g.: `getattr(pygtrie.Trie.traverse, 'uses_bool_convertible_children', False)`. [Thanks to P<NAME> for suggesting the feature] 2.3.3: 2020/04/04 * Fix to ‘[`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError): `_NoChildren` object has no attribute `sorted_items`’ failure when iterating over a trie with sorting enabled. [Thanks to Pallab Pain for reporting] * Add `value` property setter to step objects returned by [`pygtrie.Trie.walk_towards`](#pygtrie.Trie.walk_towards) et al. This deprecates the `set` method. * The module now exports pygtrie.__version__ making it possible to determine version of the library at run-time. 2.3.2: 2019/07/18 * Trivial metadata fix 2.3.1: 2019/07/18 [pulled back from PyPi] * Fix to [`pygtrie.PrefixSet`](#pygtrie.PrefixSet) initialisation incorrectly storing elements even if their prefixes are also added to the set. For example, `PrefixSet(('foo', 'foobar'))` incorrectly resulted in a two-element set even though the interface dictates that only `foo` is kept (recall that if `foo` is member of the set, `foobar` is as well). [Thanks to <NAME> for reporting] * Fix to [`pygtrie.Trie.copy`](#pygtrie.Trie.copy) method not preserving enable-sorting flag and, in case of [`pygtrie.StringTrie`](#pygtrie.StringTrie), `separator` property. * Add support for the `copy` module so [`copy.copy`](https://docs.python.org/3/library/copy.html#copy.copy) can now be used with trie objects. * Leafs and nodes with just one child use more memory-optimised representation which reduces overall memory usage of a trie structure. * Minor performance improvement for adding new elements to a [`pygtrie.PrefixSet`](#pygtrie.PrefixSet). * Improvements to string representation of objects which now includes type and, for [`pygtrie.StringTrie`](#pygtrie.StringTrie) object, value of separator property. 2.3: 2018/08/10 * New [`pygtrie.Trie.walk_towards`](#pygtrie.Trie.walk_towards) method allows walking a path towards a node with given key accessing each step of the path. Compared to pygtrie.Trie.walk_prefixes method, steps for nodes without assigned values are returned. * Fix to [`pygtrie.PrefixSet.copy`](#pygtrie.PrefixSet.copy) not preserving type of backing trie. * [`pygtrie.StringTrie`](#pygtrie.StringTrie) now checks and explicitly rejects empty separators. Previously empty separator would be accepted but lead to confusing errors later on. [Thanks to Waren Long] * Various documentation improvements, Python 2/3 compatibility and test coverage (python-coverage reports 100%). 2.2: 2017/06/03 * Fixes to `setup.py` breaking on Windows which prevents installation among other things. 2.1: 2017/03/23 * The library is now Python 3 compatible. * Value returned by [`pygtrie.Trie.shortest_prefix`](#pygtrie.Trie.shortest_prefix) and [`pygtrie.Trie.longest_prefix`](#pygtrie.Trie.longest_prefix) evaluates to false if no prefix was found. This is in addition to it being a pair of `None`s of course. 2.0: 2016/07/06 * Sorting of child nodes is disabled by default for better performance. [`pygtrie.Trie.enable_sorting`](#pygtrie.Trie.enable_sorting) method can be used to bring back old behaviour. * Tries of arbitrary depth can be pickled without reaching Python’s recursion limits. (N.B. The pickle format is incompatible with one from 1.2 release). `_Node`’s `__getstate__` and `__setstate__` method can be used to implement other serialisation methods such as JSON. 1.2: 2016/06/21 [pulled back from PyPI] * Tries can now be pickled. * Iterating no longer uses recursion so tries of arbitrary depth can be iterated over. The [`pygtrie.Trie.traverse`](#pygtrie.Trie.traverse) method, however, still uses recursion thus cannot be used on big structures. 1.1: 2016/01/18 * Fixed PyPI installation issues; all should work now. 1.0: 2015/12/16 * The module has been renamed from `trie` to `pygtrie`. This could break current users but see documentation for how to quickly upgrade your scripts. * Added [`pygtrie.Trie.traverse`](#pygtrie.Trie.traverse) method which goes through the nodes of the trie preserving structure of the tree. This is a depth-first traversal which can be used to search for elements or translate a trie into a different tree structure. * Minor documentation fixes. 0.9.3: 2015/05/28 * Minor documentation fixes. 0.9.2: 2015/05/28 * Added Sphinx configuration and updated docstrings to work better with Sphinx. 0.9.1: 2014/02/03 * New name. 0.9: 2014/02/03 * Initial release. ### Quick search ### Navigation * [pygtrie documentation](index.html#document-index) »
fExtremes
cran
R
Package ‘fExtremes’ October 13, 2022 Title Rmetrics - Modelling Extreme Events in Finance Date 2022-08-06 Version 4021.83 Description Provides functions for analysing and modelling extreme events in financial time Series. The topics include: (i) data pre-processing, (ii) explorative data analysis, (iii) peak over threshold modelling, (iv) block maxima modelling, (v) estimation of VaR and CVaR, and (vi) the computation of the extreme index. Depends R (>= 2.15.1) Imports fBasics, fGarch, graphics, methods, stats, timeDate, timeSeries Suggests RUnit, tcltk LazyData yes License GPL (>= 2) URL https://www.rmetrics.org BugReports https://r-forge.r-project.org/projects/rmetrics NeedsCompilation no Author <NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [cre, ctb] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2022-08-06 14:10:02 UTC R topics documented: fExtremes-packag... 2 DataPreprocessin... 6 ExtremeInde... 9 ExtremesDat... 11 GevDistributio... 15 GevMdaEstimatio... 17 GevModellin... 21 GevRis... 25 GpdDistributio... 28 GpdModellin... 30 gpdRis... 34 TimeSeriesDat... 38 ValueAtRis... 38 fExtremes-package Modelling Extreme Events in Finance Description The Rmetrics "fExtremes" package is a collection of functions to analyze and model extreme events in Finance and Insurance. Details Package: \tab fExtremes\cr Type: \tab Package\cr License: \tab GPL Version 2 or later\cr Copyright: \tab (c) 1999-2014 Rmetrics Assiciation\cr URL: \tab \url{https://www.rmetrics.org} 1 Introduction The fExtremes package provides functions for analyzing and modeling extreme events in financial time Series. The topics include: (i) data pre-processing, (ii) explorative data analysis, (iii) peak over threshold modeling, (iv) block maxima modeling, (v) estimation of VaR and CVaR, and (vi) the computation of the extreme index. 2 Data and their Preprocessing Data Sets: Data sets used in the examples of the timeSeries packages. Data Preprocessing: These are tools for data preprocessing, including functions to separate data beyond a threshold value, to compute blockwise data like block maxima, and to decluster point process data. blockMaxima extracts block maxima from a vector or a time series findThreshold finds upper threshold for a given number of extremes pointProcess extracts peaks over Threshold from a vector or a time series deCluster de-clusters clustered point process data 2 Explorative Data Analysis of Extremes This section contains a collection of functions for explorative data analysis of extreme values in financial time series. The tools include plot functions for emprical distributions, quantile plots, graphs exploring the properties of exceedances over a threshold, plots for mean/sum ratio and for the development of records. The functions are: emdPlot plots of empirical distribution function qqparetoPlot exponential/Pareto quantile plot mePlot plot of mean excesses over a threshold mrlPlot another variant, mean residual life plot mxfPlot another variant, with confidence intervals msratioPlot plot of the ratio of maximum and sum recordsPlot Record development compared with iid data ssrecordsPlot another variant, investigates subsamples sllnPlot verifies Kolmogorov's strong law of large numbers lilPlot verifies Hartman-Wintner's law of the iterated logarithm xacfPlot plots ACF of exceedances over a threshold Parameter Fitting of Mean Excesses: normMeanExcessFit fits mean excesses with a normal density ghMeanExcessFit fits mean excesses with a GH density hypMeanExcessFit fits mean excesses with a HYP density nigMeanExcessFit fits mean excesses with a NIG density ghtMeanExcessFit fits mean excesses with a GHT density 3 GPD Peak over Threshold Modeling GPD Distribution: A collection of functions to compute the generalized Pareto distribution. The functions compute density, distribution function, quantile function and generate random deviates for the GPD. In ad- dition functions to compute the true moments and to display the distribution and random variates changing parameters interactively are available. dgpd returns the density of the GPD distribution pgpd returns the probability function of the GPD qgpd returns quantile function of the GPD distribution rgpd generates random variates from the GPD distribution gpdSlider displays density or rvs from a GPD GPD Moments: gpdMoments computes true mean and variance of GDP GPD Parameter Estimation: This section contains functions to fit and to simulate processes that are generated from the gen- eralized Pareto distribution. Two approaches for parameter estimation are provided: Maximum likelihood estimation and the probability weighted moment method. gpdSim generates data from the GPD distribution gpdFit fits data to the GPD istribution GPD print, plot and summary methods: print print method for a fitted GPD object plot plot method for a fitted GPD object summary summary method for a fitted GPD object GDP Tail Risk: The following functions compute tail risk under the GPD approach. gpdQPlot estimation of high quantiles gpdQuantPlot variation of high quantiles with threshold gpdRiskMeasures prescribed quantiles and expected shortfalls gpdSfallPlot expected shortfall with confidence intervals gpdShapePlot variation of GPD shape with threshold gpdTailPlot plot of the GPD tail 4 GEV Block Maxima Modeling GEV Distribution: This section contains functions to fit and to simulate processes that are generated from the general- ized extreme value distribution including the Frechet, Gumbel, and Weibull distributions. dgev returns density of the GEV distribution pgev returns probability function of the GEV qgev returns quantile function of the GEV distribution rgev generates random variates from the GEV distribution gevSlider displays density or rvs from a GEV GEV Moments: gevMoments computes true mean and variance GEV Parameter Estimation: A collection to simulate and to estimate the parameters of processes generated from GEV distribu- tion. gevSim generates data from the GEV distribution gumbelSim generates data from the Gumbel distribution gevFit fits data to the GEV distribution gumbelFit fits data to the Gumbel distribution print print method for a fitted GEV object plot plot method for a fitted GEV object summary summary method for a fitted GEV object GEV MDA Estimation: Here we provide Maximum Domain of Attraction estimators and visualize the results by a Hill plot and a common shape parameter plot from the Pickands, Einmal-Decker-deHaan, and Hill estima- tors. hillPlot shape parameter and Hill estimate of the tail index shaparmPlot variation of shape parameter with tail depth GEV Risk Estimation: gevrlevelPlot k-block return level with confidence intervals 4 Value at Risk Two functions to compute Value-at-Risk and conditional Value-at-Risk. VaR computes Value-at-Risk CVaR computes conditional Value-at-Risk 5 Extreme Index A collection of functions to simulate time series with a known extremal index, and to estimate the extremal index by four different kind of methods, the blocks method, the reciprocal mean cluster size method, the runs method, and the method of Ferro and Segers. thetaSim simulates a time Series with known theta blockTheta computes theta from Block Method clusterTheta computes theta from Reciprocal Cluster Method runTheta computes theta from Run Method ferrosegersTheta computes theta according to Ferro and Segers exindexPlot calculatess and plots Theta(1,2,3) exindexesPlot calculates Theta(1,2) and plots Theta(1) About Rmetrics The fExtremes Rmetrics package is written for educational support in teaching "Computational Finance and Financial Engineering" and licensed under the GPL. DataPreprocessing Extremes Data Preprocessing Description A collection and description of functions for data preprocessing of extreme values. This includes tools to separate data beyond a threshold value, to compute blockwise data like block maxima, and to decluster point process data. The functions are: blockMaxima Block Maxima from a vector or a time series, findThreshold Upper threshold for a given number of extremes, pointProcess Peaks over Threshold from a vector or a time series, deCluster Declusters clustered point process data. Usage blockMaxima(x, block = c("monthly", "quarterly"), doplot = FALSE) findThreshold(x, n = floor(0.05*length(as.vector(x))), doplot = FALSE) pointProcess(x, u = quantile(x, 0.95), doplot = FALSE) deCluster(x, run = 20, doplot = TRUE) Arguments block the block size. A numeric value is interpreted as the number of data values in each successive block. All the data is used, so the last block may not contain block observations. If the data has a times attribute containing (in an ob- ject of class "POSIXct", or an object that can be converted to that class, see as.POSIXct) the times/dates of each observation, then block may instead take the character values "month", "quarter", "semester" or "year". By default monthly blocks from daily data are assumed. doplot a logical value. Should the results be plotted? By default TRUE. n a numeric value or vector giving number of extremes above the threshold. By default, n is set to an integer representing 5% of the data from the whole data set x. run parameter to be used in the runs method; any two consecutive threshold ex- ceedances separated by more than this number of observations/days are consid- ered to belong to different clusters. u a numeric value at which level the data are to be truncated. By default the threshold value which belongs to the 95% quantile, u=quantile(x,0.95). x a numeric data vector from which findThreshold and blockMaxima determine the threshold values and block maxima values. For the function deCluster the argument x represents a numeric vector of threshold exceedances with a times attribute which should be a numeric vector containing either the indices or the times/dates of each exceedance (if times/dates, the attribute should be an object of class "POSIXct" or an object that can be converted to that class; see as.POSIXct). Details Computing Block Maxima: The function blockMaxima calculates block maxima from a vector or a time series, whereas the function blocks is more general and allows for the calculation of an arbitrary function FUN on blocks. Finding Thresholds: The function findThreshold finds a threshold so that a given number of extremes lie above. When the data are tied a threshold is found so that at least the specified number of extremes lie above. De-Clustering Point Processes: The function deCluster declusters clustered point process data so that Poisson assumption is more tenable over a high threshold. Value blockMaxima returns a timeSeries object or a numeric vector of block maxima data. findThreshold returns a numeric value or vector of suitable thresholds. pointProcess returns a timeSeries object or a numeric vector of peaks over a threshold. deCluster returns a timeSeries object or a numeric vector for the declustered point process. Author(s) Some of the functions were implemented from Alec Stephenson’s R-package evir ported from <NAME>’s S library EVIS, Extreme Values in S, some from Alec Stephenson’s R-package ismev based on Stuart Coles code from his book, Introduction to Statistical Modeling of Extreme Values and some were written by <NAME>. References <NAME>. (2001); Introduction to Statistical Modelling of Extreme Values, Springer. <NAME>., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Examples ## findThreshold - # Threshold giving (at least) fifty exceedances for Danish data: library(timeSeries) x <- as.timeSeries(data(danishClaims)) findThreshold(x, n = c(10, 50, 100)) ## blockMaxima - # Block Maxima (Minima) for left tail of BMW log returns: BMW <- as.timeSeries(data(bmwRet)) colnames(BMW) <- "BMW.RET" head(BMW) x <- blockMaxima( BMW, block = 65) head(x) ## Not run: y <- blockMaxima(-BMW, block = 65) head(y) y <- blockMaxima(-BMW, block = "monthly") head(y) ## End(Not run) ## pointProcess - # Return Values above threshold in negative BMW log-return data: PP = pointProcess(x = -BMW, u = quantile(as.vector(x), 0.75)) PP nrow(PP) ## deCluster - # Decluster the 200 exceedances of a particular DC = deCluster(x = PP, run = 15, doplot = TRUE) DC nrow(DC) ExtremeIndex Extremal Index Estimation Description A collection and description of functions to simulate time series with a known extremal index, and to estimate the extremal index by four different kind of methods, the blocks method, the reciprocal mean cluster size method, the runs method, and the method of Ferro and Segers. The functions are: thetaSim Simulates a time Series with known theta, blockTheta Computes theta from Block Method, clusterTheta Computes theta from Reciprocal Cluster Method, runTheta Computes theta from Run Method, ferrosegersTheta Computes Theta according to Ferro and Segers, exindexPlot Calculate and Plot Theta(1,2,3), exindexesPlot Calculate Theta(1,2) and Plot Theta(1). Usage ## S4 method for signature 'fTHETA' show(object) thetaSim(model = c("max", "pair"), n = 1000, theta = 0.5) blockTheta(x, block = 22, quantiles = seq(0.950, 0.995, length = 10), title = NULL, description = NULL) clusterTheta(x, block = 22, quantiles = seq(0.950, 0.995, length = 10), title = NULL, description = NULL) runTheta(x, block = 22, quantiles = seq(0.950, 0.995, length = 10), title = NULL, description = NULL) ferrosegersTheta(x, quantiles = seq(0.950, 0.995, length = 10), title = NULL, description = NULL) exindexPlot(x, block = c("monthly", "quarterly"), start = 5, end = NA, doplot = TRUE, plottype = c("thresh", "K"), labels = TRUE, ...) exindexesPlot(x, block = 22, quantiles = seq(0.950, 0.995, length = 10), doplot = TRUE, labels = TRUE, ...) Arguments block [*Theta] - an integer value, the block size. Currently only integer specified block sizes are supported. [exindex*Plot] - the block size. Either "monthly", "quarterly" or an integer value. An integer value is interpreted as the number of data values in each successive block. The default value is "monthly" which corresponds for daily data to an approximately 22-day periods. description a character string which allows for a brief description. doplot a logical, should the results be plotted? labels whether or not axes should be labelled. If set to FALSE then user specified labels can be passed through the "..." argument. model [thetaSim] - a character string denoting the name of the model. Either "max" or "pair", the first representing the maximimum Frechet series, and the second the paired exponential series. n [thetaSim] - an integer value, the length of the time series to be generated. object an object of class "fTHETA" as returned by the functions *Theta. plottype [exindexPlot] - whether plot is to be by increasing threshold (thresh) or increasing K value (K). quantiles [exindexesPlot] - a numeric vector of quantile values. start, end [exindexPlot] - start is the lowest value of K at which to plot a point, and end the highest value; K is the number of blocks in which a specified threshold is exceeded. theta [thetaSim] - a numeric value between 0 and 1 setting the value of the extremal index for the maximum Frechet time series. (Not used in the case of the paired exponential series.) title a character string which allows for a project title. x a ’timeSeries’ object or any other object which can be transformed by the func- tion as.vector into a numeric vector. "monthly" and "quarterly" blocks require x to be an object of class "timeSeries". ... additional arguments passed to the plot function. Value exindexPlot returns a data frame of results with the following columns: N, K, un, theta2, and theta. A plot with K on the lower x-axis and threshold Values on the upper x-axis versus the extremal index is displayed. exindexesPlot returns a data.frame with four columns: thresholds, theta1, theta2, and theta3. A plot with quantiles on the x-axis and versus the extremal indexes is displayed. Author(s) <NAME>, for parts of the exindexPlot function, and <NAME> for the exindexesPlot function. References <NAME>., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Chap- ter 8, 413–429. See Also hillPlot, gevFit. Examples ## Extremal Index for the right and left tails ## of the BMW log returns: data(bmwRet) par(mfrow = c(2, 2), cex = 0.7) library(timeSeries) exindexPlot( as.timeSeries(bmwRet), block = "quarterly") exindexPlot(-as.timeSeries(bmwRet), block = "quarterly") ## Extremal Index for the right and left tails ## of the BMW log returns: exindexesPlot( as.timeSeries(bmwRet), block = 65) exindexesPlot(-as.timeSeries(bmwRet), block = 65) ExtremesData Explorative Data Analysis Description A collection and description of functions for explorative data analysis. The tools include plot func- tions for emprical distributions, quantile plots, graphs exploring the properties of exceedances over a threshold, plots for mean/sum ratio and for the development of records. The functions are: emdPlot Plot of empirical distribution function, qqparetoPlot Exponential/Pareto quantile plot, mePlot Plot of mean excesses over a threshold, mrlPlot another variant, mean residual life plot, mxfPlot another variant, with confidence intervals, msratioPlot Plot of the ratio of maximum and sum, recordsPlot Record development compared with iid data, ssrecordsPlot another variant, investigates subsamples, sllnPlot verifies Kolmogorov’s strong law of large numbers, lilPlot verifies Hartman-Wintner’s law of the iterated logarithm, xacfPlot ACF of exceedances over a threshold, normMeanExcessFit fits mean excesses with a normal density, ghMeanExcessFit fits mean excesses with a GH density, hypMeanExcessFit fits mean excesses with a HYP density, nigMeanExcessFit fits mean excesses with a NIG density, ghtMeanExcessFit fits mean excesses with a GHT density. Usage emdPlot(x, doplot = TRUE, plottype = c("xy", "x", "y", " "), labels = TRUE, ...) qqparetoPlot(x, xi = 0, trim = NULL, threshold = NULL, doplot = TRUE, labels = TRUE, ...) mePlot(x, doplot = TRUE, labels = TRUE, ...) mrlPlot(x, ci = 0.95, umin = mean(x), umax = max(x), nint = 100, doplot = TRUE, plottype = c("autoscale", ""), labels = TRUE, ...) mxfPlot(x, u = quantile(x, 0.05), doplot = TRUE, labels = TRUE, ...) msratioPlot(x, p = 1:4, doplot = TRUE, labels = TRUE, ...) recordsPlot(x, ci = 0.95, doplot = TRUE, labels = TRUE, ...) ssrecordsPlot(x, subsamples = 10, doplot = TRUE, plottype = c("lin", "log"), labels = TRUE, ...) sllnPlot(x, doplot = TRUE, labels = TRUE, ...) lilPlot(x, doplot = TRUE, labels = TRUE, ...) xacfPlot(x, u = quantile(x, 0.95), lag.max = 15, doplot = TRUE, which = c("all", 1, 2, 3, 4), labels = TRUE, ...) normMeanExcessFit(x, doplot = TRUE, trace = TRUE, ...) ghMeanExcessFit(x, doplot = TRUE, trace = TRUE, ...) hypMeanExcessFit(x, doplot = TRUE, trace = TRUE, ...) nigMeanExcessFit(x, doplot = TRUE, trace = TRUE, ...) ghtMeanExcessFit(x, doplot = TRUE, trace = TRUE, ...) Arguments ci [recordsPlot] - a confidence level. By default 0.95, i.e. 95%. doplot a logical value. Should the results be plotted? By default TRUE. labels a logical value. Whether or not x- and y-axes should be automatically labelled and a default main title should be added to the plot. By default TRUE. lag.max [xacfPlot] - maximum number of lags at which to calculate the autocorrelation functions. The default value is 15. nint [mrlPlot] - the number of intervals, see umin and umax. The default value is 100. p [msratioPlot] - the power exponents, a numeric vector. By default a sequence from 1 to 4 in unit integer steps. plottype [emdPlot] - which axes should be on a log scale: "x" x-axis only; "y" y-axis only; "xy" both axes; "" neither axis. [msratioPlot] - a logical, if set to "autoscale", then the scale of the plots are automatically determined, any other string allows user specified scale information through the ... argument. [ssrecordsPlot] - one from two options can be select either "lin" or "log". The default creates a linear plot. subsamples [ssrecordsPlot] - the number of subsamples, by default 10, an integer value. threshold, trim [qPlot][xacfPlot] - a numeric value at which data are to be left-truncated, value at which data are to be right-truncated or the threshold value, by default 95%. trace a logical flag, by default TRUE. Should the calculations be traced? u a numeric value at which level the data are to be truncated. By default the threshold value which belongs to the 95% quantile, u=quantile(x,0.95). umin, umax [mrlPlot] - range of threshold values. If umin and/or umax are not available, then by default they are set to the following values: umin=mean(x) and umax=max(x). which [xacfPlot] - a numeric or character value, if which="all" then all four plots are displayed, if which is an integer between one and four, then the first, second, third or fourth plot will be displayed. x, y numeric data vectors or in the case of x an object to be plotted. xi the shape parameter of the generalized Pareto distribution. ... additional arguments passed to the FUN or plot function. Details Empirical Distribution Function: The function emdPlot is a simple explanatory function. A straight line on the double log scale indicates Pareto tail behaviour. Quantile–Quantile Pareto Plot: qqparetoPlot creates a quantile-quantile plot for threshold data. If xi is zero the reference dis- tribution is the exponential; if xi is non-zero the reference distribution is the generalized Pareto with that parameter value expressed by xi. In the case of the exponential, the plot is interpreted as follows: Concave departures from a straight line are a sign of heavy-tailed behaviour, convex departures show thin-tailed behaviour. Mean Excess Function Plot: Three variants to plot the mean excess function are available: A sample mean excess plot over increasing thresholds, and two mean excess function plots with confidence intervals for discrimina- tion in the tails of a distribution. In general, an upward trend in a mean excess function plot shows heavy-tailed behaviour. In particular, a straight line with positive gradient above some threshold is a sign of Pareto behaviour in tail. A downward trend shows thin-tailed behaviour whereas a line with zero gradient shows an exponential tail. Here are some hints: Because upper plotting points are the average of a handful of extreme excesses, these may be omitted for a prettier plot. For mrlPlot and mxfPlot the upper tail is investigated; for the lower tail reverse the sign of the data vector. Plot of the Maximum/Sum Ratio: The ratio of maximum and sum is a simple tool for detecting heavy tails of a distribution and for giving a rough estimate of the order of its finite moments. Sharp increases in the curves of a msratioPlot are a sign for heavy tail behaviour. Plot of the Development of Records: These are functions that investigate the development of records in a dataset and calculate the ex- pected behaviour for iid data. recordsPlot counts records and reports the observations at which they occur. In addition subsamples can be investigated with the help of the function ssrecordsPlot. Plot of Kolmogorov’s and Hartman-Wintner’s Laws: The function sllnPlot verifies Kolmogorov’s strong law of large numbers, and the function lilPlot verifies Hartman-Wintner’s law of the iterated logarithm. ACF Plot of Exceedances over a Threshold: This function plots the autocorrelation functions of heights and distances of exceedances over a threshold. Value The functions return a plot. Note The plots are labeled by default with a x-label, a y-label and a main title. If the argument labels is set to FALSE neither a x-label, a y-label nor a main title will be added to the graph. To add user defined label strings just use the function title(xlab="\dots", ylab="\dots", main="\dots"). Author(s) Some of the functions were implemented from Alec Stephenson’s R-package evir ported from <NAME>’s S library EVIS, Extreme Values in S, some from Alec Stephenson’s R-package ismev based on <NAME> code from his book, Introduction to Statistical Modeling of Extreme Values and some were written by <NAME>. References <NAME>. (2001); Introduction to Statistical Modelling of Extreme Values, Springer. Embrechts, P., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Examples ## Danish fire insurance data: data(danishClaims) library(timeSeries) danishClaims = as.timeSeries(danishClaims) ## emdPlot - # Show Pareto tail behaviour: par(mfrow = c(2, 2), cex = 0.7) emdPlot(danishClaims) ## qqparetoPlot - # QQ-Plot of heavy-tailed Danish fire insurance data: qqparetoPlot(danishClaims, xi = 0.7) ## mePlot - # Sample mean excess plot of heavy-tailed Danish fire: mePlot(danishClaims) ## ssrecordsPlot - # Record fire insurance losses in Denmark: ssrecordsPlot(danishClaims, subsamples = 10) GevDistribution Generalized Extreme Value Distribution Description Density, distribution function, quantile function, random number generation, and true moments for the GEV including the Frechet, Gumbel, and Weibull distributions. The GEV distribution functions are: dgev density of the GEV distribution, pgev probability function of the GEV distribution, qgev quantile function of the GEV distribution, rgev random variates from the GEV distribution, gevMoments computes true mean and variance, gevSlider displays density or rvs from a GEV. Usage dgev(x, xi = 1, mu = 0, beta = 1, log = FALSE) pgev(q, xi = 1, mu = 0, beta = 1, lower.tail = TRUE) qgev(p, xi = 1, mu = 0, beta = 1, lower.tail = TRUE) rgev(n, xi = 1, mu = 0, beta = 1) gevMoments(xi = 0, mu = 0, beta = 1) gevSlider(method = c("dist", "rvs")) Arguments log a logical, if TRUE, the log density is returned. lower.tail a logical, if TRUE, the default, then probabilities are P[X <= x], otherwise, P[X > x]. method a character string denoting what should be displayed. Either the density and "dist" or random variates "rvs". n the number of observations. p a numeric vector of probabilities. [hillPlot] - probability required when option quantile is chosen. q a numeric vector of quantiles. x a numeric vector of quantiles. xi, mu, beta xi is the shape parameter, mu the location parameter, and beta is the scale pa- rameter. The default values are xi=1, mu=0, and beta=1. Note, if xi=0 the distribution is of type Gumbel. Value d* returns the density, p* returns the probability, q* returns the quantiles, and r* generates random variates. All values are numeric vectors. Author(s) <NAME> for R’s evd and evir package, and <NAME> for this R-port. References <NAME>. (2001); Introduction to Statistical Modelling of Extreme Values, Springer. Embrechts, P., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Examples ## rgev - # Create and plot 1000 Weibull distributed rdv: r = rgev(n = 1000, xi = -1) plot(r, type = "l", col = "steelblue", main = "Weibull Series") grid() ## dgev - # Plot empirical density and compare with true density: hist(r[abs(r)<10], nclass = 25, freq = FALSE, xlab = "r", xlim = c(-5,5), ylim = c(0,1.1), main = "Density") box() x = seq(-5, 5, by = 0.01) lines(x, dgev(x, xi = -1), col = "steelblue") ## pgev - # Plot df and compare with true df: plot(sort(r), (1:length(r)/length(r)), xlim = c(-3, 6), ylim = c(0, 1.1), cex = 0.5, ylab = "p", xlab = "q", main = "Probability") grid() q = seq(-5, 5, by = 0.1) lines(q, pgev(q, xi = -1), col = "steelblue") ## qgev - # Compute quantiles, a test: qgev(pgev(seq(-5, 5, 0.25), xi = -1), xi = -1) ## gevMoments: # Returns true mean and variance: gevMoments(xi = 0, mu = 0, beta = 1) ## Slider: # gevSlider(method = "dist") # gevSlider(method = "rvs") GevMdaEstimation Generalized Extreme Value Modelling Description A collection and description functions to estimate the parameters of the GEV distribution. To model the GEV three types of approaches for parameter estimation are provided: Maximum likelihood estimation, probability weighted moment method, and estimation by the MDA approach. MDA in- cludes functions for the Pickands, Einmal-Decker-deHaan, and Hill estimators together with several plot variants. Maximum Domain of Attraction estimators: hillPlot shape parameter and Hill estimate of the tail index, shaparmPlot variation of shape parameter with tail depth. Usage hillPlot(x, start = 15, ci = 0.95, doplot = TRUE, plottype = c("alpha", "xi"), labels = TRUE, ...) shaparmPlot(x, p = 0.01*(1:10), xiRange = NULL, alphaRange = NULL, doplot = TRUE, plottype = c("both", "upper")) shaparmPickands(x, p = 0.05, xiRange = NULL, doplot = TRUE, plottype = c("both", "upper"), labels = TRUE, ...) shaparmHill(x, p = 0.05, xiRange = NULL, doplot = TRUE, plottype = c("both", "upper"), labels = TRUE, ...) shaparmDEHaan(x, p = 0.05, xiRange = NULL, doplot = TRUE, plottype = c("both", "upper"), labels = TRUE, ...) Arguments alphaRange, xiRange [saparmPlot] - plotting ranges for alpha and xi. By default the values are automatically se- lected. ci [hillPlot] - probability for asymptotic confidence band; for no confidence band set ci to zero. doplot a logical. Should the results be plotted? [shaparmPlot] - a vector of logicals of the same lengths as tails defining for which tail depths plots should be created, by default plots will be generated for a tail depth of 5 percent. By default c(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE). labels [hillPlot] - whether or not axes should be labelled. plottype [hillPlot] - whether alpha, xi (1/alpha) or quantile (a quantile estimate) should be plot- ted. p [qgev] - a numeric vector of probabilities. [hillPlot] - probability required when option quantile is chosen. start [hillPlot] - lowest number of order statistics at which to plot a point. x [dgev][devd] - a numeric vector of quantiles. [gevFit] - data vector. In the case of method="mle" the interpretation depends on the value of block: if no block size is specified then data are interpreted as block maxima; if block size is set, then data are interpreted as raw data and block maxima are calculated. [hillPlot][shaparmPlot] - the data from which to calculate the shape parameter, a numeric vector. [print][plot] - a fitted object of class "gevFit". ... [gevFit] - control parameters optionally passed to the optimization function. Parameters for the optimization function are passed to components of the control argument of optim. [hillPlot] - other graphics parameters. [plot][summary] - arguments passed to the plot function. Details Parameter Estimation: gevFit and gumbelFit estimate the parameters either by the probability weighted moment method, method="pwm" or by maximum log likelihood estimation method="mle". The summary method produces diagnostic plots for fitted GEV or Gumbel models. Methods: print.gev, plot.gev and summary.gev are print, plot, and summary methods for a fitted object of class gev. Concerning the summary method, the data are converted to unit exponentially distributed residuals under null hypothesis that GEV fits. Two diagnostics for iid exponential data are offered. The plot method provides two different residual plots for assessing the fitted GEV model. Two diagnostics for iid exponential data are offered. Return Level Plot: gevrlevelPlot calculates and plots the k-block return level and 95% confidence interval based on a GEV model for block maxima, where k is specified by the user. The k-block return level is that level exceeded once every k blocks, on average. The GEV likelihood is reparameterized in terms of the unknown return level and profile likelihood arguments are used to construct a confidence interval. Hill Plot: The function hillPlot investigates the shape parameter and plots the Hill estimate of the tail index of heavy-tailed data, or of an associated quantile estimate. This plot is usually calculated from the alpha perspective. For a generalized Pareto analysis of heavy-tailed data using the gpdFit function, it helps to plot the Hill estimates for xi. Shape Parameter Plot: The function shaparmPlot investigates the shape parameter and plots for the upper and lower tails the shape parameter as a function of the taildepth. Three approaches are considered, the Pickands estimator, the Hill estimator, and the Decker-Einmal-deHaan estimator. Value gevSim returns a vector of data points from the simulated series. gevFit returns an object of class gev describing the fit. print.summary prints a report of the parameter fit. summary performs diagnostic analysis. The method provides two different residual plots for assessing the fitted GEV model. gevrlevelPlot returns a vector containing the lower 95% bound of the confidence interval, the estimated return level and the upper 95% bound. hillPlot displays a plot. shaparmPlot returns a list with one or two entries, depending on the selection of the input variable both.tails. The two entries upper and lower determine the position of the tail. Each of the two variables is again a list with entries pickands, hill, and dehaan. If one of the three methods will be discarded the printout will display zeroes. Note GEV Parameter Estimation: If method "mle" is selected the parameter fitting in gevFit is passed to the internal function gev.mle or gumbel.mle depending on the value of gumbel, FALSE or TRUE. On the other hand, if method "pwm" is selected the parameter fitting in gevFit is passed to the internal function gev.pwm or gumbel.pwm again depending on the value of gumbel, FALSE or TRUE. Author(s) <NAME> for R’s evd and evir package, and <NAME> for this R-port. References <NAME>. (2001); Introduction to Statistical Modelling of Extreme Values, Springer. Embrechts, P., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Examples ## Load Data: library(timeSeries) x = as.timeSeries(data(danishClaims)) colnames(x) <- "Danish" head(x) ## hillPlot - # Hill plot of heavy-tailed Danish fire insurance data par(mfrow = c(1, 1)) hillPlot(x, plottype = "xi") grid() GevModelling Generalized Extreme Value Modelling Description A collection and description functions to estimate the parameters of the GEV distribution. To model the GEV three types of approaches for parameter estimation are provided: Maximum likelihood estimation, probability weighted moment method, and estimation by the MDA approach. MDA in- cludes functions for the Pickands, Einmal-Decker-deHaan, and Hill estimators together with several plot variants. The GEV modelling functions are: gevSim generates data from the GEV distribution, gumbelSim generates data from the Gumbel distribution, gevFit fits data to the GEV distribution, gumbelFit fits data to the Gumbel distribution, print print method for a fitted GEV object, plot plot method for a fitted GEV object, summary summary method for a fitted GEV object, gevrlevelPlot k-block return level with confidence intervals. Usage gevSim(model = list(xi = -0.25, mu = 0, beta = 1), n = 1000, seed = NULL) gumbelSim(model = list(mu = 0, beta = 1), n = 1000, seed = NULL) gevFit(x, block = 1, type = c("mle", "pwm"), title = NULL, description = NULL, ...) gumbelFit(x, block = 1, type = c("mle", "pwm"), title = NULL, description = NULL, ...) ## S4 method for signature 'fGEVFIT' show(object) ## S3 method for class 'fGEVFIT' plot(x, which = "ask", ...) ## S3 method for class 'fGEVFIT' summary(object, doplot = TRUE, which = "all", ...) Arguments block block size. description a character string which allows for a brief description. doplot a logical. Should the results be plotted? [shaparmPlot] - a vector of logicals of the same lengths as tails defining for which tail depths plots should be created, by default plots will be generated for a tail depth of 5 percent. By default c(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE). model [gevSim][gumbelSim] - a list with components shape, location and scale giving the parameters of the GEV distribution. By default the shape parameter has the value -0.25, the location is zero and the scale is one. To fit random deviates from a Gumbel distribution set shape=0. n [gevSim][gumbelSim] - number of generated data points, an integer value. [rgev] - the number of observations. object [summary][grlevelPlot] - a fitted object of class "gevFit". seed [gevSim] - an integer value to set the seed for the random number generator. title [gevFit] - a character string which allows for a project title. type a character string denoting the type of parameter estimation, either by maximum likelihood estimation "mle", the default value, or by the probability weighted moment method "pwm". which [plot][summary] - a vector of logicals, one for each plot, denoting which plot should be displayed. Alternatively if which="ask" the user will be interactively asked which of the plots should be displayed. By default which="all". x [dgev][devd] - a numeric vector of quantiles. [gevFit] - data vector. In the case of method="mle" the interpretation depends on the value of block: if no block size is specified then data are interpreted as block maxima; if block size is set, then data are interpreted as raw data and block maxima are calculated. [hillPlot][shaparmPlot] - the data from which to calculate the shape parameter, a numeric vector. [print][plot] - a fitted object of class "gevFit". xi, mu, beta [*gev] - xi is the shape parameter, mu the location parameter, and beta is the scale pa- rameter. The default values are xi=1, mu=0, and beta=1. Note, if xi=0 the distribution is of type Gumbel. ... [gevFit] - control parameters optionally passed to the optimization function. Parameters for the optimization function are passed to components of the control argument of optim. [hillPlot] - other graphics parameters. [plot][summary] - arguments passed to the plot function. Details Parameter Estimation: gevFit and gumbelFit estimate the parameters either by the probability weighted moment method, method="pwm" or by maximum log likelihood estimation method="mle". The summary method produces diagnostic plots for fitted GEV or Gumbel models. Methods: print.gev, plot.gev and summary.gev are print, plot, and summary methods for a fitted object of class gev. Concerning the summary method, the data are converted to unit exponentially distributed residuals under null hypothesis that GEV fits. Two diagnostics for iid exponential data are offered. The plot method provides two different residual plots for assessing the fitted GEV model. Two diagnostics for iid exponential data are offered. Return Level Plot: gevrlevelPlot calculates and plots the k-block return level and 95% confidence interval based on a GEV model for block maxima, where k is specified by the user. The k-block return level is that level exceeded once every k blocks, on average. The GEV likelihood is reparameterized in terms of the unknown return level and profile likelihood arguments are used to construct a confidence interval. Hill Plot: The function hillPlot investigates the shape parameter and plots the Hill estimate of the tail index of heavy-tailed data, or of an associated quantile estimate. This plot is usually calculated from the alpha perspective. For a generalized Pareto analysis of heavy-tailed data using the gpdFit function, it helps to plot the Hill estimates for xi. Shape Parameter Plot: The function shaparmPlot investigates the shape parameter and plots for the upper and lower tails the shape parameter as a function of the taildepth. Three approaches are considered, the Pickands estimator, the Hill estimator, and the Decker-Einmal-deHaan estimator. Value gevSim returns a vector of data points from the simulated series. gevFit returns an object of class gev describing the fit. print.summary prints a report of the parameter fit. summary performs diagnostic analysis. The method provides two different residual plots for assessing the fitted GEV model. gevrlevelPlot returns a vector containing the lower 95% bound of the confidence interval, the estimated return level and the upper 95% bound. hillPlot displays a plot. shaparmPlot returns a list with one or two entries, depending on the selection of the input variable both.tails. The two entries upper and lower determine the position of the tail. Each of the two variables is again a list with entries pickands, hill, and dehaan. If one of the three methods will be discarded the printout will display zeroes. Note GEV Parameter Estimation: If method "mle" is selected the parameter fitting in gevFit is passed to the internal function gev.mle or gumbel.mle depending on the value of gumbel, FALSE or TRUE. On the other hand, if method "pwm" is selected the parameter fitting in gevFit is passed to the internal function gev.pwm or gumbel.pwm again depending on the value of gumbel, FALSE or TRUE. Author(s) <NAME> for R’s evd and evir package, and <NAME> for this R-port. References <NAME>. (2001); Introduction to Statistical Modelling of Extreme Values, Springer. Embrechts, P., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Examples ## gevSim - # Simulate GEV Data, use default length n=1000 x = gevSim(model = list(xi = 0.25, mu = 0 , beta = 1), n = 1000) head(x) ## gumbelSim - # Simulate GEV Data, use default length n=1000 x = gumbelSim(model = list(xi = 0.25, mu = 0 , beta = 1)) ## gevFit - # Fit GEV Data by Probability Weighted Moments: fit = gevFit(x, type = "pwm") print(fit) ## summary - # Summarize Results: par(mfcol = c(2, 2)) summary(fit) GevRisk Generalized Extreme Value Modelling Description A collection and description functions to estimate the parameters of the GEV distribution. To model the GEV three types of approaches for parameter estimation are provided: Maximum likelihood estimation, probability weighted moment method, and estimation by the MDA approach. MDA in- cludes functions for the Pickands, Einmal-Decker-deHaan, and Hill estimators together with several plot variants. The GEV modelling functions are: gevrlevelPlot k-block return level with confidence intervals. Usage gevrlevelPlot(object, kBlocks = 20, ci = c(0.90, 0.95, 0.99), plottype = c("plot", "add"), labels = TRUE,...) Arguments add [gevrlevelPlot] - whether the return level should be added graphically to a time series plot; if FALSE a graph of the profile likelihood curve showing the return level and its confidence interval is produced. ci [hillPlot] - probability for asymptotic confidence band; for no confidence band set ci to zero. kBlocks [gevrlevelPlot] - specifies the particular return level to be estimated; default set arbitrarily to 20. labels [hillPlot] - whether or not axes should be labelled. object [summary][grlevelPlot] - a fitted object of class "gevFit". plottype [hillPlot] - whether alpha, xi (1/alpha) or quantile (a quantile estimate) should be plot- ted. ... arguments passed to the plot function. Details Parameter Estimation: gevFit and gumbelFit estimate the parameters either by the probability weighted moment method, method="pwm" or by maximum log likelihood estimation method="mle". The summary method produces diagnostic plots for fitted GEV or Gumbel models. Methods: print.gev, plot.gev and summary.gev are print, plot, and summary methods for a fitted object of class gev. Concerning the summary method, the data are converted to unit exponentially distributed residuals under null hypothesis that GEV fits. Two diagnostics for iid exponential data are offered. The plot method provides two different residual plots for assessing the fitted GEV model. Two diagnostics for iid exponential data are offered. Return Level Plot: gevrlevelPlot calculates and plots the k-block return level and 95% confidence interval based on a GEV model for block maxima, where k is specified by the user. The k-block return level is that level exceeded once every k blocks, on average. The GEV likelihood is reparameterized in terms of the unknown return level and profile likelihood arguments are used to construct a confidence interval. Hill Plot: The function hillPlot investigates the shape parameter and plots the Hill estimate of the tail index of heavy-tailed data, or of an associated quantile estimate. This plot is usually calculated from the alpha perspective. For a generalized Pareto analysis of heavy-tailed data using the gpdFit function, it helps to plot the Hill estimates for xi. Shape Parameter Plot: The function shaparmPlot investigates the shape parameter and plots for the upper and lower tails the shape parameter as a function of the taildepth. Three approaches are considered, the Pickands estimator, the Hill estimator, and the Decker-Einmal-deHaan estimator. Value gevSim returns a vector of data points from the simulated series. gevFit returns an object of class gev describing the fit. print.summary prints a report of the parameter fit. summary performs diagnostic analysis. The method provides two different residual plots for assessing the fitted GEV model. gevrlevelPlot returns a vector containing the lower 95% bound of the confidence interval, the estimated return level and the upper 95% bound. hillPlot displays a plot. shaparmPlot returns a list with one or two entries, depending on the selection of the input variable both.tails. The two entries upper and lower determine the position of the tail. Each of the two variables is again a list with entries pickands, hill, and dehaan. If one of the three methods will be discarded the printout will display zeroes. Note GEV Parameter Estimation: If method "mle" is selected the parameter fitting in gevFit is passed to the internal function gev.mle or gumbel.mle depending on the value of gumbel, FALSE or TRUE. On the other hand, if method "pwm" is selected the parameter fitting in gevFit is passed to the internal function gev.pwm or gumbel.pwm again depending on the value of gumbel, FALSE or TRUE. Author(s) <NAME> for R’s evd and evir package, and <NAME> for this R-port. References Coles S. (2001); Introduction to Statistical Modelling of Extreme Values, Springer. Embrechts, P., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Examples ## Load Data: # BMW Stock Data - negative returns library(timeSeries) x = -as.timeSeries(data(bmwRet)) colnames(x)<-"BMW" head(x) ## gevFit - # Fit GEV to monthly Block Maxima: fit = gevFit(x, block = "month") print(fit) ## gevrlevelPlot - # Return Level Plot: gevrlevelPlot(fit) GpdDistribution Generalized Pareto Distribution Description A collection and description of functions to compute the generalized Pareto distribution. The func- tions compute density, distribution function, quantile function and generate random deviates for the GPD. In addition functions to compute the true moments and to display the distribution and random variates changing parameters interactively are available. The GPD distribution functions are: dgpd Density of the GPD Distribution, pgpd Probability function of the GPD Distribution, qgpd Quantile function of the GPD Distribution, rgpd random variates from the GPD distribution, gpdMoments computes true mean and variance, gpdSlider displays density or rvs from a GPD. Usage dgpd(x, xi = 1, mu = 0, beta = 1, log = FALSE) pgpd(q, xi = 1, mu = 0, beta = 1, lower.tail = TRUE) qgpd(p, xi = 1, mu = 0, beta = 1, lower.tail = TRUE) rgpd(n, xi = 1, mu = 0, beta = 1) gpdMoments(xi = 1, mu = 0, beta = 1) gpdSlider(method = c("dist", "rvs")) Arguments log a logical, if TRUE, the log density is returned. lower.tail a logical, if TRUE, the default, then probabilities are P[X <= x], otherwise, P[X > x]. method [gpdSlider] - a character string denoting what should be displayed. Either the density and "dist" or random variates "rvs". n [rgpd][gpdSim\ - the number of observations to be generated. p a vector of probability levels, the desired probability for the quantile estimate (e.g. 0.99 for the 99th percentile). q [pgpd] - a numeric vector of quantiles. x [dgpd] - a numeric vector of quantiles. xi, mu, beta xi is the shape parameter, mu the location parameter, and beta is the scale pa- rameter. Value All values are numeric vectors: d* returns the density, p* returns the probability, q* returns the quantiles, and r* generates random deviates. Author(s) <NAME> for the functions from R’s evd package, <NAME> for the functions from R’s evir package, <NAME> for the EVIS functions underlying the evir package, <NAME> for this R-port. References <NAME>., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. Examples ## rgpd - par(mfrow = c(2, 2), cex = 0.7) r = rgpd(n = 1000, xi = 1/4) plot(r, type = "l", col = "steelblue", main = "GPD Series") grid() ## dgpd - # Plot empirical density and compare with true density: # Omit values greater than 500 from plot hist(r, n = 50, probability = TRUE, xlab = "r", col = "steelblue", border = "white", xlim = c(-1, 5), ylim = c(0, 1.1), main = "Density") box() x = seq(-5, 5, by = 0.01) lines(x, dgpd(x, xi = 1/4), col = "orange") ## pgpd - # Plot df and compare with true df: plot(sort(r), (1:length(r)/length(r)), xlim = c(-3, 6), ylim = c(0, 1.1), pch = 19, cex = 0.5, ylab = "p", xlab = "q", main = "Probability") grid() q = seq(-5, 5, by = 0.1) lines(q, pgpd(q, xi = 1/4), col = "steelblue") ## qgpd - # Compute quantiles, a test: qgpd(pgpd(seq(-1, 5, 0.25), xi = 1/4 ), xi = 1/4) GpdModelling GPD Distributions for Extreme Value Theory Description A collection and description to functions to fit and to simulate processes that are generated from the generalized Pareto distribution. Two approaches for parameter estimation are provided: Maximum likelihood estimation and the probability weighted moment method. The GPD modelling functions are: gpdSim generates data from the GPD, gpdFit fits empirical or simulated data to the distribution, print print method for a fitted GPD object of class ..., plot plot method for a fitted GPD object, summary summary method for a fitted GPD object. Usage gpdSim(model = list(xi = 0.25, mu = 0, beta = 1), n = 1000, seed = NULL) gpdFit(x, u = quantile(x, 0.95), type = c("mle", "pwm"), information = c("observed", "expected"), title = NULL, description = NULL, ...) ## S4 method for signature 'fGPDFIT' show(object) ## S3 method for class 'fGPDFIT' plot(x, which = "ask", ...) ## S3 method for class 'fGPDFIT' summary(object, doplot = TRUE, which = "all", ...) Arguments description a character string which allows for a brief description. doplot a logical. Should the results be plotted? information whether standard errors should be calculated with "observed" or "expected" information. This only applies to the maximum likelihood method; for the probability-weighted moments method "expected" information is used if pos- sible. model [gpdSim] - a list with components shape, location and scale giving the parameters of the GPD distribution. By default the shape parameter has the value 0.25, the location is zero and the scale is one. n [rgpd][gpdSim\ - the number of observations to be generated. object [summary] - a fitted object of class "gpdFit". seed [gpdSim] - an integer value to set the seed for the random number generator. title a character string which allows for a project title. type a character string selecting the desired estimation method, either "mle" for the maximum likelihood method or "pwm" for the probability weighted moment method. By default, the first will be selected. Note, the function gpd uses "ml". u the threshold value. which if which is set to "ask" the function will interactively ask which plot should be displayed. By default this value is set to FALSE and then those plots will be displayed for which the elements in the logical vector which ar set to TRUE; by default all four elements are set to "all". x [dgpd] - a numeric vector of quantiles. [gpdFit] - the data vector. Note, there are two different names for the first argument x and data depending which function name is used, either gpdFit or the EVIS synonym gpd. [print][plot] - a fitted object of class "gpdFit". xi, mu, beta xi is the shape parameter, mu the location parameter, and beta is the scale pa- rameter. ... control parameters and plot parameters optionally passed to the optimization and/or plot function. Parameters for the optimization function are passed to components of the control argument of optim. Details Generalized Pareto Distribution: Compute density, distribution function, quantile function and generates random variates for the Generalized Pareto Distribution. Simulation: gpdSim simulates data from a Generalized Pareto distribution. Parameter Estimation: gpdFit fits the model parameters either by the probability weighted moment method or the maxim log likelihood method. The function returns an object of class "gpd" representing the fit of a gen- eralized Pareto model to excesses over a high threshold. The fitting functions use the probability weighted moment method, if method method="pwm" was selected, and the the general purpose opti- mization function optim when the maximum likelihood estimation, method="mle" or method="ml" is chosen. Methods: print.gpd, plot.gpd and summary.gpd are print, plot, and summary methods for a fitted ob- ject of class gpdFit. The plot method provides four different plots for assessing fitted GPD model. gpd* Functions: gpdqPlot calculates quantile estimates and confidence intervals for high quantiles above the thresh- old in a GPD analysis, and adds a graphical representation to an existing plot. The GPD approxima- tion in the tail is used to estimate quantile. The "wald" method uses the observed Fisher information matrix to calculate confidence interval. The "likelihood" method reparametrizes the likelihood in terms of the unknown quantile and uses profile likelihood arguments to construct a confidence interval. gpdquantPlot creates a plot showing how the estimate of a high quantile in the tail of a dataset based on the GPD approximation varies with threshold or number of extremes. For every model gpdFit is called. Evaluation may be slow. Confidence intervals by the Wald method may be fastest. gpdriskmeasures makes a rapid calculation of point estimates of prescribed quantiles and expected shortfalls using the output of the function gpdFit. This function simply calculates point estimates and (at present) makes no attempt to calculate confidence intervals for the risk measures. If confi- dence levels are required use gpdqPlot and gpdsfallPlot which interact with graphs of the tail of a loss distribution and are much slower. gpdsfallPlot calculates expected shortfall estimates, in other words tail conditional expectation and confidence intervals for high quantiles above the threshold in a GPD analysis. A graphical rep- resentation to an existing plot is added. Expected shortfall is the expected size of the loss, given that a particular quantile of the loss distribution is exceeded. The GPD approximation in the tail is used to estimate expected shortfall. The likelihood is reparametrized in terms of the unknown expected shortfall and profile likelihood arguments are used to construct a confidence interval. gpdshapePlot creates a plot showing how the estimate of shape varies with threshold or number of extremes. For every model gpdFit is called. Evaluation may be slow. gpdtailPlot produces a plot of the tail of the underlying distribution of the data. Value gpdSim returns a vector of datapoints from the simulated series. gpdFit returns an object of class "gpd" describing the fit including parameter estimates and standard errors. gpdQuantPlot returns invisible a table of results. gpdShapePlot returns invisible a table of results. gpdTailPlot returns invisible a list object containing details of the plot is returned invisibly. This object should be used as the first argument of gpdqPlot or gpdsfallPlot to add quantile estimates or expected shortfall estimates to the plot. Author(s) <NAME> for the functions from R’s evd package, <NAME> for the functions from R’s evir package, <NAME> for the EVIS functions underlying the evir package, <NAME> for this R-port. References <NAME>., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. <NAME>., <NAME>., (1987); Parameter and quantile estimation for the generalized Pareto distribution, Technometrics 29, 339–349. Examples ## gpdSim - x = gpdSim(model = list(xi = 0.25, mu = 0, beta = 1), n = 1000) ## gpdFit - par(mfrow = c(2, 2), cex = 0.7) fit = gpdFit(x, u = min(x), type = "pwm") print(fit) summary(fit) gpdRisk GPD Distributions for Extreme Value Theory Description A collection and description to functions to compute tail risk under the GPD approach. The GPD modelling functions are: gpdQPlot estimation of high quantiles, gpdQuantPlot variation of high quantiles with threshold, gpdRiskMeasures prescribed quantiles and expected shortfalls, gpdSfallPlot expected shortfall with confidence intervals, gpdShapePlot variation of shape with threshold, gpdTailPlot plot of the tail, tailPlot , tailSlider , tailRisk . Usage gpdQPlot(x, p = 0.99, ci = 0.95, type = c("likelihood", "wald"), like.num = 50) gpdQuantPlot(x, p = 0.99, ci = 0.95, models = 30, start = 15, end = 500, doplot = TRUE, plottype = c("normal", "reverse"), labels = TRUE, ...) gpdSfallPlot(x, p = 0.99, ci = 0.95, like.num = 50) gpdShapePlot(x, ci = 0.95, models = 30, start = 15, end = 500, doplot = TRUE, plottype = c("normal", "reverse"), labels = TRUE, ...) gpdTailPlot(object, plottype = c("xy", "x", "y", ""), doplot = TRUE, extend = 1.5, labels = TRUE, ...) gpdRiskMeasures(object, prob = c(0.99, 0.995, 0.999, 0.9995, 0.9999)) tailPlot(object, p = 0.99, ci = 0.95, nLLH = 25, extend = 1.5, grid = TRUE, labels = TRUE, ...) tailSlider(x) tailRisk(object, prob = c(0.99, 0.995, 0.999, 0.9995, 0.9999), ...) Arguments ci the probability for asymptotic confidence band; for no confidence band set to zero. doplot a logical. Should the results be plotted? extend optional argument for plots 1 and 2 expressing how far x-axis should extend as a multiple of the largest data value. This argument must take values greater than 1 and is useful for showing estimated quantiles beyond data. grid ... labels optional argument for plots 1 and 2 specifying whether or not axes should be labelled. like.num the number of times to evaluate profile likelihood. models the number of consecutive gpd models to be fitted. nLLH ... object [summary] - a fitted object of class "gpdFit". p a vector of probability levels, the desired probability for the quantile estimate (e.g. 0.99 for the 99th percentile). reverse should plot be by increasing threshold (TRUE) or number of extremes (FALSE). prob a numeric value. plottype a character string. start, end the lowest and maximum number of exceedances to be considered. type a character string selecting the desired estimation method, either "mle" for the maximum likelihood method or "pwm" for the probability weighted moment method. By default, the first will be selected. Note, the function gpd uses "ml". x [dgpd] - a numeric vector of quantiles. [gpdFit] - the data vector. Note, there are two different names for the first argument x and data depending which function name is used, either gpdFit or the EVIS synonym gpd. [print][plot] - a fitted object of class "gpdFit". ... control parameters and plot parameters optionally passed to the optimization and/or plot function. Parameters for the optimization function are passed to components of the control argument of optim. Details Generalized Pareto Distribution: Compute density, distribution function, quantile function and generates random variates for the Generalized Pareto Distribution. Simulation: gpdSim simulates data from a Generalized Pareto distribution. Parameter Estimation: gpdFit fits the model parameters either by the probability weighted moment method or the maxim log likelihood method. The function returns an object of class "gpd" representing the fit of a gen- eralized Pareto model to excesses over a high threshold. The fitting functions use the probability weighted moment method, if method method="pwm" was selected, and the the general purpose opti- mization function optim when the maximum likelihood estimation, method="mle" or method="ml" is chosen. Methods: print.gpd, plot.gpd and summary.gpd are print, plot, and summary methods for a fitted ob- ject of class gpdFit. The plot method provides four different plots for assessing fitted GPD model. gpd* Functions: gpdqPlot calculates quantile estimates and confidence intervals for high quantiles above the thresh- old in a GPD analysis, and adds a graphical representation to an existing plot. The GPD approxima- tion in the tail is used to estimate quantile. The "wald" method uses the observed Fisher information matrix to calculate confidence interval. The "likelihood" method reparametrizes the likelihood in terms of the unknown quantile and uses profile likelihood arguments to construct a confidence interval. gpdquantPlot creates a plot showing how the estimate of a high quantile in the tail of a dataset based on the GPD approximation varies with threshold or number of extremes. For every model gpdFit is called. Evaluation may be slow. Confidence intervals by the Wald method may be fastest. gpdriskmeasures makes a rapid calculation of point estimates of prescribed quantiles and expected shortfalls using the output of the function gpdFit. This function simply calculates point estimates and (at present) makes no attempt to calculate confidence intervals for the risk measures. If confi- dence levels are required use gpdqPlot and gpdsfallPlot which interact with graphs of the tail of a loss distribution and are much slower. gpdsfallPlot calculates expected shortfall estimates, in other words tail conditional expectation and confidence intervals for high quantiles above the threshold in a GPD analysis. A graphicalx representation to an existing plot is added. Expected shortfall is the expected size of the loss, given that a particular quantile of the loss distribution is exceeded. The GPD approximation in the tail is used to estimate expected shortfall. The likelihood is reparametrized in terms of the unknown expected shortfall and profile likelihood arguments are used to construct a confidence interval. gpdshapePlot creates a plot showing how the estimate of shape varies with threshold or number of extremes. For every model gpdFit is called. Evaluation may be slow. gpdtailPlot produces a plot of the tail of the underlying distribution of the data. Value gpdSim returns a vector of datapoints from the simulated series. gpdFit returns an object of class "gpd" describing the fit including parameter estimates and standard errors. gpdQuantPlot returns invisible a table of results. gpdShapePlot returns invisible a table of results. gpdTailPlot returns invisible a list object containing details of the plot is returned invisibly. This object should be used as the first argument of gpdqPlot or gpdsfallPlot to add quantile estimates or expected shortfall estimates to the plot. Author(s) <NAME> for the functions from R’s evd package, <NAME> for the functions from R’s evir package, <NAME> for the EVIS functions underlying the evir package, <NAME> for this R-port. References <NAME>., <NAME>., <NAME>. (1997); Modelling Extremal Events, Springer. <NAME>., <NAME>., (1987); Parameter and quantile estimation for the generalized Pareto distribution, Technometrics 29, 339–349. Examples ## Load Data: library(timeSeries) danish = as.timeSeries(data(danishClaims)) ## Tail Plot: x = as.timeSeries(data(danishClaims)) fit = gpdFit(x, u = 10) tailPlot(fit) ## Try Tail Slider: # tailSlider(x) ## Tail Risk: tailRisk(fit) TimeSeriesData Time Series Data Sets Description Data sets used in the examples of the fExtremes packages. Usage bmwRet danishClaims Format bmwRet. A data frame with 6146 observations on 2 variables. The first column contains dates (Tuesday 2nd January 1973 until Tuesday 23rd July 1996) and the second column contains the respective value of daily log returns on the BMW share price made on each of those dates. These data are an irregular time series because there is no trading at weekends. danishClaims. A data frame with 2167 observations on 2 variables. The first column contains dates and the second column contains the respective value of a fire insurance claim in Denmark made on each of those dates. These data are an irregular time series. Examples head(bmwRet) head(danishClaims) ValueAtRisk Value-at-Risk Description A collection and description of functions to compute Value-at-Risk and conditional Value-at-Risk The functions are: VaR Computes Value-at-Risk, CVaR Computes conditional Value-at-Risk. Usage VaR(x, alpha = 0.05, type = "sample", tail = c("lower", "upper")) CVaR(x, alpha = 0.05, type = "sample", tail = c("lower", "upper")) Arguments x an uni- or multivariate timeSeries object alpha a numeric value, the confidence interval. type a character string, the type to calculate the value-at-risk. tail a character string denoting which tail will be considered, either "lower" or "upper". If tail="lower", then alpha will be converted to alpha=1-alpha. Value VaR CVaR returns a numeric vector or value with the (conditional) value-at-risk for each time series column. Author(s) <NAME> for this R-port. See Also hillPlot, gevFit.
github.com/untoldwind/gopter
go
Go
README [¶](#section-readme) --- ### GOPTER ... the GOlang Property TestER [![Build Status](https://travis-ci.org/leanovate/gopter.svg?branch=master)](https://travis-ci.org/leanovate/gopter) [![codecov](https://codecov.io/gh/leanovate/gopter/branch/master/graph/badge.svg)](https://codecov.io/gh/leanovate/gopter) [![GoDoc](https://godoc.org/github.com/leanovate/gopter?status.png)](https://godoc.org/github.com/leanovate/gopter) [![Go Report Card](https://goreportcard.com/badge/github.com/leanovate/gopter)](https://goreportcard.com/report/github.com/leanovate/gopter) [Change Log](https://github.com/untoldwind/gopter/blob/v0.2.8/CHANGELOG.md) #### Synopsis Gopter tries to bring the goodness of [ScalaCheck](https://www.scalacheck.org/) (and implicitly, the goodness of [QuickCheck](http://hackage.haskell.org/package/QuickCheck)) to Go. It can also be seen as a more sophisticated version of the testing/quick package. Main differences to ScalaCheck: * It is Go ... duh * ... nevertheless: Do not expect the same typesafety and elegance as in ScalaCheck. * For simplicity [Shrink](https://www.scalacheck.org/files/scalacheck_2.11-1.14.0-api/index.html#org.scalacheck.Shrink) has become part of the generators. They can still be easily changed if necessary. * There is no [Pretty](https://www.scalacheck.org/files/scalacheck_2.11-1.14.0-api/index.html#org.scalacheck.util.Pretty) ... so far gopter feels quite comfortable being ugly. * A generator for regex matches * No parallel commands ... yet? Main differences to the testing/quick package: * Much tighter control over generators * Shrinkers, i.e. automatically find the minimum value falsifying a property * A generator for regex matches (already mentioned that ... but it's cool) * Support for stateful tests #### Documentation Current godocs: * [gopter](https://godoc.org/github.com/leanovate/gopter): Main interfaces * [gopter/gen](https://godoc.org/github.com/leanovate/gopter/gen): All commonly used generators * [gopter/prop](https://godoc.org/github.com/leanovate/gopter/prop): Common helpers to create properties from a condition function and specific generators * [gopter/arbitrary](https://godoc.org/github.com/leanovate/gopter/arbitrary): Helpers automatically combine generators for arbitrary types * [gopter/commands](https://godoc.org/github.com/leanovate/gopter/commands): Helpers to create stateful tests based on arbitrary commands * [gopter/convey](https://godoc.org/github.com/leanovate/gopter/convey): Helpers used by gopter inside goconvey tests #### License [MIT Licence](http://opensource.org/licenses/MIT) Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package gopter contain the main interfaces of the GOlang Property TestER. A simple property test might look like this: ``` func TestSqrt(t *testing.T) { properties := gopter.NewProperties(nil) properties.Property("greater one of all greater one", prop.ForAll( func(v float64) bool { return math.Sqrt(v) >= 1 }, gen.Float64Range(1, math.MaxFloat64), )) properties.Property("squared is equal to value", prop.ForAll( func(v float64) bool { r := math.Sqrt(v) return math.Abs(r*r-v) < 1e-10*v }, gen.Float64Range(0, math.MaxFloat64), )) properties.TestingRun(t) } ``` Generally a property is just a function that takes GenParameters and produces a PropResult: ``` type Prop func(*GenParameters) *PropResult ``` but usually you will use prop.ForAll, prop.ForAllNoShrink or arbitrary.ForAll. There is also the commands package, which can be helpful for stateful testing. Example (Fizzbuzz) [¶](#example-package-Fizzbuzz) ``` package main import ( "errors" "math" "strconv" "strings" "github.com/leanovate/gopter" "github.com/leanovate/gopter/gen" "github.com/leanovate/gopter/prop" ) // Fizzbuzz: See https://wikipedia.org/wiki/Fizz_buzz func fizzbuzz(number int) (string, error) { if number <= 0 { return "", errors.New("Undefined") } switch { case number%15 == 0: return "FizzBuzz", nil case number%3 == 0: return "Fizz", nil case number%5 == 0: return "Buzz", nil } return strconv.Itoa(number), nil } func main() { properties := gopter.NewProperties(nil) properties.Property("Undefined for all <= 0", prop.ForAll( func(number int) bool { result, err := fizzbuzz(number) return err != nil && result == "" }, gen.IntRange(math.MinInt32, 0), )) properties.Property("Start with Fizz for all multiples of 3", prop.ForAll( func(i int) bool { result, err := fizzbuzz(i * 3) return err == nil && strings.HasPrefix(result, "Fizz") }, gen.IntRange(1, math.MaxInt32/3), )) properties.Property("End with Buzz for all multiples of 5", prop.ForAll( func(i int) bool { result, err := fizzbuzz(i * 5) return err == nil && strings.HasSuffix(result, "Buzz") }, gen.IntRange(1, math.MaxInt32/5), )) properties.Property("Int as string for all non-divisible by 3 or 5", prop.ForAll( func(number int) bool { result, err := fizzbuzz(number) if err != nil { return false } parsed, err := strconv.ParseInt(result, 10, 64) return err == nil && parsed == int64(number) }, gen.IntRange(1, math.MaxInt32).SuchThat(func(v interface{}) bool { return v.(int)%3 != 0 && v.(int)%5 != 0 }), )) // When using testing.T you might just use: properties.TestingRun(t) properties.Run(gopter.ConsoleReporter(false)) } ``` ``` Output: + Undefined for all <= 0: OK, passed 100 tests. + Start with Fizz for all multiples of 3: OK, passed 100 tests. + End with Buzz for all multiples of 5: OK, passed 100 tests. + Int as string for all non-divisible by 3 or 5: OK, passed 100 tests. ``` Share Format Run Example (Labels) [¶](#example-package-Labels) Example_labels demonstrates how labels may help, in case of more complex conditions. The output will be: ``` ! Check spooky: Falsified after 0 passed tests. > Labels of failing property: even result a: 3 a_ORIGINAL (44 shrinks): 861384713 b: 0 b_ORIGINAL (1 shrinks): -642623569 ``` ``` package main import ( "github.com/leanovate/gopter" "github.com/leanovate/gopter/gen" "github.com/leanovate/gopter/prop" ) func spookyCalculation(a, b int) int { if a < 0 { a = -a } if b < 0 { b = -b } return 2*b + 3*(2+(a+1)+b*(b+1)) } // Example_labels demonstrates how labels may help, in case of more complex // conditions. // The output will be: // // ! Check spooky: Falsified after 0 passed tests. // > Labels of failing property: even result // a: 3 // a_ORIGINAL (44 shrinks): 861384713 // b: 0 // b_ORIGINAL (1 shrinks): -642623569 func main() { parameters := gopter.DefaultTestParameters() parameters.Rng.Seed(1234) // Just for this example to generate reproducible results parameters.MinSuccessfulTests = 10000 properties := gopter.NewProperties(parameters) properties.Property("Check spooky", prop.ForAll( func(a, b int) string { result := spookyCalculation(a, b) if result < 0 { return "negative result" } if result%2 == 0 { return "even result" } return "" }, gen.Int().WithLabel("a"), gen.Int().WithLabel("b"), )) // When using testing.T you might just use: properties.TestingRun(t) properties.Run(gopter.ConsoleReporter(false)) } ``` ``` Output: ! Check spooky: Falsified after 0 passed tests. > Labels of failing property: even result a: 3 a_ORIGINAL (44 shrinks): 861384713 b: 0 b_ORIGINAL (1 shrinks): -642623569 ``` Share Format Run Example (Libraries) [¶](#example-package-Libraries) ``` package main import ( "reflect" "github.com/leanovate/gopter" "github.com/leanovate/gopter/arbitrary" "github.com/leanovate/gopter/gen" ) type TestBook struct { Title string Content string } func genTestBook() gopter.Gen { return gen.Struct(reflect.TypeOf(&TestBook{}), map[string]gopter.Gen{ "Title": gen.AlphaString(), "Content": gen.AlphaString(), }) } type TestLibrary struct { Name string Librarians uint8 Books []TestBook } func genTestLibrary() gopter.Gen { return gen.Struct(reflect.TypeOf(&TestLibrary{}), map[string]gopter.Gen{ "Name": gen.AlphaString().SuchThat(func(s string) bool { return s != "" }), "Librarians": gen.UInt8Range(1, 255), "Books": gen.SliceOf(genTestBook()), }) } type CityName = string type TestCities struct { Libraries map[CityName][]TestLibrary } func genTestCities() gopter.Gen { return gen.StructPtr(reflect.TypeOf(&TestCities{}), map[string]gopter.Gen{ "Libraries": (gen.MapOf(gen.AlphaString(), gen.SliceOf(genTestLibrary()))), }) } func main() { parameters := gopter.DefaultTestParameters() parameters.Rng.Seed(1234) // Just for this example to generate reproducible results parameters.MaxSize = 5 arbitraries := arbitrary.DefaultArbitraries() arbitraries.RegisterGen(genTestCities()) properties := gopter.NewProperties(parameters) properties.Property("no unsupervised libraries", arbitraries.ForAll( func(tc *TestCities) bool { for _, libraries := range tc.Libraries { for _, library := range libraries { if library.Librarians == 0 { return false } } } return true }, )) // When using testing.T you might just use: properties.TestingRun(t) properties.Run(gopter.ConsoleReporter(false)) } ``` ``` Output: + no unsupervised libraries: OK, passed 100 tests. ``` Share Format Run Example (Libraries2) [¶](#example-package-Libraries2) ``` package main import ( "github.com/leanovate/gopter" "github.com/leanovate/gopter/arbitrary" "github.com/leanovate/gopter/gen" ) type TestBook struct { Title string Content string } type TestLibrary struct { Name string Librarians uint8 Books []TestBook } type CityName = string type TestCities struct { Libraries map[CityName][]TestLibrary } func main() { parameters := gopter.DefaultTestParameters() parameters.Rng.Seed(1234) // Just for this example to generate reproducible results arbitraries := arbitrary.DefaultArbitraries() // All string are alphanumeric arbitraries.RegisterGen(gen.AlphaString()) properties := gopter.NewProperties(parameters) properties.Property("libraries always empty", arbitraries.ForAll( func(tc *TestCities) bool { return len(tc.Libraries) == 0 }, )) // When using testing.T you might just use: properties.TestingRun(t) properties.Run(gopter.ConsoleReporter(false)) } ``` ``` Output: ! libraries always empty: Falsified after 2 passed tests. ARG_0: &{Libraries:map[z:[]]} ``` Share Format Run Example (Panic) [¶](#example-package-Panic) ``` package main import ( "github.com/leanovate/gopter" "github.com/leanovate/gopter/gen" "github.com/leanovate/gopter/prop" ) func main() { parameters := gopter.DefaultTestParameters() parameters.Rng.Seed(1234) // Just for this example to generate reproducible results properties := gopter.NewProperties(parameters) properties.Property("Will panic", prop.ForAll( func(i int) bool { if i%2 == 0 { panic("hi") } return true }, gen.Int().WithLabel("number"))) // When using testing.T you might just use: properties.TestingRun(t) properties.Run(gopter.ConsoleReporter(false)) } ``` ``` Output: ! Will panic: Error on property evaluation after 6 passed tests: Check paniced: hi number: 0 number_ORIGINAL (1 shrinks): 2015020988 ``` Share Format Run Example (Sqrt) [¶](#example-package-Sqrt) ``` package main import ( "math" "github.com/leanovate/gopter" "github.com/leanovate/gopter/gen" "github.com/leanovate/gopter/prop" ) func main() { parameters := gopter.DefaultTestParameters() parameters.Rng.Seed(1234) // Just for this example to generate reproducible results properties := gopter.NewProperties(parameters) properties.Property("greater one of all greater one", prop.ForAll( func(v float64) bool { return math.Sqrt(v) >= 1 }, gen.Float64().SuchThat(func(x float64) bool { return x >= 1.0 }), )) properties.Property("squared is equal to value", prop.ForAll( func(v float64) bool { r := math.Sqrt(v) return math.Abs(r*r-v) < 1e-10*v }, gen.Float64().SuchThat(func(x float64) bool { return x >= 0.0 }), )) // When using testing.T you might just use: properties.TestingRun(t) properties.Run(gopter.ConsoleReporter(false)) } ``` ``` Output: + greater one of all greater one: OK, passed 100 tests. + squared is equal to value: OK, passed 100 tests. ``` Share Format Run ### Index [¶](#pkg-index) * [Constants](#pkg-constants) * [Variables](#pkg-variables) * [func NewLockedSource(seed int64) *lockedSource](#NewLockedSource) * [type BiMapper](#BiMapper) * + [func NewBiMapper(downstream interface{}, upstream interface{}) *BiMapper](#NewBiMapper) * + [func (b *BiMapper) ConvertDown(up []interface{}) []interface{}](#BiMapper.ConvertDown) + [func (b *BiMapper) ConvertUp(down []interface{}) []interface{}](#BiMapper.ConvertUp) * [type Flag](#Flag) * + [func (f *Flag) Get() bool](#Flag.Get) + [func (f *Flag) Set()](#Flag.Set) + [func (f *Flag) Unset()](#Flag.Unset) * [type FormatedReporter](#FormatedReporter) * + [func (r *FormatedReporter) ReportTestResult(propName string, result *TestResult)](#FormatedReporter.ReportTestResult) * [type Gen](#Gen) * + [func CombineGens(gens ...Gen) Gen](#CombineGens) + [func DeriveGen(downstream interface{}, upstream interface{}, gens ...Gen) Gen](#DeriveGen) * + [func (g Gen) FlatMap(f func(interface{}) Gen, resultType reflect.Type) Gen](#Gen.FlatMap) + [func (g Gen) Map(f interface{}) Gen](#Gen.Map) + [func (g Gen) MapResult(f func(*GenResult) *GenResult) Gen](#Gen.MapResult) + [func (g Gen) Sample() (interface{}, bool)](#Gen.Sample) + [func (g Gen) SuchThat(f interface{}) Gen](#Gen.SuchThat) + [func (g Gen) WithLabel(label string) Gen](#Gen.WithLabel) + [func (g Gen) WithShrinker(shrinker Shrinker) Gen](#Gen.WithShrinker) * [type GenParameters](#GenParameters) * + [func DefaultGenParameters() *GenParameters](#DefaultGenParameters) + [func MinGenParameters() *GenParameters](#MinGenParameters) * + [func (p *GenParameters) CloneWithSeed(seed int64) *GenParameters](#GenParameters.CloneWithSeed) + [func (p *GenParameters) NextBool() bool](#GenParameters.NextBool) + [func (p *GenParameters) NextInt64() int64](#GenParameters.NextInt64) + [func (p *GenParameters) NextUint64() uint64](#GenParameters.NextUint64) + [func (p *GenParameters) WithSize(size int) *GenParameters](#GenParameters.WithSize) * [type GenResult](#GenResult) * + [func NewEmptyResult(resultType reflect.Type) *GenResult](#NewEmptyResult) + [func NewGenResult(result interface{}, shrinker Shrinker) *GenResult](#NewGenResult) * + [func (r *GenResult) Retrieve() (interface{}, bool)](#GenResult.Retrieve) + [func (r *GenResult) RetrieveAsValue() (reflect.Value, bool)](#GenResult.RetrieveAsValue) * [type Prop](#Prop) * + [func SaveProp(prop Prop) Prop](#SaveProp) * + [func (prop Prop) Check(parameters *TestParameters) *TestResult](#Prop.Check) * [type PropArg](#PropArg) * + [func NewPropArg(genResult *GenResult, shrinks int, value, origValue interface{}) *PropArg](#NewPropArg) * + [func (p *PropArg) String() string](#PropArg.String) * [type PropArgs](#PropArgs) * [type PropResult](#PropResult) * + [func NewPropResult(success bool, label string) *PropResult](#NewPropResult) * + [func (r *PropResult) AddArgs(args ...*PropArg) *PropResult](#PropResult.AddArgs) + [func (r *PropResult) And(other *PropResult) *PropResult](#PropResult.And) + [func (r *PropResult) Success() bool](#PropResult.Success) + [func (r *PropResult) WithArgs(args []*PropArg) *PropResult](#PropResult.WithArgs) * [type Properties](#Properties) * + [func NewProperties(parameters *TestParameters) *Properties](#NewProperties) * + [func (p *Properties) Property(name string, prop Prop)](#Properties.Property) + [func (p *Properties) Run(reporter Reporter) bool](#Properties.Run) + [func (p *Properties) TestingRun(t *testing.T, opts ...interface{})](#Properties.TestingRun) * [type Reporter](#Reporter) * + [func ConsoleReporter(verbose bool) Reporter](#ConsoleReporter) + [func NewFormatedReporter(verbose bool, width int, output io.Writer) Reporter](#NewFormatedReporter) * [type Shrink](#Shrink) * + [func ConcatShrinks(shrinks ...Shrink) Shrink](#ConcatShrinks) * + [func (s Shrink) All() []interface{}](#Shrink.All) + [func (s Shrink) Filter(condition func(interface{}) bool) Shrink](#Shrink.Filter) + [func (s Shrink) Interleave(other Shrink) Shrink](#Shrink.Interleave) + [func (s Shrink) Map(f interface{}) Shrink](#Shrink.Map) * [type Shrinker](#Shrinker) * + [func CombineShrinker(shrinkers ...Shrinker) Shrinker](#CombineShrinker) * [type TestParameters](#TestParameters) * + [func DefaultTestParameters() *TestParameters](#DefaultTestParameters) + [func DefaultTestParametersWithSeed(seed int64) *TestParameters](#DefaultTestParametersWithSeed) * [type TestResult](#TestResult) * + [func (r *TestResult) Passed() bool](#TestResult.Passed) #### Examples [¶](#pkg-examples) * [Package (Fizzbuzz)](#example-package-Fizzbuzz) * [Package (Labels)](#example-package-Labels) * [Package (Libraries)](#example-package-Libraries) * [Package (Libraries2)](#example-package-Libraries2) * [Package (Panic)](#example-package-Panic) * [Package (Sqrt)](#example-package-Sqrt) ### Constants [¶](#pkg-constants) ``` const ( // PropProof THe property was proved (i.e. it is known to be correct and will be always true) PropProof propStatus = [iota](/builtin#iota) // PropTrue The property was true this time PropTrue // PropFalse The property was false this time PropFalse // PropUndecided The property has no clear outcome this time PropUndecided // PropError The property has generated an error PropError ) ``` ``` const ( // TestPassed indicates that the property check has passed. TestPassed testStatus = [iota](/builtin#iota) // TestProved indicates that the property has been proved. TestProved // TestFailed indicates that the property check has failed. TestFailed // TestExhausted indicates that the property check has exhausted, i.e. the generators have // generated too many empty results. TestExhausted // TestError indicates that the property check has finished with an error. TestError ) ``` ### Variables [¶](#pkg-variables) ``` var ( // DefaultGenParams can be used as default für *GenParameters DefaultGenParams = [DefaultGenParameters](#DefaultGenParameters)() MinGenParams = [MinGenParameters](#MinGenParameters)() ) ``` ``` var NoShrink = [Shrink](#Shrink)(func() (interface{}, [bool](/builtin#bool)) { return [nil](/builtin#nil), [false](/builtin#false) }) ``` NoShrink is an empty shrink. ``` var NoShrinker = [Shrinker](#Shrinker)(func(value interface{}) [Shrink](#Shrink) { return [NoShrink](#NoShrink) }) ``` NoShrinker is a shrinker for NoShrink, i.e. a Shrinker that will not shrink any values. This is the default Shrinker if none is provided. ### Functions [¶](#pkg-functions) #### func [NewLockedSource](https://github.com/untoldwind/gopter/blob/v0.2.8/locked_source.go#L20) [¶](#NewLockedSource) added in v0.2.2 ``` func NewLockedSource(seed [int64](/builtin#int64)) *lockedSource ``` NewLockedSource takes a seed and returns a new lockedSource for use with rand.New ### Types [¶](#pkg-types) #### type [BiMapper](https://github.com/untoldwind/gopter/blob/v0.2.8/bi_mapper.go#L10) [¶](#BiMapper) ``` type BiMapper struct { UpTypes [][reflect](/reflect).[Type](/reflect#Type) DownTypes [][reflect](/reflect).[Type](/reflect#Type) Downstream [reflect](/reflect).[Value](/reflect#Value) Upstream [reflect](/reflect).[Value](/reflect#Value) } ``` BiMapper is a bi-directional (or bijective) mapper of a tuple of values (up) to another tuple of values (down). #### func [NewBiMapper](https://github.com/untoldwind/gopter/blob/v0.2.8/bi_mapper.go#L21) [¶](#NewBiMapper) ``` func NewBiMapper(downstream interface{}, upstream interface{}) *[BiMapper](#BiMapper) ``` NewBiMapper creates a BiMapper of two functions `downstream` and its inverse `upstream`. That is: The return values of `downstream` must match the parameters of `upstream` and vice versa. #### func (*BiMapper) [ConvertDown](https://github.com/untoldwind/gopter/blob/v0.2.8/bi_mapper.go#L92) [¶](#BiMapper.ConvertDown) ``` func (b *[BiMapper](#BiMapper)) ConvertDown(up []interface{}) []interface{} ``` ConvertDown calls the Downstream function on the elements of the up array and returns the results. #### func (*BiMapper) [ConvertUp](https://github.com/untoldwind/gopter/blob/v0.2.8/bi_mapper.go#L69) [¶](#BiMapper.ConvertUp) ``` func (b *[BiMapper](#BiMapper)) ConvertUp(down []interface{}) []interface{} ``` ConvertUp calls the Upstream function on the arguments in the down array and returns the results. #### type [Flag](https://github.com/untoldwind/gopter/blob/v0.2.8/flag.go#L6) [¶](#Flag) ``` type Flag struct { // contains filtered or unexported fields } ``` Flag is a convenient helper for an atomic boolean #### func (*Flag) [Get](https://github.com/untoldwind/gopter/blob/v0.2.8/flag.go#L11) [¶](#Flag.Get) ``` func (f *[Flag](#Flag)) Get() [bool](/builtin#bool) ``` Get the value of the flag #### func (*Flag) [Set](https://github.com/untoldwind/gopter/blob/v0.2.8/flag.go#L16) [¶](#Flag.Set) ``` func (f *[Flag](#Flag)) Set() ``` Set the the flag #### func (*Flag) [Unset](https://github.com/untoldwind/gopter/blob/v0.2.8/flag.go#L21) [¶](#Flag.Unset) ``` func (f *[Flag](#Flag)) Unset() ``` Unset the flag #### type [FormatedReporter](https://github.com/untoldwind/gopter/blob/v0.2.8/formated_reporter.go#L14) [¶](#FormatedReporter) ``` type FormatedReporter struct { // contains filtered or unexported fields } ``` FormatedReporter reports test results in a human readable manager. #### func (*FormatedReporter) [ReportTestResult](https://github.com/untoldwind/gopter/blob/v0.2.8/formated_reporter.go#L38) [¶](#FormatedReporter.ReportTestResult) ``` func (r *[FormatedReporter](#FormatedReporter)) ReportTestResult(propName [string](/builtin#string), result *[TestResult](#TestResult)) ``` ReportTestResult reports a single property result #### type [Gen](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L17) [¶](#Gen) ``` type Gen func(*[GenParameters](#GenParameters)) *[GenResult](#GenResult) ``` Gen generator of arbitrary values. Usually properties are checked by verifing a condition holds true for arbitrary input parameters generated by a Gen. IMPORTANT: Even though a generator is supposed to generate random values, it should do this in a reproducible way. Therefore a generator has to create the same result for the same GenParameters, i.e. ensure that you just use the RNG provided by GenParameters and no external one. If you just plug generators together you do not have to worry about this. #### func [CombineGens](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L221) [¶](#CombineGens) ``` func CombineGens(gens ...[Gen](#Gen)) [Gen](#Gen) ``` CombineGens creates a generators from a list of generators. The result type will be a []interface{} containing the generated values of each generators in the list. Note: The combined generator will not have a sieve or shrinker. #### func [DeriveGen](https://github.com/untoldwind/gopter/blob/v0.2.8/derived_gen.go#L96) [¶](#DeriveGen) ``` func DeriveGen(downstream interface{}, upstream interface{}, gens ...[Gen](#Gen)) [Gen](#Gen) ``` DeriveGen derives a generator with shrinkers from a sequence of other generators mapped by a bijective function (BiMapper) #### func (Gen) [FlatMap](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L191) [¶](#Gen.FlatMap) ``` func (g [Gen](#Gen)) FlatMap(f func(interface{}) [Gen](#Gen), resultType [reflect](/reflect).[Type](/reflect#Type)) [Gen](#Gen) ``` FlatMap creates a derived generator by passing a generated value to a function which itself creates a generator. #### func (Gen) [Map](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L107) [¶](#Gen.Map) ``` func (g [Gen](#Gen)) Map(f interface{}) [Gen](#Gen) ``` Map creates a derived generator by mapping all generatored values with a given function. f: has to be a function with one parameter (matching the generated value) and a single return. Note: The derived generator will not have a sieve or shrinker unless you are mapping to the same type Note: The mapping function may have a second parameter "*GenParameters" Note: The first parameter of the mapping function and its return may be a *GenResult (this makes MapResult obsolete) #### func (Gen) [MapResult](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L211) [¶](#Gen.MapResult) ``` func (g [Gen](#Gen)) MapResult(f func(*[GenResult](#GenResult)) *[GenResult](#GenResult)) [Gen](#Gen) ``` MapResult creates a derived generator by mapping the GenResult directly. Contrary to `Map` and `FlatMap` this also allow the conversion of shrinkers and sieves, but implementation is more cumbersome. Deprecation note: Map now has the same functionality #### func (Gen) [Sample](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L27) [¶](#Gen.Sample) ``` func (g [Gen](#Gen)) Sample() (interface{}, [bool](/builtin#bool)) ``` Sample generate a sample value. Depending on the state of the RNG the generate might fail to provide a sample #### func (Gen) [SuchThat](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L47) [¶](#Gen.SuchThat) ``` func (g [Gen](#Gen)) SuchThat(f interface{}) [Gen](#Gen) ``` SuchThat creates a derived generator by adding a sieve. f: has to be a function with one parameter (matching the generated value) returning a bool. All generated values are expected to satisfy ``` f(value) == true. ``` Use this care, if the sieve to to fine the generator will have many misses which results in an undecided property. #### func (Gen) [WithLabel](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L33) [¶](#Gen.WithLabel) ``` func (g [Gen](#Gen)) WithLabel(label [string](/builtin#string)) [Gen](#Gen) ``` WithLabel adds a label to a generated value. Labels are usually used for reporting for the arguments of a property check. #### func (Gen) [WithShrinker](https://github.com/untoldwind/gopter/blob/v0.2.8/gen.go#L90) [¶](#Gen.WithShrinker) ``` func (g [Gen](#Gen)) WithShrinker(shrinker [Shrinker](#Shrinker)) [Gen](#Gen) ``` WithShrinker creates a derived generator with a specific shrinker #### type [GenParameters](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L9) [¶](#GenParameters) ``` type GenParameters struct { MinSize [int](/builtin#int) MaxSize [int](/builtin#int) MaxShrinkCount [int](/builtin#int) Rng *[rand](/math/rand).[Rand](/math/rand#Rand) } ``` GenParameters encapsulates the parameters for all generators. #### func [DefaultGenParameters](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L59) [¶](#DefaultGenParameters) ``` func DefaultGenParameters() *[GenParameters](#GenParameters) ``` DefaultGenParameters creates default GenParameters. #### func [MinGenParameters](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L72) [¶](#MinGenParameters) added in v0.2.4 ``` func MinGenParameters() *[GenParameters](#GenParameters) ``` MinGenParameters creates minimal GenParameters. Note: Most likely you do not want to use these for actual testing #### func (*GenParameters) [CloneWithSeed](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L49) [¶](#GenParameters.CloneWithSeed) ``` func (p *[GenParameters](#GenParameters)) CloneWithSeed(seed [int64](/builtin#int64)) *[GenParameters](#GenParameters) ``` CloneWithSeed clone the current parameters with a new seed. This is useful to create subsections that can rerun (provided you keep the seed) #### func (*GenParameters) [NextBool](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L25) [¶](#GenParameters.NextBool) ``` func (p *[GenParameters](#GenParameters)) NextBool() [bool](/builtin#bool) ``` NextBool create a random boolean using the underlying Rng. #### func (*GenParameters) [NextInt64](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L30) [¶](#GenParameters.NextInt64) ``` func (p *[GenParameters](#GenParameters)) NextInt64() [int64](/builtin#int64) ``` NextInt64 create a random int64 using the underlying Rng. #### func (*GenParameters) [NextUint64](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L39) [¶](#GenParameters.NextUint64) ``` func (p *[GenParameters](#GenParameters)) NextUint64() [uint64](/builtin#uint64) ``` NextUint64 create a random uint64 using the underlying Rng. #### func (*GenParameters) [WithSize](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_parameters.go#L18) [¶](#GenParameters.WithSize) ``` func (p *[GenParameters](#GenParameters)) WithSize(size [int](/builtin#int)) *[GenParameters](#GenParameters) ``` WithSize modifies the size parameter. The size parameter defines an upper bound for the size of generated slices or strings. #### type [GenResult](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_result.go#L6) [¶](#GenResult) ``` type GenResult struct { Labels [][string](/builtin#string) Shrinker [Shrinker](#Shrinker) ResultType [reflect](/reflect).[Type](/reflect#Type) Result interface{} Sieve func(interface{}) [bool](/builtin#bool) } ``` GenResult contains the result of a generator. #### func [NewEmptyResult](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_result.go#L28) [¶](#NewEmptyResult) ``` func NewEmptyResult(resultType [reflect](/reflect).[Type](/reflect#Type)) *[GenResult](#GenResult) ``` NewEmptyResult creates an empty generator result. Unless the sieve does not explicitly allow it, empty (i.e. nil-valued) results are considered invalid. #### func [NewGenResult](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_result.go#L17) [¶](#NewGenResult) ``` func NewGenResult(result interface{}, shrinker [Shrinker](#Shrinker)) *[GenResult](#GenResult) ``` NewGenResult creates a new generator result from for a concrete value and shrinker. Note: The concrete value "result" not be nil #### func (*GenResult) [Retrieve](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_result.go#L38) [¶](#GenResult.Retrieve) ``` func (r *[GenResult](#GenResult)) Retrieve() (interface{}, [bool](/builtin#bool)) ``` Retrieve gets the concrete generator result. If the result is invalid or does not pass the sieve there is no concrete value and the property using the generator should be undecided. #### func (*GenResult) [RetrieveAsValue](https://github.com/untoldwind/gopter/blob/v0.2.8/gen_result.go#L48) [¶](#GenResult.RetrieveAsValue) ``` func (r *[GenResult](#GenResult)) RetrieveAsValue() ([reflect](/reflect).[Value](/reflect#Value), [bool](/builtin#bool)) ``` RetrieveAsValue get the concrete generator result as reflect value. If the result is invalid or does not pass the sieve there is no concrete value and the property using the generator should be undecided. #### type [Prop](https://github.com/untoldwind/gopter/blob/v0.2.8/prop.go#L10) [¶](#Prop) ``` type Prop func(*[GenParameters](#GenParameters)) *[PropResult](#PropResult) ``` Prop represent some kind of property that (drums please) can and should be checked #### func [SaveProp](https://github.com/untoldwind/gopter/blob/v0.2.8/prop.go#L13) [¶](#SaveProp) ``` func SaveProp(prop [Prop](#Prop)) [Prop](#Prop) ``` SaveProp creates s save property by handling all panics from an inner property #### func (Prop) [Check](https://github.com/untoldwind/gopter/blob/v0.2.8/prop.go#L30) [¶](#Prop.Check) ``` func (prop [Prop](#Prop)) Check(parameters *[TestParameters](#TestParameters)) *[TestResult](#TestResult) ``` Check the property using specific parameters #### type [PropArg](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_arg.go#L10) [¶](#PropArg) ``` type PropArg struct { Arg interface{} OrigArg interface{} Label [string](/builtin#string) Shrinks [int](/builtin#int) } ``` PropArg contains information about the specific values for a certain property check. This is mostly used for reporting when a property has falsified. #### func [NewPropArg](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_arg.go#L25) [¶](#NewPropArg) ``` func NewPropArg(genResult *[GenResult](#GenResult), shrinks [int](/builtin#int), value, origValue interface{}) *[PropArg](#PropArg) ``` NewPropArg creates a new PropArg. #### func (*PropArg) [String](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_arg.go#L17) [¶](#PropArg.String) ``` func (p *[PropArg](#PropArg)) String() [string](/builtin#string) ``` #### type [PropArgs](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_arg.go#L22) [¶](#PropArgs) ``` type PropArgs []*[PropArg](#PropArg) ``` PropArgs is a list of PropArg. #### type [PropResult](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_result.go#L35) [¶](#PropResult) ``` type PropResult struct { Status propStatus Error [error](/builtin#error) ErrorStack [][byte](/builtin#byte) Args []*[PropArg](#PropArg) Labels [][string](/builtin#string) } ``` PropResult contains the result of a property #### func [NewPropResult](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_result.go#L44) [¶](#NewPropResult) ``` func NewPropResult(success [bool](/builtin#bool), label [string](/builtin#string)) *[PropResult](#PropResult) ``` NewPropResult create a PropResult with label #### func (*PropResult) [AddArgs](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_result.go#L71) [¶](#PropResult.AddArgs) ``` func (r *[PropResult](#PropResult)) AddArgs(args ...*[PropArg](#PropArg)) *[PropResult](#PropResult) ``` AddArgs add argument descriptors to the PropResult for reporting #### func (*PropResult) [And](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_result.go#L78) [¶](#PropResult.And) ``` func (r *[PropResult](#PropResult)) And(other *[PropResult](#PropResult)) *[PropResult](#PropResult) ``` And combines two PropResult by an and operation. The resulting PropResult will be only true if both PropResults are true. #### func (*PropResult) [Success](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_result.go#L60) [¶](#PropResult.Success) ``` func (r *[PropResult](#PropResult)) Success() [bool](/builtin#bool) ``` Success checks if the result was successful #### func (*PropResult) [WithArgs](https://github.com/untoldwind/gopter/blob/v0.2.8/prop_result.go#L65) [¶](#PropResult.WithArgs) ``` func (r *[PropResult](#PropResult)) WithArgs(args []*[PropArg](#PropArg)) *[PropResult](#PropResult) ``` WithArgs sets argument descriptors to the PropResult for reporting #### type [Properties](https://github.com/untoldwind/gopter/blob/v0.2.8/properties.go#L6) [¶](#Properties) ``` type Properties struct { // contains filtered or unexported fields } ``` Properties is a collection of properties that should be checked in a test #### func [NewProperties](https://github.com/untoldwind/gopter/blob/v0.2.8/properties.go#L14) [¶](#NewProperties) ``` func NewProperties(parameters *[TestParameters](#TestParameters)) *[Properties](#Properties) ``` NewProperties create new Properties with given test parameters. If parameters is nil default test parameters will be used #### func (*Properties) [Property](https://github.com/untoldwind/gopter/blob/v0.2.8/properties.go#L26) [¶](#Properties.Property) ``` func (p *[Properties](#Properties)) Property(name [string](/builtin#string), prop [Prop](#Prop)) ``` Property add/defines a property in a test. #### func (*Properties) [Run](https://github.com/untoldwind/gopter/blob/v0.2.8/properties.go#L32) [¶](#Properties.Run) ``` func (p *[Properties](#Properties)) Run(reporter [Reporter](#Reporter)) [bool](/builtin#bool) ``` Run checks all definied propertiesand reports the result #### func (*Properties) [TestingRun](https://github.com/untoldwind/gopter/blob/v0.2.8/properties.go#L49) [¶](#Properties.TestingRun) ``` func (p *[Properties](#Properties)) TestingRun(t *[testing](/testing).[T](/testing#T), opts ...interface{}) ``` TestingRun checks all definied properties with a testing.T context. This the preferred wait to run property tests as part of a go unit test. #### type [Reporter](https://github.com/untoldwind/gopter/blob/v0.2.8/reporter.go#L4) [¶](#Reporter) ``` type Reporter interface { // ReportTestResult reports a single property result ReportTestResult(propName [string](/builtin#string), result *[TestResult](#TestResult)) } ``` Reporter is a simple interface to report/format the results of a property check. #### func [ConsoleReporter](https://github.com/untoldwind/gopter/blob/v0.2.8/formated_reporter.go#L33) [¶](#ConsoleReporter) ``` func ConsoleReporter(verbose [bool](/builtin#bool)) [Reporter](#Reporter) ``` ConsoleReporter creates a FormatedReporter writing to the console (i.e. stdout) #### func [NewFormatedReporter](https://github.com/untoldwind/gopter/blob/v0.2.8/formated_reporter.go#L24) [¶](#NewFormatedReporter) ``` func NewFormatedReporter(verbose [bool](/builtin#bool), width [int](/builtin#int), output [io](/io).[Writer](/io#Writer)) [Reporter](#Reporter) ``` NewFormatedReporter create a new formated reporter verbose toggles verbose output of the property results width is the maximal width per line output is the writer were the report will be written to #### type [Shrink](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L16) [¶](#Shrink) ``` type Shrink func() (interface{}, [bool](/builtin#bool)) ``` Shrink is a stream of shrunk down values. Once the result of a shrink is false, it is considered to be exhausted. Important notes for implementors: * Ensure that the returned stream is finite, even though shrinking will eventually be aborted, infinite streams may result in very slow running test. * Ensure that modifications to the returned value will not affect the internal state of your Shrink. If in doubt return by value not by reference #### func [ConcatShrinks](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L86) [¶](#ConcatShrinks) ``` func ConcatShrinks(shrinks ...[Shrink](#Shrink)) [Shrink](#Shrink) ``` ConcatShrinks concats an array of shrinks to a single shrinks #### func (Shrink) [All](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L59) [¶](#Shrink.All) ``` func (s [Shrink](#Shrink)) All() []interface{} ``` All collects all shrinks as a slice. Use with care as this might create large results depending on the complexity of the shrink #### func (Shrink) [Filter](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L19) [¶](#Shrink.Filter) ``` func (s [Shrink](#Shrink)) Filter(condition func(interface{}) [bool](/builtin#bool)) [Shrink](#Shrink) ``` Filter creates a shrink filtered by a condition #### func (Shrink) [Interleave](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L124) [¶](#Shrink.Interleave) ``` func (s [Shrink](#Shrink)) Interleave(other [Shrink](#Shrink)) [Shrink](#Shrink) ``` Interleave this shrink with another Both shrinks are expected to produce the same result #### func (Shrink) [Map](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L34) [¶](#Shrink.Map) ``` func (s [Shrink](#Shrink)) Map(f interface{}) [Shrink](#Shrink) ``` Map creates a shrink by applying a converter to each element of a shrink. f: has to be a function with one parameter (matching the generated value) and a single return. #### type [Shrinker](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L133) [¶](#Shrinker) ``` type Shrinker func(value interface{}) [Shrink](#Shrink) ``` Shrinker creates a shrink for a given value #### func [CombineShrinker](https://github.com/untoldwind/gopter/blob/v0.2.8/shrink.go#L157) [¶](#CombineShrinker) ``` func CombineShrinker(shrinkers ...[Shrinker](#Shrinker)) [Shrinker](#Shrinker) ``` CombineShrinker create a shrinker by combining a list of shrinkers. The resulting shrinker will shrink an []interface{} where each element will be shrunk by the corresonding shrinker in 'shrinkers'. This method is implicitly used by CombineGens. #### type [TestParameters](https://github.com/untoldwind/gopter/blob/v0.2.8/test_parameters.go#L9) [¶](#TestParameters) ``` type TestParameters struct { MinSuccessfulTests [int](/builtin#int) // MinSize is an (inclusive) lower limit on the size of the parameters MinSize [int](/builtin#int) // MaxSize is an (exclusive) upper limit on the size of the parameters MaxSize [int](/builtin#int) MaxShrinkCount [int](/builtin#int) Seed [int64](/builtin#int64) Rng *[rand](/math/rand).[Rand](/math/rand#Rand) Workers [int](/builtin#int) MaxDiscardRatio [float64](/builtin#float64) } ``` TestParameters to run property tests #### func [DefaultTestParameters](https://github.com/untoldwind/gopter/blob/v0.2.8/test_parameters.go#L37) [¶](#DefaultTestParameters) ``` func DefaultTestParameters() *[TestParameters](#TestParameters) ``` DefaultTestParameterWithSeeds creates reasonable default Parameters for most cases with an undefined RNG-seed #### func [DefaultTestParametersWithSeed](https://github.com/untoldwind/gopter/blob/v0.2.8/test_parameters.go#L23) [¶](#DefaultTestParametersWithSeed) added in v0.2.2 ``` func DefaultTestParametersWithSeed(seed [int64](/builtin#int64)) *[TestParameters](#TestParameters) ``` DefaultTestParameterWithSeeds creates reasonable default Parameters for most cases based on a fixed RNG-seed #### type [TestResult](https://github.com/untoldwind/gopter/blob/v0.2.8/test_result.go#L38) [¶](#TestResult) ``` type TestResult struct { Status testStatus Succeeded [int](/builtin#int) Discarded [int](/builtin#int) Labels [][string](/builtin#string) Error [error](/builtin#error) ErrorStack [][byte](/builtin#byte) Args [PropArgs](#PropArgs) Time [time](/time).[Duration](/time#Duration) } ``` TestResult contains the result of a property property check. #### func (*TestResult) [Passed](https://github.com/untoldwind/gopter/blob/v0.2.8/test_result.go#L50) [¶](#TestResult.Passed) ``` func (r *[TestResult](#TestResult)) Passed() [bool](/builtin#bool) ``` Passed checks if the check has passed
brglm
cran
R
Package ‘brglm’ October 12, 2022 Type Package Title Bias Reduction in Binomial-Response Generalized Linear Models Version 0.7.2 URL https://github.com/ikosmidis/brglm BugReports https://github.com/ikosmidis/brglm/issues Description Fit generalized linear models with binomial responses using either an adjusted-score ap- proach to bias reduction or maximum penalized likelihood where penalization is by Jeffreys in- variant prior. These procedures return estimates with improved frequentist proper- ties (bias, mean squared error) that are always finite even in cases where the maximum likeli- hood estimates are infinite (data separation). Fitting takes place by fitting generalized linear mod- els on iteratively updated pseudo-data. The interface is essentially the same as 'glm'. More flexi- bility is provided by the fact that custom pseudo-data representations can be speci- fied and used for model fitting. Functions are provided for the construction of confidence inter- vals for the reduced-bias estimates. License GPL (>= 2) Depends R (>= 2.6.0), profileModel Suggests MASS NeedsCompilation yes Author <NAME> [aut, cre] (<https://orcid.org/0000-0003-1556-0302>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2021-04-22 11:30:05 UTC R topics documented: brgl... 2 brglm.contro... 7 confint.brgl... 8 gethat... 12 glm.control... 12 lizard... 13 modification... 14 plot.profile.brgl... 18 profile.brgl... 20 profileObjectives-brgl... 21 separation.detectio... 22 brglm Bias reduction in Binomial-response GLMs Description Fits binomial-response GLMs using the bias-reduction method developed in Firth (1993) for the removal of the leading (O(n−1 )) term from the asymptotic expansion of the bias of the maximum likelihood estimator. Fitting is performed using pseudo-data representations, as described in Kos- midis (2007, Chapter 5). For estimation in binomial-response GLMs, the bias-reduction method is an improvement over traditional maximum likelihood because: • the bias-reduced estimator is second-order unbiased and has smaller variance than the maxi- mum likelihood estimator and • the resulting estimates and their corresponding standard errors are always finite while the maximum likelihood estimates can be infinite (in situations where complete or quasi sepa- ration occurs); see Kosmidis & Firth (2021) for the proof of finiteness in logistic regression models. Usage brglm(formula, family = binomial, data, weights, subset, na.action, start = NULL, etastart, mustart, offset, control.glm = glm.control1(...), model = TRUE, method = "brglm.fit", pl = FALSE, x = FALSE, y = TRUE, contrasts = NULL, control.brglm = brglm.control(...), ...) brglm.fit(x, y, weights = rep(1, nobs), start = NULL, etastart = NULL, mustart = NULL, offset = rep(0, nobs), family = binomial(), control = glm.control(), control.brglm = brglm.control(), intercept = TRUE, pl = FALSE) Arguments formula as in glm. family as in glm. brglm currently supports only the "binomial" family with links "logit", "probit", "cloglog", "cauchit". data as in glm. weights as in glm. subset as in glm. na.action as in glm. start as in glm. etastart as in glm. mustart as in glm. offset as in glm. control.glm control.glm replaces the control argument in glm but essentially does the same job. It is a list of parameters to control glm.fit. See the documentation of glm.control1 for details. control same as in glm. Only available to brglm.fit. intercept as in glm. model as in glm. method the method to be used for fitting the model. The default method is "brglm.fit", which uses either the modified-scores approach to estimation or maximum pe- nalized likelihood (see the pl argument below). The standard glm methods "glm.fit" for maximum likelihood and "model.frame" for returning the model frame without any fitting, are also accepted. pl a logical value indicating whether the model should be fitted using maximum penalized likelihood, where the penalization is done using Jeffreys invariant prior, or using the bias-reducing modified scores. It is only used when method = "brglm.fit". The default value is FALSE (see also the Details section). x as in glm. y as in glm. contrasts as in glm. control.brglm a list of parameters for controlling the fitting process when method = "brglm.fit". See documentation of brglm.control for details. ... further arguments passed to or from other methods. Details brglm.fit is the workhorse function for fitting the model using either the bias-reduction method or maximum penalized likelihood. If method = "glm.fit", usual maximum likelihood is used via glm.fit. The main iteration of brglm.fit consists of the following steps: 1. Calculate the diagonal components of the hat matrix (see gethats and hatvalues). 2. Obtain the pseudo-data representation at the current value of the parameters (see modifications for more information). 3. Fit a local GLM, using glm.fit on the pseudo data. 4. Adjust the quadratic weights to agree with the original binomial totals. Iteration is repeated until either the iteration limit has been reached or the sum of the absolute values of the modified scores is less than some specified positive constant (see the br.maxit and br.epsilon arguments in brglm.control). The default value (FALSE) of pl, when method = "brglm.fit", results in estimates that are free of any O(n−1 ) terms in the asymptotic expansion of their bias. When pl = TRUE bias-reduction is again achieved but generally not at such order of magnitude. In the case of logistic regression the value of pl is irrelevant since maximum penalized likelihood and the modified-scores approach coincide for natural exponential families (see Firth, 1993). For other language related details see the details section in glm. Value brglm returns an object of class "brglm". A "brglm" object inherits first from "glm" and then from "lm" and is a list containing the following components: coefficients as in glm. residuals as in glm. fitted.values as in glm. effects as in glm. R as in glm. rank as in glm. qr as in glm. family as in glm. linear.predictors as in glm. deviance as in glm. aic as in glm (see Details). null.deviance as in glm. iter as in glm. weights as in glm. prior.weights as in glm. df.residual as in glm. df.null as in glm. y as in glm. converged as in glm. boundary as in glm. ModifiedScores the vector of the modified scores for the parameters at the final iteration. If pl = TRUE they are the derivatives of the penalized likelihood at the final iteration. FisherInfo the Fisher information matrix evaluated at the resulting estimates. Only avail- able when method = "brglm.fit". hats the diagonal elements of the hat matrix. Only available when method = "brglm.fit" nIter the number of iterations that were required until convergence. Only available when method = "brglm.fit". cur.model a list with components ar and at which contains the values of the additive mod- ifications to the responses (y) and to the binomial totals (prior.weights) at the resulting estimates (see modifications for more information). Only available when method = "brglm.fit". model as in glm. call as in glm. formula as in glm. terms as in glm. data as in glm. offset as in glm. control.glm as control in the result of glm. control.brglm the control.brglm argument that was passed to brglm. Only available when method = "brglm.fit". method the method used for fitting the model. contrasts as in glm. xlevels as in glm. pl logical having the same value with the pl argument passed to brglm. Only available when method = "brglm.fit". Warnings 1. It is not advised to use methods associated with model comparison (add1, drop1, anova, etc.) on objects of class "brglm". Model comparison when estimation is performed using the modified scores or the penalized likelihood is an on-going research topic and will be implemented as soon as it is concluded. 2. The use of Akaike’s information criterion (AIC) for model selection when method = "brglm.fit" is asymptotically valid, because the log-likelihood derivatives dominate the modification (in terms of asymptotic order). Note 1. Supported methods for objects of class "brglm" are: • printthrough print.brglm. • summarythrough summary.brglm. • coefficientsinherited from the "glm" class. • vcovinherited from the"glm" class. • predictinherited from the"glm" class. • residualsinherited from the"glm" class. • and other methods that apply to objects of class "glm" 2. A similar implementation of the bias-reduction method could be done for every GLM, following Kosmidis (2007) (see also Kosmidis and Firth, 2009). The full set of families and links will be available in a future version. However, bias-reduction is not generally beneficial as it is in the binomial family and it could cause inflation of the variance (see Firth, 1993). 3. Basically, the differences between maximum likelihood, maximum penalized likelihood and the modified scores approach are more apparent in small sample sizes, in sparse data sets and in cases where complete or quasi-complete separation occurs. Asymptotically (as n goes to infinity), the three different approaches are equivalent to first order. 4. When an offset is not present in the model, the modified-scores based estimates are usually smaller in magnitude than the corresponding maximum likelihood estimates, shrinking towards the origin of the scale imposed by the link function. Thus, the corresponding estimated asymptotic standard errors are also smaller. The same is true for the maximum penalized likelihood estimates when for example, the logit (where the maximum penalized likelihood and modified-scores approaches coincide) or the pro- bit links are used. However, generally the maximum penalized likelihood estimates do not shrink towards the origin. In terms of mean-value parameterization, in the case of maximum penalized likelihood the fitted probabilities would shrink towards the point where the Jeffreys prior is max- imized or equivalently where the quadratic weights are simultaneously maximized (see Kosmidis, 2007). 5. Implementations of the bias-reduction method for logistic regressions can also be found in the logistf package. In addition to the obvious advantage of brglm in the range of link functions that can be used ("logit", "probit", "cloglog" and "cauchit"), brglm is also more efficient compu- tationally. Furthermore, for any user-specified link function (see the Example section of family), the user can specify the corresponding pseudo-data representation to be used within brglm (see modifications for details). Author(s) <NAME>, <<EMAIL>> References <NAME>. and <NAME>. (2021). Jeffreys-prior penalty, finiteness and shrinkage in binomial- response generalized linear models. Biometrika, 108, 71–82. <NAME>., <NAME>. and <NAME>. (2007). Confidence intervals for multinomial logistic regression in sparse data. Statistics in Medicine 26, 903–918. <NAME>. (1992) Bias reduction, the Jeffreys prior and GLIM. In Advances in GLIM and statisti- cal modelling: Proceedings of the GLIM 92 conference, Munich, Eds. L.~Fahrmeir, B.~Francis, R.~Gilchrist and G.Tutz, pp. 91–100. New York: Springer. Firth, D. (1992) Generalized linear models and Jeffreys priors: An iterative generalized least- squares approach. In Computational Statistics I, Eds. <NAME> and <NAME>. Heidelberg: Physica-Verlag. <NAME>. (1993). Bias reduction of maximum likelihood estimates. Biometrika 80, 27–38. <NAME>. and <NAME>. (2002). A solution to the problem of separation in logistic regression. Statistics in Medicine 21, 2409–2419. <NAME>. (2007). Bias reduction in exponential family nonlinear models. PhD Thesis, Depart- ment of Statistics, University of Warwick. <NAME>. and <NAME>. (2009). Bias reduction in exponential family nonlinear models. Biometrika 96, 793–804. See Also glm, glm.fit Examples ## Begin Example data(lizards) # Fit the GLM using maximum likelihood lizards.glm <- brglm(cbind(grahami, opalinus) ~ height + diameter + light + time, family = binomial(logit), data=lizards, method = "glm.fit") # Now the bias-reduced fit: lizards.brglm <- brglm(cbind(grahami, opalinus) ~ height + diameter + light + time, family = binomial(logit), data=lizards, method = "brglm.fit") lizards.glm lizards.brglm # Other links update(lizards.brglm, family = binomial(probit)) update(lizards.brglm, family = binomial(cloglog)) update(lizards.brglm, family = binomial(cauchit)) # Using penalized maximum likelihood update(lizards.brglm, family = binomial(probit), pl = TRUE) update(lizards.brglm, family = binomial(cloglog), pl = TRUE) update(lizards.brglm, family = binomial(cauchit), pl = TRUE) brglm.control Auxiliary for Controlling BRGLM Fitting Description Auxiliary function as user interface for brglm fitting. Typically only used when calling brglm or brglm.fit. Usage brglm.control(br.epsilon = 1e-08, br.maxit = 100, br.trace=FALSE, br.consts = NULL, ...) Arguments br.epsilon positive convergence tolerance for the iteration described in brglm.fit. br.maxit integer giving the maximum number of iterations for the iteration in brglm.fit. br.trace logical indicating if output should be prooduced for each iteration. br.consts a (small) positive constant or a vector of such. ... further arguments passed to or from other methods. Details If br.trace=TRUE then for each iteration the iteration number and the current value of the modified scores is cat’ed. If br.consts is specified then br.consts is added to the original binomial counts and 2*br.consts. Then the model is fitted to the adjusted data to provide starting values for the iteration in brglm.fit. If br.consts = NULL (default) then brglm.fit adjusts the responses and totals by "number of parameters"/"number of observations" and twice that, respectively. Value A list with the arguments as components. Author(s) <NAME>, <<EMAIL>> References <NAME>. and <NAME>. (2021). Jeffreys-prior penalty, finiteness and shrinkage in binomial- response generalized linear models. Biometrika, 108, 71–82. <NAME>. (2007). Bias reduction in exponential family nonlinear models. PhD Thesis, Depart- ment of Statistics, University of Warwick. See Also brglm.fit, the fitting procedure used by brglm. confint.brglm Computes confidence intervals of parameters for bias-reduced estima- tion Description Computes confidence intervals for one or more parameters when estimation is performed using brglm. The resulting confidence intervals are based on manipulation of the profiles of the deviance, the penalized deviance and the modified score statistic (see profileObjectives). Usage ## S3 method for class 'brglm' confint(object, parm = 1:length(coef(object)), level = 0.95, verbose = TRUE, endpoint.tolerance = 0.001, max.zoom = 100, zero.bound = 1e-08, stepsize = 0.5, stdn = 5, gridsize = 10, scale = FALSE, method = "smooth", ci.method = "union", n.interpolations = 100, ...) ## S3 method for class 'profile.brglm' confint(object, parm, level = 0.95, method = "smooth", ci.method = "union", endpoint.tolerance = 0.001, max.zoom = 100, n.interpolations = 100, verbose = TRUE, ...) Arguments object an object of class "brglm" or "profile.brglm". parm either a numeric vector of indices or a character vector of names, specifying the parameters for which confidence intervals are to be estimated. The default is all parameters in the fitted model. When object is of class "profile.brglm", parm is not used and confidence intervals are returned for all the parameters for which profiling took place. level the confidence level required. The default is 0.95. When object is of class "profile.brglm", level is not used and the level attribute of object is used instead. verbose logical. If TRUE (default) progress indicators are printed during the progress of calculating the confidence intervals. endpoint.tolerance as in confintModel. max.zoom as in confintModel. zero.bound as in confintModel. stepsize as in confintModel. stdn as in confintModel. gridsize as in confintModel. scale as in confintModel. method as in confintModel. ci.method The method to be used for the construction of confidence intervals. It can take values "union" (default) and "mean" (see Details). n.interpolations as in confintModel. ... further arguments to or from other methods. Details In the case of logistic regression <NAME> (2002) and Bull et. al. (2007) suggest the use of confidence intervals based on the profiles of the penalized likelihood, when estimation is performed using maximum penalized likelihood. Kosmidis (2007) illustrated that because of the shape of the penalized likelihood, confidence in- tervals based on the penalized likelihood could exhibit low or even zero coverage for hypothesis testing on large parameter values and also misbehave illustrating severe oscillation (see Brown et. al., 2001); see, also Kosmidis & Firth (2021) for discussion on the schrinkage implied by bias re- duction and what that entails for inference. Kosmidis (2007) suggested an alternative confidence interval that is based on the union of the confidence intervals resulted by profiling the ordinary de- viance for the maximum likelihood fit and by profiling the penalized deviance for the maximum penalized fit. Such confidence intervals, despite of being slightly conservative, illustrate less oscil- lation and avoid the loss of coverage. Another possibility is to use the mean of the corresponding endpoints instead of “union”. Yet unpublished simulation studies suggest that such confidence in- tervals are not as conservative as the “union” based intervals but illustrate more oscillation, which however is not as severe as in the case of the penalized likelihood based ones. The properties of the “union” and “mean” confidence intervals extend to all the links that are sup- ported by brglm, when estimation is performed using maximum penalized likelihood. In the case of estimation using modified scores and for models other than logistic, where there is not an objective that is maximized, the profiles of the penalized likelihood for the construction of the “union” and “mean” confidence intervals can be replaced by the profiles of modified score statistic (see profileObjectives). The confint method for brglm and profile.brglm objects implements the “union” and “mean” confidence intervals. The method is chosen through the ci.method argument. Value A matrix with columns the endpoints of the confidence intervals for the specified (or profiled) parameters. Author(s) <NAME>, <<EMAIL>> References <NAME>. and <NAME>. (2021). Jeffreys-prior penalty, finiteness and shrinkage in binomial- response generalized linear models. Biometrika, 108, 71–82. <NAME>., <NAME>. and <NAME>. (2001). Interval estimation for a binomial proportion (with discussion). Statistical Science 16, 101–117. <NAME>., <NAME>. and <NAME>. (2007). Confidence intervals for multinomial logistic regression in sparse data. Statistics in Medicine 26, 903–918. <NAME>. and <NAME>. (2002). A solution to the problem of separation in logistic regression. Statistics in Medicine 21, 2409–2419. <NAME>. (2007). Bias reduction in exponential family nonlinear models. PhD Thesis, Depart- ment of Statistics, University of Warwick. See Also confintModel, profileModel, profile.brglm. Examples ## Begin Example 1 ## Not run: library(MASS) data(bacteria) contrasts(bacteria$trt) <- structure(contr.sdif(3), dimnames = list(NULL, c("drug", "encourage"))) # fixed effects analyses m.glm.logit <- brglm(y ~ trt * week, family = binomial, data = bacteria, method = "glm.fit") m.brglm.logit <- brglm(y ~ trt * week, family = binomial, data = bacteria, method = "brglm.fit") p.glm.logit <- profile(m.glm.logit) p.brglm.logit <- profile(m.brglm.logit) # plot(p.glm.logit) plot(p.brglm.logit) # confidence intervals for the glm fit based on the profiles of the # ordinary deviance confint(p.glm.logit) # confidence intervals for the brglm fit confint(p.brglm.logit, ci.method = "union") confint(p.brglm.logit, ci.method = "mean") # A cloglog link m.brglm.cloglog <- update(m.brglm.logit, family = binomial(cloglog)) p.brglm.cloglog <- profile(m.brglm.cloglog) plot(p.brglm.cloglog) confint(m.brglm.cloglog, ci.method = "union") confint(m.brglm.cloglog, ci.method = "mean") ## End example ## End(Not run) ## Not run: ## Begin Example 2 y <- c(1, 1, 0, 0) totals <- c(2, 2, 2, 2) x1 <- c(1, 0, 1, 0) x2 <- c(1, 1, 0, 0) m1 <- brglm(y/totals ~ x1 + x2, weights = totals, family = binomial(cloglog)) p.m1 <- profile(m1) confint(p.m1, method="zoom") ## End(Not run) gethats Calculates the Leverages for a GLM through a C Routine Description Calculates the leverages of a GLM through a C routine. It is intended to be used only within brglm.fit. Usage gethats(nobs, nvars, x.t, XWXinv, ww) Arguments nobs The number of observations, i.e. dim(X)[1]. nvars The number of parameters, i.e. dim(X)[1], where X is the model matrix, ex- cluding the columns that correspond to aliased parameters. x.t t(X). XWXinv The inverse of the Fisher information. ww The ‘working’ weights. Value A vector containing the diagonal elements of the hat matrix. Author(s) <NAME>, <<EMAIL>> See Also hatvalues, brglm.fit glm.control1 Auxiliary for Controlling BRGLM Fitting Description Auxiliary function as user interface for brglm fitting. Typically only used when calling brglm or brglm.fit. Usage glm.control1(epsilon = 1e-08, maxit = 25, trace = FALSE, ...) Arguments epsilon as in glm.control. maxit as in glm.control. trace as in glm.control. ... further arguments passed to or from other methods. Details The only difference with glm.control is that glm.control1 supports further arguments to be passed from other methods. However, this additional arguments have no effect on the resulting list. Author(s) <NAME>, <<EMAIL>> lizards Habitat Preferences of Lizards Description The lizards data frame has 23 rows and 6 columns. Variables grahami and opalinus are counts of two lizard species at two different perch heights, two different perch diameters, in sun and in shade, at three times of day. Usage data(lizards) Format This data frame contains the following columns: grahami count of grahami lizards opalinus count of opalinus lizards height a factor with levels "<5ft", ">=5ft" diameter a factor with levels "<=2in", ">2in" light a factor with levels "sunny", "shady" time a factor with levels "early", "midday", "late" Source <NAME>. and <NAME>. (1989) Generalized Linear Models (2nd Edition). London: Chap- man and Hall. Originally from <NAME>. (1970) Nonsynchronous spatial overlap of lizards in patchy habitats. Ecology 51, 408–418. Examples data(lizards) glm(cbind(grahami, opalinus) ~ height + diameter + light + time, family = binomial, data=lizards) brglm(cbind(grahami, opalinus) ~ height + diameter + light + time, family = binomial, data=lizards) modifications Additive Modifications to the Binomial Responses and Totals for Use within ‘brglm.fit’ Description Get, test and set the functions that calculate the additive modifications to the responses and totals in binomial-response GLMs, for the application of bias-reduction either via modified scores or via maximum penalized likelihood (where penalization is by Jeffreys invariant prior). Usage modifications(family, pl = FALSE) Arguments family a family object of the form binomial(link = "link"), where "link" can be one of "logit", "probit", "cloglog" and "cauchit". The usual ways of giving the family name are supported (see family). pl logical determining whether the function returned corresponds to modifications for the penalized maximum likelihood approach or for the modified-scores ap- proach to bias-reduction. Default value is FALSE. Details The function returned from modifications accepts the argument p which are the binomial prob- abilities and returns a list with components ar and at, which are the link-dependent parts of the additive modifications to the actual responses and totals, respectively. Since the resulting function is used in brglm.fit, for efficiency reasons no check is made for p >= 0 | p <= 1, for length(at) == length(p) and for length(ap) == length(p). Construction of custom pseudo-data representations If y ∗ are the pseudo-responses (pseudo-counts) and m∗ are the pseudo-totals then we call the pair (y ∗ , m∗ ) a pseudo-data representation. Both the modified-scores approach and the maximum pe- nalized likelihood have a common property: there exists (y ∗ , m∗ ) such that if we replace the actual data (y, m) with (y ∗ , m∗ ) in the expres- sion for the ordinary scores (first derivatives of the likelihood) of a binomial-response GLM, then we end-up either with the modified-scores or with the derivatives of the penalized likelihood (see Kosmidis, 2007, Chapter 5). Let µ be the mean of the binomial response y (i.e. µ = mp, where p is the binomial probability corresponding to the count y). Also, let d and d0 denote the first and the second derivatives, respec- tively, of µ with respect to the linear predictor η of the model. All the above are viewed as functions of p. The pseudo-data representations have the generic form pseudo-response : y ∗ = y + har (p) pseudo-totals : m∗ = m + hat (p), where h is the leverage corresponding to y. The general expressions for ar (p) ("r" for "response") and at (p) ("t" for "totals") are: modified-scores approach ar (p) = d0 (p)/(2w(p)) at (p) = 0, maximum penalized likelihood approach ar (p) = d0 (p)/w(p) + p − 0.5 at (p) = 0. For supplying (y ∗ , m∗ ) in glm.fit (as is done by brglm.fit), an essential requirement for the pseudo-data representation is that it should mimic the behaviour of the original responses and totals, i.e. 0 ≤ y ∗ ≤ m∗ . Since h ∈ [0, 1], the requirement translates to 0 ≤ ar (p) ≤ at (p) for every p ∈ (0, 1). However, the above definitions of ar (p) and at (p) do not necessarily respect this requirement. On the other hand, the pair (ar (p), at (p)) is not unique in the sense that for a given link function and once the link-specific structure of the pair has been extrapolated, there is a class of equivalent pairs that can be resulted following only the following two rules: • add and subtract the same quantity from either ar (p) or at (p). • if a quantity is to be moved from ar (p) to at (p) it first has to be divided by −p. For example, in the case of penalized maximum likelihood, the pairs (d0 (p)/w(p) + p − 0.5, 0) and (d0 (p)/w(p) + p, 0.5/p) are equivalent, in the sense that if the corresponding pseudo-data representations are substituted in the ordinary scores both return the same expression. So, in order to construct a pseudo-data representation that corresponds to a user-specified link func- tion and has the property 0 ≤ ar (p) ≤ at (p) for every p ∈ (0, 1), one merely has to pursue a simple algebraic calculation on the initial pair (ar (p), at (p)) using only the two aforementioned rules until an appropriate pair is resulted. There is always a pair! Once the pair has been found the following steps should be followed. 1. For a user-specified link function the user has to write a modification function with name "br.custom.family" or "pml.custom.family" for pl=FALSE or pl=TRUE, respectively. The func- tion should take as argument the probabilities p and return a list of two vectors with same length as p and with names c("ar", "at"). The result corresponds to the pair (ar (p), at (p)). 2. Check if the custom-made modifications function is appropriate. This can be done via the function checkModifications which has arguments fun (the function to be tested) and Length with default value Length=100. Length is to be used when the user-specified link function takes as argument a vector of values (e.g. the logexp link in ?family). Then the value of Length should be the length of that vector. 3. Put the function in the search patch so that modifications can find it. 4. brglm can now be used with the custom family as glm would be used. Note The user could also deviate from modified-scores and maximum penalized likelihood and exper- iment with implemented (or not) links, e.g. probit, constructing his own pseudo-data represen- tations of the aforementioned general form. This could be done by changing the link name, e.g. by probitt <- make.link(probit) ; probitt$name <- "probitt" and then setting a custom br.custom.family that does not necessarily depend on the probit link. Then, brglm could be used with pl=FALSE. A further generalization would be to completely remove the hat value h in the generic expression of the pseudo-data representation and have general additive modifications that depend on p. To do this divide both ar and at by pmax(get("hats",parent.frame()),.Machine\$double.eps) within the custom modification function (see also Examples). Author(s) <NAME>, <<EMAIL>> References <NAME>. and <NAME>. (2021). Jeffreys-prior penalty, finiteness and shrinkage in binomial- response generalized linear models. Biometrika, 108, 71–82. Kosmidis, I. (2007). Bias reduction in exponential family nonlinear models. PhD Thesis, Depart- ment of Statistics, University of Warwick. See Also brglm, brglm.fit Examples ## Begin Example 1 ## logistic exposure model, following the Example in ?family. See, ## <NAME>. 2004. Auk 121(2): 526-540. # Definition of the link function logexp <- function(days = 1) { linkfun <- function(mu) qlogis(mu^(1/days)) linkinv <- function(eta) plogis(eta)^days mu.eta <- function(eta) days * plogis(eta)^(days-1) * binomial()$mu.eta(eta) valideta <- function(eta) TRUE link <- paste("logexp(", days, ")", sep="") structure(list(linkfun = linkfun, linkinv = linkinv, mu.eta = mu.eta, valideta = valideta, name = link), class = "link-glm") } # Here d(p) = days * p * ( 1 - p^(1/days) ) # d'(p) = (days - (days+1) * p^(1/days)) * d(p) # w(p) = days^2 * p * (1-p^(1/days))^2 / (1-p) # Initial modifications, as given from the general expressions above: br.custom.family <- function(p) { etas <- binomial(logexp(.days))$linkfun(p) # the link function argument `.days' will be detected by lexical # scoping. So, make sure that the link-function inputted arguments # have unusual names, like `.days' and that # the link function enters `brglm' as # `family=binomial(logexp(.days))'. list(ar = 0.5*(1-p)-0.5*(1-p)*exp(etas)/.days, at = 0*p/p) # so that to fix the length of at } .days <-3 # `.days' could be a vector as well but then it should have the same # length as the number of observations (`length(.days)' should be # equal to `length(p)'). In this case, `checkModifications' should # have argument `Length=length(.days)'. # # Check: ## Not run: checkModifications(br.custom.family) # OOOPS error message... the condition is not satisfied # # After some trivial algebra using the two allowed operations, we # get new modifications: br.custom.family <- function(p) { etas <- binomial(logexp(.days))$linkfun(p) list(ar=0.5*p/p, # so that to fix the length of ar at=0.5+exp(etas)*(1-p)/(2*p*.days)) } # Check: checkModifications(br.custom.family) # It is OK. # Now, modifications(binomial(logexp(.days))) # works. # Notice that for `.days <- 1', `logexp(.days)' is the `logit' link # model and `a_r=0.5', `a_t=1'. # In action: library(MASS) example(birthwt) m.glm <- glm(formula = low ~ ., family = binomial, data = bwt) .days <- bwt$age m.glm.logexp <- update(m.glm,family=binomial(logexp(.days))) m.brglm.logexp <- brglm(formula = low ~ ., family = binomial(logexp(.days)), data = bwt) # The fit for the `logexp' link via maximum likelihood m.glm.logexp # and the fit for the `logexp' link via modified scores m.brglm.logexp ## End Example ## Begin Example 2 ## Another possible use of brglm.fit: ## Deviating from bias reducing modified-scores: ## Add 1/2 to the response of a probit model. y <- c(1,2,3,4) totals <- c(5,5,5,5) x1 <- c(1,0,1,0) x2 <- c(1,1,0,0) my.probit <- make.link("probit") my.probit$name <- "my.probit" br.custom.family <- function(p) { h <- pmax(get("hats",parent.frame()),.Machine$double.eps) list(ar=0.5/h,at=1/h) } m1 <- brglm(y/totals~x1+x2,weights=totals,family=binomial(my.probit)) m2 <- glm((y+0.5)/(totals+1)~x1+x2,weights=totals+1,family=binomial(probit)) # m1 and m2 should be the same. # End example # Begin example 3: Maximum penalized likelihood for logistic regression, # with the penalty being a powerof the Jeffreys prior (`.const` below) # Setup a custom logit link mylogit <- make.link("logit") mylogit$name <- "mylogit" ## Set-up the custom family br.custom.family <- function(p) { list(ar = .const * p/p, at = 2 * .const * p/p) } data("lizards") ## The reduced-bias fit is .const <- 1/2 brglm(cbind(grahami, opalinus) ~ height + diameter + light + time, family = binomial(mylogit), data=lizards) ## which is the same as what brglm does by default for logistic regression brglm(cbind(grahami, opalinus) ~ height + diameter + light + time, family = binomial(logit), data=lizards) ## Stronger penalization (e.g. 5/2) can be achieved by .const <- 5/2 brglm(cbind(grahami, opalinus) ~ height + diameter + light + time, family = binomial(mylogit), data=lizards) # End example plot.profile.brglm Plot methods for ’profile.brglm’ objects Description plot.profile.brglm plots the objects of class "profileModel" that are contained in an object of class "profile.brglm". pairs.profile.brglm is a diagnostic tool that plots pairwise profile traces. Usage ## S3 method for class 'profile.brglm' plot(x, signed = FALSE, interpolate = TRUE, n.interpolations = 100, print.grid.points = FALSE, ...) ## S3 method for class 'profile.brglm' pairs(x, colours = 2:3, ...) Arguments x a "profile.brglm" object. signed as in plot.profileModel. interpolate as in plot.profileModel. n.interpolations as in plot.profileModel. print.grid.points as in plot.profileModel. colours as in plot.profileModel. ... further arguments passed to or from other methods. Details See Details in plot.profileModel. Author(s) <NAME>, <<EMAIL>> See Also plot.profileModel, profile.brglm. Examples # see example in 'confint.brglm'. profile.brglm Calculate profiles for objects of class ’brglm’. Description Creates "profile.brglm" objects to be used for the calculation of confidence intervals and for plotting. Usage ## S3 method for class 'brglm' profile(fitted, gridsize = 10, stdn = 5, stepsize = 0.5, level = 0.95, which = 1:length(coef(fitted)), verbose = TRUE, zero.bound = 1e-08, scale = FALSE, ...) Arguments fitted an object of class "brglm". gridsize as in profileModel. stdn as in profileModel. stepsize as in profileModel. level qchisq(level,1) indicates the range that the profiles must cover. which as in profileModel. verbose as in profileModel. zero.bound as in profileModel. scale as in profileModel. ... further arguments passed to or from other methods. Details profile.brglm calculates the profiles of the appropriate objectives to be used for the construction of confidence intervals for the bias-reduced estimates (see confint.brglm for the objectives that are profiled). Value An object of class "profile.glm" with attribute “level” corresponding to the argument level. The object supports the methods print, plot, pairs and confint and it is a list of the components: profilesML a "profileModel" object containing the profiles of the ordinary deviance for the maximum likelihood fit corresponding to fitted. profilesBR NULL if method = "glm.fit" in brglm. If method = "brglm.fit" and pl = TRUE, profilesBR is a "profileModel" object containing the profiles of the penalized deviance for the parameters of fitted. If method = "brglm.fit" and pl = FALSE profilesBR is a "profileModel" object containing the profiles of the modified score statistic (see profileObjectives) for the parameters of fitted. Note Objects of class "profile.brglm" support the methods: • printwhich prints the "level" attribute of the object, as well as the supported methods. • confintsee confint.brglm. • plotsee plot.profile.brglm. • pairssee plot.profile.brglm. Author(s) <NAME>, <<EMAIL>> See Also profileModel, profile.brglm. Examples # see example in 'confint.brglm'. profileObjectives-brglm Objectives to be profiled Description Objectives that are used in profile.brglm Usage penalizedDeviance(fm, X, dispersion = 1) modifiedScoreStatistic(fm, X, dispersion = 1) Arguments fm the restricted fit. X the model matrix of the fit on all parameters. dispersion the dispersion parameter. Details These objectives follow the specifications for objectives in the profileModel package and are used from profile.brglm. penalizedDeviance returns a deviance-like value corresponding to a likelihood function penalized by Jeffreys invariant prior. It has been used by Heinze & Schemper (2002) and by Bull et. al. (2002) for the construction of confidence intervals for the bias-reduced estimates in logistic regression. The X argument is the model matrix of the full (not the restricted) fit. modifiedScoreStatistic mimics RaoScoreStatistic in profileModel, but with the ordinary scores replaced with the modified scores used for bias reduction. The argument X has the same interpretation as for penalizedDeviance. Value A scalar. Author(s) <NAME>, <<EMAIL>> References <NAME>. and <NAME>. (2021). Jeffreys-prior penalty, finiteness and shrinkage in binomial- response generalized linear models. Biometrika, 108, 71–82. <NAME>., <NAME>. and <NAME>. (2007). Confidence intervals for multinomial logistic regression in sparse data. Statistics in Medicine 26, 903–918. <NAME>. and <NAME>. (2002). A solution to the problem of separation in logistic regression. Statistics in Medicine 21, 2409–2419. See Also profileModel, profile.brglm. separation.detection Separation Identification. Description Provides a tool for identifying whether or not separation has occurred. Usage separation.detection(fit, nsteps = 30) Arguments fit the result of a glm call. nsteps Starting from maxit = 1, the GLM is refitted for maxit = 2, maxit = 3, . . . , maxit = nsteps. Default value is 30. Details Identifies separated cases for binomial-response GLMs, by refitting the model. At each iteration the maximum number of allowed IWLS iterations is fixed starting from 1 to nsteps (by setting control = glm.control(maxit = j), where j takes values 1, . . . , nsteps in glm). For each value of maxit, the estimated asymptotic standard errors are divided to the corresponding ones resulted for control = glm.control(maxit = 1). Based on the results in Lesaffre & Albert (1989), if the sequence of ratios in any column of the resulting matrix diverges, then separation occurs and the maximum likelihood estimate for the corresponding parameter has value minus or plus infinity. Value A matrix of dimension nsteps by length(coef(fit)), that contains the ratios of the estimated asymptotic standard errors. Author(s) <NAME>, <<EMAIL>> References <NAME>. and <NAME>. (2021). Jeffreys-prior penalty, finiteness and shrinkage in binomial- response generalized linear models. Biometrika, 108, 71–82. Lesaffre, E. and <NAME>. (1989). Partial separation in logistic discrimination. J. R. Statist. Soc. B, 51, 109–116. Examples ## Begin Example y <- c(1,1,0,0) totals <- c(2,2,2,2) x1 <- c(1,0,1,0) x2 <- c(1,1,0,0) m1 <- glm(y/totals ~ x1 + x2, weights = totals, family = binomial()) # No warning from glm... m1 # However estimates for (Intercept) and x2 are unusually large in # absolute value... Investigate further: # separation.detection(m1,nsteps=30) # Note that the values in the column for (Intercept) and x2 diverge, # while for x1 converged. Hence, separation has occurred and the # maximum lieklihood estimate for (Intercept) is minus infinity and # for x2 is plus infinity. The signs for infinity are taken from the # signs of (Intercept) and x1 in coef(m1). 24 separation.detection ## End Example
ckb-metrics-config
rust
Rust
Crate ckb_metrics_config === CKB metrics configurations. This crate is used to configure the CKB metrics service. Structs --- * ConfigThe whole CKB metrics configuration. * ExporterThe configuration of an exporter. Enums --- * TargetThe target to output the metrics data. Crate ckb_metrics_config === CKB metrics configurations. This crate is used to configure the CKB metrics service. Structs --- * ConfigThe whole CKB metrics configuration. * ExporterThe configuration of an exporter. Enums --- * TargetThe target to output the metrics data. Struct ckb_metrics_config::Config === ``` pub struct Config { pub exporter: HashMap<String, Exporter>, } ``` The whole CKB metrics configuration. This struct is used to configure CKB metrics service. An example which is used in `ckb.toml`: --- ``` [metrics.exporter.prometheus] target = { type = "prometheus", listen_address = "127.0.0.1:8100" } ``` Fields --- `exporter: HashMap<String, Exporter>`Stores all exporters configurations. Trait Implementations --- ### impl Clone for Config #### fn clone(&self) -> Config Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Config Returns the “default value” for a type. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Config ### impl Send for Config ### impl Sync for Config ### impl Unpin for Config ### impl UnwindSafe for Config Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct ckb_metrics_config::Exporter === ``` pub struct Exporter { pub target: Target, } ``` The configuration of an exporter. Fields --- `target: Target`How to output the metrics data. Trait Implementations --- ### impl Clone for Exporter #### fn clone(&self) -> Exporter Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Exporter ### impl Send for Exporter ### impl Sync for Exporter ### impl Unpin for Exporter ### impl UnwindSafe for Exporter Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Enum ckb_metrics_config::Target === ``` pub enum Target { Prometheus { listen_address: String, }, } ``` The target to output the metrics data. Variants --- ### Prometheus #### Fields `listen_address: String`The HTTP listen address. Outputs the metrics data through Prometheus. Trait Implementations --- ### impl Clone for Target #### fn clone(&self) -> Target Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Target ### impl Send for Target ### impl Sync for Target ### impl Unpin for Target ### impl UnwindSafe for Target Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,
PointersAndMemory.pdf
free_programming_book
Unknown
Pointers and Memory By <NAME> Copyright 1998-2000, <NAME> Abstract This document explains how pointers and memory work and how to use themfrom the basic concepts through all the major programming techniques. For each topic there is a combination of discussion, sample C code, and drawings. Audience This document can be used as an introduction to pointers for someone with basic programming experience. Alternately, it can be used to review and to fill in gaps for someone with a partial understanding of pointers and memory. Many advanced programming and debugging problems only make sense with a complete understanding of pointers and memory this document tries to provide that understanding. This document concentrates on explaining how pointers work. For more advanced pointer applications and practice problems, see the other resources below. Pace Like most CS Education Library documents, the coverage here tries to be complete but fast. The document starts with the basics and advances through all the major topics. The pace is fairly quick each basic concept is covered once and usually there is some example code and a memory drawing. Then the text moves on to the next topic. For more practice, you can take the time to work through the examples and sample problems. Also, see the references below for more practice problems. Topics Topics include: pointers, local memory, allocation, deallocation, dereference operations, pointer assignment, deep vs. shallow copies, the ampersand operator (&), bad pointers, the NULL pointer, value parameters, reference parameters, heap allocation and deallocation, memory ownership models, and memory leaks. The text focuses on pointers and memory in compiled languages like C and C++. At the end of each section, there is some related but optional material, and in particular there are occasional notes on other languages, such as Java. Pointers and Memory document #102 in the Stanford CS Education Library. This and other free educational materials are available at http://cslibrary.stanford.edu/102/. This document is free to be used, reproduced, sold, or retransmitted so long as this notice is clearly reproduced at its beginning. Other CS Education Library Documents Point Fun With Binky Video (http://cslibrary.stanford.edu/104/) A silly video about pointer basics. Linked list Basics (http://cslibrary.stanford.edu/103/) Introduces the basic techniques for building linked lists in C. 2 Linked List Problems (http://cslibrary.stanford.edu/105/) 18 classic linked list problems with solutions a great way to practice with realistic, pointer intensive C code, and there's just no substitute for practice! Essential C (http://cslibrary.stanford.edu/101/) Complete coverage of the C language, including all of the syntax used in this document. Table of Contents Section 1 Basic Pointers... pg. 3 The basic rules and drawings for pointers: pointers, pointees, pointer assignment (=), pointer comparison (==), the ampersand operator (&), the NULL pointer, bad pointers, and bad dereferences. Section 2 Local Memory ... pg. 11 How local variables and parameters work: local storage, allocation, deallocation, the ampersand bug. Understanding the separation of local memory between separate functions. Section 3 Reference Parameters... pg. 17 Combines the previous two sections to show how a function can use "reference parameters" to communicate back to its caller. Section 4 Heap Memory ... pg. 24 Builds on all the previous sections to explain dynamic heap memory: heap allocation, heap deallocation, array allocation, memory ownership models, and memory leaks. Edition The first edition of this document was on Jan 19, 1999. This Feb 21, 2000 edition represents only very minor changes. The author may be reached at <EMAIL>. The CS Education Library may be reached at <EMAIL>. Dedication This document is distributed for the benefit and education of all. That someone seeking education should have the opportunity to find it. May you learn from it in the spirit in which it is given to make efficiency and beauty in your designs, peace and fairness in your actions. Preface To The First Edition This article has appeared to hover at around 80% done for 6 months! Every time I add one section, I think of two more which also need to be written. I was motivated to keep working on it since there are so many other articles which use memory, &, ... in passing where I wanted something to refer to. I hope you find it valuable in its current form. I'm going to ship it quickly before I accidentally start adding another section! 3 Section 1 Basic Pointers Pointers Before and After There's a lot of nice, tidy code you can write without knowing about pointers. But once you learn to use the power of pointers, you can never go back. There are too many things that can only be done with pointers. But with increased power comes increased responsibility. Pointers allow new and more ugly types of bugs, and pointer bugs can crash in random ways which makes them more difficult to debug. Nonetheless, even with their problems, pointers are an irresistibly powerful programming construct. (The following explanation uses the C language syntax where a syntax is required; there is a discussion of Java at the section.) Why Have Pointers? Pointers solve two common software problems. First, pointers allow different sections of code to share information easily. You can get the same effect by copying information back and forth, but pointers solve the problem better. Second, pointers enable complex "linked" data structures like linked lists and binary trees. What Is A Pointer? Simple int and float variables operate pretty intuitively. An int variable is like a box which can store a single int value such as 42. In a drawing, a simple variable is a box with its current value drawn inside. num 42 A pointer works a little differently it does not store a simple value directly. Instead, a pointer stores a reference to another value. The variable the pointer refers to is sometimes known as its "pointee". In a drawing, a pointer is a box which contains the beginning of an arrow which leads to its pointee. (There is no single, official, word for the concept of a pointee pointee is just the word used in these explanations.) The following drawing shows two variables: num and numPtr. The simple variable num contains the value 42 in the usual way. The variable numPtr is a pointer which contains a reference to the variable num. The numPtr variable is the pointer and num is its pointee. What is stored inside of numPtr? Its value is not an int. Its value is a reference to an int. num numPtr 42 A simple int variable. The current value is the integer 42. This variable also plays the role of pointee for the pointer below. A pointer variable. The current value is a reference to the pointee num above. 4 Pointer Dereference The "dereference" operation follows a pointer's reference to get the value of its pointee. The value of the dereference of numPtr above is 42. When the dereference operation is used correctly, it's simple. It just accesses the value of the pointee. The only restriction is that the pointer must have a pointee for the dereference to access. Almost all bugs in pointer code involve violating that one restriction. A pointer must be assigned a pointee before dereference operations will work. The NULL Pointer The constant NULL is a special pointer value which encodes the idea of "points to nothing." It turns out to be convenient to have a well defined pointer value which represents the idea that a pointer does not have a pointee. It is a runtime error to dereference a NULL pointer. In drawings, the value NULL is usually drawn as a diagonal line between the corners of the pointer variable's box... numPtr The C language uses the symbol NULL for this purpose. NULL is equal to the integer constant 0, so NULL can play the role of a boolean false. Official C++ no longer uses the NULL symbolic constant use the integer constant 0 directly. Java uses the symbol null. Pointer Assignment The assignment operation (=) between two pointers makes them point to the same pointee. It's a simple rule for a potentially complex situation, so it is worth repeating: assigning one pointer to another makes them point to the same thing. The example below adds a second pointer, second, assigned with the statement second = numPtr;. The result is that second points to the same pointee as numPtr. In the drawing, this means that the second and numPtr boxes both contain arrows pointing to num. Assignment between pointers does not change or even touch the pointees. It just changes which pointee a pointer refers to. num numPtr second 42 A second pointer ptr initialized with the assignment second = numPtr;. This causes second to refer to the same pointeee as numPtr. After assignment, the == test comparing the two pointers will return true. For example (second==numPtr) above is true. The assignment operation also works with the NULL value. An assignment operation with a NULL pointer copies the NULL value from one pointer to another. Make A Drawing Memory drawings are the key to thinking about pointer code. When you are looking at code, thinking about how it will use memory at run time....make a quick drawing to work out your ideas. This article certainly uses drawings to show how pointers work. That's the way to do it. 5 Sharing Two pointers which both refer to a single pointee are said to be "sharing". That two or more entities can cooperatively share a single memory structure is a key advantage of pointers in all computer languages. Pointer manipulation is just technique sharing is often the real goal. In Section 3 we will see how sharing can be used to provide efficient communication between parts of a program. Shallow and Deep Copying In particular, sharing can enable communication between two functions. One function passes a pointer to the value of interest to another function. Both functions can access the value of interest, but the value of interest itself is not copied. This communication is called "shallow" since instead of making and sending a (large) copy of the value of interest, a (small) pointer is sent and the value of interest is shared. The recipient needs to understand that they have a shallow copy, so they know not to change or delete it since it is shared. The alternative where a complete copy is made and sent is known as a "deep" copy. Deep copies are simpler in a way, since each function can change their copy without interfering with the other copy, but deep copies run slower because of all the copying. The drawing below shows shallow and deep copying between two functions, A() and B(). In the shallow case, the smiley face is shared by passing a pointer between the two. In the deep case, the smiley face is copied, and each function gets their own... Shallow / Sharing Deep / Copying A() A() B() B() Section 2 will explain the above sharing technique in detail. Bad Pointers When a pointer is first allocated, it does not have a pointee. The pointer is "uninitialized" or simply "bad". A dereference operation on a bad pointer is a serious runtime error. If you are lucky, the dereference operation will crash or halt immediately (Java behaves this way). If you are unlucky, the bad pointer dereference will corrupt a random area of memory, slightly altering the operation of the program so that it goes wrong some indefinite time later. Each pointer must be assigned a pointee before it can support dereference operations. Before that, the pointer is bad and must not be used. In our memory drawings, the bad pointer value is shown with an XXX value... numPtr Bad pointers are very common. In fact, every pointer starts out with a bad value. Correct code overwrites the bad value with a correct reference to a pointee, and thereafter the pointer works fine. There is nothing automatic that gives a pointer a valid pointee. 6 Quite the opposite most languages make it easy to omit this important step. You just have to program carefully. If your code is crashing, a bad pointer should be your first suspicion. Pointers in dynamic languages such as Perl, LISP, and Java work a little differently. The run-time system sets each pointer to NULL when it is allocated and checks it each time it is dereferenced. So code can still exhibit pointer bugs, but they will halt politely on the offending line instead of crashing haphazardly like C. As a result, it is much easier to locate and fix pointer bugs in dynamic languages. The run-time checks are also a reason why such languages always run at least a little slower than a compiled language like C or C++. Two Levels One way to think about pointer code is that operates at two levels pointer level and pointee level. The trick is that both levels need to be initialized and connected for things to work. (1) the pointer must be allocated, (1) the pointee must be allocated, and (3) the pointer must be assigned to point to the pointee. It's rare to forget step (1). But forget (2) or (3), and the whole thing will blow up at the first dereference. Remember to account for both levels make a memory drawing during your design to make sure it's right. Syntax The above basic features of pointers, pointees, dereferencing, and assigning are the only concepts you need to build pointer code. However, in order to talk about pointer code, we need to use a known syntax which is about as interesting as....a syntax. We will use the C language syntax which has the advantage that it has influenced the syntaxes of several languages. Pointer Type Syntax A pointer type in C is just the pointee type followed by a asterisk (*)... int* type: pointer to int float* type: pointer to float struct fraction* type: pointer to struct fraction struct fraction** type: pointer to struct fraction* Pointer Variables Pointer variables are declared just like any other variable. The declaration gives the type and name of the new variable and reserves memory to hold its value. The declaration does not assign a pointee for the pointer the pointer starts out with a bad value. int* numPtr; // Declare the int* (pointer to int) variable "numPtr". // This allocates space for the pointer, but not the pointee. // The pointer starts out "bad". 7 The & Operator Reference To There are several ways to compute a reference to a pointee suitable for storing in a pointer. The simplest way is the & operator. The & operator can go to the left of any variable, and it computes a reference to that variable. The code below uses a pointer and an & to produce the earlier num/numPtr example. num 42 numPtr void NumPtrExample() { int num; int* numPtr; num = 42; numPtr = &num; // Compute a reference to "num", and store it in numPtr // At this point, memory looks like drawing above } It is possible to use & in a way which compiles fine but which creates problems at run time the full discussion of how to correctly use & is in Section 2. For now we will just use & in a simple way. The * Operator Dereference The star operator (*) dereferences a pointer. The * is a unary operator which goes to the left of the pointer it dereferences. The pointer must have a pointee, or it's a runtime error. Example Pointer Code With the syntax defined, we can now write some pointer code that demonstrates all the pointer rules... void PointerTest() { // allocate three integers and two pointers int a = 1; int b = 2; int c = 3; int* p; int* q; // Here is the state of memory at this point. // T1 -- Notice that the pointers start out bad... p = &a; a 1 p b 2 q c 3 // set p to refer to a 8 q = &b; // set q to refer to b // T2 -- The pointers now have pointees a 1 p b 2 q c 3 // Now we mix things up a bit... c = *p; // retrieve p's pointee value (1) and put it in c p = q; // change p to share with q (p's pointee is now b) *p = 13; // dereference p to set its pointee (b) to 13 (*q is now 13) // T3 -- Dereferences and assignments mix things up a 1 p b 13 q c 1 } Bad Pointer Example Code with the most common sort of pointer bug will look like the above correct code, but without the middle step where the pointers are assigned pointees. The bad code will compile fine, but at run-time, each dereference with a bad pointer will corrupt memory in some way. The program will crash sooner or later. It is up to the programmer to ensure that each pointer is assigned a pointee before it is used. The following example shows a simple example of the bad code and a drawing of how memory is likely to react... void BadPointer() { int* p; // allocate the pointer, but not the pointee *p = 42; // this dereference is a serious runtime error } // What happens at runtime when the bad pointer is dereferenced... p Pow! 9 Pointer Rules Summary No matter how complex a pointer structure gets, the list of rules remains short. A pointer stores a reference to its pointee. The pointee, in turn, stores something useful. The dereference operation on a pointer accesses its pointee. A pointer may only be dereferenced after it has been assigned to refer to a pointee. Most pointer bugs involve violating this one rule. Allocating a pointer does not automatically assign it to refer to a pointee. Assigning the pointer to refer to a specific pointee is a separate operation which is easy to forget. Assignment between two pointers makes them refer to the same pointee which introduces sharing. Section 1 Extra Optional Material Extra: How Do Pointers Work In Java Java has pointers, but they are not manipulated with explicit operators such as * and &. In Java, simple data types such as int and char operate just as in C. More complex types such as arrays and objects are automatically implemented using pointers. The language automatically uses pointers behind the scenes for such complex types, and no pointer specific syntax is required. The programmer just needs to realize that operations like a=b; will automatically be implemented with pointers if a and b are arrays or objects. Or put another way, the programmer needs to remember that assignments and parameters with arrays and objects are intrinsically shallow or shared see the Deep vs. Shallow material above. The following code shows some Java object references. Notice that there are no *'s or &'s in the code to create pointers. The code intrinsically uses pointers. Also, the garbage collector (Section 4), takes care of the deallocation automatically at the end of the function. public void JavaShallow() { Foo a = new Foo(); // Create a Foo object (no * in the declaration) Foo b = new Foo(); // Create another Foo object b=a; // This is automatically a shallow assignment -// a and b now refer to the same object. a.Bar(); // This could just as well be written b.Bar(); // There is no memory leak here -- the garbage collector // will automatically recycle the memory for the two objects. } The Java approach has two main features... Fewer bugs. Because the language implements the pointer manipulation accurately and automatically, the most common pointer bug are no longer possible, Yay! Also, the Java runtime system checks each pointer value every time it is used, so NULL pointer dereferences are caught immediately on the line where they occur. This can make a programmer much more productive. 10 Slower. Because the language takes responsibility for implementing so much pointer machinery at runtime, Java code runs slower than the equivalent C code. (There are other reasons for Java to run slowly as well. There is active research in making Java faser in interesting ways the Sun "Hot Spot" project.) In any case, the appeal of increased programmer efficiency and fewer bugs makes the slowness worthwhile for some applications. Extra: How Are Pointers Implemented In The Machine? How are pointers implemented? The short explanation is that every area of memory in the machine has a numeric address like 1000 or 20452. A pointer to an area of memory is really just an integer which is storing the address of that area of memory. The dereference operation looks at the address, and goes to that area of memory to retrieve the pointee stored there. Pointer assignment just copies the numeric address from one pointer to another. The NULL value is generally just the numeric address 0 the computer just never allocates a pointee at 0 so that address can be used to represent NULL. A bad pointer is really just a pointer which contains a random address just like an uninitialized int variable which starts out with a random int value. The pointer has not yet been assigned the specific address of a valid pointee. This is why dereference operations with bad pointers are so unpredictable. They operate on whatever random area of memory they happen to have the address of. Extra: The Term "Reference" The word "reference" means almost the same thing as the word "pointer". The difference is that "reference" tends to be used in a discussion of pointer issues which is not specific to any particular language or implementation. The word "pointer" connotes the common C/C++ implementation of pointers as addresses. The word "reference" is also used in the phrase "reference parameter" which is a technique which uses pointer parameters for twoway communication between functions this technique is the subject of Section 3. Extra: Why Are Bad Pointer Bugs So Common? Why is it so often the case that programmers will allocate a pointer, but forget to set it to refer to a pointee? The rules for pointers don't seem that complex, yet every programmer makes this error repeatedly. Why? The problem is that we are trained by the tools we use. Simple variables don't require any extra setup. You can allocate a simple variable, such as int, and use it immediately. All that int, char, struct fraction code you have written has trained you, quite reasonably, that a variable may be used once it is declared. Unfortunately, pointers look like simple variables but they require the extra initialization before use. It's unfortunate, in a way, that pointers happen look like other variables, since it makes it easy to forget that the rules for their use are very different. Oh well. Try to remember to assign your pointers to refer to pointees. Don't be surprised when you forget. 11 Section 2 Local Memory Thanks For The Memory Local variables are the programming structure everyone uses but no one thinks about. You think about them a little when first mastering the syntax. But after a few weeks, the variables are so automatic that you soon forget to think about how they work. This situation is a credit to modern programming languages most of the time variables appear automatically when you need them, and they disappear automatically when you are finished. For basic programming, this is a fine situation. However, for advanced programming, it's going to be useful to have an idea of how variables work... Allocation And Deallocation Variables represent storage space in the computer's memory. Each variable presents a convenient names like length or sum in the source code. Behind the scenes at runtime, each variable uses an area of the computer's memory to store its value. It is not the case that every variable in a program has a permanently assigned area of memory. Instead, modern languages are smart about giving memory to a variable only when necessary. The terminology is that a variable is allocated when it is given an area of memory to store its value. While the variable is allocated, it can operate as a variable in the usual way to hold a value. A variable is deallocated when the system reclaims the memory from the variable, so it no longer has an area to store its value. For a variable, the period of time from its allocation until its deallocation is called its lifetime. The most common memory related error is using a deallocated variable. For local variables, modern languages automatically protect against this error. With pointers, as we will see however, the programmer must make sure that allocation is handled correctly.. Local Memory The most common variables you use are "local" variables within functions such as the variables num and result in the following function. All of the local variables and parameters taken together are called its "local storage" or just its "locals", such as num and result in the following code... // Local storage example int Square(int num) { int result; result = num * num; return result; } The variables are called "local" to capture the idea that their lifetime is tied to the function where they are declared. Whenever the function runs, its local variables are allocated. When the function exits, its locals are deallocated. For the above example, that means that when the Square() function is called, local storage is allocated for num and result. Statements like result = num * num; in the function use the local storage. When the function finally exits, its local storage is deallocated. 12 Here is a more detailed version of the rules of local storage... 1. When a function is called, memory is allocated for all of its locals. In other words, when the flow of control hits the starting '{' for the function, all of its locals are allocated memory. Parameters such as num and local variables such as result in the above example both count as locals. The only difference between parameters and local variables is that parameters start out with a value copied from the caller while local variables start with random initial values. This article mostly uses simple int variables for its examples, however local allocation works for any type: structs, arrays... these can all be allocated locally. 2. The memory for the locals continues to be allocated so long as the thread of control is within the owning function. Locals continue to exist even if the function temporarily passes off the thread of control by calling another function. The locals exist undisturbed through all of this. 3. Finally, when the function finishes and exits, its locals are deallocated. This makes sense in a way suppose the locals were somehow to continue to exist how could the code even refer to them? The names like num and result only make sense within the body of Square() anyway. Once the flow of control leaves that body, there is no way to refer to the locals even if they were allocated. That locals are available ("scoped") only within their owning function is known as "lexical scoping" and pretty much all languages do it that way now. Small Locals Example Here is a simple example of the lifetime of local storage... void Foo(int a) { // (1) Locals (a, b, i, scores) allocated when Foo runs int i; float scores[100]; // This array of 100 floats is allocated locally. a = a + 1; // (2) Local storage is used by the computation for (i=0; i<a; i++) { Bar(i + a); // (3) Locals continue to exist undisturbed, } // even during calls to other functions. } // (4) The locals are all deallocated when the function exits. Large Locals Example Here is a larger example which shows how the simple rule "the locals are allocated when their function begins running and are deallocated when it exits" can build more complex behavior. You will need a firm grasp of how local allocation works to understand the material in sections 3 and 4 later. The drawing shows the sequence of allocations and deallocations which result when the function X() calls the function Y() twice. The points in time T1, T2, etc. are marked in the code and the state of memory at that time is shown in the drawing. 13 void X() { int a = 1; int b = 2; // T1 Y(a); // T3 Y(b); // T5 } void Y(int p) { int q; q = p + 2; // T2 (first time through), T4 (second time through) } T1 - X()'s locals T2 - Y() is T3 - Y() exits have been called with p=1, and its locals allocated and and its locals are deallocated. given values.. are allocated. We are left only X()'s locals with X()'s continue to be locals. allocated. X() a b 1 2 Y() p q 1 3 X() a b 1 2 X() a b 1 2 T4 - Y() is called again with p=2, and its locals are allocated a second time. Y() p q 2 4 X() a b 1 2 T5 - Y() exits and its locals are deallocated. X()'s locals will be deallocated when it exits. X() a b 1 2 (optional extra...) The drawing shows the sequence of the locals being allocated and deallocated in effect the drawing shows the operation over time of the "stack" which is the data structure which the system uses to implement local storage. Observations About Local Parameters Local variables are tightly associated with their function they are used there and nowhere else. Only the X() code can refer to its a and b. Only the Y() code can refer to its p and q. This independence of local storage is the root cause of both its advantages and disadvantages. Advantages Of Locals Locals are great for 90% of a program's memory needs.... Convenient. Locals satisfy a convenient need functions often need some temporary memory which exists only during the function's computation. Local variables conveniently provide this sort of temporary, independent memory. Efficient. Relative to other memory use techniques, locals are very efficient. Allocating and deallocating them is time efficient (fast) and they are space efficient in the way they use and recycle memory. 14 Local Copies. Local parameters are basically local copies of the information from the caller. This is also known as "pass by value." Parameters are local variables which are initialized with an assignment (=) operation from the caller. The caller is not "sharing" the parameter value with the callee in the pointer sense the callee is getting its own copy. This has the advantage that the callee can change its local copy without affecting the caller. (Such as with the "p" parameter in the above example.) This independence is good since it keeps the operation of the caller and callee functions separate which follows the rules of good software engineering keep separate components as independent as possible. Disadvantages Of Locals There are two disadvantages of Locals Short Lifetime. Their allocation and deallocation schedule (their "lifetime") is very strict. Sometimes a program needs memory which continues to be allocated even after the function which originally allocated it has exited. Local variables will not work since they are deallocated automatically when their owning function exits. This problem will be solved later in Section 4 with "heap" memory. Restricted Communication. Since locals are copies of the caller parameters, they do not provide a means of communication from the callee back to the caller. This is the downside of the "independence" advantage. Also, sometimes making copies of a value is undesirable for other reasons. We will see the solution to this problem below in Section 3 "Reference Parameters". Synonyms For "Local" Local variables are also known as "automatic" variables since their allocation and deallocation is done automatically as part of the function call mechanism. Local variables are also sometimes known as "stack" variables because, at a low level, languages almost always implement local variables using a stack structure in memory. The Ampersand (&) Bug TAB Now that you understand the allocation schedule of locals, you can appreciate one of the more ugly bugs possible in C and C++. What is wrong with the following code where the function Victim() calls the function TAB()? To see the problem, it may be useful to make a drawing to trace the local storage of the two functions... // TAB -- The Ampersand Bug function // Returns a pointer to an int int* TAB() { int temp; return(&temp); // return a pointer to the local int } void Victim() { int* ptr; ptr = TAB(); *ptr = 42; } // Runtime error! The pointee was local to TAB 15 TAB() is actually fine while it is running. The problem happens to its caller after TAB() exits. TAB() returns a pointer to an int, but where is that int allocated? The problem is that the local int, temp, is allocated only while TAB() is running. When TAB() exits, all of its locals are deallocated. So the caller is left with a pointer to a deallocated variable. TAB()'s locals are deallocated when it exits, just as happened to the locals for Y() in the previous example. It is incorrect (and useless) for TAB() to return a pointer to memory which is about to be deallocated. We are essentially running into the "lifetime" constraint of local variables. We want the int to exist, but it gets deallocated automatically. Not all uses of & between functions are incorrect only when used to pass a pointer back to the caller. The correct uses of & are discussed in section 3, and the way to pass a pointer back to the caller is shown in section 4. Local Memory Summary Locals are very convenient for what they do providing convenient and efficient memory for a function which exists only so long as the function is executing. Locals have two deficiencies which we will address in the following sections how a function can communicate back to its caller (Section 3), and how a function can allocate separate memory with a less constrained lifetime (section 4). Section 2 Extra Optional Material Extra: How Does The Function Call Stack Work? You do not need to know how local variables are implemented during a function call, but here is a rough outline of the steps if you are curious. The exact details of the implementation are language and compiler specific. However, the basic structure below is approximates the method used by many different systems and languages... To call a function such as foo(6, x+1)... 1. Evaluate the actual parameter expressions, such as the x+1, in the caller's context. 2. Allocate memory for foo()'s locals by pushing a suitable "local block" of memory onto a runtime "call stack" dedicated to this purpose. For parameters but not local variables, store the values from step (1) into the appropriate slot in foo()'s local block. 3. Store the caller's current address of execution (its "return address") and switch execution to foo(). 4. foo() executes with its local block conveniently available at the end of the call stack. 5. When foo() is finished, it exits by popping its locals off the stack and "returns" to the caller using the previously stored return address. Now the caller's locals are on the end of the stack and it can resume executing. 16 For the extremely curious, here are other miscellaneous notes on the function call process... This is why infinite recursion results in a "Stack Overflow Error" the code keeps calling and calling resulting in steps (1) (2) (3), (1) (2) (3), but never a step (4)....eventually the call stack runs out of memory. This is why local variables have random initial values step (2) just pushes the whole local block in one operation. Each local gets its own area of memory, but the memory will contain whatever the most recent tenant left there. To clear all of the local block for each function call would be too time expensive. The "local block" is also known as the function's "activation record" or "stack frame". The entire block can be pushed onto the stack (step 2), in a single CPU operation it is a very fast operation. For a multithreaded environment, each thread gets its own call stack instead of just having single, global call stack. For performance reasons, some languages pass some parameters through registers and others through the stack, so the overall process is complex. However, the apparent the lifetime of the variables will always follow the "stack" model presented here. 17 Section 3 Reference Parameters In the simplest "pass by value" or "value parameter" scheme, each function has separate, local memory and parameters are copied from the caller to the callee at the moment of the function call. But what about the other direction? How can the callee communicate back to its caller? Using a "return" at the end of the callee to copy a result back to the caller works for simple cases, but does not work well for all situations. Also, sometimes copying values back and forth is undesirable. "Pass by reference" parameters solve all of these problems. For the following discussion, the term "value of interest" will be a value that the caller and callee wish to communicate between each other. A reference parameter passes a pointer to the value of interest instead of a copy of the value of interest. This technique uses the sharing property of pointers so that the caller and callee can share the value of interest. <NAME> Example Suppose functions A() and B() both do computations involving <NAME>' net worth measured in billions of dollars the value of interest for this problem. A() is the main function and its stores the initial value (about 55 as of 1998). A() calls B() which tries to add 1 to the value of interest. Bill Gates By Value Here is the code and memory drawing for a simple, but incorrect implementation where A() and B() use pass by value. Three points in time, T1, T2, and T3 are marked in the code and the state of memory is shown for each state... void B(int worth) { worth = worth + 1; // T2 } void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth } T1 -- The value of interest netWorth is local to A(). T2 -- netWorth is copied to B()'s local worth. B() changes its local worth from 55 to 56. B() A() netWorth 55 T3 -- B() exits and its local worth is deallocated. The value of interest has not been changed. worth 55 56 A() netWorth 55 A() netWorth 55 18 B() adds 1 to its local worth copy, but when B() exits, worth is deallocated, so changing it was useless. The value of interest, netWorth, rests unchanged the whole time in A()'s local storage. A function can change its local copy of the value of interest, but that change is not reflected back in the original value. This is really just the old "independence" property of local storage, but in this case it is not what is wanted. By Reference The reference solution to the Bill Gates problem is to use a single netWorth variable for the value of interest and never copy it. Instead, each function can receives a pointer to netWorth. Each function can see the current value of netWorth by dereferencing its pointer. More importantly, each function can change the net worth just dereference the pointer to the centralized netWorth and change it directly. Everyone agrees what the current value of netWorth because it exists in only one place everyone has a pointer to the one master copy. The following memory drawing shows A() and B() functions changed to use "reference" parameters. As before, T1, T2, and T3 correspond to points in the code (below), but you can study the memory structure without looking at the code yet. T1 -- The value of interest, T2 -- Instead of a copy, B() T3 -- B() exits, and netWorth, is local to A() receives a pointer to netWorth has been as before. netWorth. B() changed. dereferences its pointer to access and change the real netWorth. B() A() netWorth 55 worth A() netWorth 55 56 A() netWorth 56 The reference parameter strategy: B() receives a pointer to the value of interest instead of a copy. Passing By Reference Here are the steps to use in the code to use the pass-by-reference strategy... Have a single copy of the value of interest. The single "master" copy. Pass pointers to that value to any function which wants to see or change the value. Functions can dereference their pointer to see or change the value of interest. Functions must remember that they do not have their own local copies. If they dereference their pointer and change the value, they really are changing the master value. If a function wants a local copy to change safely, the function must explicitly allocate and initialize such a local copy. 19 Syntax The syntax for by reference parameters in the C language just uses pointer operations on the parameters... 1. Suppose a function wants to communicate about some value of interest int or float or struct fraction. 2. The function takes as its parameter a pointer to the value of interest an int* or float* or struct fraction*. Some programmers will add the word "ref" to the name of a reference parameter as a reminder that it is a reference to the value of interest instead of a copy. 3. At the time of the call, the caller computes a pointer to the value of interest and passes that pointer. The type of the pointer (pointer to the value of interest) will agree with the type in (2) above. If the value of interest is local to the caller, then this will often involve a use of the & operator (Section 1). 4. When the callee is running, if it wishes to access the value of interest, it must dereference its pointer to access the actual value of interest. Typically, this equates to use of the dereference operator (*) in the function to see the value of interest. Bill Gates By Reference Here is the Bill Gates example written to use reference parameters. This code now matches the by-reference memory drawing above. // B() now uses a reference parameter -- a pointer to // the value of interest. B() uses a dereference (*) on the // reference parameter to get at the value of interest. void B(int* worthRef) { // reference parameter *worthRef = *worthRef + 1; // use * to get at value of interest // T2 } void A() { int netWorth; netWorth = 55; B(&netWorth); // T1 -- the value of interest is local to A() // Pass a pointer to the value of interest. // In this case using &. // T3 -- B() has used its pointer to change the value of interest } Don't Make Copies Reference parameters enable communication between the callee and its caller. Another reason to use reference parameters is to avoid making copies. For efficiency, making copies may be undesirable if the value of interest is large, such as an array. Making the copy requires extra space for the copy itself and extra time to do the copying. From a design point of view, making copies may be undesirable because as soon as there are two copies, it is unclear which one is the "correct" one if either is changed. Proverb: "A person with one watch always knows what time it is. A person with two watches is never sure." Avoid making copies. 20 Simple Reference Parameter Example Swap() The standard example of reference parameters is a Swap() function which exchanges the values of two ints. It's a simple function, but it does need to change the caller's memory which is the key feature of pass by reference. Swap() Function The values of interest for Swap() are two ints. Therefore, Swap() does not take ints as its parameters. It takes a pointers to int (int*)'s. In the body of Swap() the parameters, a and b, are dereferenced with * to get at the actual (int) values of interest. void Swap(int* a, int* b) { int temp; temp = *a; *a = *b; *b = temp; } Swap() Caller To call Swap(), the caller must pass pointers to the values of interest... void SwapCaller() { int x = 1; int y = 2; Swap(&x, &y); // Use & to pass pointers to the int values of interest // (x and y). } Swap() a SwapCaller() x 1 2 b temp 1 y2 1 The parameters to Swap() are pointers to values of interest which are back in the caller's locals. The Swap() code can dereference the pointers to get back to the caller's memory to exchange the values. In this case, Swap() follows the pointers to exchange the values in the variables x and y back in SwapCaller(). Swap() will exchange any two ints given pointers to those two ints. Swap() With Arrays Just to demonstrate that the value of interest does not need to be a simple variable, here's a call to Swap() to exchange the first and last ints in an array. Swap() takes int*'s, but the ints can be anywhere. An int inside an array is still an int. void SwapCaller2() { int scores[10]; scores[0] = 1; scores[9[ = 2; Swap(&(scores[0]), &(scores[9]));// the ints of interest do not need to be // simple variables -- they can be any int. The caller is responsible // for computing a pointer to the int. 21 The above call to Swap() can be written equivalently as Swap(scores, scores+9) due to the array syntax in C. You can ignore this case if it is not familiar to you it's not an important area of the language and both forms compile to the exact same thing anyway. Is The & Always Necessary? When passing by reference, the caller does not always need to use & to compute a new pointer to the value of interest. Sometimes the caller already has a pointer to the value of interest, and so no new pointer computation is required. The pointer to the value of interest can be passed through unchanged. For example, suppose B() is changed so it calls a C() function which adds 2 to the value of interest... // Takes the value of interest by reference and adds 2. void C(int* worthRef) { *worthRef = *worthRef + 2; } // Adds 1 to the value of interest, and calls C(). void B(int* worthRef) { *worthRef = *worthRef + 1; // add 1 to value of interest as before C(worthRef); // NOTE no & required. We already have // a pointer to the value of interest, so // it can be passed through directly. } What About The & Bug TAB? All this use of & might make you nervous are we committing the & bug from Section 2? No, it turns out the above uses of & are fine. The & bug happens when an & passes a pointer to local storage from the callee back to its caller. When the callee exits, its local memory is deallocated and so the pointer no longer has a pointee. In the above, correct cases, we use & to pass a pointer from the caller to the callee. The pointer remains valid for the callee to use because the caller locals continue to exist while the callee is running. The pointees will remain valid due to the simple constraint that the caller can only exit sometime after its callee exits. Using & to pass a pointer to local storage from the caller to the callee is fine. The reverse case, from the callee to the caller, is the & bug. The ** Case What if the value of interest to be shared and changed between the caller and callee is already a pointer, such as an int* or a struct fraction*? Does that change the rules for setting up reference parameters? No. In that case, there is no change in the rules. They operate just as before. The reference parameter is still a pointer to the value of interest, even if the value of interest is itself a pointer. Suppose the value of interest is int*. This means there is an int* value which the caller and callee want to share and change. Then the reference parameter should be an int**. For a struct fraction* value of interest, the reference parameter is struct fraction**. A single dereference (*) operation on the reference parameter yields the value of interest as it did in the simple cases. Double pointer (**) parameters are common in linked list or other pointer manipulating code were the value of interest to share and change is itself a pointer, such as a linked list head pointer. 22 Reference Parameter Summary Passing by value (copying) does not allow the callee to communicate back to its caller and has also has the usual disadvantages of making copies. Pass by reference uses pointers to avoid copying the value of interest, and allow the callee to communicate back to the caller. For pass by reference, there is only one copy of the value of interest, and pointers to that one copy are passed. So if the value of interest is an int, its reference parameter is an int*. If the value of interest is a struct fraction*, its reference parameters is a struct fraction**. Functions use the dereference operator (*) on the reference parameter to see or change the value of interest. Section 3 Extra Optional Material Extra: Reference Parameters in Java Because Java has no */& operators, it is not possible to implement reference parameters in Java directly. Maybe this is ok in the OOP paradigm, you should change objects by sending them messages which makes the reference parameter concept unnecessary. The caller passes the callee a (shallow) reference to the value of interest (object of interest?), and the callee can send it a message to change it. Since all objects are intrinsically shallow, any change is communicated back to the caller automatically since the object of interest was never copied. Extra: Reference Parameters in C++ Reference parameters are such a common programming task that they have been added as an official feature to the C++ language. So programming reference parameters in C++ is simpler than in C. All the programmer needs to do is syntactically indicate that they wish for a particular parameter to be passed by reference, and the compiler takes care of it. The syntax is to append a single '&' to right hand side of the parameter type. So an int parameter passes an integer by value, but an int& parameter passes an integer value by reference. The key is that the compiler takes care of it. In the source code, there's no additional fiddling around with &'s or *'s. So Swap() and SwapCaller() written with C++ look simpler than in C, even though they accomplish the same thing... 23 void Swap(int& a, int& b) { int temp; temp = a; a = b; b = temp; // The & declares pass by reference // No *'s required -- the compiler takes care of it } void SwapCaller() { int x = 1; int y = 2; Swap(x, y); // No &'s required -- the compiler takes care of it } The types of the various variables and parameters operate simply as they are declared (int in this case). The complicating layer of pointers required to implement the reference parameters is hidden. The compiler takes care of it without allowing the complication to disturb the types in the source code. 24 Section 4 Heap Memory "Heap" memory, also known as "dynamic" memory, is an alternative to local stack memory. Local memory (Section 2) is quite automatic it is allocated automatically on function call and it is deallocated automatically when a function exits. Heap memory is different in every way. The programmer explicitly requests the allocation of a memory "block" of a particular size, and the block continues to be allocated until the programmer explicitly requests that it be deallocated. Nothing happens automatically. So the programmer has much greater control of memory, but with greater responsibility since the memory must now be actively managed. The advantages of heap memory are... Lifetime. Because the programmer now controls exactly when memory is allocated and deallocated, it is possible to build a data structure in memory, and return that data structure to the caller. This was never possible with local memory which was automatically deallocated when the function exited. Size. The size of allocated memory can be controlled with more detail. For example, a string buffer can be allocated at run-time which is exactly the right size to hold a particular string. With local memory, the code is more likely to declare a buffer size 1000 and hope for the best. (See the StringCopy() example below.) The disadvantages of heap memory are... More Work. Heap allocation needs to arranged explicitly in the code which is just more work. More Bugs. Because it's now done explicitly in the code, realistically on occasion the allocation will be done incorrectly leading to memory bugs. Local memory is constrained, but at least it's never wrong. Nonetheless, there are many problems that can only be solved with heap memory, so that's that way it has to be. In languages with garbage collectors such as Perl, LISP, or Java, the above disadvantages are mostly eliminated. The garbage collector takes over most of the responsibility for heap management at the cost of a little extra time taken at run-time. What Does The Heap Look Like? Before seeing the exact details, let's look at a rough example of allocation and deallocation in the heap... Allocation The heap is a large area of memory available for use by the program. The program can request areas, or "blocks", of memory for its use within the heap. In order to allocate a block of some size, the program makes an explicit request by calling the heap allocation function. The allocation function reserves a block of memory of the requested size in the heap and returns a pointer to it. Suppose a program makes three allocation requests to 25 allocate memory to hold three separate GIF images in the heap each of which takes 1024 bytes of memory. After the three allocation requests, memory might look like... Local Heap (Free) (Gif3) (Gif2) (Gif1) 3 separate heap blocks each 1024 bytes in size. Each allocation request reserves a contiguous area of the requested size in the heap and returns a pointer to that new block to the program. Since each block is always referred to by a pointer, the block always plays the role of a "pointee" (Section 1) and the program always manipulates its heap blocks through pointers. The heap block pointers are sometimes known as "base address" pointers since by convention they point to the base (lowest address byte) of the block. In this example, the three blocks have been allocated contiguously starting at the bottom of the heap, and each block is 1024 bytes in size as requested. In reality, the heap manager can allocate the blocks wherever it wants in the heap so long as the blocks do not overlap and they are at least the requested size. At any particular moment, some areas in the heap have been allocated to the program, and so are "in use". Other areas have yet to be committed and so are "free" and are available to satisfy allocation requests. The heap manager has its own, private data structures to record what areas of the heap are committed to what purpose at any moment The heap manager satisfies each allocation request from the pool of free memory and updates its private data structures to record which areas of the heap are in use. Deallocation When the program is finished using a block of memory, it makes an explicit deallocation request to indicate to the heap manager that the program is now finished with that block. The heap manager updates its private data structures to show that the area of memory occupied by the block is free again and so may be re-used to satisfy future allocation requests. Here's what the heap would look like if the program deallocates the second of the three blocks... 26 Local Heap (Free) (Gif3) (Free) (Gif1) After the deallocation, the pointer continues to point to the now deallocated block. The program must not access the deallocated pointee. This is why the pointer is drawn in gray the pointer is there, but it must not be used. Sometimes the code will set the pointer to NULL immediately after the deallocation to make explicit the fact that it is no longer valid. Programming The Heap Programming the heap looks pretty much the same in most languages. The basic features are.... The heap is an area of memory available to allocate areas ("blocks") of memory for the program. There is some "heap manager" library code which manages the heap for the program. The programmer makes requests to the heap manager, which in turn manages the internals of the heap. In C, the heap is managed by the ANSI library functions malloc(), free(), and realloc(). The heap manager uses its own private data structures to keep track of which blocks in the heap are "free" (available for use) and which blocks are currently in use by the program and how large those blocks are. Initially, all of the heap is free. The heap may be of a fixed size (the usual conceptualization), or it may appear to be of a fixed but extremely large size backed by virtual memory. In either case, it is possible for the heap to get "full" if all of its memory has been allocated and so it cannot satisfy an allocation request. The allocation function will communicate this run-time condition in some way to the program usually by returning a NULL pointer or raising a language specific run-time exception. The allocation function requests a block in the heap of a particular size. The heap manager selects an area of memory to use to satisfy the request, marks that area as "in use" in its private data structures, and returns a pointer to the heap block. The caller is now free to use that memory by dereferencing the pointer. The block is guaranteed to be reserved for the sole use of the caller the heap will not hand out that same area of memory to some other caller. The block does not move around inside the 27 heap its location and size are fixed once it is allocated. Generally, when a block is allocated, its contents are random. The new owner is responsible for setting the memory to something meaningful. Sometimes there is variation on the memory allocation function which sets the block to all zeros (calloc() in C). The deallocation function is the opposite of the allocation function. The program makes a single deallocation call to return a block of memory to the heap free area for later re-use. Each block should only be deallocated once. The deallocation function takes as its argument a pointer to a heap block previously furnished by the allocation function. The pointer must be exactly the same pointer returned earlier by the allocation function, not just any pointer into the block. After the deallocation, the program must treat the pointer as bad and not access the deallocated pointee. C Specifics In the C language, the library functions which make heap requests are malloc() ("memory allocate") and free(). The prototypes for these functions are in the header file <stdlib.h>. Although the syntax varies between languages, the roles of malloc() and free() are nearly identical in all languages... void* malloc(unsigned long size); The malloc() function takes an unsigned integer which is the requested size of the block measured in bytes. Malloc() returns a pointer to a new heap block if the allocation is successful, and NULL if the request cannot be satisfied because the heap is full. The C operator sizeof() is a convenient way to compute the size in bytes of a type sizeof(int) for an int pointee, sizeof(struct fraction) for a struct fraction pointee. void free(void* heapBlockPointer); The free() function takes a pointer to a heap block and returns it to the free pool for later reuse. The pointer passed to free() must be exactly the pointer returned earlier by malloc(), not just a pointer to somewhere in the block. Calling free() with the wrong sort of pointer is famous for the particularly ugly sort of crashing which it causes. The call to free() does not need to give the size of the heap block the heap manager will have noted the size in its private data structures. The call to free() just needs to identify which block to deallocate by its pointer. If a program correctly deallocates all of the memory it allocates, then every call to malloc() will later be matched by exactly one call to free() As a practical matter however, it is not always necessary for a program to deallocate every block it allocates see "Memory Leaks" below. Simple Heap Example Here is a simple example which allocates an int block in the heap, stores the number 42 in the block, and then deallocates it. This is the simplest possible example of heap block allocation, use, and deallocation. The example shows the state of memory at three different times during the execution of the above code. The stack and heap are shown separately in the drawing a drawing for code which uses stack and heap memory needs to distinguish between the two areas to be accurate since the rules which govern the two areas are so different. In this case, the lifetime of the local variable intPtr is totally separate from the lifetime of the heap block, and the drawing needs to reflect that difference. 28 void Heap1() { int* intPtr; // Allocates local pointer local variable (but not its pointee) // T1 Local Heap intPtr // Allocates heap block and stores its pointer in local variable. // Dereferences the pointer to set the pointee to 42. intPtr = malloc(sizeof(int)); *intPtr = 42; // T2 Local intPtr Heap 42 // Deallocates heap block making the pointer bad. // The programmer must remember not to use the pointer // after the pointee has been deallocated (this is // why the pointer is shown in gray). free(intPtr); // T3 Local Heap intPtr } Simple Heap Observations After the allocation call allocates the block in the heap. The program stores the pointer to the block in the local variable intPtr. The block is the "pointee" and intPtr is its pointer as shown at T2. In this state, the pointer may be dereferenced safely to manipulate the pointee. The pointer/pointee rules from Section 1 still apply, the only difference is how the pointee is initially allocated. 29 At T1 before the call to malloc(), intPtr is uninitialized does not have a pointee at this point intPtr "bad" in the same sense as discussed in Section 1. As before, dereferencing such an uninitialized pointer is a common, but catastrophic error. Sometimes this error will crash immediately (lucky). Other times it will just slightly corrupt a random data structure (unlucky). The call to free() deallocates the pointee as shown at T3. Dereferencing the pointer after the pointee has been deallocated is an error. Unfortunately, this error will almost never be flagged as an immediate run-time error. 99% of the time the dereference will produce reasonable results 1% of the time the dereference will produce slightly wrong results. Ironically, such a rarely appearing bug is the most difficult type to track down. When the function exits, its local variable intPtr will be automatically deallocated following the usual rules for local variables (Section 2). So this function has tidy memory behavior all of the memory it allocates while running (its local variable, its one heap block) is deallocated by the time it exits. Heap Array In the C language, it's convenient to allocate an array in the heap, since C can treat any pointer as an array. The size of the array memory block is the size of each element (as computed by the sizeof() operator) multiplied by the number of elements (See CS Education Library/101 The C Language, for a complete discussion of C, and arrays and pointers in particular). So the following code heap allocates an array of 100 struct fraction's in the heap, sets them all to 22/7, and deallocates the heap array... void HeapArray() { struct fraction* fracts; int i; // allocate the array fracts = malloc(sizeof(struct fraction) * 100); // use it like an array -- in this case set them all to 22/7 for (i=0; i<99; i++) { fracts[i].numerator = 22; fracts[i].denominator = 7; } // Deallocate the whole array free(fracts); } 30 Heap String Example Here is a more useful heap array example. The StringCopy() function takes a C string, makes a copy of that string in the heap, and returns a pointer to the new string. The caller takes over ownership of the new string and is responsible for freeing it. /* Given a C string, return a heap allocated copy of the string. Allocate a block in the heap of the appropriate size, copies the string into the block, and returns a pointer to the block. The caller takes over ownership of the block and is responsible for freeing it. */ char* StringCopy(const char* string) { char* newString; int len; len = strlen(string) + 1; // +1 to account for the '\0' newString = malloc(sizeof(char)*len); // elem-size * number-of-elements assert(newString != NULL); // simplistic error check (a good habit) strcpy(newString, string); // copy the passed in string to the block return(newString); // return a ptr to the block } Heap String Observations StringCopy() takes advantage of both of the key features of heap memory... Size. StringCopy() specifies, at run-time, the exact size of the block needed to store the string in its call to malloc(). Local memory cannot do that since its size is specified at compile-time. The call to sizeof(char) is not really necessary, since the size of char is 1 by definition. In any case, the example demonstrates the correct formula for the size of an array block which is element-size * number-of-elements. Lifetime. StringCopy() allocates the block, but then passes ownership of it to the caller. There is no call to free(), so the block continues to exist even after the function exits. Local memory cannot do that. The caller will need to take care of the deallocation when it is finished with the string. Memory Leaks What happens if some memory is heap allocated, but never deallocated? A program which forgets to deallocate a block is said to have a "memory leak" which may or may not be a serious problem. The result will be that the heap gradually fill up as there continue to be allocation requests, but no deallocation requests to return blocks for re-use. For a program which runs, computes something, and exits immediately, memory leaks are not usually a concern. Such a "one shot" program could omit all of its deallocation requests and still mostly work. Memory leaks are more of a problem for a program which runs for an indeterminate amount of time. In that case, the memory leaks can gradually fill the heap until allocation requests cannot be satisfied, and the program stops working or crashes. Many commercial programs have memory leaks, so that when run for long enough, or with large data-sets, they fill their heaps and crash. Often the error detection and avoidance code for the heap-full error condition is not well tested, precisely because the case is rarely encountered with short runs of the program that's why filling the heap often results in a real crash instead of a polite error message. Most compilers have a 31 "heap debugging" utility which adds debugging code to a program to track every allocation and deallocation. When an allocation has no matching deallocation, that's a leak, and the heap debugger can help you find them. Ownership StringCopy() allocates the heap block, but it does not deallocate it. This is so the caller can use the new string. However, this introduces the problem that somebody does need to remember to deallocate the block, and it is not going to be StringCopy(). That is why the comment for StringCopy() mentions specifically that the caller is taking on ownership of the block. Every block of memory has exactly one "owner" who takes responsibility for deallocating it. Other entities can have pointers, but they are just sharing. There's only one owner, and the comment for StringCopy() makes it clear that ownership is being passed from StringCopy() to the caller. Good documentation always remembers to discuss the ownership rules which a function expects to apply to its parameters or return value. Or put the other way, a frequent error in documentation is that it forgets to mention, one way or the other, what the ownership rules are for a parameter or return value. That's one way that memory errors and leaks are created. Ownership Models The two common patterns for ownership are... Caller ownership. The caller owns its own memory. It may pass a pointer to the callee for sharing purposes, but the caller retains ownership. The callee can access things while it runs, and allocate and deallocate its own memory, but it should not disrupt the caller's memory. Callee allocated and returned. The callee allocates some memory and returns it to the caller. This happens because the result of the callee computation needs new memory to be stored or represented. The new memory is passed to the caller so they can see the result, and the caller must take over ownership of the memory. This is the pattern demonstrated in StringCopy(). Heap Memory Summary Heap memory provides greater control for the programmer the blocks of memory can be requested in any size, and they remain allocated until they are deallocated explicitly. Heap memory can be passed back to the caller since it is not deallocated on exit, and it can be used to build linked structures such as linked lists and binary trees. The disadvantage of heap memory is that the program must make explicit allocation and deallocate calls to manage the heap memory. The heap memory does not operate automatically and conveniently the way local memory does.
git-hash
rust
Rust
Crate git_hash === This crate provides types for identifying git objects using a hash digest. These are provided in borrowed versions as well as owned ones. ### Feature Flags * **`serde1`** — Data structures implement `serde::Serialize` and `serde::Deserialize`. Modules --- decodeprefixStructs --- PrefixAn partial owned hash possibly identifying an object uniquely, whose non-prefix bytes are zeroed.oidA borrowed reference to a hash identifying objects.Enums --- KindDenotes the kind of function to produce a `Id`ObjectIdAn owned hash identifying objects, most commonly Sha1 Crate git_hash === This crate provides types for identifying git objects using a hash digest. These are provided in borrowed versions as well as owned ones. ### Feature Flags * **`serde1`** — Data structures implement `serde::Serialize` and `serde::Deserialize`. Modules --- decodeprefixStructs --- PrefixAn partial owned hash possibly identifying an object uniquely, whose non-prefix bytes are zeroed.oidA borrowed reference to a hash identifying objects.Enums --- KindDenotes the kind of function to produce a `Id`ObjectIdAn owned hash identifying objects, most commonly Sha1 Module git_hash::prefix === Modules --- from_hexEnums --- ErrorThe error returned by Prefix::new(). Struct git_hash::Prefix === ``` pub struct Prefix { /* private fields */ } ``` An partial owned hash possibly identifying an object uniquely, whose non-prefix bytes are zeroed. Implementations --- ### impl Prefix #### pub const MIN_HEX_LEN: usize = 4usize The smallest allowed prefix length below which chances for collisions are too high even in small repositories. #### pub fn new(id: impl AsRef<oid>, hex_len: usize) -> Result<Self, ErrorCreate a new instance by taking a full `id` as input and truncating it to `hex_len`. For instance, with `hex_len` of 7 the resulting prefix is 3.5 bytes, or 3 bytes and 4 bits wide, with all other bytes and bits set to zero. #### pub fn as_oid(&self) -> &oid Returns the prefix as object id. Note that it may be deceptive to use given that it looks like a full object id, even though its post-prefix bytes/bits are set to zero. #### pub fn hex_len(&self) -> usize Return the amount of hexadecimal characters that are set in the prefix. This gives the prefix a granularity of 4 bits. #### pub fn cmp_oid(&self, candidate: &oid) -> Ordering Provided with candidate id which is a full hash, determine how this prefix compares to it, only looking at the prefix bytes, ignoring everything behind that. #### pub fn from_hex(value: &str) -> Result<Self, ErrorCreate an instance from the given hexadecimal prefix `value`, e.g. `35e77c16` would yield a `Prefix` with `hex_len()` = 8. Trait Implementations --- ### impl Clone for Prefix #### fn clone(&self) -> Prefix Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(oid: ObjectId) -> Self Converts to this type from the input type.### impl Hash for Prefix #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Prefix) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Prefix) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Prefix> for Prefix #### fn partial_cmp(&self, other: &Prefix) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Create an instance from the given hexadecimal prefix, e.g. `35e77c16` would yield a `Prefix` with `hex_len()` = 8. #### type Error = Error The type returned in the event of a conversion error.#### fn try_from(value: &str) -> Result<Self, Self::ErrorPerforms the conversion.### impl Copy for Prefix ### impl Eq for Prefix ### impl StructuralEq for Prefix ### impl StructuralPartialEq for Prefix Auto Trait Implementations --- ### impl RefUnwindSafe for Prefix ### impl Send for Prefix ### impl Sync for Prefix ### impl Unpin for Prefix ### impl UnwindSafe for Prefix Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct git_hash::oid === ``` #[repr(transparent)]pub struct oid { /* private fields */ } ``` A borrowed reference to a hash identifying objects. Future Proofing --- In case we wish to support multiple hashes with the same length we cannot discriminate using the slice length anymore. To make that work, we will use the high bits of the internal `bytes` slice length (a fat pointer, pointing to data and its length in bytes) to encode additional information. Before accessing or returning the bytes, a new adjusted slice will be constructed, while the high bits will be used to help resolving the hash `[`kind()`][oid::kind()]`. We expect to have quite a few bits available for such ‘conflict resolution’ as most hashes aren’t longer than 64 bytes. Implementations --- ### impl oid Conversion #### pub fn try_from_bytes(digest: &[u8]) -> Result<&Self, ErrorTry to create a shared object id from a slice of bytes representing a hash `digest` #### pub fn from_bytes_unchecked(value: &[u8]) -> &Self Create an OID from the input `value` slice without performing any safety check. Use only once sure that `value` is a hash of valid length. ### impl oid Access #### pub fn kind(&self) -> Kind The kind of hash used for this Digest #### pub fn first_byte(&self) -> u8 The first byte of the hash, commonly used to partition a set of `Id`s #### pub fn as_bytes(&self) -> &[u8] Interpret this object id as raw byte slice. #### pub fn to_hex_with_len(&self, len: usize) -> HexDisplay<'_Return a type which can display itself in hexadecimal form with the `len` amount of characters. #### pub fn to_hex(&self) -> HexDisplay<'_Return a type which displays this oid as hex in full. ### impl oid Sha1 specific methods #### pub fn hex_to_buf(&self, buf: &mut [u8]) -> usize Write ourselves to the `out` in hexadecimal notation, returning the amount of written bytes. **Panics** if the buffer isn’t big enough to hold twice as many bytes as the current binary size. #### pub fn write_hex_to(&self, out: impl Write) -> Result<()Write ourselves to `out` in hexadecimal notation Trait Implementations --- ### impl AsRef<oid> for &oid #### fn as_ref(&self) -> &oid Converts this type into a shared reference of the (usually inferred) input type.### impl AsRef<oid> for ObjectId #### fn as_ref(&self) -> &oid Converts this type into a shared reference of the (usually inferred) input type.### impl Borrow<oid> for ObjectId #### fn borrow(&self) -> &oid Immutably borrows from an owned value. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Available on **crate feature `serde1`** only.Manually created from a version that uses a slice, and we forcefully try to convert it into a borrowed array of the desired size Could be improved by fitting this into serde Unfortunately the serde::Deserialize derive wouldn’t work for borrowed arrays. #### fn deserialize<D>( deserializer: D ) -> Result<Self, <D as Deserializer<'de>>::Error>where D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(v: &'a [u8; 20]) -> Self Converts to this type from the input type.### impl From<&oid> for ObjectId #### fn from(v: &oid) -> Self Converts to this type from the input type.### impl Hash for oid #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. #### fn cmp(&self, other: &oid) -> Ordering This method returns an `Ordering` between `self` and `other`. #### fn eq(&self, other: &&oid) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<ObjectId> for &oid #### fn eq(&self, other: &ObjectId) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<oid> for oid #### fn eq(&self, other: &oid) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<oid> for oid #### fn partial_cmp(&self, other: &oid) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. #### type Owned = ObjectId The resulting type after obtaining ownership.#### fn to_owned(&self) -> Self::Owned Creates owned data from borrowed data, usually by cloning. Read more1.63.0 · source#### fn clone_into(&self, target: &mut Self::Owned) Uses borrowed data to replace owned data, usually by cloning. ### impl StructuralEq for oid ### impl StructuralPartialEq for oid Auto Trait Implementations --- ### impl RefUnwindSafe for oid ### impl Send for oid ### impl !Sized for oid ### impl Sync for oid ### impl Unpin for oid ### impl UnwindSafe for oid Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. Read more{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Enum git_hash::Kind === ``` pub enum Kind { Sha1, } ``` Denotes the kind of function to produce a `Id` Variants --- ### Sha1 The Sha1 hash with 160 bits. Implementations --- ### impl Kind #### pub const fn shortest() -> Self Returns the shortest hash we support #### pub const fn longest() -> Self Returns the longest hash we support #### pub const fn hex_buf() -> [u8; 40] Returns a buffer suitable to hold the longest possible hash in hex. #### pub const fn buf() -> [u8; 20] Returns a buffer suitable to hold the longest possible hash as raw bytes. #### pub const fn len_in_hex(&self) -> usize Returns the amount of ascii-characters needed to encode this has in hex #### pub const fn len_in_bytes(&self) -> usize Returns the amount of bytes taken up by the hash of the current kind #### pub const fn from_hex_len(hex_len: usize) -> Option<SelfReturns the kind of hash that would fit the given `hex_len`, or `None` if there is no fitting hash. Note that 0 as `hex_len` fits always yields Sha1. #### pub fn null_ref(&self) -> &'static oid Create a null-id of our hash kind. #### pub const fn null(&self) -> ObjectId Create a null-id of our hash kind. Trait Implementations --- ### impl Clone for Kind #### fn clone(&self) -> Kind Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Self Returns the “default value” for a type. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### type Err = String The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Self, Self::ErrParses a string `s` to return a value of this type. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Kind) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Kind) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Kind> for Kind #### fn partial_cmp(&self, other: &Kind) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. #### type Error = u8 The type returned in the event of a conversion error.#### fn try_from(value: u8) -> Result<Self, Self::ErrorPerforms the conversion.### impl Copy for Kind ### impl Eq for Kind ### impl StructuralEq for Kind ### impl StructuralPartialEq for Kind Auto Trait Implementations --- ### impl RefUnwindSafe for Kind ### impl Send for Kind ### impl Sync for Kind ### impl Unpin for Kind ### impl UnwindSafe for Kind Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Enum git_hash::ObjectId === ``` pub enum ObjectId { Sha1([u8; 20]), } ``` An owned hash identifying objects, most commonly Sha1 Variants --- ### Sha1([u8; 20]) A SHA 1 hash digest Implementations --- ### impl ObjectId Hash decoding #### pub fn from_hex(buffer: &[u8]) -> Result<ObjectId, ErrorCreate an instance from a `buffer` of 40 bytes encoded with hexadecimal notation. Such a buffer can be obtained using `oid::write_hex_to(buffer)` ### impl ObjectId Access and conversion #### pub fn kind(&self) -> Kind Returns the kind of hash used in this `Id` #### pub fn as_slice(&self) -> &[u8] Return the raw byte slice representing this hash #### pub fn as_mut_slice(&mut self) -> &mut [u8] Return the raw mutable byte slice representing this hash #### pub const fn empty_tree(hash: Kind) -> ObjectId The hash of an empty tree #### pub fn is_null(&self) -> bool Returns true if this hash consists of all null bytes #### pub const fn null(kind: Kind) -> ObjectId Returns an Digest representing a hash with whose memory is zeroed. Methods from Deref<Target = oid> --- #### pub fn kind(&self) -> Kind The kind of hash used for this Digest #### pub fn first_byte(&self) -> u8 The first byte of the hash, commonly used to partition a set of `Id`s #### pub fn as_bytes(&self) -> &[u8] Interpret this object id as raw byte slice. #### pub fn to_hex_with_len(&self, len: usize) -> HexDisplay<'_Return a type which can display itself in hexadecimal form with the `len` amount of characters. #### pub fn to_hex(&self) -> HexDisplay<'_Return a type which displays this oid as hex in full. #### pub fn hex_to_buf(&self, buf: &mut [u8]) -> usize Write ourselves to the `out` in hexadecimal notation, returning the amount of written bytes. **Panics** if the buffer isn’t big enough to hold twice as many bytes as the current binary size. #### pub fn write_hex_to(&self, out: impl Write) -> Result<()Write ourselves to `out` in hexadecimal notation Trait Implementations --- ### impl AsRef<oid> for ObjectId #### fn as_ref(&self) -> &oid Converts this type into a shared reference of the (usually inferred) input type.### impl Borrow<oid> for ObjectId #### fn borrow(&self) -> &oid Immutably borrows from an owned value. #### fn clone(&self) -> ObjectId Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### type Target = oid The resulting type after dereferencing.#### fn deref(&self) -> &Self::Target Dereferences the value.### impl<'de> Deserialize<'de> for ObjectId #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(v: &[u8]) -> Self Converts to this type from the input type.### impl From<&oid> for ObjectId #### fn from(v: &oid) -> Self Converts to this type from the input type.### impl From<[u8; 20]> for ObjectId #### fn from(v: [u8; 20]) -> Self Converts to this type from the input type.### impl From<ObjectId> for Prefix #### fn from(oid: ObjectId) -> Self Converts to this type from the input type.### impl FromStr for ObjectId #### type Err = Error The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Self, Self::ErrParses a string `s` to return a value of this type. #### fn hash<H: Hasher>(&self, state: &mut H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &ObjectId) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &&oid) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<ObjectId> for &oid #### fn eq(&self, other: &ObjectId) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<ObjectId> for ObjectId #### fn eq(&self, other: &ObjectId) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<ObjectId> for ObjectId #### fn partial_cmp(&self, other: &ObjectId) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. ### impl Eq for ObjectId ### impl StructuralEq for ObjectId ### impl StructuralPartialEq for ObjectId Auto Trait Implementations --- ### impl RefUnwindSafe for ObjectId ### impl Send for ObjectId ### impl Sync for ObjectId ### impl Unpin for ObjectId ### impl UnwindSafe for ObjectId Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","&mut [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for &amp;mut [<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"}
@aws-cdk/aws-codepipeline
npm
JavaScript
AWS CodePipeline Construct Library === --- > AWS CDK v1 has reached End-of-Support on 2023-06-01. > This package is no longer being updated, and users should migrate to AWS CDK v2. > For more information on how to migrate, see the [*Migrating to AWS CDK v2* guide](https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html). --- Pipeline --- To construct an empty Pipeline: ``` // Construct an empty Pipeline const pipeline = new codepipeline.Pipeline(this, 'MyFirstPipeline'); ``` To give the Pipeline a nice, human-readable name: ``` // Give the Pipeline a nice, human-readable name const pipeline = new codepipeline.Pipeline(this, 'MyFirstPipeline', { pipelineName: 'MyPipeline', }); ``` Be aware that in the default configuration, the `Pipeline` construct creates an AWS Key Management Service (AWS KMS) Customer Master Key (CMK) for you to encrypt the artifacts in the artifact bucket, which incurs a cost of **$1/month**. This default configuration is necessary to allow cross-account actions. If you do not intend to perform cross-account deployments, you can disable the creation of the Customer Master Keys by passing `crossAccountKeys: false` when defining the Pipeline: ``` // Don't create Customer Master Keys const pipeline = new codepipeline.Pipeline(this, 'MyFirstPipeline', { crossAccountKeys: false, }); ``` If you want to enable key rotation for the generated KMS keys, you can configure it by passing `enableKeyRotation: true` when creating the pipeline. Note that key rotation will incur an additional cost of **$1/month**. ``` // Enable key rotation for the generated KMS key const pipeline = new codepipeline.Pipeline(this, 'MyFirstPipeline', { // ... enableKeyRotation: true, }); ``` Stages --- You can provide Stages when creating the Pipeline: ``` // Provide a Stage when creating a pipeline const pipeline = new codepipeline.Pipeline(this, 'MyFirstPipeline', { stages: [ { stageName: 'Source', actions: [ // see below... ], }, ], }); ``` Or append a Stage to an existing Pipeline: ``` // Append a Stage to an existing Pipeline declare const pipeline: codepipeline.Pipeline; const sourceStage = pipeline.addStage({ stageName: 'Source', actions: [ // optional property // see below... ], }); ``` You can insert the new Stage at an arbitrary point in the Pipeline: ``` // Insert a new Stage at an arbitrary point declare const pipeline: codepipeline.Pipeline; declare const anotherStage: codepipeline.IStage; declare const yetAnotherStage: codepipeline.IStage; const someStage = pipeline.addStage({ stageName: 'SomeStage', placement: { // note: you can only specify one of the below properties rightBefore: anotherStage, justAfter: yetAnotherStage, } }); ``` You can disable transition to a Stage: ``` // Disable transition to a stage declare const pipeline: codepipeline.Pipeline; const someStage = pipeline.addStage({ stageName: 'SomeStage', transitionToEnabled: false, transitionDisabledReason: 'Manual transition only', // optional reason }) ``` This is useful if you don't want every executions of the pipeline to flow into this stage automatically. The transition can then be "manually" enabled later on. Actions --- Actions live in a separate package, `@aws-cdk/aws-codepipeline-actions`. To add an Action to a Stage, you can provide it when creating the Stage, in the `actions` property, or you can use the `IStage.addAction()` method to mutate an existing Stage: ``` // Use the `IStage.addAction()` method to mutate an existing Stage. declare const sourceStage: codepipeline.IStage; declare const someAction: codepipeline.Action; sourceStage.addAction(someAction); ``` Custom Action Registration --- To make your own custom CodePipeline Action requires registering the action provider. Look to the `JenkinsProvider` in `@aws-cdk/aws-codepipeline-actions` for an implementation example. ``` // Make a custom CodePipeline Action new codepipeline.CustomActionRegistration(this, 'GenericGitSourceProviderResource', { category: codepipeline.ActionCategory.SOURCE, artifactBounds: { minInputs: 0, maxInputs: 0, minOutputs: 1, maxOutputs: 1 }, provider: 'GenericGitSource', version: '1', entityUrl: 'https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-custom-action.html', executionUrl: 'https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-custom-action.html', actionProperties: [ { name: 'Branch', required: true, key: false, secret: false, queryable: false, description: 'Git branch to pull', type: 'String', }, { name: 'GitUrl', required: true, key: false, secret: false, queryable: false, description: 'SSH git clone URL', type: 'String', }, ], }); ``` Cross-account CodePipelines --- > Cross-account Pipeline actions require that the Pipeline has *not* been > created with `crossAccountKeys: false`. Most pipeline Actions accept an AWS resource object to operate on. For example: * `S3DeployAction` accepts an `s3.IBucket`. * `CodeBuildAction` accepts a `codebuild.IProject`. * etc. These resources can be either newly defined (`new s3.Bucket(...)`) or imported (`s3.Bucket.fromBucketAttributes(...)`) and identify the resource that should be changed. These resources can be in different accounts than the pipeline itself. For example, the following action deploys to an imported S3 bucket from a different account: ``` // Deploy an imported S3 bucket from a different account declare const stage: codepipeline.IStage; declare const input: codepipeline.Artifact; stage.addAction(new codepipeline_actions.S3DeployAction({ bucket: s3.Bucket.fromBucketAttributes(this, 'Bucket', { account: '123456789012', // ... }), input: input, actionName: 's3-deploy-action', // ... })); ``` Actions that don't accept a resource object accept an explicit `account` parameter: ``` // Actions that don't accept a resource objet accept an explicit `account` parameter declare const stage: codepipeline.IStage; declare const templatePath: codepipeline.ArtifactPath; stage.addAction(new codepipeline_actions.CloudFormationCreateUpdateStackAction({ account: '123456789012', templatePath, adminPermissions: false, stackName: Stack.of(this).stackName, actionName: 'cloudformation-create-update', // ... })); ``` The `Pipeline` construct automatically defines an **IAM Role** for you in the target account which the pipeline will assume to perform that action. This Role will be defined in a **support stack** named `<PipelineStackName>-support-<account>`, that will automatically be deployed before the stack containing the pipeline. If you do not want to use the generated role, you can also explicitly pass a `role` when creating the action. In that case, the action will operate in the account the role belongs to: ``` // Explicitly pass in a `role` when creating an action. declare const stage: codepipeline.IStage; declare const templatePath: codepipeline.ArtifactPath; stage.addAction(new codepipeline_actions.CloudFormationCreateUpdateStackAction({ templatePath, adminPermissions: false, stackName: Stack.of(this).stackName, actionName: 'cloudformation-create-update', // ... role: iam.Role.fromRoleArn(this, 'ActionRole', '...'), })); ``` Cross-region CodePipelines --- Similar to how you set up a cross-account Action, the AWS resource object you pass to actions can also be in different *Regions*. For example, the following Action deploys to an imported S3 bucket from a different Region: ``` // Deploy to an imported S3 bucket from a different Region. declare const stage: codepipeline.IStage; declare const input: codepipeline.Artifact; stage.addAction(new codepipeline_actions.S3DeployAction({ bucket: s3.Bucket.fromBucketAttributes(this, 'Bucket', { region: 'us-west-1', // ... }), input: input, actionName: 's3-deploy-action', // ... })); ``` Actions that don't take an AWS resource will accept an explicit `region` parameter: ``` // Actions that don't take an AWS resource will accept an explicit `region` parameter. declare const stage: codepipeline.IStage; declare const templatePath: codepipeline.ArtifactPath; stage.addAction(new codepipeline_actions.CloudFormationCreateUpdateStackAction({ templatePath, adminPermissions: false, stackName: Stack.of(this).stackName, actionName: 'cloudformation-create-update', // ... region: 'us-west-1', })); ``` The `Pipeline` construct automatically defines a **replication bucket** for you in the target region, which the pipeline will replicate artifacts to and from. This Bucket will be defined in a **support stack** named `<PipelineStackName>-support-<region>`, that will automatically be deployed before the stack containing the pipeline. If you don't want to use these support stacks, and already have buckets in place to serve as replication buckets, you can supply these at Pipeline definition time using the `crossRegionReplicationBuckets` parameter. Example: ``` // Supply replication buckets for the Pipeline instead of using the generated support stack const pipeline = new codepipeline.Pipeline(this, 'MyFirstPipeline', { // ... crossRegionReplicationBuckets: { // note that a physical name of the replication Bucket must be known at synthesis time 'us-west-1': s3.Bucket.fromBucketAttributes(this, 'UsWest1ReplicationBucket', { bucketName: 'my-us-west-1-replication-bucket', // optional KMS key encryptionKey: kms.Key.fromKeyArn(this, 'UsWest1ReplicationKey', 'arn:aws:kms:us-west-1:123456789012:key/1234-5678-9012' ), }), }, }); ``` See [the AWS docs here](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-cross-region.html) for more information on cross-region CodePipelines. ### Creating an encrypted replication bucket If you're passing a replication bucket created in a different stack, like this: ``` // Passing a replication bucket created in a different stack. const app = new App(); const replicationStack = new Stack(app, 'ReplicationStack', { env: { region: 'us-west-1', }, }); const key = new kms.Key(replicationStack, 'ReplicationKey'); const replicationBucket = new s3.Bucket(replicationStack, 'ReplicationBucket', { // like was said above - replication buckets need a set physical name bucketName: PhysicalName.GENERATE_IF_NEEDED, encryptionKey: key, // does not work! }); // later... new codepipeline.Pipeline(replicationStack, 'Pipeline', { crossRegionReplicationBuckets: { 'us-west-1': replicationBucket, }, }); ``` When trying to encrypt it (and note that if any of the cross-region actions happen to be cross-account as well, the bucket *has to* be encrypted - otherwise the pipeline will fail at runtime), you cannot use a key directly - KMS keys don't have physical names, and so you can't reference them across environments. In this case, you need to use an alias in place of the key when creating the bucket: ``` // Passing an encrypted replication bucket created in a different stack. const app = new App(); const replicationStack = new Stack(app, 'ReplicationStack', { env: { region: 'us-west-1', }, }); const key = new kms.Key(replicationStack, 'ReplicationKey'); const alias = new kms.Alias(replicationStack, 'ReplicationAlias', { // aliasName is required aliasName: PhysicalName.GENERATE_IF_NEEDED, targetKey: key, }); const replicationBucket = new s3.Bucket(replicationStack, 'ReplicationBucket', { bucketName: PhysicalName.GENERATE_IF_NEEDED, encryptionKey: alias, }); ``` Variables --- The library supports the CodePipeline Variables feature. Each action class that emits variables has a separate variables interface, accessed as a property of the action instance called `variables`. You instantiate the action class and assign it to a local variable; when you want to use a variable in the configuration of a different action, you access the appropriate property of the interface returned from `variables`, which represents a single variable. Example: ``` // MyAction is some action type that produces variables, like EcrSourceAction const myAction = new MyAction({ // ... actionName: 'myAction', }); new OtherAction({ // ... config: myAction.variables.myVariable, actionName: 'otherAction', }); ``` The namespace name that will be used will be automatically generated by the pipeline construct, based on the stage and action name; you can pass a custom name when creating the action instance: ``` // MyAction is some action type that produces variables, like EcrSourceAction const myAction = new MyAction({ // ... variablesNamespace: 'MyNamespace', actionName: 'myAction', }); ``` There are also global variables available, not tied to any action; these are accessed through static properties of the `GlobalVariables` class: ``` // OtherAction is some action type that produces variables, like EcrSourceAction new OtherAction({ // ... config: codepipeline.GlobalVariables.executionId, actionName: 'otherAction', }); ``` Check the documentation of the `@aws-cdk/aws-codepipeline-actions` for details on how to use the variables for each action class. See the [CodePipeline documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-variables.html) for more details on how to use the variables feature. Events --- ### Using a pipeline as an event target A pipeline can be used as a target for a CloudWatch event rule: ``` // A pipeline being used as a target for a CloudWatch event rule. import * as targets from '@aws-cdk/aws-events-targets'; import * as events from '@aws-cdk/aws-events'; // kick off the pipeline every day const rule = new events.Rule(this, 'Daily', { schedule: events.Schedule.rate(Duration.days(1)), }); declare const pipeline: codepipeline.Pipeline; rule.addTarget(new targets.CodePipeline(pipeline)); ``` When a pipeline is used as an event target, the "codepipeline:StartPipelineExecution" permission is granted to the AWS CloudWatch Events service. ### Event sources Pipelines emit CloudWatch events. To define event rules for events emitted by the pipeline, stages or action, use the `onXxx` methods on the respective construct: ``` // Define event rules for events emitted by the pipeline import * as events from '@aws-cdk/aws-events'; declare const myPipeline: codepipeline.Pipeline; declare const myStage: codepipeline.IStage; declare const myAction: codepipeline.Action; declare const target: events.IRuleTarget; myPipeline.onStateChange('MyPipelineStateChange', { target: target } ); myStage.onStateChange('MyStageStateChange', target); myAction.onStateChange('MyActionStateChange', target); ``` CodeStar Notifications --- To define CodeStar Notification rules for Pipelines, use one of the `notifyOnXxx()` methods. They are very similar to `onXxx()` methods for CloudWatch events: ``` // Define CodeStar Notification rules for Pipelines import * as chatbot from '@aws-cdk/aws-chatbot'; const target = new chatbot.SlackChannelConfiguration(this, 'MySlackChannel', { slackChannelConfigurationName: 'YOUR_CHANNEL_NAME', slackWorkspaceId: 'YOUR_SLACK_WORKSPACE_ID', slackChannelId: 'YOUR_SLACK_CHANNEL_ID', }); declare const pipeline: codepipeline.Pipeline; const rule = pipeline.notifyOnExecutionStateChange('NotifyOnExecutionStateChange', target); ``` Readme --- ### Keywords * aws * cdk * constructs * codepipeline * pipeline
dbplot
cran
R
Package ‘dbplot’ October 13, 2022 Version 0.3.3 Title Simplifies Plotting Data Inside Databases Description Leverages 'dplyr' to process the calculations of a plot inside a database. This package provides helper functions that abstract the work at three levels: outputs a 'ggplot', outputs the calculations, outputs the formula needed to calculate bins. Depends R (>= 3.1) Imports dplyr (>= 0.7), rlang (>= 0.3), ggplot2, purrr, magrittr Suggests dbplyr (>= 1.4.0), testthat, tidyr, covr License GPL-3 URL https://github.com/edgararuiz/dbplot BugReports https://github.com/edgararuiz/dbplot/issues RoxygenNote 7.0.2 Encoding UTF-8 NeedsCompilation no Author <NAME> [aut, cre] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2020-02-07 01:10:09 UTC R topics documented: dbplot_ba... 2 dbplot_boxplo... 3 dbplot_histogra... 3 dbplot_lin... 4 dbplot_raste... 5 db_bi... 6 db_compute_bin... 7 db_compute_boxplo... 8 db_compute_coun... 8 db_compute_raste... 9 dbplot_bar Bar plot Description Uses very generic dplyr code to aggregate data and then ‘ggplot2‘ to create the plot. Because of this approach, the calculations automatically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_spark Usage dbplot_bar(data, x, ..., y = n()) Arguments data A table (tbl) x A discrete variable ... A set of named or unamed aggregations y The aggregation formula. Defaults to count (n) See Also dbplot_line , dbplot_histogram, dbplot_raster Examples library(ggplot2) library(dplyr) # Returns a plot of the row count per am mtcars %>% dbplot_bar(am) # Returns a plot of the average mpg per am mtcars %>% dbplot_bar(am, mean(mpg)) # Returns the average and sum of mpg per am mtcars %>% dbplot_bar(am, avg_mpg = mean(mpg), sum_mpg = sum(mpg)) dbplot_boxplot Boxplot Description Uses very generic dplyr code to aggregate data and then ‘ggplot2‘ to create the boxplot Because of this approach, the calculations automatically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_spark It currently only works with Spark and Hive connections. Usage dbplot_boxplot(data, x, var, coef = 1.5) Arguments data A table (tbl) x A discrete variable in which to group the boxplots var A continuous variable coef Length of the whiskers as multiple of IQR. Defaults to 1.5 See Also dbplot_bar, dbplot_line , dbplot_raster, dbplot_histogram dbplot_histogram Histogram Description Uses very generic dplyr code to aggregate data and then ‘ggplot2‘ to create the histogram. Because of this approach, the calculations automatically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_spark Usage dbplot_histogram(data, x, bins = 30, binwidth = NULL) Arguments data A table (tbl) x A continuous variable bins Number of bins. Defaults to 30. binwidth Single value that sets the side of the bins, it overrides bins See Also dbplot_bar, dbplot_line , dbplot_raster Examples library(ggplot2) library(dplyr) # A ggplot histogram with 30 bins mtcars %>% dbplot_histogram(mpg) # A ggplot histogram with bins of size 10 mtcars %>% dbplot_histogram(mpg, binwidth = 10) dbplot_line Bar plot Description Uses very generic dplyr code to aggregate data and then ‘ggplot2‘ to create a line plot. Because of this approach, the calculations automatically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_spark If multiple named aggregations are passed, ‘dbplot‘ will only use one SQL query to perform all of the operations. The purpose is to increase efficiency, and only make one "trip" to the database in order to obtains multiple, related, plots. Usage dbplot_line(data, x, ..., y = n()) Arguments data A table (tbl) x A discrete variable ... A set of named or unamed aggregations y The aggregation formula. Defaults to count (n) See Also dbplot_bar, dbplot_histogram, dbplot_raster Examples library(ggplot2) library(dplyr) # Returns a plot of the row count per cyl mtcars %>% dbplot_line(cyl) # Returns a plot of the average mpg per cyl mtcars %>% dbplot_line(cyl, mean(mpg)) # Returns the average and sum of mpg per am mtcars %>% dbplot_line(am, avg_mpg = mean(mpg), sum_mpg = sum(mpg)) dbplot_raster Raster plot Description To visualize two continuous variables, we typically resort to a Scatter plot. However, this may not be practical when visualizing millions or billions of dots representing the intersections of the two variables. A Raster plot may be a better option, because it concentrates the intersections into squares that are easier to parse visually. Uses very generic dplyr code to aggregate data and ggplot2 to create a raster plot. Because of this approach, the calculations automatically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_spark Usage dbplot_raster(data, x, y, fill = n(), resolution = 100, complete = FALSE) Arguments data A table (tbl) x A continuous variable y A continuous variable fill The aggregation formula. Defaults to count (n) resolution The number of bins created by variable. The highest the number, the more records can be potentially imported from the sourd complete Uses tidyr::complete to include empty bins. Inserts value of 0. Details There are two considerations when using a Raster plot with a database. Both considerations are related to the size of the results downloaded from the database: - The number of bins requested: The higher the bins value is, the more data is downloaded from the database. - How concentrated the data is: This refers to how many intersections return a value. The more intersections without a value, the less data is downloaded from the database. See Also dbplot_bar, dbplot_line , dbplot_histogram Examples library(ggplot2) library(dplyr) # Returns a 100x100 raster plot of record count of intersections of eruptions and waiting faithful %>% dbplot_raster(eruptions, waiting) # Returns a 50x50 raster plot of eruption averages of intersections of eruptions and waiting faithful %>% dbplot_raster(eruptions, waiting, fill = mean(eruptions), resolution = 50) db_bin Bin formula Description Uses the rlang package to build the formula needed to create the bins of a numeric variable in an unevaluated fashion. This way, the formula can be then passed inside a dplyr verb. Usage db_bin(var, bins = 30, binwidth = NULL) Arguments var Variable name or formula bins Number of bins. Defaults to 30. binwidth Single value that sets the side of the bins, it overrides bins Examples library(dplyr) # Important: Always name the field and # prefix the function with `!!`` (See Details) # Uses the default 30 bins mtcars %>% group_by(x = !!db_bin(mpg)) %>% tally() # Uses binwidth which overrides bins mtcars %>% group_by(x = !!db_bin(mpg, binwidth = 10)) %>% tally() db_compute_bins Calculates a histogram bins Description Uses very generic dplyr code to create histogram bins. Because of this approach, the calculations automatically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_spark Usage db_compute_bins(data, x, bins = 30, binwidth = NULL) Arguments data A table (tbl) x A continuous variable bins Number of bins. Defaults to 30. binwidth Single value that sets the side of the bins, it overrides bins See Also db_bin, Examples # Returns record count for 30 bins in mpg mtcars %>% db_compute_bins(mpg) # Returns record count for bins of size 10 mtcars %>% db_compute_bins(mpg, binwidth = 10) db_compute_boxplot Returns a dataframe with boxplot calculations Description Uses very generic dplyr code to create boxplot calculations. Because of this approach, the calcu- lations automatically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_spark It currently only works with Spark, Hive, and SQL Server connections. Note that this function supports input tbl that already contains grouping variables. This can be useful when creating faceted boxplots. Usage db_compute_boxplot(data, x, var, coef = 1.5) Arguments data A table (tbl), can already contain additional grouping vars specified x A discrete variable in which to group the boxplots var A continuous variable coef Length of the whiskers as multiple of IQR. Defaults to 1.5 Examples mtcars %>% db_compute_boxplot(am, mpg) db_compute_count Aggregates over a discrete field Description Uses very generic dplyr code to aggregate data. Because of this approach, the calculations automat- ically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_sql Usage db_compute_count(data, x, ..., y = n()) Arguments data A table (tbl) x A discrete variable ... A set of named or unamed aggregations y The aggregation formula. Defaults to count (n) Examples # Returns the row count per am mtcars %>% db_compute_count(am) # Returns the average mpg per am mtcars %>% db_compute_count(am, mean(mpg)) # Returns the average and sum of mpg per am mtcars %>% db_compute_count(am, mean(mpg), sum(mpg)) db_compute_raster Aggregates intersections of two variables Description To visualize two continuous variables, we typically resort to a Scatter plot. However, this may not be practical when visualizing millions or billions of dots representing the intersections of the two variables. A Raster plot may be a better option, because it concentrates the intersections into squares that are easier to parse visually. Uses very generic dplyr code to aggregate data. Because of this approach, the calculations automat- ically run inside the database if ‘data‘ has a database or sparklyr connection. The ‘class()‘ of such tables in R are: tbl_sql, tbl_dbi, tbl_sql Usage db_compute_raster(data, x, y, fill = n(), resolution = 100, complete = FALSE) db_compute_raster2(data, x, y, fill = n(), resolution = 100, complete = FALSE) Arguments data A table (tbl) x A continuous variable y A continuous variable fill The aggregation formula. Defaults to count (n) resolution The number of bins created by variable. The highest the number, the more records can be potentially imported from the source complete Uses tidyr::complete to include empty bins. Inserts value of 0. Details There are two considerations when using a Raster plot with a database. Both considerations are related to the size of the results downloaded from the database: - The number of bins requested: The higher the bins value is, the more data is downloaded from the database. - How concentrated the data is: This refers to how many intersections return a value. The more intersections without a value, the less data is downloaded from the database. Examples # Returns a 100x100 grid of record count of intersections of eruptions and waiting faithful %>% db_compute_raster(eruptions, waiting) # Returns a 50x50 grid of eruption averages of intersections of eruptions and waiting faithful %>% db_compute_raster(eruptions, waiting, fill = mean(eruptions), resolution = 50)
yandex_translator
hex
Erlang
Toggle Theme yandex_translator v0.9.6 API Reference === Modules --- [YandexTranslator](YandexTranslator.html) Elixir client for Yandex.Translate API [YandexTranslator.Client](YandexTranslator.Client.html) Client requests for old version of api, v1.5 [YandexTranslator.Cloud](YandexTranslator.Cloud.html) Client requests for new version of cloud api Toggle Theme yandex_translator v0.9.6 YandexTranslator === Elixir client for Yandex.Translate API Configuration (new API) --- An API key and folder id can be set in your application’s config. For getting api key and folder is check readme. ``` config :yandex_translator, cloud_api_key: "API_KEY" config :yandex_translator, cloud_folder_id: "FOLDER_ID" ``` Configuration (old API) --- An API key can be set in your application’s config. For getting api key check readme. ``` config :yandex_translator, api_key: "API_KEY" ``` [Link to this section](#summary) Summary === [Functions](#functions) --- [detect(options)](#detect/1) Detect language for text For using cloud api options must contain iam_token param [get_iam_token()](#get_iam_token/0) Get IAM-token for using it in requests to Yandex.Cloud Valid 12 hours [get_iam_token(options)](#get_iam_token/1) Get IAM-token for using it in requests to Yandex.Cloud Valid 12 hours [langs()](#langs/0) Get available languages for translation [langs(options)](#langs/1) Get available languages for translation For using cloud api options must contain iam_token param [translate(options)](#translate/1) Translate word or phrase For using cloud api options must contain iam_token param [Link to this section](#functions) Functions === [Link to this function](#detect/1 "Link to this function") detect(options) ``` detect([keyword](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: {:ok, %{}} ``` Detect language for text For using cloud api options must contain iam_token param. Example (cloud API) --- ``` iex> YandexTranslator.detect([iam_token: "", text: "Hello"]) {:ok, %{"language" => "en"}} ``` ### Options (cloud API) ``` iam_token - IAM-token, required folder_id - folder ID of your account at Yandex.Cloud, required or optional (if presented in configuration) text - text for detection, required hint - list of possible languages, optional, example - "en,ru" ``` Example (old API) --- ``` iex> YandexTranslator.detect([text: "Hello", format: "json"]) {:ok, %{"code" => 200, "lang" => "en"}} ``` Options (old API) --- ``` key - API KEY, required or optional (if presented in config) format - one of the [xml|json], optional, default - xml text - text for detection, required hint - list of possible languages, optional, example - "en,ru" ``` [Link to this function](#get_iam_token/0 "Link to this function") get_iam_token() ``` get_iam_token() :: {:ok, %{iamToken: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()}} ``` Get IAM-token for using it in requests to Yandex.Cloud Valid 12 hours. Example --- ``` iex> YandexTranslator.get_iam_token {:ok, %{"iamToken" => ""}} ``` [Link to this function](#get_iam_token/1 "Link to this function") get_iam_token(options) ``` get_iam_token([keyword](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: {:ok, %{iamToken: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()}} ``` Get IAM-token for using it in requests to Yandex.Cloud Valid 12 hours. Example --- ``` iex> YandexTranslator.get_iam_token([]) {:ok, %{"iamToken" => ""}} ``` ### Options ``` key - API KEY, required or optional (if presented in configuration) ``` [Link to this function](#langs/0 "Link to this function") langs() ``` langs() :: {:ok, %{}} ``` Get available languages for translation Example --- ``` iex> YandexTranslator.langs ``` [Link to this function](#langs/1 "Link to this function") langs(options) ``` langs([keyword](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: {:ok, %{}} ``` Get available languages for translation For using cloud api options must contain iam_token param. Example (cloud API) --- ``` iex> YandexTranslator.langs([iam_token: ""]) {:ok, %{"languages" => [%{"language" => "az"}, %{...}, ...]}} ``` ### Options (cloud API) ``` iam_token - IAM-token, required folder_id - folder ID of your account at Yandex.Cloud, required or optional (if presented in configuration) ``` Example (old API) --- ``` iex> YandexTranslator.langs([format: "json"]) {:ok, %{"dirs" => ["az-ru", ...]}} ``` ### Options (old API) ``` key - API KEY, required or optional (if presented in configuration) format - one of the [xml|json], optional, default - xml ui - language code for getting language translations, optional, example - "en" ``` [Link to this function](#translate/1 "Link to this function") translate(options) ``` translate([keyword](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: {:ok, %{}} ``` Translate word or phrase For using cloud api options must contain iam_token param. Example (cloud API) --- ``` iex> YandexTranslator.translate([iam_token: iam_token, text: "hello world", source: "en", target: "es"]) {:ok, %{"translations" => [%{"text" => "hola mundo"}]}} ``` ### Options (cloud API) ``` iam_token - IAM-token, required folder_id - folder ID of your account at Yandex.Cloud, required or optional (if presented in configuration) text - text for detection, required source - source language, ISO 639-1 format (like "en"), optional target - target language, ISO 639-1 format (like "ru"), required format - text format, one of the [plain|html], default - plain, optional ``` Example (old API) --- ``` iex> YandexTranslator.translate([format: "json", text: "Hello", lang: "en-es"]) {:ok, %{"code" => 200, "lang" => "en-es", "text" => ["Hola"]}} ``` Options (old API) --- ``` key - API KEY, required or optional (if presented in config) format - one of the [xml|json], optional, default - xml text - text, required lang - direction of translation, optional, example - "from-to" or "to" ``` Toggle Theme yandex_translator v0.9.6 YandexTranslator.Client === Client requests for old version of api, v1.5 [Link to this section](#summary) Summary === [Types](#types) --- [api_key()](#t:api_key/0) [path()](#t:path/0) [Functions](#functions) --- [call(type, args)](#call/2) Performs a request [Link to this section](#types) Types === [Link to this type](#t:api_key/0 "Link to this type") api_key() ``` api_key() :: {:api_key, [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()} ``` [Link to this type](#t:path/0 "Link to this type") path() ``` path() :: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)() ``` [Link to this section](#functions) Functions === [Link to this function](#call/2 "Link to this function") call(type, args) ``` call([String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [list](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: {} ``` Performs a request Examples --- ``` iex> YandexTranslator.Client.call("langs", args) ``` Toggle Theme yandex_translator v0.9.6 YandexTranslator.Cloud === Client requests for new version of cloud api [Link to this section](#summary) Summary === [Functions](#functions) --- [call(type, args)](#call/2) Performs a request [get_iam_token(args)](#get_iam_token/1) Get IAM-token [Link to this section](#functions) Functions === [Link to this function](#call/2 "Link to this function") call(type, args) ``` call([String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [list](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: {:ok, %{}} ``` Performs a request Examples --- ``` iex> YandexTranslator.Cloud.call("languages", args) ``` [Link to this function](#get_iam_token/1 "Link to this function") get_iam_token(args) ``` get_iam_token([keyword](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: {:ok, %{iamToken: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()}} ``` Get IAM-token Examples --- ``` iex> YandexTranslator.Cloud.get_iam_token([]) {:ok, %{"iamToken" => ""}} ```
github.com/fortytw2/leaktest
go
Go
README [¶](#section-readme) --- ### Leaktest [Build Status](https://travis-ci.org/fortytw2/leaktest) [codecov](https://codecov.io/gh/fortytw2/leaktest) [Sourcegraph](https://sourcegraph.com/github.com/fortytw2/leaktest?badge) [Documentation](http://godoc.org/github.com/fortytw2/leaktest) Refactored, tested variant of the goroutine leak detector found in both `net/http` tests and the `cockroachdb` source tree. Takes a snapshot of running goroutines at the start of a test, and at the end - compares the two and *voila*. Ignores runtime/sys goroutines. Doesn't play nice with `t.Parallel()` right now, but there are plans to do so. #### Installation Go 1.7+ ``` go get -u github.com/fortytw2/leaktest ``` Go 1.5/1.6 need to use the tag `v1.0.0`, as newer versions depend on `context.Context`. #### Example These tests fail, because they leak a goroutine ``` // Default "Check" will poll for 5 seconds to check that all // goroutines are cleaned up func TestPool(t *testing.T) { defer leaktest.Check(t)() go func() { for { time.Sleep(time.Second) } }() } // Helper function to timeout after X duration func TestPoolTimeout(t *testing.T) { defer leaktest.CheckTimeout(t, time.Second)() go func() { for { time.Sleep(time.Second) } }() } // Use Go 1.7+ context.Context for cancellation func TestPoolContext(t *testing.T) { ctx, _ := context.WithTimeout(context.Background(), time.Second) defer leaktest.CheckContext(ctx, t)() go func() { for { time.Sleep(time.Second) } }() } ``` ### LICENSE Same BSD-style as Go, see LICENSE Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package leaktest provides tools to detect leaked goroutines in tests. To use it, call "defer leaktest.Check(t)()" at the beginning of each test that may use goroutines. copied out of the cockroachdb source tree with slight modifications to be more re-useable ### Index [¶](#pkg-index) * [func Check(t ErrorReporter) func()](#Check) * [func CheckContext(ctx context.Context, t ErrorReporter) func()](#CheckContext) * [func CheckTimeout(t ErrorReporter, dur time.Duration) func()](#CheckTimeout) * [type ErrorReporter](#ErrorReporter) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) #### func [Check](https://github.com/fortytw2/leaktest/blob/v1.3.0/leaktest.go#L103) [¶](#Check) ``` func Check(t [ErrorReporter](#ErrorReporter)) func() ``` Check snapshots the currently-running goroutines and returns a function to be run at the end of tests to see whether any goroutines leaked, waiting up to 5 seconds in error conditions #### func [CheckContext](https://github.com/fortytw2/leaktest/blob/v1.3.0/leaktest.go#L122) [¶](#CheckContext) added in v1.1.0 ``` func CheckContext(ctx [context](/context).[Context](/context#Context), t [ErrorReporter](#ErrorReporter)) func() ``` CheckContext is the same as Check, but uses a context.Context for cancellation and timeout control #### func [CheckTimeout](https://github.com/fortytw2/leaktest/blob/v1.3.0/leaktest.go#L108) [¶](#CheckTimeout) added in v1.1.0 ``` func CheckTimeout(t [ErrorReporter](#ErrorReporter), dur [time](/time).[Duration](/time#Duration)) func() ``` CheckTimeout is the same as Check, but with a configurable timeout ### Types [¶](#pkg-types) #### type [ErrorReporter](https://github.com/fortytw2/leaktest/blob/v1.3.0/leaktest.go#L96) [¶](#ErrorReporter) ``` type ErrorReporter interface { Errorf(format [string](/builtin#string), args ...interface{}) } ``` ErrorReporter is a tiny subset of a testing.TB to make testing not such a massive pain
wasmer-types
rust
Rust
Crate wasmer_types === This are the common types and utility tools for using WebAssembly in a Rust environment. This crate provides common structures such as `Type` or `Value`, type indexes and native function wrappers with `Func`. Re-exports --- * `pub use crate::compilation::target::CpuFeature;` * `pub use crate::compilation::target::Target;` * `pub use error::CompileError;` * `pub use error::DeserializeError;` * `pub use error::ImportError;` * `pub use error::MemoryError;` * `pub use error::MiddlewareError;` * `pub use error::ParseCpuFeatureError;` * `pub use error::PreInstantiationError;` * `pub use error::SerializeError;` * `pub use error::WasmError;` * `pub use error::WasmResult;` * `pub use crate::compilation::relocation::ArchivedRelocation;` * `pub use crate::compilation::relocation::Relocation;` * `pub use crate::compilation::relocation::RelocationKind;` * `pub use crate::compilation::relocation::RelocationLike;` * `pub use crate::compilation::relocation::RelocationTarget;` * `pub use crate::compilation::relocation::Relocations;` * `pub use crate::compilation::section::ArchivedCustomSection;` * `pub use crate::compilation::section::CustomSection;` * `pub use crate::compilation::section::CustomSectionLike;` * `pub use crate::compilation::section::CustomSectionProtection;` * `pub use crate::compilation::section::SectionBody;` * `pub use crate::compilation::section::SectionIndex;` * `pub use crate::compilation::address_map::FunctionAddressMap;` * `pub use crate::compilation::address_map::InstructionAddressMap;` * `pub use crate::compilation::function::ArchivedFunctionBody;` * `pub use crate::compilation::function::Compilation;` * `pub use crate::compilation::function::CompiledFunction;` * `pub use crate::compilation::function::CompiledFunctionFrameInfo;` * `pub use crate::compilation::function::CustomSections;` * `pub use crate::compilation::function::Dwarf;` * `pub use crate::compilation::function::FunctionBody;` * `pub use crate::compilation::function::FunctionBodyLike;` * `pub use crate::compilation::function::Functions;` * `pub use crate::compilation::module::CompileModuleInfo;` * `pub use crate::compilation::symbols::Symbol;` * `pub use crate::compilation::symbols::SymbolRegistry;` * `pub use crate::compilation::unwind::ArchivedCompiledFunctionUnwindInfo;` * `pub use crate::compilation::unwind::CompiledFunctionUnwindInfo;` * `pub use crate::compilation::unwind::CompiledFunctionUnwindInfoLike;` * `pub use crate::compilation::unwind::CompiledFunctionUnwindInfoReference;` Modules --- * compilationTypes for compilation. * entityThe entity module, with common helpers for Rust structures * errorThe WebAssembly possible errors * libThe `lib` module defines a `std` module that is identical whether the `core` or the `std` feature is enabled. Macros --- * entity_implMacro which provides the common implementation of a 32-bit entity reference. Structs --- * ArchivedDataInitializerLocationAn archived `DataInitializerLocation` * ArchivedOwnedDataInitializerAn archived `OwnedDataInitializer` * ArchivedSerializableCompilationAn archived `SerializableCompilation` * ArchivedSerializableModuleAn archived `SerializableModule` * BytesUnits of WebAssembly memory in terms of 8-bit bytes. * CustomSectionIndexIndex type of a custom section inside a WebAssembly module. * DataIndexIndex type of a passive data segment inside the WebAssembly module. * DataInitializerA data initializer for linear memory. * DataInitializerLocationA memory index and offset within that memory where a data initialization should be performed. * ElemIndexIndex type of a passive element segment inside the WebAssembly module. * ExportTypeA descriptor for an exported WebAssembly value. * ExportsIteratorThis iterator allows us to iterate over the exports and offer nice API ergonomics over it. * FeaturesControls which experimental features will be enabled. Features usually have a corresponding WebAssembly proposal. * FrameInfoDescription of a frame in a backtrace. * FunctionIndexIndex type of a function (imported or local) inside the WebAssembly module. * FunctionTypeThe signature of a function that is either implemented in a Wasm module or exposed to Wasm by the host. * GlobalIndexIndex type of a global variable (imported or local) inside the WebAssembly module. * GlobalTypeWebAssembly global. * ImportKeyHash key of an import * ImportTypeA descriptor for an imported value into a wasm module. * ImportsIteratorThis iterator allows us to iterate over the imports and offer nice API ergonomics over it. * LocalFunctionIndexIndex type of a function defined locally inside the WebAssembly module. * LocalGlobalIndexIndex type of a global defined locally inside the WebAssembly module. * LocalMemoryIndexIndex type of a memory defined locally inside the WebAssembly module. * LocalTableIndexIndex type of a table defined locally inside the WebAssembly module. * Memory32Marker trait for 32-bit memories. * Memory64Marker trait for 64-bit memories. * MemoryIndexIndex type of a linear memory (imported or local) inside the WebAssembly module. * MemoryTypeA descriptor for a WebAssembly memory type. * MetadataHeaderMetadata header which holds an ABI version and the length of the remaining metadata. * ModuleInfoA translated WebAssembly module, excluding the function bodies and memory initializers. * OwnedDataInitializerAs `DataInitializer` but owning the data rather than holding a reference to it * PageCountOutOfRangeThe only error that can happen when converting `Bytes` to `Pages` * PagesUnits of WebAssembly pages (as specified to be 65,536 bytes). * SerializableCompilationThe compilation related data for a serialized modules * SerializableModuleSerializable struct that is able to serialize from and to a `ArtifactInfo`. * SignatureIndexIndex type of a signature (imported or local) inside the WebAssembly module. * SourceLocA source location. * StoreIdUnique ID to identify a context. * TableIndexIndex type of a table (imported or local) inside the WebAssembly module. * TableInitializerA WebAssembly table initializer. * TableTypeA descriptor for a table in a WebAssembly module. * TargetSharedSignatureIndexTarget specific type for shared signature index. * TrapInformationInformation about trap. * TripleA target “triple”. Historically such things had three fields, though they’ve added additional fields over time. * V128The WebAssembly V128 type * VMBuiltinFunctionIndexAn index type for builtin functions. * VMOffsetsThis class computes offsets to fields within VMContext and other related structs that JIT code accesses directly. Enums --- * Aarch64Architecture * ArchitectureThe “architecture” field, which in some cases also specifies a specific subarchitecture. * BinaryFormatThe “binary format” field, which is usually omitted, and the binary format is implied by the other fields. * CallingConventionThe calling convention, which specifies things like which registers are used for passing arguments, which registers are callee-saved, and so on. * EndiannessThe target memory endianness. * EnvironmentThe “environment” field, which specifies an ABI environment on top of the operating system. In many configurations, this field is omitted, and the environment is implied by the operating system. * ExportIndexAn entity to export. * ExternTypeA list of all possible types which can be externally referenced from a WebAssembly module. * GlobalInitGlobals are initialized via the `const` operators or by referring to another import. * ImportIndexAn entity to import. * LibCallThe name of a runtime library routine. * MemoryStyleImplementation styles for WebAssembly linear memory. * MutabilityIndicator of whether a global is mutable or not * OnCalledActionAfter the stack is unwound via asyncify what should the call loop do next * OperatingSystemThe “operating system” field, which sometimes implies an environment, and sometimes isn’t an actual operating system. * PointerWidthThe width of a pointer (in the default address space). * TableStyleImplementation styles for WebAssembly tables. * TrapCodeA trap code describing the reason for a trap. * TypeA list of all possible value types in WebAssembly. * VendorThe “vendor” field, which in practice is little more than an arbitrary modifier. Constants --- * VERSIONVersion number of this crate. * WASM_MAX_PAGESThe number of pages we can have before we run out of byte index space. * WASM_MIN_PAGESThe minimum number of pages allowed. * WASM_PAGE_SIZEWebAssembly page sizes are fixed to be 64KiB. Note: large page support may be added in an opt-in manner in the future. Traits --- * DataInitializerLikeAny struct that acts like a `DataInitializer`. * DataInitializerLocationLikeAny struct that acts like a `DataInitializerLocation`. * MemorySizeTrait for the `Memory32` and `Memory64` marker types. * NativeWasmType`NativeWasmType` represents a Wasm type that has a direct representation on the host (hence the “native” term). * ValueTypeTrait for a Value type. A Value type is a type that is always valid and may be safely copied. Functions --- * is_wasmCheck if the provided bytes are wasm-like Type Aliases --- * AddendAddend to add to the symbol value. * CodeOffsetOffset in bytes from the beginning of the function. Unions --- * RawValueRaw representation of a WebAssembly value. Crate wasmer_types === This are the common types and utility tools for using WebAssembly in a Rust environment. This crate provides common structures such as `Type` or `Value`, type indexes and native function wrappers with `Func`. Re-exports --- * `pub use crate::compilation::target::CpuFeature;` * `pub use crate::compilation::target::Target;` * `pub use error::CompileError;` * `pub use error::DeserializeError;` * `pub use error::ImportError;` * `pub use error::MemoryError;` * `pub use error::MiddlewareError;` * `pub use error::ParseCpuFeatureError;` * `pub use error::PreInstantiationError;` * `pub use error::SerializeError;` * `pub use error::WasmError;` * `pub use error::WasmResult;` * `pub use crate::compilation::relocation::ArchivedRelocation;` * `pub use crate::compilation::relocation::Relocation;` * `pub use crate::compilation::relocation::RelocationKind;` * `pub use crate::compilation::relocation::RelocationLike;` * `pub use crate::compilation::relocation::RelocationTarget;` * `pub use crate::compilation::relocation::Relocations;` * `pub use crate::compilation::section::ArchivedCustomSection;` * `pub use crate::compilation::section::CustomSection;` * `pub use crate::compilation::section::CustomSectionLike;` * `pub use crate::compilation::section::CustomSectionProtection;` * `pub use crate::compilation::section::SectionBody;` * `pub use crate::compilation::section::SectionIndex;` * `pub use crate::compilation::address_map::FunctionAddressMap;` * `pub use crate::compilation::address_map::InstructionAddressMap;` * `pub use crate::compilation::function::ArchivedFunctionBody;` * `pub use crate::compilation::function::Compilation;` * `pub use crate::compilation::function::CompiledFunction;` * `pub use crate::compilation::function::CompiledFunctionFrameInfo;` * `pub use crate::compilation::function::CustomSections;` * `pub use crate::compilation::function::Dwarf;` * `pub use crate::compilation::function::FunctionBody;` * `pub use crate::compilation::function::FunctionBodyLike;` * `pub use crate::compilation::function::Functions;` * `pub use crate::compilation::module::CompileModuleInfo;` * `pub use crate::compilation::symbols::Symbol;` * `pub use crate::compilation::symbols::SymbolRegistry;` * `pub use crate::compilation::unwind::ArchivedCompiledFunctionUnwindInfo;` * `pub use crate::compilation::unwind::CompiledFunctionUnwindInfo;` * `pub use crate::compilation::unwind::CompiledFunctionUnwindInfoLike;` * `pub use crate::compilation::unwind::CompiledFunctionUnwindInfoReference;` Modules --- * compilationTypes for compilation. * entityThe entity module, with common helpers for Rust structures * errorThe WebAssembly possible errors * libThe `lib` module defines a `std` module that is identical whether the `core` or the `std` feature is enabled. Macros --- * entity_implMacro which provides the common implementation of a 32-bit entity reference. Structs --- * ArchivedDataInitializerLocationAn archived `DataInitializerLocation` * ArchivedOwnedDataInitializerAn archived `OwnedDataInitializer` * ArchivedSerializableCompilationAn archived `SerializableCompilation` * ArchivedSerializableModuleAn archived `SerializableModule` * BytesUnits of WebAssembly memory in terms of 8-bit bytes. * CustomSectionIndexIndex type of a custom section inside a WebAssembly module. * DataIndexIndex type of a passive data segment inside the WebAssembly module. * DataInitializerA data initializer for linear memory. * DataInitializerLocationA memory index and offset within that memory where a data initialization should be performed. * ElemIndexIndex type of a passive element segment inside the WebAssembly module. * ExportTypeA descriptor for an exported WebAssembly value. * ExportsIteratorThis iterator allows us to iterate over the exports and offer nice API ergonomics over it. * FeaturesControls which experimental features will be enabled. Features usually have a corresponding WebAssembly proposal. * FrameInfoDescription of a frame in a backtrace. * FunctionIndexIndex type of a function (imported or local) inside the WebAssembly module. * FunctionTypeThe signature of a function that is either implemented in a Wasm module or exposed to Wasm by the host. * GlobalIndexIndex type of a global variable (imported or local) inside the WebAssembly module. * GlobalTypeWebAssembly global. * ImportKeyHash key of an import * ImportTypeA descriptor for an imported value into a wasm module. * ImportsIteratorThis iterator allows us to iterate over the imports and offer nice API ergonomics over it. * LocalFunctionIndexIndex type of a function defined locally inside the WebAssembly module. * LocalGlobalIndexIndex type of a global defined locally inside the WebAssembly module. * LocalMemoryIndexIndex type of a memory defined locally inside the WebAssembly module. * LocalTableIndexIndex type of a table defined locally inside the WebAssembly module. * Memory32Marker trait for 32-bit memories. * Memory64Marker trait for 64-bit memories. * MemoryIndexIndex type of a linear memory (imported or local) inside the WebAssembly module. * MemoryTypeA descriptor for a WebAssembly memory type. * MetadataHeaderMetadata header which holds an ABI version and the length of the remaining metadata. * ModuleInfoA translated WebAssembly module, excluding the function bodies and memory initializers. * OwnedDataInitializerAs `DataInitializer` but owning the data rather than holding a reference to it * PageCountOutOfRangeThe only error that can happen when converting `Bytes` to `Pages` * PagesUnits of WebAssembly pages (as specified to be 65,536 bytes). * SerializableCompilationThe compilation related data for a serialized modules * SerializableModuleSerializable struct that is able to serialize from and to a `ArtifactInfo`. * SignatureIndexIndex type of a signature (imported or local) inside the WebAssembly module. * SourceLocA source location. * StoreIdUnique ID to identify a context. * TableIndexIndex type of a table (imported or local) inside the WebAssembly module. * TableInitializerA WebAssembly table initializer. * TableTypeA descriptor for a table in a WebAssembly module. * TargetSharedSignatureIndexTarget specific type for shared signature index. * TrapInformationInformation about trap. * TripleA target “triple”. Historically such things had three fields, though they’ve added additional fields over time. * V128The WebAssembly V128 type * VMBuiltinFunctionIndexAn index type for builtin functions. * VMOffsetsThis class computes offsets to fields within VMContext and other related structs that JIT code accesses directly. Enums --- * Aarch64Architecture * ArchitectureThe “architecture” field, which in some cases also specifies a specific subarchitecture. * BinaryFormatThe “binary format” field, which is usually omitted, and the binary format is implied by the other fields. * CallingConventionThe calling convention, which specifies things like which registers are used for passing arguments, which registers are callee-saved, and so on. * EndiannessThe target memory endianness. * EnvironmentThe “environment” field, which specifies an ABI environment on top of the operating system. In many configurations, this field is omitted, and the environment is implied by the operating system. * ExportIndexAn entity to export. * ExternTypeA list of all possible types which can be externally referenced from a WebAssembly module. * GlobalInitGlobals are initialized via the `const` operators or by referring to another import. * ImportIndexAn entity to import. * LibCallThe name of a runtime library routine. * MemoryStyleImplementation styles for WebAssembly linear memory. * MutabilityIndicator of whether a global is mutable or not * OnCalledActionAfter the stack is unwound via asyncify what should the call loop do next * OperatingSystemThe “operating system” field, which sometimes implies an environment, and sometimes isn’t an actual operating system. * PointerWidthThe width of a pointer (in the default address space). * TableStyleImplementation styles for WebAssembly tables. * TrapCodeA trap code describing the reason for a trap. * TypeA list of all possible value types in WebAssembly. * VendorThe “vendor” field, which in practice is little more than an arbitrary modifier. Constants --- * VERSIONVersion number of this crate. * WASM_MAX_PAGESThe number of pages we can have before we run out of byte index space. * WASM_MIN_PAGESThe minimum number of pages allowed. * WASM_PAGE_SIZEWebAssembly page sizes are fixed to be 64KiB. Note: large page support may be added in an opt-in manner in the future. Traits --- * DataInitializerLikeAny struct that acts like a `DataInitializer`. * DataInitializerLocationLikeAny struct that acts like a `DataInitializerLocation`. * MemorySizeTrait for the `Memory32` and `Memory64` marker types. * NativeWasmType`NativeWasmType` represents a Wasm type that has a direct representation on the host (hence the “native” term). * ValueTypeTrait for a Value type. A Value type is a type that is always valid and may be safely copied. Functions --- * is_wasmCheck if the provided bytes are wasm-like Type Aliases --- * AddendAddend to add to the symbol value. * CodeOffsetOffset in bytes from the beginning of the function. Unions --- * RawValueRaw representation of a WebAssembly value. Enum wasmer_types::compilation::target::CpuFeature === ``` pub enum CpuFeature { SSE2, SSE3, SSSE3, SSE41, SSE42, POPCNT, AVX, BMI1, BMI2, AVX2, AVX512DQ, AVX512VL, AVX512F, LZCNT, } ``` The nomenclature is inspired by the `cpuid` crate. The list of supported features was initially retrieved from `cranelift-native`. The `CpuFeature` enum values are likely to grow closer to the original `cpuid`. However, we prefer to start small and grow from there. If you would like to use a flag that doesn’t exist yet here, please open a PR. Variants --- ### SSE2 ### SSE3 ### SSSE3 ### SSE41 ### SSE42 ### POPCNT ### AVX ### BMI1 ### BMI2 ### AVX2 ### AVX512DQ ### AVX512VL ### AVX512F ### LZCNT Implementations --- ### impl CpuFeature #### pub fn for_host() -> EnumSet<SelfRetrieves the features for the current Host #### pub fn set() -> EnumSet<SelfRetrieves an empty set of `CpuFeature`s. Trait Implementations --- ### impl<O: Into<EnumSet<CpuFeature>>> BitAnd<O> for CpuFeature #### type Output = EnumSet<CpuFeatureThe resulting type after applying the `&` operator.#### fn bitand(self, other: O) -> Self::Output Performs the `&` operation. #### type Output = EnumSet<CpuFeatureThe resulting type after applying the `|` operator.#### fn bitor(self, other: O) -> Self::Output Performs the `|` operation. #### type Output = EnumSet<CpuFeatureThe resulting type after applying the `^` operator.#### fn bitxor(self, other: O) -> Self::Output Performs the `^` operation. #### fn clone(&self) -> Self Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### type Repr = u16 The underlying type used to store the bitset.#### const ALL_BITS: Self::Repr = {transmute(0x3fff): <compilation::target::CpuFeature as enumset::__internal::EnumSetTypePrivate>::Repr} A mask of bits that are valid in the bitset.#### const BIT_WIDTH: u32 = 14u32 The largest bit used in the bitset.#### const VARIANT_COUNT: u32 = 14u32 The number of variants in the bitset.#### fn enum_into_u32(self) -> u32 Converts an enum of this type into its bit position.#### unsafe fn enum_from_u32(val: u32) -> Self Converts a bit position into an enum value.### impl FromStr for CpuFeature #### type Err = ParseCpuFeatureError The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Self, Self::ErrParses a string `s` to return a value of this type. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Output = EnumSet<CpuFeatureThe resulting type after applying the `!` operator.#### fn not(self) -> Self::Output Performs the unary `!` operation. #### fn eq(&self, other: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<EnumSet<CpuFeature>> for CpuFeature #### fn eq(&self, other: &EnumSet<CpuFeature>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<O: Into<EnumSet<CpuFeature>>> Sub<O> for CpuFeature #### type Output = EnumSet<CpuFeatureThe resulting type after applying the `-` operator.#### fn sub(self, other: O) -> Self::Output Performs the `-` operation. #### fn to_string(&self) -> String Converts the given value to a `String`. ### impl EnumSetType for CpuFeature ### impl Eq for CpuFeature Auto Trait Implementations --- ### impl RefUnwindSafe for CpuFeature ### impl Send for CpuFeature ### impl Sync for CpuFeature ### impl Unpin for CpuFeature ### impl UnwindSafe for CpuFeature Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::target::Target === ``` pub struct Target { /* private fields */ } ``` This is the target that we will use for compiling the WebAssembly ModuleInfo, and then run it. Implementations --- ### impl Target #### pub fn new(triple: Triple, cpu_features: EnumSet<CpuFeature>) -> Self Creates a new target given a triple #### pub fn triple(&self) -> &Triple The triple associated for the target. #### pub fn cpu_features(&self) -> &EnumSet<CpuFeatureThe triple associated for the target. #### pub fn is_native(&self) -> bool Check if target is a native (eq to host) or not Trait Implementations --- ### impl Clone for Target #### fn clone(&self) -> Target Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. The default for the Target will use the HOST as the triple #### fn default() -> Self Returns the “default value” for a type. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Target) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for Target ### impl StructuralEq for Target ### impl StructuralPartialEq for Target Auto Trait Implementations --- ### impl RefUnwindSafe for Target ### impl Send for Target ### impl Sync for Target ### impl Unpin for Target ### impl UnwindSafe for Target Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::CompileError === ``` pub enum CompileError { Wasm(WasmError), Codegen(String), Validate(String), UnsupportedFeature(String), UnsupportedTarget(String), Resource(String), } ``` The WebAssembly.CompileError object indicates an error during WebAssembly decoding or validation. This is based on the [Wasm Compile Error][compile-error] API. Variants --- ### Wasm(WasmError) A Wasm translation error occured. ### Codegen(String) A compilation error occured. ### Validate(String) The module did not pass validation. ### UnsupportedFeature(String) The compiler doesn’t support a Wasm feature ### UnsupportedTarget(String) The compiler cannot compile for the given target. This can refer to the OS, the chipset or any other aspect of the target system. ### Resource(String) Insufficient resources available for execution. Trait Implementations --- ### impl Debug for CompileError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(source: CompileError) -> Self Converts to this type from the input type.### impl From<WasmError> for CompileError #### fn from(original: WasmError) -> Self Converts to this type from the input type.Auto Trait Implementations --- ### impl RefUnwindSafe for CompileError ### impl Send for CompileError ### impl Sync for CompileError ### impl Unpin for CompileError ### impl UnwindSafe for CompileError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::DeserializeError === ``` pub enum DeserializeError { Io(Error), Generic(String), Incompatible(String), CorruptedBinary(String), Compiler(CompileError), InvalidByteLength { expected: usize, got: usize, }, } ``` The Deserialize error can occur when loading a compiled Module from a binary. Variants --- ### Io(Error) An IO error ### Generic(String) A generic deserialization error ### Incompatible(String) Incompatible serialized binary ### CorruptedBinary(String) The provided binary is corrupted ### Compiler(CompileError) The binary was valid, but we got an error when trying to allocate the required resources. ### InvalidByteLength #### Fields `expected: usize`How many bytes were expected `got: usize`How many bytes the artifact contained Input artifact bytes have an invalid length Trait Implementations --- ### impl Debug for DeserializeError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(source: CompileError) -> Self Converts to this type from the input type.### impl From<Error> for DeserializeError #### fn from(source: Error) -> Self Converts to this type from the input type.Auto Trait Implementations --- ### impl !RefUnwindSafe for DeserializeError ### impl Send for DeserializeError ### impl Sync for DeserializeError ### impl Unpin for DeserializeError ### impl !UnwindSafe for DeserializeError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::ImportError === ``` pub enum ImportError { IncompatibleType(ExternType, ExternType), UnknownImport(ExternType), MemoryError(String), } ``` An ImportError. Note: this error is not standard to WebAssembly, but it’s useful to determine the import issue on the API side. Variants --- ### IncompatibleType(ExternType, ExternType) Incompatible Import Type. This error occurs when the import types mismatch. ### UnknownImport(ExternType) Unknown Import. This error occurs when an import was expected but not provided. ### MemoryError(String) Memory Error Trait Implementations --- ### impl Debug for ImportError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for ImportError ### impl Send for ImportError ### impl Sync for ImportError ### impl Unpin for ImportError ### impl UnwindSafe for ImportError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::MemoryError === ``` #[non_exhaustive]pub enum MemoryError { Region(String), CouldNotGrow { current: Pages, attempted_delta: Pages, }, InvalidMemory { reason: String, }, MinimumMemoryTooLarge { min_requested: Pages, max_allowed: Pages, }, MaximumMemoryTooLarge { max_requested: Pages, max_allowed: Pages, }, MemoryNotShared, Generic(String), } ``` Error type describing things that can go wrong when operating on Wasm Memories. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### Region(String) Low level error with mmap. ### CouldNotGrow #### Fields `current: Pages`The current size in pages. `attempted_delta: Pages`The attempted amount to grow by in pages. The operation would cause the size of the memory to exceed the maximum or would cause an overflow leading to unindexable memory. ### InvalidMemory #### Fields `reason: String`The reason why the provided memory is invalid. Invalid memory was provided. ### MinimumMemoryTooLarge #### Fields `min_requested: Pages`The number of pages requested as the minimum amount of memory. `max_allowed: Pages`The maximum amount of memory we can allocate. Caller asked for more minimum memory than we can give them. ### MaximumMemoryTooLarge #### Fields `max_requested: Pages`The number of pages requested as the maximum amount of memory. `max_allowed: Pages`The number of pages requested as the maximum amount of memory. Caller asked for a maximum memory greater than we can give them. ### MemoryNotShared Returned when a shared memory is required, but the given memory is not shared. ### Generic(String) A user defined error value, used for error cases not listed above. Trait Implementations --- ### impl Clone for MemoryError #### fn clone(&self) -> MemoryError Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &MemoryError) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for MemoryError ### impl StructuralEq for MemoryError ### impl StructuralPartialEq for MemoryError Auto Trait Implementations --- ### impl RefUnwindSafe for MemoryError ### impl Send for MemoryError ### impl Sync for MemoryError ### impl Unpin for MemoryError ### impl UnwindSafe for MemoryError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::error::MiddlewareError === ``` pub struct MiddlewareError { pub name: String, pub message: String, } ``` A error in the middleware. Fields --- `name: String`The name of the middleware where the error was created `message: String`The error message Implementations --- ### impl MiddlewareError #### pub fn new<A: Into<String>, B: Into<String>>(name: A, message: B) -> Self Create a new `MiddlewareError` Trait Implementations --- ### impl Debug for MiddlewareError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(original: MiddlewareError) -> Self Converts to this type from the input type.Auto Trait Implementations --- ### impl RefUnwindSafe for MiddlewareError ### impl Send for MiddlewareError ### impl Sync for MiddlewareError ### impl Unpin for MiddlewareError ### impl UnwindSafe for MiddlewareError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::ParseCpuFeatureError === ``` pub enum ParseCpuFeatureError { Missing(String), } ``` The error that can happen while parsing a `str` to retrieve a `CpuFeature`. Variants --- ### Missing(String) The provided string feature doesn’t exist Trait Implementations --- ### impl Debug for ParseCpuFeatureError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for ParseCpuFeatureError ### impl Send for ParseCpuFeatureError ### impl Sync for ParseCpuFeatureError ### impl Unpin for ParseCpuFeatureError ### impl UnwindSafe for ParseCpuFeatureError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::PreInstantiationError === ``` pub enum PreInstantiationError { CpuFeature(String), } ``` An error while preinstantiating a module. Variants --- ### CpuFeature(String) The module was compiled with a CPU feature that is not available on the current host. Trait Implementations --- ### impl Debug for PreInstantiationError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for PreInstantiationError ### impl Send for PreInstantiationError ### impl Sync for PreInstantiationError ### impl Unpin for PreInstantiationError ### impl UnwindSafe for PreInstantiationError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::SerializeError === ``` pub enum SerializeError { Io(Error), Generic(String), } ``` The Serialize error can occur when serializing a compiled Module into a binary. Variants --- ### Io(Error) An IO error ### Generic(String) A generic serialization error Trait Implementations --- ### impl Debug for SerializeError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(source: Error) -> Self Converts to this type from the input type.Auto Trait Implementations --- ### impl !RefUnwindSafe for SerializeError ### impl Send for SerializeError ### impl Sync for SerializeError ### impl Unpin for SerializeError ### impl !UnwindSafe for SerializeError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::error::WasmError === ``` pub enum WasmError { InvalidWebAssembly { message: String, offset: usize, }, Unsupported(String), ImplLimitExceeded, Middleware(MiddlewareError), Generic(String), } ``` A WebAssembly translation error. When a WebAssembly function can’t be translated, one of these error codes will be returned to describe the failure. Variants --- ### InvalidWebAssembly #### Fields `message: String`A string describing the validation error. `offset: usize`The bytecode offset where the error occurred. The input WebAssembly code is invalid. This error code is used by a WebAssembly translator when it encounters invalid WebAssembly code. This should never happen for validated WebAssembly code. ### Unsupported(String) A feature used by the WebAssembly code is not supported by the embedding environment. Embedding environments may have their own limitations and feature restrictions. ### ImplLimitExceeded An implementation limit was exceeded. ### Middleware(MiddlewareError) An error from the middleware error. ### Generic(String) A generic error. Trait Implementations --- ### impl Debug for WasmError #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(original: MiddlewareError) -> Self Converts to this type from the input type.### impl From<WasmError> for CompileError #### fn from(original: WasmError) -> Self Converts to this type from the input type.Auto Trait Implementations --- ### impl RefUnwindSafe for WasmError ### impl Send for WasmError ### impl Sync for WasmError ### impl Unpin for WasmError ### impl UnwindSafe for WasmError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToString for Twhere T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Type Alias wasmer_types::error::WasmResult === ``` pub type WasmResult<T> = Result<T, WasmError>; ``` A convenient alias for a `Result` that uses `WasmError` as the error type. Aliased Type --- ``` enum WasmResult<T> { Ok(T), Err(WasmError), } ``` Variants --- 1.0.0### Ok(T) Contains the success value 1.0.0### Err(WasmError) Contains the error value Trait Implementations --- 1.0.0 · source### impl<T, E> Debug for Result<T, E>where T: Debug, E: Debug, #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. Read more1.0.0 · source### impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>where V: FromIterator<A>, #### fn from_iter<I>(iter: I) -> Result<V, E>where I: IntoIterator<Item = Result<A, E>>, Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, a container with the values of each `Result` is returned. Here is an example which increments every integer in a vector, checking for overflow: ``` let v = vec![1, 2]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` Here is another example that tries to subtract one from another list of integers, this time checking for underflow: ``` let v = vec![1, 2, 0]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` Here is a variation on the previous example, showing that no further elements are taken from `iter` after the first `Err`. ``` let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` Since the third element caused an underflow, no further elements were taken, so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. ### impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>where F: From<E>, #### fn from_residual(residual: Result<Infallible, E>) -> Result<T, F🔬This is a nightly-only experimental API. (`try_trait_v2`)Constructs the type from a compatible `Residual` type. F: From<E>, #### fn from_residual(_: Yeet<E>) -> Result<T, F🔬This is a nightly-only experimental API. (`try_trait_v2`)Constructs the type from a compatible `Residual` type. Read more1.0.0 · source### impl<T, E> Hash for Result<T, E>where T: Hash, E: Hash, #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. Read more1.0.0 · source### impl<T, E> IntoIterator for Result<T, E#### fn into_iter(self) -> IntoIter<TReturns a consuming iterator over the possibly contained value. The iterator yields one value if the result is `Result::Ok`, otherwise none. ##### Examples ``` let x: Result<u32, &str> = Ok(5); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result<u32, &str> = Err("nothing!"); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, []); ``` #### type Item = T The type of the elements being iterated over.#### type IntoIter = IntoIter<TWhich kind of iterator are we turning this into?1.0.0 · source### impl<T, E> Ord for Result<T, E>where T: Ord, E: Ord, #### fn cmp(&self, other: &Result<T, E>) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. T: PartialEq<U>, E: PartialEq<F>, #### fn eq(&self, other: &ArchivedResult<T, E>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl<T, E> PartialEq<Result<T, E>> for Result<T, E>where T: PartialEq<T>, E: PartialEq<E>, #### fn eq(&self, other: &Result<T, E>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl<T, E> PartialOrd<Result<T, E>> for Result<T, E>where T: PartialOrd<T>, E: PartialOrd<E>, #### fn partial_cmp(&self, other: &Result<T, E>) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. Read more1.16.0 · source### impl<T, U, E> Product<Result<U, E>> for Result<T, E>where T: Product<U>, #### fn product<I>(iter: I) -> Result<T, E>where I: Iterator<Item = Result<U, E>>, Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, the product of all elements is returned. ##### Examples This multiplies each number in a vector of strings, if a string could not be parsed the operation returns `Err`: ``` let nums = vec!["5", "10", "1", "2"]; let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product(); assert!(total.is_err()); ``` ### impl<T, E> Residual<T> for Result<Infallible, E#### type TryType = Result<T, E🔬This is a nightly-only experimental API. (`try_trait_v2_residual`)The “return” type of this meta-function.1.16.0 · source### impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where T: Sum<U>, #### fn sum<I>(iter: I) -> Result<T, E>where I: Iterator<Item = Result<U, E>>, Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, the sum of all elements is returned. ##### Examples This sums up every integer in a vector, rejecting the sum if a negative element is encountered: ``` let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result<i32, _> = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result<i32, _> = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` ### impl<T, E> Try for Result<T, E#### type Output = T 🔬This is a nightly-only experimental API. (`try_trait_v2`)The type of the value produced by `?` when *not* short-circuiting.#### type Residual = Result<Infallible, E🔬This is a nightly-only experimental API. (`try_trait_v2`)The type of the value passed to `FromResidual::from_residual` as part of `?` when short-circuiting. self ) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output🔬This is a nightly-only experimental API. (`try_trait_v2`)Used in `?` to decide whether the operator should produce a value (because this returned `ControlFlow::Continue`) or propagate a value back to the caller (because this returned `ControlFlow::Break`). Read more1.0.0 · source### impl<T, E> Copy for Result<T, E>where T: Copy, E: Copy, 1.0.0 · source### impl<T, E> Eq for Result<T, E>where T: Eq, E: Eq, 1.0.0 · source### impl<T, E> StructuralEq for Result<T, E1.0.0 · source### impl<T, E> StructuralPartialEq for Result<T, E{"IntoIter<T>":"<h3>Notable traits for <code><a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/result/struct.IntoIter.html\" title=\"struct core::result::IntoIter\">IntoIter</a>&lt;T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;T&gt; <a class=\"trait\" href=\"../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"https://doc.rust-lang.org/nightly/core/result/struct.IntoIter.html\" title=\"struct core::result::IntoIter\">IntoIter</a>&lt;T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = T;</span>"} Struct wasmer_types::compilation::relocation::ArchivedRelocation === ``` #[repr(C,)]pub struct ArchivedRelocationwhere RelocationKind: Archive, RelocationTarget: Archive, CodeOffset: Archive, Addend: Archive,{ pub kind: Archived<RelocationKind>, pub reloc_target: Archived<RelocationTarget>, pub offset: Archived<CodeOffset>, pub addend: Archived<Addend>, } ``` An archived `Relocation` Fields --- `kind: Archived<RelocationKind>`The archived counterpart of `Relocation::kind` `reloc_target: Archived<RelocationTarget>`The archived counterpart of `Relocation::reloc_target` `offset: Archived<CodeOffset>`The archived counterpart of `Relocation::offset` `addend: Archived<Addend>`The archived counterpart of `Relocation::addend` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedRelocationwhere RelocationKind: Archive, RelocationTarget: Archive, CodeOffset: Archive, Addend: Archive, Archived<RelocationKind>: CheckBytes<__C>, Archived<RelocationTarget>: CheckBytes<__C>, Archived<CodeOffset>: CheckBytes<__C>, Archived<Addend>: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn kind(&self) -> RelocationKind #### fn reloc_target(&self) -> RelocationTarget #### fn offset(&self) -> CodeOffset #### fn addend(&self) -> Addend #### fn for_address(&self, start: usize, target_func_address: u64) -> (usize, u64) Given a function start address, provide the relocation relative to that address. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for ArchivedRelocation ### impl Send for ArchivedRelocation ### impl Sync for ArchivedRelocation ### impl Unpin for ArchivedRelocation ### impl UnwindSafe for ArchivedRelocation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::relocation::Relocation === ``` pub struct Relocation { pub kind: RelocationKind, pub reloc_target: RelocationTarget, pub offset: CodeOffset, pub addend: Addend, } ``` A record of a relocation to perform. Fields --- `kind: RelocationKind`The relocation kind. `reloc_target: RelocationTarget`Relocation target. `offset: CodeOffset`The offset where to apply the relocation. `addend: Addend`The addend to add to the relocation value. Trait Implementations --- ### impl Archive for Relocationwhere RelocationKind: Archive, RelocationTarget: Archive, CodeOffset: Archive, Addend: Archive, #### type Archived = ArchivedRelocation The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> Relocation Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. RelocationKind: Archive, Archived<RelocationKind>: Deserialize<RelocationKind, __D>, RelocationTarget: Archive, Archived<RelocationTarget>: Deserialize<RelocationTarget, __D>, CodeOffset: Archive, Archived<CodeOffset>: Deserialize<CodeOffset, __D>, Addend: Archive, Archived<Addend>: Deserialize<Addend, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<Relocation, __D::ErrorDeserializes using the given deserializer### impl PartialEq<Relocation> for Relocation #### fn eq(&self, other: &Relocation) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl RelocationLike for Relocation #### fn kind(&self) -> RelocationKind #### fn reloc_target(&self) -> RelocationTarget #### fn offset(&self) -> CodeOffset #### fn addend(&self) -> Addend #### fn for_address(&self, start: usize, target_func_address: u64) -> (usize, u64) Given a function start address, provide the relocation relative to that address. RelocationKind: Serialize<__S>, RelocationTarget: Serialize<__S>, CodeOffset: Serialize<__S>, Addend: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for Relocation ### impl StructuralEq for Relocation ### impl StructuralPartialEq for Relocation Auto Trait Implementations --- ### impl RefUnwindSafe for Relocation ### impl Send for Relocation ### impl Sync for Relocation ### impl Unpin for Relocation ### impl UnwindSafe for Relocation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::compilation::relocation::RelocationKind === ``` #[repr(u8)]pub enum RelocationKind { Abs4, Abs8, X86PCRel4, X86PCRel8, X86CallPCRel4, X86CallPLTRel4, X86GOTPCRel4, Arm32Call, Arm64Call, Arm64Movw0, Arm64Movw1, Arm64Movw2, Arm64Movw3, RiscvPCRelHi20, RiscvPCRelLo12I, RiscvCall, ElfX86_64TlsGd, } ``` Relocation kinds for every ISA. Variants --- ### Abs4 absolute 4-byte ### Abs8 absolute 8-byte ### X86PCRel4 x86 PC-relative 4-byte ### X86PCRel8 x86 PC-relative 8-byte ### X86CallPCRel4 x86 call to PC-relative 4-byte ### X86CallPLTRel4 x86 call to PLT-relative 4-byte ### X86GOTPCRel4 x86 GOT PC-relative 4-byte ### Arm32Call Arm32 call target ### Arm64Call Arm64 call target ### Arm64Movw0 Arm64 movk/z part 0 ### Arm64Movw1 Arm64 movk/z part 1 ### Arm64Movw2 Arm64 movk/z part 2 ### Arm64Movw3 Arm64 movk/z part 3 ### RiscvPCRelHi20 RISC-V PC-relative high 20bit ### RiscvPCRelLo12I RISC-V PC-relative low 12bit, I-type ### RiscvCall RISC-V call target ### ElfX86_64TlsGd Elf x86_64 32 bit signed PC relative offset to two GOT entries for GD symbol. Trait Implementations --- ### impl Archive for RelocationKind #### type Archived = RelocationKind The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> RelocationKind Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. &self, deserializer: &mut __D ) -> Result<RelocationKind, __D::ErrorDeserializes using the given deserializer### impl Display for RelocationKind #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Display trait implementation drops the arch, since its used in contexts where the arch is already unambiguous, e.g. clif syntax with isa specified. In other contexts, use Debug. ### impl PartialEq<RelocationKind> for RelocationKind #### fn eq(&self, other: &RelocationKind) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for RelocationKind #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for RelocationKind ### impl Eq for RelocationKind ### impl StructuralEq for RelocationKind ### impl StructuralPartialEq for RelocationKind Auto Trait Implementations --- ### impl RefUnwindSafe for RelocationKind ### impl Send for RelocationKind ### impl Sync for RelocationKind ### impl Unpin for RelocationKind ### impl UnwindSafe for RelocationKind Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Trait wasmer_types::compilation::relocation::RelocationLike === ``` pub trait RelocationLike { // Required methods fn kind(&self) -> RelocationKind; fn reloc_target(&self) -> RelocationTarget; fn offset(&self) -> CodeOffset; fn addend(&self) -> Addend; // Provided method fn for_address( &self, start: usize, target_func_address: u64 ) -> (usize, u64) { ... } } ``` Any struct that acts like a `Relocation`. Required Methods --- #### fn kind(&self) -> RelocationKind #### fn reloc_target(&self) -> RelocationTarget #### fn offset(&self) -> CodeOffset #### fn addend(&self) -> Addend Provided Methods --- #### fn for_address(&self, start: usize, target_func_address: u64) -> (usize, u64) Given a function start address, provide the relocation relative to that address. The function returns the relocation address and the delta. Implementors --- ### impl RelocationLike for ArchivedRelocation ### impl RelocationLike for Relocation Enum wasmer_types::compilation::relocation::RelocationTarget === ``` #[repr(u8)]pub enum RelocationTarget { LocalFunc(LocalFunctionIndex), LibCall(LibCall), CustomSection(SectionIndex), } ``` Destination function. Can be either user function or some special one, like `memory.grow`. Variants --- ### LocalFunc(LocalFunctionIndex) A relocation to a function defined locally in the wasm (not an imported one). ### LibCall(LibCall) A compiler-generated libcall. ### CustomSection(SectionIndex) Custom sections generated by the compiler Trait Implementations --- ### impl Archive for RelocationTargetwhere LocalFunctionIndex: Archive, LibCall: Archive, SectionIndex: Archive, #### type Archived = RelocationTarget The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. LocalFunctionIndex: CheckBytes<__C>, LibCall: CheckBytes<__C>, SectionIndex: CheckBytes<__C>, #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> RelocationTarget Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. LocalFunctionIndex: Archive, Archived<LocalFunctionIndex>: Deserialize<LocalFunctionIndex, __D>, LibCall: Archive, Archived<LibCall>: Deserialize<LibCall, __D>, SectionIndex: Archive, Archived<SectionIndex>: Deserialize<SectionIndex, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<RelocationTarget, __D::ErrorDeserializes using the given deserializer### impl PartialEq<RelocationTarget> for RelocationTarget #### fn eq(&self, other: &RelocationTarget) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for RelocationTargetwhere LocalFunctionIndex: Serialize<__S>, LibCall: Serialize<__S>, SectionIndex: Serialize<__S>, #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for RelocationTarget ### impl Eq for RelocationTarget ### impl StructuralEq for RelocationTarget ### impl StructuralPartialEq for RelocationTarget Auto Trait Implementations --- ### impl RefUnwindSafe for RelocationTarget ### impl Send for RelocationTarget ### impl Sync for RelocationTarget ### impl Unpin for RelocationTarget ### impl UnwindSafe for RelocationTarget Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Type Alias wasmer_types::compilation::relocation::Relocations === ``` pub type Relocations = PrimaryMap<LocalFunctionIndex, Vec<Relocation>>; ``` Relocations to apply to function bodies. Aliased Type --- ``` struct Relocations { /* private fields */ } ``` Implementations --- ### impl<K, V> PrimaryMap<K, V>where K: EntityRef, #### pub fn new() -> Self Create a new empty map. #### pub fn with_capacity(capacity: usize) -> Self Create a new empty map with the given capacity. #### pub fn is_valid(&self, k: K) -> bool Check if `k` is a valid key in the map. #### pub fn get(&self, k: K) -> Option<&VGet the element at `k` if it exists. #### pub fn get_mut(&mut self, k: K) -> Option<&mut VGet the element at `k` if it exists, mutable version. #### pub fn is_empty(&self) -> bool Is this map completely empty? #### pub fn len(&self) -> usize Get the total number of entity references created. #### pub fn keys(&self) -> Keys<KIterate over all the keys in this map. #### pub fn values(&self) -> Iter<'_, VIterate over all the values in this map. #### pub fn values_mut(&mut self) -> IterMut<'_, VIterate over all the values in this map, mutable edition. #### pub fn iter(&self) -> Iter<'_, K, VIterate over all the keys and values in this map. #### pub fn iter_mut(&mut self) -> IterMut<'_, K, VIterate over all the keys and values in this map, mutable edition. #### pub fn clear(&mut self) Remove all entries from this map. #### pub fn next_key(&self) -> K Get the key that will be assigned to the next pushed value. #### pub fn push(&mut self, v: V) -> K Append `v` to the mapping, assigning a new key which is returned. #### pub fn last(&self) -> Option<&VReturns the last element that was inserted in the map. #### pub fn reserve(&mut self, additional: usize) Reserves capacity for at least `additional` more elements to be inserted. #### pub fn reserve_exact(&mut self, additional: usize) Reserves the minimum capacity for exactly `additional` more elements to be inserted. #### pub fn shrink_to_fit(&mut self) Shrinks the capacity of the `PrimaryMap` as much as possible. #### pub fn into_boxed_slice(self) -> BoxedSlice<K, VConsumes this `PrimaryMap` and produces a `BoxedSlice`. Trait Implementations --- ### impl<K, V> Archive for PrimaryMap<K, V>where K: EntityRef, Vec<V>: Archive, PhantomData<K>: Archive, #### type Archived = ArchivedPrimaryMap<K, VThe archived representation of this type. &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. K: EntityRef + Clone, #### fn clone(&self) -> PrimaryMap<K, VReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. K: EntityRef + Debug, #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. K: EntityRef, #### fn default() -> Self Returns the “default value” for a type. K: EntityRef, Vec<V>: Archive, Archived<Vec<V>>: Deserialize<Vec<V>, __D>, PhantomData<K>: Archive, Archived<PhantomData<K>>: Deserialize<PhantomData<K>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<PrimaryMap<K, V>, __D::ErrorDeserializes using the given deserializer### impl<K, V> FromIterator<V> for PrimaryMap<K, V>where K: EntityRef, #### fn from_iter<T>(iter: T) -> Selfwhere T: IntoIterator<Item = V>, Creates a value from an iterator. K: EntityRef + Hash, #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. K: EntityRef, Immutable indexing into an `PrimaryMap`. The indexed value must be in the map. #### type Output = V The returned type after indexing.#### fn index(&self, k: K) -> &V Performs the indexing (`container[index]`) operation. K: EntityRef, Mutable indexing into an `PrimaryMap`. #### fn index_mut(&mut self, k: K) -> &mut V Performs the mutable indexing (`container[index]`) operation. K: EntityRef, #### type Item = (K, V) The type of the elements being iterated over.#### type IntoIter = IntoIter<K, VWhich kind of iterator are we turning this into?#### fn into_iter(self) -> Self::IntoIter Creates an iterator from a value. K: EntityRef + PartialEq, #### fn eq(&self, other: &PrimaryMap<K, V>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized, K, V> Serialize<__S> for PrimaryMap<K, V>where K: EntityRef, Vec<V>: Serialize<__S>, PhantomData<K>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl<K, V: Eq> Eq for PrimaryMap<K, V>where K: EntityRef + Eq, ### impl<K, V> StructuralEq for PrimaryMap<K, V>where K: EntityRef, ### impl<K, V> StructuralPartialEq for PrimaryMap<K, V>where K: EntityRef, {"Iter<'_, K, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.Iter.html\" title=\"struct wasmer_types::entity::Iter\">Iter</a>&lt;'a, K, V&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>, V&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.Iter.html\" title=\"struct wasmer_types::entity::Iter\">Iter</a>&lt;'a, K, V&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (K, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a V</a>);</span>","Iter<'_, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../lib/std/slice/struct.Iter.html\" title=\"struct wasmer_types::lib::std::slice::Iter\">Iter</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../lib/std/slice/struct.Iter.html\" title=\"struct wasmer_types::lib::std::slice::Iter\">Iter</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>;</span>","IterMut<'_, K, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.IterMut.html\" title=\"struct wasmer_types::entity::IterMut\">IterMut</a>&lt;'a, K, V&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>, V&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.IterMut.html\" title=\"struct wasmer_types::entity::IterMut\">IterMut</a>&lt;'a, K, V&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (K, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a mut V</a>);</span>","IterMut<'_, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../lib/std/slice/struct.IterMut.html\" title=\"struct wasmer_types::lib::std::slice::IterMut\">IterMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../lib/std/slice/struct.IterMut.html\" title=\"struct wasmer_types::lib::std::slice::IterMut\">IterMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a mut T</a>;</span>","Keys<K>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.Keys.html\" title=\"struct wasmer_types::entity::Keys\">Keys</a>&lt;K&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.Keys.html\" title=\"struct wasmer_types::entity::Keys\">Keys</a>&lt;K&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = K;</span>"} Struct wasmer_types::compilation::section::ArchivedCustomSection === ``` #[repr(C,)]pub struct ArchivedCustomSectionwhere CustomSectionProtection: Archive, SectionBody: Archive, Vec<Relocation>: Archive,{ pub protection: Archived<CustomSectionProtection>, pub bytes: Archived<SectionBody>, pub relocations: Archived<Vec<Relocation>>, } ``` An archived `CustomSection` Fields --- `protection: Archived<CustomSectionProtection>`The archived counterpart of `CustomSection::protection` `bytes: Archived<SectionBody>`The archived counterpart of `CustomSection::bytes` `relocations: Archived<Vec<Relocation>>`The archived counterpart of `CustomSection::relocations` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedCustomSectionwhere CustomSectionProtection: Archive, SectionBody: Archive, Vec<Relocation>: Archive, Archived<CustomSectionProtection>: CheckBytes<__C>, Archived<SectionBody>: CheckBytes<__C>, Archived<Vec<Relocation>>: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### type Relocations = ArchivedRelocation #### fn protection(&self) -> &CustomSectionProtection #### fn bytes(&self) -> &[u8] #### fn relocations(&'a self) -> &[Self::Relocations] Auto Trait Implementations --- ### impl RefUnwindSafe for ArchivedCustomSection ### impl Send for ArchivedCustomSection ### impl Sync for ArchivedCustomSection ### impl !Unpin for ArchivedCustomSection ### impl UnwindSafe for ArchivedCustomSection Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct wasmer_types::compilation::section::CustomSection === ``` pub struct CustomSection { pub protection: CustomSectionProtection, pub bytes: SectionBody, pub relocations: Vec<Relocation>, } ``` A Section for a `Compilation`. This is used so compilers can store arbitrary information in the emitted module. Fields --- `protection: CustomSectionProtection`Memory protection that applies to this section. `bytes: SectionBody`The bytes corresponding to this section. > Note: These bytes have to be at-least 8-byte aligned > (the start of the memory pointer). > We might need to create another field for alignment in case it’s > needed in the future. `relocations: Vec<Relocation>`Relocations that apply to this custom section. Trait Implementations --- ### impl Archive for CustomSectionwhere CustomSectionProtection: Archive, SectionBody: Archive, Vec<Relocation>: Archive, #### type Archived = ArchivedCustomSection The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> CustomSection Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### type Relocations = Relocation #### fn protection(&self) -> &CustomSectionProtection #### fn bytes(&self) -> &[u8] #### fn relocations(&'a self) -> &[Self::Relocations] ### impl Debug for CustomSection #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. CustomSectionProtection: Archive, Archived<CustomSectionProtection>: Deserialize<CustomSectionProtection, __D>, SectionBody: Archive, Archived<SectionBody>: Deserialize<SectionBody, __D>, Vec<Relocation>: Archive, Archived<Vec<Relocation>>: Deserialize<Vec<Relocation>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<CustomSection, __D::ErrorDeserializes using the given deserializer### impl PartialEq<CustomSection> for CustomSection #### fn eq(&self, other: &CustomSection) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for CustomSectionwhere CustomSectionProtection: Serialize<__S>, SectionBody: Serialize<__S>, Vec<Relocation>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for CustomSection ### impl StructuralEq for CustomSection ### impl StructuralPartialEq for CustomSection Auto Trait Implementations --- ### impl RefUnwindSafe for CustomSection ### impl Send for CustomSection ### impl Sync for CustomSection ### impl Unpin for CustomSection ### impl UnwindSafe for CustomSection Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Trait wasmer_types::compilation::section::CustomSectionLike === ``` pub trait CustomSectionLike<'a> { type Relocations: RelocationLike; // Required methods fn protection(&self) -> &CustomSectionProtection; fn bytes(&self) -> &[u8] ; fn relocations(&'a self) -> &[Self::Relocations]; } ``` Any struct that acts like a `CustomSection`. Required Associated Types --- #### type Relocations: RelocationLike Required Methods --- #### fn protection(&self) -> &CustomSectionProtection #### fn bytes(&self) -> &[u8] #### fn relocations(&'a self) -> &[Self::Relocations] Implementors --- ### impl<'a> CustomSectionLike<'a> for ArchivedCustomSection #### type Relocations = ArchivedRelocation ### impl<'a> CustomSectionLike<'a> for CustomSection #### type Relocations = Relocation {"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Enum wasmer_types::compilation::section::CustomSectionProtection === ``` #[repr(u8)]pub enum CustomSectionProtection { Read, ReadExecute, } ``` Custom section Protection. Determines how a custom section may be used. Variants --- ### Read A custom section with read permission. ### ReadExecute A custom section with read and execute permissions. Trait Implementations --- ### impl Archive for CustomSectionProtection #### type Archived = CustomSectionProtection The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> CustomSectionProtection Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. &self, deserializer: &mut __D ) -> Result<CustomSectionProtection, __D::ErrorDeserializes using the given deserializer### impl PartialEq<CustomSectionProtection> for CustomSectionProtection #### fn eq(&self, other: &CustomSectionProtection) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for CustomSectionProtection #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for CustomSectionProtection ### impl StructuralEq for CustomSectionProtection ### impl StructuralPartialEq for CustomSectionProtection Auto Trait Implementations --- ### impl RefUnwindSafe for CustomSectionProtection ### impl Send for CustomSectionProtection ### impl Sync for CustomSectionProtection ### impl Unpin for CustomSectionProtection ### impl UnwindSafe for CustomSectionProtection Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::section::SectionBody === ``` pub struct SectionBody(/* private fields */); ``` The bytes in the section. Implementations --- ### impl SectionBody #### pub fn new_with_vec(contents: Vec<u8>) -> Self Create a new section body with the given contents. #### pub fn as_ptr(&self) -> *constu8 Returns a raw pointer to the section’s buffer. #### pub fn len(&self) -> usize Returns the length of this section in bytes. #### pub fn as_slice(&self) -> &[u8] Dereferences into the section’s buffer. #### pub fn is_empty(&self) -> bool Returns whether or not the section body is empty. Trait Implementations --- ### impl Archive for SectionBodywhere Vec<u8>: Archive, #### type Archived = ArchivedSectionBody The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> SectionBody Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> SectionBody Returns the “default value” for a type. Vec<u8>: Archive, Archived<Vec<u8>>: Deserialize<Vec<u8>, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<SectionBody, __D::ErrorDeserializes using the given deserializer### impl PartialEq<SectionBody> for SectionBody #### fn eq(&self, other: &SectionBody) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for SectionBodywhere Vec<u8>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for SectionBody ### impl StructuralEq for SectionBody ### impl StructuralPartialEq for SectionBody Auto Trait Implementations --- ### impl RefUnwindSafe for SectionBody ### impl Send for SectionBody ### impl Sync for SectionBody ### impl Unpin for SectionBody ### impl UnwindSafe for SectionBody Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct wasmer_types::compilation::section::SectionIndex === ``` pub struct SectionIndex(/* private fields */); ``` Index type of a Section defined inside a WebAssembly `Compilation`. Implementations --- ### impl SectionIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for SectionIndexwhere u32: Archive, #### type Archived = SectionIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> SectionIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> SectionIndex Returns the “default value” for a type. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<SectionIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for SectionIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for SectionIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &SectionIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &SectionIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<SectionIndex> for SectionIndex #### fn partial_cmp(&self, other: &SectionIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> SectionIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for SectionIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for SectionIndex ### impl Eq for SectionIndex ### impl StructuralEq for SectionIndex ### impl StructuralPartialEq for SectionIndex Auto Trait Implementations --- ### impl RefUnwindSafe for SectionIndex ### impl Send for SectionIndex ### impl Sync for SectionIndex ### impl Unpin for SectionIndex ### impl UnwindSafe for SectionIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::address_map::FunctionAddressMap === ``` pub struct FunctionAddressMap { pub instructions: Vec<InstructionAddressMap>, pub start_srcloc: SourceLoc, pub end_srcloc: SourceLoc, pub body_offset: usize, pub body_len: usize, } ``` Function and its instructions addresses mappings. Fields --- `instructions: Vec<InstructionAddressMap>`Instructions maps. The array is sorted by the InstructionAddressMap::code_offset field. `start_srcloc: SourceLoc`Function start source location (normally declaration). `end_srcloc: SourceLoc`Function end source location. `body_offset: usize`Generated function body offset if applicable, otherwise 0. `body_len: usize`Generated function body length. Trait Implementations --- ### impl Archive for FunctionAddressMapwhere Vec<InstructionAddressMap>: Archive, SourceLoc: Archive, usize: Archive, #### type Archived = ArchivedFunctionAddressMap The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> FunctionAddressMap Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> FunctionAddressMap Returns the “default value” for a type. Vec<InstructionAddressMap>: Archive, Archived<Vec<InstructionAddressMap>>: Deserialize<Vec<InstructionAddressMap>, __D>, SourceLoc: Archive, Archived<SourceLoc>: Deserialize<SourceLoc, __D>, usize: Archive, Archived<usize>: Deserialize<usize, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<FunctionAddressMap, __D::ErrorDeserializes using the given deserializer### impl PartialEq<FunctionAddressMap> for FunctionAddressMap #### fn eq(&self, other: &FunctionAddressMap) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for FunctionAddressMapwhere Vec<InstructionAddressMap>: Serialize<__S>, SourceLoc: Serialize<__S>, usize: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for FunctionAddressMap ### impl StructuralEq for FunctionAddressMap ### impl StructuralPartialEq for FunctionAddressMap Auto Trait Implementations --- ### impl RefUnwindSafe for FunctionAddressMap ### impl Send for FunctionAddressMap ### impl Sync for FunctionAddressMap ### impl Unpin for FunctionAddressMap ### impl UnwindSafe for FunctionAddressMap Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::address_map::InstructionAddressMap === ``` pub struct InstructionAddressMap { pub srcloc: SourceLoc, pub code_offset: usize, pub code_len: usize, } ``` Single source location to generated address mapping. Fields --- `srcloc: SourceLoc`Original source location. `code_offset: usize`Generated instructions offset. `code_len: usize`Generated instructions length. Trait Implementations --- ### impl Archive for InstructionAddressMapwhere SourceLoc: Archive, usize: Archive, #### type Archived = ArchivedInstructionAddressMap The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> InstructionAddressMap Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. SourceLoc: Archive, Archived<SourceLoc>: Deserialize<SourceLoc, __D>, usize: Archive, Archived<usize>: Deserialize<usize, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<InstructionAddressMap, __D::ErrorDeserializes using the given deserializer### impl PartialEq<InstructionAddressMap> for InstructionAddressMap #### fn eq(&self, other: &InstructionAddressMap) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for InstructionAddressMapwhere SourceLoc: Serialize<__S>, usize: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for InstructionAddressMap ### impl StructuralEq for InstructionAddressMap ### impl StructuralPartialEq for InstructionAddressMap Auto Trait Implementations --- ### impl RefUnwindSafe for InstructionAddressMap ### impl Send for InstructionAddressMap ### impl Sync for InstructionAddressMap ### impl Unpin for InstructionAddressMap ### impl UnwindSafe for InstructionAddressMap Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::function::ArchivedFunctionBody === ``` #[repr(C,)]pub struct ArchivedFunctionBodywhere Vec<u8>: Archive, Option<CompiledFunctionUnwindInfo>: Archive,{ pub body: Archived<Vec<u8>>, pub unwind_info: Archived<Option<CompiledFunctionUnwindInfo>>, } ``` An archived `FunctionBody` Fields --- `body: Archived<Vec<u8>>`The archived counterpart of `FunctionBody::body` `unwind_info: Archived<Option<CompiledFunctionUnwindInfo>>`The archived counterpart of `FunctionBody::unwind_info` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedFunctionBodywhere Vec<u8>: Archive, Option<CompiledFunctionUnwindInfo>: Archive, Archived<Vec<u8>>: CheckBytes<__C>, Archived<Option<CompiledFunctionUnwindInfo>>: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### type UnwindInfo = ArchivedCompiledFunctionUnwindInfo #### fn body(&'a self) -> &'a [u8] #### fn unwind_info(&'a self) -> Option<&Self::UnwindInfoAuto Trait Implementations --- ### impl RefUnwindSafe for ArchivedFunctionBody ### impl Send for ArchivedFunctionBody ### impl Sync for ArchivedFunctionBody ### impl !Unpin for ArchivedFunctionBody ### impl UnwindSafe for ArchivedFunctionBody Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&'a [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct wasmer_types::compilation::function::Compilation === ``` pub struct Compilation { pub functions: Functions, pub custom_sections: CustomSections, pub function_call_trampolines: PrimaryMap<SignatureIndex, FunctionBody>, pub dynamic_function_trampolines: PrimaryMap<FunctionIndex, FunctionBody>, pub debug: Option<Dwarf>, } ``` The result of compiling a WebAssembly module’s functions. Fields --- `functions: Functions`Compiled code for the function bodies. `custom_sections: CustomSections`Custom sections for the module. It will hold the data, for example, for constants used in a function, global variables, rodata_64, hot/cold function partitioning, … `function_call_trampolines: PrimaryMap<SignatureIndex, FunctionBody>`Trampolines to call a function defined locally in the wasm via a provided `Vec` of values. This allows us to call easily Wasm functions, such as: ``` let func = instance.exports.get_function("my_func"); func.call(&[Value::I32(1)]); ``` `dynamic_function_trampolines: PrimaryMap<FunctionIndex, FunctionBody>`Trampolines to call a dynamic function defined in a host, from a Wasm module. This allows us to create dynamic Wasm functions, such as: ``` fn my_func(values: &[Val]) -> Result<Vec<Val>, RuntimeError> { // do something } let my_func_type = FunctionType::new(vec![Type::I32], vec![Type::I32]); let imports = imports!{ "namespace" => { "my_func" => Function::new(&store, my_func_type, my_func), } } ``` Note: Dynamic function trampolines are only compiled for imported function types. `debug: Option<Dwarf>`Section ids corresponding to the Dwarf debug info Trait Implementations --- ### impl Debug for Compilation #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn eq(&self, other: &Compilation) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for Compilation ### impl StructuralEq for Compilation ### impl StructuralPartialEq for Compilation Auto Trait Implementations --- ### impl RefUnwindSafe for Compilation ### impl Send for Compilation ### impl Sync for Compilation ### impl Unpin for Compilation ### impl UnwindSafe for Compilation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::function::CompiledFunction === ``` pub struct CompiledFunction { pub body: FunctionBody, pub relocations: Vec<Relocation>, pub frame_info: CompiledFunctionFrameInfo, } ``` The result of compiling a WebAssembly function. This structure only have the compiled information data (function bytecode body, relocations, traps, jump tables and unwind information). Fields --- `body: FunctionBody`The function body. `relocations: Vec<Relocation>`The relocations (in the body) `frame_info: CompiledFunctionFrameInfo`The frame information. Trait Implementations --- ### impl Archive for CompiledFunctionwhere FunctionBody: Archive, Vec<Relocation>: Archive, CompiledFunctionFrameInfo: Archive, #### type Archived = ArchivedCompiledFunction The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> CompiledFunction Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. FunctionBody: Archive, Archived<FunctionBody>: Deserialize<FunctionBody, __D>, Vec<Relocation>: Archive, Archived<Vec<Relocation>>: Deserialize<Vec<Relocation>, __D>, CompiledFunctionFrameInfo: Archive, Archived<CompiledFunctionFrameInfo>: Deserialize<CompiledFunctionFrameInfo, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<CompiledFunction, __D::ErrorDeserializes using the given deserializer### impl PartialEq<CompiledFunction> for CompiledFunction #### fn eq(&self, other: &CompiledFunction) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for CompiledFunctionwhere FunctionBody: Serialize<__S>, Vec<Relocation>: Serialize<__S>, CompiledFunctionFrameInfo: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for CompiledFunction ### impl StructuralEq for CompiledFunction ### impl StructuralPartialEq for CompiledFunction Auto Trait Implementations --- ### impl RefUnwindSafe for CompiledFunction ### impl Send for CompiledFunction ### impl Sync for CompiledFunction ### impl Unpin for CompiledFunction ### impl UnwindSafe for CompiledFunction Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::function::CompiledFunctionFrameInfo === ``` pub struct CompiledFunctionFrameInfo { pub traps: Vec<TrapInformation>, pub address_map: FunctionAddressMap, } ``` The frame info for a Compiled function. This structure is only used for reconstructing the frame information after a `Trap`. Fields --- `traps: Vec<TrapInformation>`The traps (in the function body). Code offsets of the traps MUST be in ascending order. `address_map: FunctionAddressMap`The address map. Trait Implementations --- ### impl Archive for CompiledFunctionFrameInfowhere Vec<TrapInformation>: Archive, FunctionAddressMap: Archive, #### type Archived = ArchivedCompiledFunctionFrameInfo The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> CompiledFunctionFrameInfo Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> CompiledFunctionFrameInfo Returns the “default value” for a type. Vec<TrapInformation>: Archive, Archived<Vec<TrapInformation>>: Deserialize<Vec<TrapInformation>, __D>, FunctionAddressMap: Archive, Archived<FunctionAddressMap>: Deserialize<FunctionAddressMap, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<CompiledFunctionFrameInfo, __D::ErrorDeserializes using the given deserializer### impl PartialEq<CompiledFunctionFrameInfo> for CompiledFunctionFrameInfo #### fn eq(&self, other: &CompiledFunctionFrameInfo) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for CompiledFunctionFrameInfowhere Vec<TrapInformation>: Serialize<__S>, FunctionAddressMap: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for CompiledFunctionFrameInfo ### impl StructuralEq for CompiledFunctionFrameInfo ### impl StructuralPartialEq for CompiledFunctionFrameInfo Auto Trait Implementations --- ### impl RefUnwindSafe for CompiledFunctionFrameInfo ### impl Send for CompiledFunctionFrameInfo ### impl Sync for CompiledFunctionFrameInfo ### impl Unpin for CompiledFunctionFrameInfo ### impl UnwindSafe for CompiledFunctionFrameInfo Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Type Alias wasmer_types::compilation::function::CustomSections === ``` pub type CustomSections = PrimaryMap<SectionIndex, CustomSection>; ``` The custom sections for a Compilation. Aliased Type --- ``` struct CustomSections { /* private fields */ } ``` Implementations --- ### impl<K, V> PrimaryMap<K, V>where K: EntityRef, #### pub fn new() -> Self Create a new empty map. #### pub fn with_capacity(capacity: usize) -> Self Create a new empty map with the given capacity. #### pub fn is_valid(&self, k: K) -> bool Check if `k` is a valid key in the map. #### pub fn get(&self, k: K) -> Option<&VGet the element at `k` if it exists. #### pub fn get_mut(&mut self, k: K) -> Option<&mut VGet the element at `k` if it exists, mutable version. #### pub fn is_empty(&self) -> bool Is this map completely empty? #### pub fn len(&self) -> usize Get the total number of entity references created. #### pub fn keys(&self) -> Keys<KIterate over all the keys in this map. #### pub fn values(&self) -> Iter<'_, VIterate over all the values in this map. #### pub fn values_mut(&mut self) -> IterMut<'_, VIterate over all the values in this map, mutable edition. #### pub fn iter(&self) -> Iter<'_, K, VIterate over all the keys and values in this map. #### pub fn iter_mut(&mut self) -> IterMut<'_, K, VIterate over all the keys and values in this map, mutable edition. #### pub fn clear(&mut self) Remove all entries from this map. #### pub fn next_key(&self) -> K Get the key that will be assigned to the next pushed value. #### pub fn push(&mut self, v: V) -> K Append `v` to the mapping, assigning a new key which is returned. #### pub fn last(&self) -> Option<&VReturns the last element that was inserted in the map. #### pub fn reserve(&mut self, additional: usize) Reserves capacity for at least `additional` more elements to be inserted. #### pub fn reserve_exact(&mut self, additional: usize) Reserves the minimum capacity for exactly `additional` more elements to be inserted. #### pub fn shrink_to_fit(&mut self) Shrinks the capacity of the `PrimaryMap` as much as possible. #### pub fn into_boxed_slice(self) -> BoxedSlice<K, VConsumes this `PrimaryMap` and produces a `BoxedSlice`. Trait Implementations --- ### impl<K, V> Archive for PrimaryMap<K, V>where K: EntityRef, Vec<V>: Archive, PhantomData<K>: Archive, #### type Archived = ArchivedPrimaryMap<K, VThe archived representation of this type. &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. K: EntityRef + Clone, #### fn clone(&self) -> PrimaryMap<K, VReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. K: EntityRef + Debug, #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. K: EntityRef, #### fn default() -> Self Returns the “default value” for a type. K: EntityRef, Vec<V>: Archive, Archived<Vec<V>>: Deserialize<Vec<V>, __D>, PhantomData<K>: Archive, Archived<PhantomData<K>>: Deserialize<PhantomData<K>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<PrimaryMap<K, V>, __D::ErrorDeserializes using the given deserializer### impl<K, V> FromIterator<V> for PrimaryMap<K, V>where K: EntityRef, #### fn from_iter<T>(iter: T) -> Selfwhere T: IntoIterator<Item = V>, Creates a value from an iterator. K: EntityRef + Hash, #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. K: EntityRef, Immutable indexing into an `PrimaryMap`. The indexed value must be in the map. #### type Output = V The returned type after indexing.#### fn index(&self, k: K) -> &V Performs the indexing (`container[index]`) operation. K: EntityRef, Mutable indexing into an `PrimaryMap`. #### fn index_mut(&mut self, k: K) -> &mut V Performs the mutable indexing (`container[index]`) operation. K: EntityRef, #### type Item = (K, V) The type of the elements being iterated over.#### type IntoIter = IntoIter<K, VWhich kind of iterator are we turning this into?#### fn into_iter(self) -> Self::IntoIter Creates an iterator from a value. K: EntityRef + PartialEq, #### fn eq(&self, other: &PrimaryMap<K, V>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized, K, V> Serialize<__S> for PrimaryMap<K, V>where K: EntityRef, Vec<V>: Serialize<__S>, PhantomData<K>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl<K, V: Eq> Eq for PrimaryMap<K, V>where K: EntityRef + Eq, ### impl<K, V> StructuralEq for PrimaryMap<K, V>where K: EntityRef, ### impl<K, V> StructuralPartialEq for PrimaryMap<K, V>where K: EntityRef, {"Iter<'_, K, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.Iter.html\" title=\"struct wasmer_types::entity::Iter\">Iter</a>&lt;'a, K, V&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>, V&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.Iter.html\" title=\"struct wasmer_types::entity::Iter\">Iter</a>&lt;'a, K, V&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (K, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a V</a>);</span>","Iter<'_, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../lib/std/slice/struct.Iter.html\" title=\"struct wasmer_types::lib::std::slice::Iter\">Iter</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../lib/std/slice/struct.Iter.html\" title=\"struct wasmer_types::lib::std::slice::Iter\">Iter</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>;</span>","IterMut<'_, K, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.IterMut.html\" title=\"struct wasmer_types::entity::IterMut\">IterMut</a>&lt;'a, K, V&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>, V&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.IterMut.html\" title=\"struct wasmer_types::entity::IterMut\">IterMut</a>&lt;'a, K, V&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (K, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a mut V</a>);</span>","IterMut<'_, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../lib/std/slice/struct.IterMut.html\" title=\"struct wasmer_types::lib::std::slice::IterMut\">IterMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../lib/std/slice/struct.IterMut.html\" title=\"struct wasmer_types::lib::std::slice::IterMut\">IterMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a mut T</a>;</span>","Keys<K>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.Keys.html\" title=\"struct wasmer_types::entity::Keys\">Keys</a>&lt;K&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.Keys.html\" title=\"struct wasmer_types::entity::Keys\">Keys</a>&lt;K&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = K;</span>"} Struct wasmer_types::compilation::function::Dwarf === ``` pub struct Dwarf { pub eh_frame: SectionIndex, } ``` The DWARF information for this Compilation. It is used for retrieving the unwind information once an exception happens. In the future this structure may also hold other information useful for debugging. Fields --- `eh_frame: SectionIndex`The section index in the `Compilation` that corresponds to the exception frames. Learn more. Implementations --- ### impl Dwarf #### pub fn new(eh_frame: SectionIndex) -> Self Creates a `Dwarf` struct with the corresponding indices for its sections Trait Implementations --- ### impl Archive for Dwarfwhere SectionIndex: Archive, #### type Archived = Dwarf The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. SectionIndex: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> Dwarf Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. SectionIndex: Archive, Archived<SectionIndex>: Deserialize<SectionIndex, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<Dwarf, __D::ErrorDeserializes using the given deserializer### impl PartialEq<Dwarf> for Dwarf #### fn eq(&self, other: &Dwarf) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for Dwarfwhere SectionIndex: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for Dwarf ### impl StructuralEq for Dwarf ### impl StructuralPartialEq for Dwarf Auto Trait Implementations --- ### impl RefUnwindSafe for Dwarf ### impl Send for Dwarf ### impl Sync for Dwarf ### impl Unpin for Dwarf ### impl UnwindSafe for Dwarf Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::compilation::function::FunctionBody === ``` pub struct FunctionBody { pub body: Vec<u8>, pub unwind_info: Option<CompiledFunctionUnwindInfo>, } ``` The function body. Fields --- `body: Vec<u8>`The function body bytes. `unwind_info: Option<CompiledFunctionUnwindInfo>`The function unwind info Trait Implementations --- ### impl Archive for FunctionBodywhere Vec<u8>: Archive, Option<CompiledFunctionUnwindInfo>: Archive, #### type Archived = ArchivedFunctionBody The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> FunctionBody Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Vec<u8>: Archive, Archived<Vec<u8>>: Deserialize<Vec<u8>, __D>, Option<CompiledFunctionUnwindInfo>: Archive, Archived<Option<CompiledFunctionUnwindInfo>>: Deserialize<Option<CompiledFunctionUnwindInfo>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<FunctionBody, __D::ErrorDeserializes using the given deserializer### impl<'a> FunctionBodyLike<'a> for FunctionBody #### type UnwindInfo = CompiledFunctionUnwindInfo #### fn body(&'a self) -> &'a [u8] #### fn unwind_info(&'a self) -> Option<&Self::UnwindInfo### impl PartialEq<FunctionBody> for FunctionBody #### fn eq(&self, other: &FunctionBody) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for FunctionBodywhere Vec<u8>: Serialize<__S>, Option<CompiledFunctionUnwindInfo>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for FunctionBody ### impl StructuralEq for FunctionBody ### impl StructuralPartialEq for FunctionBody Auto Trait Implementations --- ### impl RefUnwindSafe for FunctionBody ### impl Send for FunctionBody ### impl Sync for FunctionBody ### impl Unpin for FunctionBody ### impl UnwindSafe for FunctionBody Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&'a [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Trait wasmer_types::compilation::function::FunctionBodyLike === ``` pub trait FunctionBodyLike<'a> { type UnwindInfo: CompiledFunctionUnwindInfoLike<'a>; // Required methods fn body(&'a self) -> &'a [u8] ; fn unwind_info(&'a self) -> Option<&Self::UnwindInfo>; } ``` Any struct that acts like a `FunctionBody`. Required Associated Types --- #### type UnwindInfo: CompiledFunctionUnwindInfoLike<'aRequired Methods --- #### fn body(&'a self) -> &'a [u8] #### fn unwind_info(&'a self) -> Option<&Self::UnwindInfoImplementors --- ### impl<'a> FunctionBodyLike<'a> for ArchivedFunctionBody #### type UnwindInfo = ArchivedCompiledFunctionUnwindInfo ### impl<'a> FunctionBodyLike<'a> for FunctionBody #### type UnwindInfo = CompiledFunctionUnwindInfo {"&'a [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Type Alias wasmer_types::compilation::function::Functions === ``` pub type Functions = PrimaryMap<LocalFunctionIndex, CompiledFunction>; ``` The compiled functions map (index in the Wasm -> function) Aliased Type --- ``` struct Functions { /* private fields */ } ``` Implementations --- ### impl<K, V> PrimaryMap<K, V>where K: EntityRef, #### pub fn new() -> Self Create a new empty map. #### pub fn with_capacity(capacity: usize) -> Self Create a new empty map with the given capacity. #### pub fn is_valid(&self, k: K) -> bool Check if `k` is a valid key in the map. #### pub fn get(&self, k: K) -> Option<&VGet the element at `k` if it exists. #### pub fn get_mut(&mut self, k: K) -> Option<&mut VGet the element at `k` if it exists, mutable version. #### pub fn is_empty(&self) -> bool Is this map completely empty? #### pub fn len(&self) -> usize Get the total number of entity references created. #### pub fn keys(&self) -> Keys<KIterate over all the keys in this map. #### pub fn values(&self) -> Iter<'_, VIterate over all the values in this map. #### pub fn values_mut(&mut self) -> IterMut<'_, VIterate over all the values in this map, mutable edition. #### pub fn iter(&self) -> Iter<'_, K, VIterate over all the keys and values in this map. #### pub fn iter_mut(&mut self) -> IterMut<'_, K, VIterate over all the keys and values in this map, mutable edition. #### pub fn clear(&mut self) Remove all entries from this map. #### pub fn next_key(&self) -> K Get the key that will be assigned to the next pushed value. #### pub fn push(&mut self, v: V) -> K Append `v` to the mapping, assigning a new key which is returned. #### pub fn last(&self) -> Option<&VReturns the last element that was inserted in the map. #### pub fn reserve(&mut self, additional: usize) Reserves capacity for at least `additional` more elements to be inserted. #### pub fn reserve_exact(&mut self, additional: usize) Reserves the minimum capacity for exactly `additional` more elements to be inserted. #### pub fn shrink_to_fit(&mut self) Shrinks the capacity of the `PrimaryMap` as much as possible. #### pub fn into_boxed_slice(self) -> BoxedSlice<K, VConsumes this `PrimaryMap` and produces a `BoxedSlice`. Trait Implementations --- ### impl<K, V> Archive for PrimaryMap<K, V>where K: EntityRef, Vec<V>: Archive, PhantomData<K>: Archive, #### type Archived = ArchivedPrimaryMap<K, VThe archived representation of this type. &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. K: EntityRef + Clone, #### fn clone(&self) -> PrimaryMap<K, VReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. K: EntityRef + Debug, #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. K: EntityRef, #### fn default() -> Self Returns the “default value” for a type. K: EntityRef, Vec<V>: Archive, Archived<Vec<V>>: Deserialize<Vec<V>, __D>, PhantomData<K>: Archive, Archived<PhantomData<K>>: Deserialize<PhantomData<K>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<PrimaryMap<K, V>, __D::ErrorDeserializes using the given deserializer### impl<K, V> FromIterator<V> for PrimaryMap<K, V>where K: EntityRef, #### fn from_iter<T>(iter: T) -> Selfwhere T: IntoIterator<Item = V>, Creates a value from an iterator. K: EntityRef + Hash, #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. K: EntityRef, Immutable indexing into an `PrimaryMap`. The indexed value must be in the map. #### type Output = V The returned type after indexing.#### fn index(&self, k: K) -> &V Performs the indexing (`container[index]`) operation. K: EntityRef, Mutable indexing into an `PrimaryMap`. #### fn index_mut(&mut self, k: K) -> &mut V Performs the mutable indexing (`container[index]`) operation. K: EntityRef, #### type Item = (K, V) The type of the elements being iterated over.#### type IntoIter = IntoIter<K, VWhich kind of iterator are we turning this into?#### fn into_iter(self) -> Self::IntoIter Creates an iterator from a value. K: EntityRef + PartialEq, #### fn eq(&self, other: &PrimaryMap<K, V>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized, K, V> Serialize<__S> for PrimaryMap<K, V>where K: EntityRef, Vec<V>: Serialize<__S>, PhantomData<K>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl<K, V: Eq> Eq for PrimaryMap<K, V>where K: EntityRef + Eq, ### impl<K, V> StructuralEq for PrimaryMap<K, V>where K: EntityRef, ### impl<K, V> StructuralPartialEq for PrimaryMap<K, V>where K: EntityRef, {"Iter<'_, K, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.Iter.html\" title=\"struct wasmer_types::entity::Iter\">Iter</a>&lt;'a, K, V&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>, V&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.Iter.html\" title=\"struct wasmer_types::entity::Iter\">Iter</a>&lt;'a, K, V&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (K, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a V</a>);</span>","Iter<'_, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../lib/std/slice/struct.Iter.html\" title=\"struct wasmer_types::lib::std::slice::Iter\">Iter</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../lib/std/slice/struct.Iter.html\" title=\"struct wasmer_types::lib::std::slice::Iter\">Iter</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>;</span>","IterMut<'_, K, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.IterMut.html\" title=\"struct wasmer_types::entity::IterMut\">IterMut</a>&lt;'a, K, V&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>, V&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.IterMut.html\" title=\"struct wasmer_types::entity::IterMut\">IterMut</a>&lt;'a, K, V&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (K, <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a mut V</a>);</span>","IterMut<'_, V>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../lib/std/slice/struct.IterMut.html\" title=\"struct wasmer_types::lib::std::slice::IterMut\">IterMut</a>&lt;'a, T&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, T&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../lib/std/slice/struct.IterMut.html\" title=\"struct wasmer_types::lib::std::slice::IterMut\">IterMut</a>&lt;'a, T&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a mut T</a>;</span>","Keys<K>":"<h3>Notable traits for <code><a class=\"struct\" href=\"../../entity/struct.Keys.html\" title=\"struct wasmer_types::entity::Keys\">Keys</a>&lt;K&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;K: <a class=\"trait\" href=\"../../entity/trait.EntityRef.html\" title=\"trait wasmer_types::entity::EntityRef\">EntityRef</a>&gt; <a class=\"trait\" href=\"../../lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"../../entity/struct.Keys.html\" title=\"struct wasmer_types::entity::Keys\">Keys</a>&lt;K&gt;</span><span class=\"where fmt-newline\"> type <a href=\"../../lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = K;</span>"} Struct wasmer_types::compilation::module::CompileModuleInfo === ``` pub struct CompileModuleInfo { pub features: Features, pub module: Arc<ModuleInfo>, pub memory_styles: PrimaryMap<MemoryIndex, MemoryStyle>, pub table_styles: PrimaryMap<TableIndex, TableStyle>, } ``` The required info for compiling a module. This differs from `ModuleInfo` because it have extra info only possible after translation (such as the features used for compiling, or the `MemoryStyle` and `TableStyle`). Fields --- `features: Features`The features used for compiling the module `module: Arc<ModuleInfo>`The module information `memory_styles: PrimaryMap<MemoryIndex, MemoryStyle>`The memory styles used for compiling. The compiler will emit the most optimal code based on the memory style (static or dynamic) chosen. `table_styles: PrimaryMap<TableIndex, TableStyle>`The table plans used for compiling. Trait Implementations --- ### impl Archive for CompileModuleInfowhere Features: Archive, Arc<ModuleInfo>: Archive, PrimaryMap<MemoryIndex, MemoryStyle>: Archive, PrimaryMap<TableIndex, TableStyle>: Archive, #### type Archived = ArchivedCompileModuleInfo The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> CompileModuleInfo Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Features: Archive, Archived<Features>: Deserialize<Features, __D>, Arc<ModuleInfo>: Archive, Archived<Arc<ModuleInfo>>: Deserialize<Arc<ModuleInfo>, __D>, PrimaryMap<MemoryIndex, MemoryStyle>: Archive, Archived<PrimaryMap<MemoryIndex, MemoryStyle>>: Deserialize<PrimaryMap<MemoryIndex, MemoryStyle>, __D>, PrimaryMap<TableIndex, TableStyle>: Archive, Archived<PrimaryMap<TableIndex, TableStyle>>: Deserialize<PrimaryMap<TableIndex, TableStyle>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<CompileModuleInfo, __D::ErrorDeserializes using the given deserializer### impl PartialEq<CompileModuleInfo> for CompileModuleInfo #### fn eq(&self, other: &CompileModuleInfo) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for CompileModuleInfowhere Features: Serialize<__S>, Arc<ModuleInfo>: Serialize<__S>, PrimaryMap<MemoryIndex, MemoryStyle>: Serialize<__S>, PrimaryMap<TableIndex, TableStyle>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for CompileModuleInfo ### impl StructuralEq for CompileModuleInfo ### impl StructuralPartialEq for CompileModuleInfo Auto Trait Implementations --- ### impl RefUnwindSafe for CompileModuleInfo ### impl Send for CompileModuleInfo ### impl Sync for CompileModuleInfo ### impl Unpin for CompileModuleInfo ### impl UnwindSafe for CompileModuleInfo Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::compilation::symbols::Symbol === ``` pub enum Symbol { Metadata, LocalFunction(LocalFunctionIndex), Section(SectionIndex), FunctionCallTrampoline(SignatureIndex), DynamicFunctionTrampoline(FunctionIndex), } ``` The kinds of wasmer_types objects that might be found in a native object file. Variants --- ### Metadata A metadata section, indexed by a unique prefix (usually the wasm file SHA256 hash) ### LocalFunction(LocalFunctionIndex) A function defined in the wasm. ### Section(SectionIndex) A wasm section. ### FunctionCallTrampoline(SignatureIndex) The function call trampoline for a given signature. ### DynamicFunctionTrampoline(FunctionIndex) The dynamic function trampoline for a given function. Trait Implementations --- ### impl Archive for Symbolwhere LocalFunctionIndex: Archive, SectionIndex: Archive, SignatureIndex: Archive, FunctionIndex: Archive, #### type Archived = Symbol The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> Symbol Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. LocalFunctionIndex: Archive, Archived<LocalFunctionIndex>: Deserialize<LocalFunctionIndex, __D>, SectionIndex: Archive, Archived<SectionIndex>: Deserialize<SectionIndex, __D>, SignatureIndex: Archive, Archived<SignatureIndex>: Deserialize<SignatureIndex, __D>, FunctionIndex: Archive, Archived<FunctionIndex>: Deserialize<FunctionIndex, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<Symbol, __D::ErrorDeserializes using the given deserializer### impl Hash for Symbol #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Symbol) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Symbol) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Symbol> for Symbol #### fn partial_cmp(&self, other: &Symbol) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. LocalFunctionIndex: Serialize<__S>, SectionIndex: Serialize<__S>, SignatureIndex: Serialize<__S>, FunctionIndex: Serialize<__S>, #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for Symbol ### impl StructuralEq for Symbol ### impl StructuralPartialEq for Symbol Auto Trait Implementations --- ### impl RefUnwindSafe for Symbol ### impl Send for Symbol ### impl Sync for Symbol ### impl Unpin for Symbol ### impl UnwindSafe for Symbol Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Trait wasmer_types::compilation::symbols::SymbolRegistry === ``` pub trait SymbolRegistry: Send + Sync { // Required methods fn symbol_to_name(&self, symbol: Symbol) -> String; fn name_to_symbol(&self, name: &str) -> Option<Symbol>; } ``` This trait facilitates symbol name lookups in a native object file. Required Methods --- #### fn symbol_to_name(&self, symbol: Symbol) -> String Given a `Symbol` it returns the name for that symbol in the object file #### fn name_to_symbol(&self, name: &str) -> Option<SymbolGiven a name it returns the `Symbol` for that name in the object file This function is the inverse of `SymbolRegistry::symbol_to_name` Implementors --- ### impl SymbolRegistry for ModuleMetadataSymbolRegistry Enum wasmer_types::compilation::unwind::ArchivedCompiledFunctionUnwindInfo === ``` #[repr(u8,)]pub enum ArchivedCompiledFunctionUnwindInfowhere Vec<u8>: Archive,{ WindowsX64(Archived<Vec<u8>>), Dwarf, } ``` An archived `CompiledFunctionUnwindInfo` Variants --- ### WindowsX64(Archived<Vec<u8>>) #### Tuple Fields `0: Archived<Vec<u8>>`The archived counterpart of `CompiledFunctionUnwindInfo::WindowsX64::0` The archived counterpart of `CompiledFunctionUnwindInfo::WindowsX64` ### Dwarf The archived counterpart of `CompiledFunctionUnwindInfo::Dwarf` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedCompiledFunctionUnwindInfowhere Vec<u8>: Archive, Archived<Vec<u8>>: CheckBytes<__C>, #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn get(&'a self) -> CompiledFunctionUnwindInfoReference<'aAuto Trait Implementations --- ### impl RefUnwindSafe for ArchivedCompiledFunctionUnwindInfo ### impl Send for ArchivedCompiledFunctionUnwindInfo ### impl Sync for ArchivedCompiledFunctionUnwindInfo ### impl !Unpin for ArchivedCompiledFunctionUnwindInfo ### impl UnwindSafe for ArchivedCompiledFunctionUnwindInfo Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::compilation::unwind::CompiledFunctionUnwindInfo === ``` pub enum CompiledFunctionUnwindInfo { WindowsX64(Vec<u8>), Dwarf, } ``` Compiled function unwind information. > Note: Windows OS have a different way of representing the unwind info, > That’s why we keep the Windows data and the Unix frame layout in different > fields. Variants --- ### WindowsX64(Vec<u8>) Windows UNWIND_INFO. ### Dwarf The unwind info is added to the Dwarf section in `Compilation`. Trait Implementations --- ### impl Archive for CompiledFunctionUnwindInfowhere Vec<u8>: Archive, #### type Archived = ArchivedCompiledFunctionUnwindInfo The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> CompiledFunctionUnwindInfo Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn get(&'a self) -> CompiledFunctionUnwindInfoReference<'a### impl Debug for CompiledFunctionUnwindInfo #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Vec<u8>: Archive, Archived<Vec<u8>>: Deserialize<Vec<u8>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<CompiledFunctionUnwindInfo, __D::ErrorDeserializes using the given deserializer### impl PartialEq<CompiledFunctionUnwindInfo> for CompiledFunctionUnwindInfo #### fn eq(&self, other: &CompiledFunctionUnwindInfo) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for CompiledFunctionUnwindInfowhere Vec<u8>: Serialize<__S>, #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for CompiledFunctionUnwindInfo ### impl StructuralEq for CompiledFunctionUnwindInfo ### impl StructuralPartialEq for CompiledFunctionUnwindInfo Auto Trait Implementations --- ### impl RefUnwindSafe for CompiledFunctionUnwindInfo ### impl Send for CompiledFunctionUnwindInfo ### impl Sync for CompiledFunctionUnwindInfo ### impl Unpin for CompiledFunctionUnwindInfo ### impl UnwindSafe for CompiledFunctionUnwindInfo Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Trait wasmer_types::compilation::unwind::CompiledFunctionUnwindInfoLike === ``` pub trait CompiledFunctionUnwindInfoLike<'a> { // Required method fn get(&'a self) -> CompiledFunctionUnwindInfoReference<'a>; } ``` Any struct that acts like a `CompiledFunctionUnwindInfo`. Required Methods --- #### fn get(&'a self) -> CompiledFunctionUnwindInfoReference<'aImplementors --- ### impl<'a> CompiledFunctionUnwindInfoLike<'a> for ArchivedCompiledFunctionUnwindInfo ### impl<'a> CompiledFunctionUnwindInfoLike<'a> for CompiledFunctionUnwindInfo Enum wasmer_types::compilation::unwind::CompiledFunctionUnwindInfoReference === ``` pub enum CompiledFunctionUnwindInfoReference<'a> { WindowsX64(&'a [u8]), Dwarf, } ``` Generic reference to data in a `CompiledFunctionUnwindInfo` Variants --- ### WindowsX64(&'a [u8]) ### Dwarf Trait Implementations --- ### impl<'a> Clone for CompiledFunctionUnwindInfoReference<'a#### fn clone(&self) -> CompiledFunctionUnwindInfoReference<'aReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<'a> Eq for CompiledFunctionUnwindInfoReference<'a### impl<'a> StructuralEq for CompiledFunctionUnwindInfoReference<'a### impl<'a> StructuralPartialEq for CompiledFunctionUnwindInfoReference<'aAuto Trait Implementations --- ### impl<'a> RefUnwindSafe for CompiledFunctionUnwindInfoReference<'a### impl<'a> Send for CompiledFunctionUnwindInfoReference<'a### impl<'a> Sync for CompiledFunctionUnwindInfoReference<'a### impl<'a> Unpin for CompiledFunctionUnwindInfoReference<'a### impl<'a> UnwindSafe for CompiledFunctionUnwindInfoReference<'aBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Module wasmer_types::compilation === Types for compilation. Modules --- * address_mapData structures to provide transformation of the source * functionA `Compilation` contains the compiled function bodies for a WebAssembly module (`CompiledFunction`). * moduleTypes for modules. * relocationRelocation is the process of assigning load addresses for position-dependent code and data of a program and adjusting the code and data to reflect the assigned addresses. * sectionThis module define the required structures to emit custom Sections in a `Compilation`. * symbolsThis module define the required structures for compilation symbols. * targetTarget configuration * unwindA `CompiledFunctionUnwindInfo` contains the function unwind information. Module wasmer_types::entity === The entity module, with common helpers for Rust structures Modules --- * packed_optionCompact representation of `Option<T>` for types with a reserved value. Macros --- * entity_implMacro which provides the common implementation of a 32-bit entity reference. Structs --- * ArchivedPrimaryMapAn archived `PrimaryMap` * BoxedSliceA slice mapping `K -> V` allocating dense entity references. * IterIterate over all keys in order. * IterMutIterate over all keys in order. * KeysIterate over all keys in order. * PrimaryMapA primary mapping `K -> V` allocating dense entity references. * SecondaryMapA mapping `K -> V` for densely indexed entity references. Traits --- * EntityRefA type wrapping a small integer index should implement `EntityRef` so it can be used as the key of an `SecondaryMap` or `SparseMap`. Module wasmer_types::error === The WebAssembly possible errors Structs --- * MiddlewareErrorA error in the middleware. Enums --- * CompileErrorThe WebAssembly.CompileError object indicates an error during WebAssembly decoding or validation. * DeserializeErrorThe Deserialize error can occur when loading a compiled Module from a binary. * ImportErrorAn ImportError. * MemoryErrorError type describing things that can go wrong when operating on Wasm Memories. * ParseCpuFeatureErrorThe error that can happen while parsing a `str` to retrieve a `CpuFeature`. * PreInstantiationErrorAn error while preinstantiating a module. * SerializeErrorThe Serialize error can occur when serializing a compiled Module into a binary. * WasmErrorA WebAssembly translation error. Type Aliases --- * WasmResultA convenient alias for a `Result` that uses `WasmError` as the error type. Module wasmer_types::lib === The `lib` module defines a `std` module that is identical whether the `core` or the `std` feature is enabled. Modules --- * stdCustom `std` module. Macro wasmer_types::entity_impl === ``` macro_rules! entity_impl { ($entity:ident) => { ... }; ($entity:ident, $display_prefix:expr) => { ... }; } ``` Macro which provides the common implementation of a 32-bit entity reference. Struct wasmer_types::ArchivedDataInitializerLocation === ``` #[repr(C,)]pub struct ArchivedDataInitializerLocationwhere MemoryIndex: Archive, Option<GlobalIndex>: Archive, usize: Archive,{ pub memory_index: Archived<MemoryIndex>, pub base: Archived<Option<GlobalIndex>>, pub offset: Archived<usize>, } ``` An archived `DataInitializerLocation` Fields --- `memory_index: Archived<MemoryIndex>`The archived counterpart of `DataInitializerLocation::memory_index` `base: Archived<Option<GlobalIndex>>`The archived counterpart of `DataInitializerLocation::base` `offset: Archived<usize>`The archived counterpart of `DataInitializerLocation::offset` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedDataInitializerLocationwhere MemoryIndex: Archive, Option<GlobalIndex>: Archive, usize: Archive, Archived<MemoryIndex>: CheckBytes<__C>, Archived<Option<GlobalIndex>>: CheckBytes<__C>, Archived<usize>: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn memory_index(&self) -> MemoryIndex #### fn base(&self) -> Option<GlobalIndex#### fn offset(&self) -> usize Auto Trait Implementations --- ### impl RefUnwindSafe for ArchivedDataInitializerLocation ### impl Send for ArchivedDataInitializerLocation ### impl Sync for ArchivedDataInitializerLocation ### impl Unpin for ArchivedDataInitializerLocation ### impl UnwindSafe for ArchivedDataInitializerLocation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::DataInitializerLocation === ``` pub struct DataInitializerLocation { pub memory_index: MemoryIndex, pub base: Option<GlobalIndex>, pub offset: usize, } ``` A memory index and offset within that memory where a data initialization should be performed. Fields --- `memory_index: MemoryIndex`The index of the memory to initialize. `base: Option<GlobalIndex>`Optionally a Global variable base to initialize at. `offset: usize`A constant offset to initialize at. Trait Implementations --- ### impl Archive for DataInitializerLocationwhere MemoryIndex: Archive, Option<GlobalIndex>: Archive, usize: Archive, #### type Archived = ArchivedDataInitializerLocation The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> DataInitializerLocation Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn memory_index(&self) -> MemoryIndex #### fn base(&self) -> Option<GlobalIndex#### fn offset(&self) -> usize ### impl Debug for DataInitializerLocation #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. MemoryIndex: Archive, Archived<MemoryIndex>: Deserialize<MemoryIndex, __D>, Option<GlobalIndex>: Archive, Archived<Option<GlobalIndex>>: Deserialize<Option<GlobalIndex>, __D>, usize: Archive, Archived<usize>: Deserialize<usize, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<DataInitializerLocation, __D::ErrorDeserializes using the given deserializer### impl PartialEq<DataInitializerLocation> for DataInitializerLocation #### fn eq(&self, other: &DataInitializerLocation) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for DataInitializerLocationwhere MemoryIndex: Serialize<__S>, Option<GlobalIndex>: Serialize<__S>, usize: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for DataInitializerLocation ### impl StructuralEq for DataInitializerLocation ### impl StructuralPartialEq for DataInitializerLocation Auto Trait Implementations --- ### impl RefUnwindSafe for DataInitializerLocation ### impl Send for DataInitializerLocation ### impl Sync for DataInitializerLocation ### impl Unpin for DataInitializerLocation ### impl UnwindSafe for DataInitializerLocation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ArchivedOwnedDataInitializer === ``` #[repr(C,)]pub struct ArchivedOwnedDataInitializerwhere DataInitializerLocation: Archive, Box<[u8]>: Archive,{ pub location: Archived<DataInitializerLocation>, pub data: Archived<Box<[u8]>>, } ``` An archived `OwnedDataInitializer` Fields --- `location: Archived<DataInitializerLocation>`The archived counterpart of `OwnedDataInitializer::location` `data: Archived<Box<[u8]>>`The archived counterpart of `OwnedDataInitializer::data` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedOwnedDataInitializerwhere DataInitializerLocation: Archive, Box<[u8]>: Archive, Archived<DataInitializerLocation>: CheckBytes<__C>, Archived<Box<[u8]>>: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### type Location = &'a ArchivedDataInitializerLocation #### fn location(&self) -> Self::Location #### fn data(&self) -> &'a [u8] Auto Trait Implementations --- ### impl RefUnwindSafe for ArchivedOwnedDataInitializer ### impl Send for ArchivedOwnedDataInitializer ### impl Sync for ArchivedOwnedDataInitializer ### impl !Unpin for ArchivedOwnedDataInitializer ### impl UnwindSafe for ArchivedOwnedDataInitializer Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&'a [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct wasmer_types::OwnedDataInitializer === ``` pub struct OwnedDataInitializer { pub location: DataInitializerLocation, pub data: Box<[u8]>, } ``` As `DataInitializer` but owning the data rather than holding a reference to it Fields --- `location: DataInitializerLocation`The location where the initialization is to be performed. `data: Box<[u8]>`The initialization owned data. Implementations --- ### impl OwnedDataInitializer #### pub fn new(borrowed: &DataInitializer<'_>) -> Self Creates a new `OwnedDataInitializer` from a `DataInitializer`. Trait Implementations --- ### impl Archive for OwnedDataInitializerwhere DataInitializerLocation: Archive, Box<[u8]>: Archive, #### type Archived = ArchivedOwnedDataInitializer The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> OwnedDataInitializer Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### type Location = &'a DataInitializerLocation #### fn location(&self) -> Self::Location #### fn data(&self) -> &'a [u8] ### impl Debug for OwnedDataInitializer #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. DataInitializerLocation: Archive, Archived<DataInitializerLocation>: Deserialize<DataInitializerLocation, __D>, Box<[u8]>: Archive, Archived<Box<[u8]>>: Deserialize<Box<[u8]>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<OwnedDataInitializer, __D::ErrorDeserializes using the given deserializer### impl PartialEq<OwnedDataInitializer> for OwnedDataInitializer #### fn eq(&self, other: &OwnedDataInitializer) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for OwnedDataInitializerwhere DataInitializerLocation: Serialize<__S>, Box<[u8]>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for OwnedDataInitializer ### impl StructuralEq for OwnedDataInitializer ### impl StructuralPartialEq for OwnedDataInitializer Auto Trait Implementations --- ### impl RefUnwindSafe for OwnedDataInitializer ### impl Send for OwnedDataInitializer ### impl Sync for OwnedDataInitializer ### impl Unpin for OwnedDataInitializer ### impl UnwindSafe for OwnedDataInitializer Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&'a [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Struct wasmer_types::ArchivedSerializableCompilation === ``` #[repr(C,)]pub struct ArchivedSerializableCompilationwhere PrimaryMap<LocalFunctionIndex, FunctionBody>: Archive, PrimaryMap<LocalFunctionIndex, Vec<Relocation>>: Archive, PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>: Archive, PrimaryMap<SignatureIndex, FunctionBody>: Archive, PrimaryMap<FunctionIndex, FunctionBody>: Archive, PrimaryMap<SectionIndex, CustomSection>: Archive, PrimaryMap<SectionIndex, Vec<Relocation>>: Archive, Option<Dwarf>: Archive, SectionIndex: Archive, u32: Archive,{ pub function_bodies: Archived<PrimaryMap<LocalFunctionIndex, FunctionBody>>, pub function_relocations: Archived<PrimaryMap<LocalFunctionIndex, Vec<Relocation>>>, pub function_frame_info: Archived<PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>>, pub function_call_trampolines: Archived<PrimaryMap<SignatureIndex, FunctionBody>>, pub dynamic_function_trampolines: Archived<PrimaryMap<FunctionIndex, FunctionBody>>, pub custom_sections: Archived<PrimaryMap<SectionIndex, CustomSection>>, pub custom_section_relocations: Archived<PrimaryMap<SectionIndex, Vec<Relocation>>>, pub debug: Archived<Option<Dwarf>>, pub libcall_trampolines: Archived<SectionIndex>, pub libcall_trampoline_len: Archived<u32>, } ``` An archived `SerializableCompilation` Fields --- `function_bodies: Archived<PrimaryMap<LocalFunctionIndex, FunctionBody>>`The archived counterpart of `SerializableCompilation::function_bodies` `function_relocations: Archived<PrimaryMap<LocalFunctionIndex, Vec<Relocation>>>`The archived counterpart of `SerializableCompilation::function_relocations` `function_frame_info: Archived<PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>>`The archived counterpart of `SerializableCompilation::function_frame_info` `function_call_trampolines: Archived<PrimaryMap<SignatureIndex, FunctionBody>>`The archived counterpart of `SerializableCompilation::function_call_trampolines` `dynamic_function_trampolines: Archived<PrimaryMap<FunctionIndex, FunctionBody>>`The archived counterpart of `SerializableCompilation::dynamic_function_trampolines` `custom_sections: Archived<PrimaryMap<SectionIndex, CustomSection>>`The archived counterpart of `SerializableCompilation::custom_sections` `custom_section_relocations: Archived<PrimaryMap<SectionIndex, Vec<Relocation>>>`The archived counterpart of `SerializableCompilation::custom_section_relocations` `debug: Archived<Option<Dwarf>>`The archived counterpart of `SerializableCompilation::debug` `libcall_trampolines: Archived<SectionIndex>`The archived counterpart of `SerializableCompilation::libcall_trampolines` `libcall_trampoline_len: Archived<u32>`The archived counterpart of `SerializableCompilation::libcall_trampoline_len` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedSerializableCompilationwhere PrimaryMap<LocalFunctionIndex, FunctionBody>: Archive, PrimaryMap<LocalFunctionIndex, Vec<Relocation>>: Archive, PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>: Archive, PrimaryMap<SignatureIndex, FunctionBody>: Archive, PrimaryMap<FunctionIndex, FunctionBody>: Archive, PrimaryMap<SectionIndex, CustomSection>: Archive, PrimaryMap<SectionIndex, Vec<Relocation>>: Archive, Option<Dwarf>: Archive, SectionIndex: Archive, u32: Archive, Archived<PrimaryMap<LocalFunctionIndex, FunctionBody>>: CheckBytes<__C>, Archived<PrimaryMap<LocalFunctionIndex, Vec<Relocation>>>: CheckBytes<__C>, Archived<PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>>: CheckBytes<__C>, Archived<PrimaryMap<SignatureIndex, FunctionBody>>: CheckBytes<__C>, Archived<PrimaryMap<FunctionIndex, FunctionBody>>: CheckBytes<__C>, Archived<PrimaryMap<SectionIndex, CustomSection>>: CheckBytes<__C>, Archived<PrimaryMap<SectionIndex, Vec<Relocation>>>: CheckBytes<__C>, Archived<Option<Dwarf>>: CheckBytes<__C>, Archived<SectionIndex>: CheckBytes<__C>, Archived<u32>: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for ArchivedSerializableCompilation ### impl Send for ArchivedSerializableCompilation ### impl Sync for ArchivedSerializableCompilation ### impl !Unpin for ArchivedSerializableCompilation ### impl UnwindSafe for ArchivedSerializableCompilation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::SerializableCompilation === ``` pub struct SerializableCompilation { pub function_bodies: PrimaryMap<LocalFunctionIndex, FunctionBody>, pub function_relocations: PrimaryMap<LocalFunctionIndex, Vec<Relocation>>, pub function_frame_info: PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>, pub function_call_trampolines: PrimaryMap<SignatureIndex, FunctionBody>, pub dynamic_function_trampolines: PrimaryMap<FunctionIndex, FunctionBody>, pub custom_sections: PrimaryMap<SectionIndex, CustomSection>, pub custom_section_relocations: PrimaryMap<SectionIndex, Vec<Relocation>>, pub debug: Option<Dwarf>, pub libcall_trampolines: SectionIndex, pub libcall_trampoline_len: u32, } ``` The compilation related data for a serialized modules Fields --- `function_bodies: PrimaryMap<LocalFunctionIndex, FunctionBody>``function_relocations: PrimaryMap<LocalFunctionIndex, Vec<Relocation>>``function_frame_info: PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>``function_call_trampolines: PrimaryMap<SignatureIndex, FunctionBody>``dynamic_function_trampolines: PrimaryMap<FunctionIndex, FunctionBody>``custom_sections: PrimaryMap<SectionIndex, CustomSection>``custom_section_relocations: PrimaryMap<SectionIndex, Vec<Relocation>>``debug: Option<Dwarf>``libcall_trampolines: SectionIndex``libcall_trampoline_len: u32`Implementations --- ### impl SerializableCompilation #### pub fn serialize(&self) -> Result<Vec<u8>, SerializeErrorSerialize a Compilation into bytes The bytes will have the following format: RKYV serialization (any length) + POS (8 bytes) Trait Implementations --- ### impl Archive for SerializableCompilationwhere PrimaryMap<LocalFunctionIndex, FunctionBody>: Archive, PrimaryMap<LocalFunctionIndex, Vec<Relocation>>: Archive, PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>: Archive, PrimaryMap<SignatureIndex, FunctionBody>: Archive, PrimaryMap<FunctionIndex, FunctionBody>: Archive, PrimaryMap<SectionIndex, CustomSection>: Archive, PrimaryMap<SectionIndex, Vec<Relocation>>: Archive, Option<Dwarf>: Archive, SectionIndex: Archive, u32: Archive, #### type Archived = ArchivedSerializableCompilation The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn default() -> SerializableCompilation Returns the “default value” for a type. PrimaryMap<LocalFunctionIndex, FunctionBody>: Archive, Archived<PrimaryMap<LocalFunctionIndex, FunctionBody>>: Deserialize<PrimaryMap<LocalFunctionIndex, FunctionBody>, __D>, PrimaryMap<LocalFunctionIndex, Vec<Relocation>>: Archive, Archived<PrimaryMap<LocalFunctionIndex, Vec<Relocation>>>: Deserialize<PrimaryMap<LocalFunctionIndex, Vec<Relocation>>, __D>, PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>: Archive, Archived<PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>>: Deserialize<PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>, __D>, PrimaryMap<SignatureIndex, FunctionBody>: Archive, Archived<PrimaryMap<SignatureIndex, FunctionBody>>: Deserialize<PrimaryMap<SignatureIndex, FunctionBody>, __D>, PrimaryMap<FunctionIndex, FunctionBody>: Archive, Archived<PrimaryMap<FunctionIndex, FunctionBody>>: Deserialize<PrimaryMap<FunctionIndex, FunctionBody>, __D>, PrimaryMap<SectionIndex, CustomSection>: Archive, Archived<PrimaryMap<SectionIndex, CustomSection>>: Deserialize<PrimaryMap<SectionIndex, CustomSection>, __D>, PrimaryMap<SectionIndex, Vec<Relocation>>: Archive, Archived<PrimaryMap<SectionIndex, Vec<Relocation>>>: Deserialize<PrimaryMap<SectionIndex, Vec<Relocation>>, __D>, Option<Dwarf>: Archive, Archived<Option<Dwarf>>: Deserialize<Option<Dwarf>, __D>, SectionIndex: Archive, Archived<SectionIndex>: Deserialize<SectionIndex, __D>, u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<SerializableCompilation, __D::ErrorDeserializes using the given deserializer### impl<__S: Fallible + ?Sized> Serialize<__S> for SerializableCompilationwhere PrimaryMap<LocalFunctionIndex, FunctionBody>: Serialize<__S>, PrimaryMap<LocalFunctionIndex, Vec<Relocation>>: Serialize<__S>, PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>: Serialize<__S>, PrimaryMap<SignatureIndex, FunctionBody>: Serialize<__S>, PrimaryMap<FunctionIndex, FunctionBody>: Serialize<__S>, PrimaryMap<SectionIndex, CustomSection>: Serialize<__S>, PrimaryMap<SectionIndex, Vec<Relocation>>: Serialize<__S>, Option<Dwarf>: Serialize<__S>, SectionIndex: Serialize<__S>, u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.Auto Trait Implementations --- ### impl RefUnwindSafe for SerializableCompilation ### impl Send for SerializableCompilation ### impl Sync for SerializableCompilation ### impl Unpin for SerializableCompilation ### impl UnwindSafe for SerializableCompilation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ArchivedSerializableModule === ``` #[repr(C,)]pub struct ArchivedSerializableModulewhere SerializableCompilation: Archive, CompileModuleInfo: Archive, Box<[OwnedDataInitializer]>: Archive, u64: Archive,{ pub compilation: Archived<SerializableCompilation>, pub compile_info: Archived<CompileModuleInfo>, pub data_initializers: Archived<Box<[OwnedDataInitializer]>>, pub cpu_features: Archived<u64>, } ``` An archived `SerializableModule` Fields --- `compilation: Archived<SerializableCompilation>`The archived counterpart of `SerializableModule::compilation` `compile_info: Archived<CompileModuleInfo>`The archived counterpart of `SerializableModule::compile_info` `data_initializers: Archived<Box<[OwnedDataInitializer]>>`The archived counterpart of `SerializableModule::data_initializers` `cpu_features: Archived<u64>`The archived counterpart of `SerializableModule::cpu_features` Trait Implementations --- ### impl<__C: ?Sized> CheckBytes<__C> for ArchivedSerializableModulewhere SerializableCompilation: Archive, CompileModuleInfo: Archive, Box<[OwnedDataInitializer]>: Archive, u64: Archive, Archived<SerializableCompilation>: CheckBytes<__C>, Archived<CompileModuleInfo>: CheckBytes<__C>, Archived<Box<[OwnedDataInitializer]>>: CheckBytes<__C>, Archived<u64>: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for ArchivedSerializableModule ### impl Send for ArchivedSerializableModule ### impl Sync for ArchivedSerializableModule ### impl !Unpin for ArchivedSerializableModule ### impl UnwindSafe for ArchivedSerializableModule Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::SerializableModule === ``` pub struct SerializableModule { pub compilation: SerializableCompilation, pub compile_info: CompileModuleInfo, pub data_initializers: Box<[OwnedDataInitializer]>, pub cpu_features: u64, } ``` Serializable struct that is able to serialize from and to a `ArtifactInfo`. Fields --- `compilation: SerializableCompilation`The main serializable compilation object `compile_info: CompileModuleInfo`Compilation informations `data_initializers: Box<[OwnedDataInitializer]>`Datas initializers `cpu_features: u64`CPU Feature flags for this compilation Implementations --- ### impl SerializableModule #### pub fn serialize(&self) -> Result<Vec<u8>, SerializeErrorSerialize a Module into bytes The bytes will have the following format: RKYV serialization (any length) + POS (8 bytes) #### pub unsafe fn deserialize_unchecked( metadata_slice: &[u8] ) -> Result<Self, DeserializeErrorDeserialize a Module from a slice. The slice must have the following format: RKYV serialization (any length) + POS (8 bytes) ##### Safety This method is unsafe since it deserializes data directly from memory. Right now we are not doing any extra work for validation, but `rkyv` has an option to do bytecheck on the serialized data before serializing (via `rkyv::check_archived_value`). #### pub unsafe fn deserialize( metadata_slice: &[u8] ) -> Result<Self, DeserializeErrorDeserialize a Module from a slice. The slice must have the following format: RKYV serialization (any length) + POS (8 bytes) Unlike `Self::deserialize`, this function will validate the data. ##### Safety Unsafe because it loads executable code into memory. The loaded bytes must be trusted. #### pub unsafe fn archive_from_slice( metadata_slice: &[u8] ) -> Result<&ArchivedSerializableModule, DeserializeError##### Safety This method is unsafe. Please check `SerializableModule::deserialize` for more details. #### pub fn archive_from_slice_checked( metadata_slice: &[u8] ) -> Result<&ArchivedSerializableModule, DeserializeErrorDeserialize an archived module. In contrast to `Self::deserialize`, this method performs validation and is not unsafe. #### pub fn deserialize_from_archive( archived: &ArchivedSerializableModule ) -> Result<Self, DeserializeErrorDeserialize a compilation module from an archive #### pub fn create_module_info(&self) -> ModuleInfo Create a `ModuleInfo` for instantiation #### pub fn module_info(&self) -> &ModuleInfo Returns the `ModuleInfo` for instantiation #### pub fn features(&self) -> &Features Returns the features for this Artifact #### pub fn cpu_features(&self) -> EnumSet<CpuFeatureReturns the CPU features for this Artifact #### pub fn data_initializers(&self) -> &[OwnedDataInitializer] Returns data initializers to pass to `VMInstance::initialize` #### pub fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyleReturns the memory styles associated with this `Artifact`. #### pub fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyleReturns the table plans associated with this `Artifact`. Trait Implementations --- ### impl Archive for SerializableModulewhere SerializableCompilation: Archive, CompileModuleInfo: Archive, Box<[OwnedDataInitializer]>: Archive, u64: Archive, #### type Archived = ArchivedSerializableModule The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. SerializableCompilation: Archive, Archived<SerializableCompilation>: Deserialize<SerializableCompilation, __D>, CompileModuleInfo: Archive, Archived<CompileModuleInfo>: Deserialize<CompileModuleInfo, __D>, Box<[OwnedDataInitializer]>: Archive, Archived<Box<[OwnedDataInitializer]>>: Deserialize<Box<[OwnedDataInitializer]>, __D>, u64: Archive, Archived<u64>: Deserialize<u64, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<SerializableModule, __D::ErrorDeserializes using the given deserializer### impl<__S: Fallible + ?Sized> Serialize<__S> for SerializableModulewhere SerializableCompilation: Serialize<__S>, CompileModuleInfo: Serialize<__S>, Box<[OwnedDataInitializer]>: Serialize<__S>, u64: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.Auto Trait Implementations --- ### impl RefUnwindSafe for SerializableModule ### impl Send for SerializableModule ### impl Sync for SerializableModule ### impl Unpin for SerializableModule ### impl UnwindSafe for SerializableModule Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::Bytes === ``` pub struct Bytes(pub usize); ``` Units of WebAssembly memory in terms of 8-bit bytes. Tuple Fields --- `0: usize`Trait Implementations --- ### impl<T> Add<T> for Byteswhere T: Into<Self>, #### type Output = Bytes The resulting type after applying the `+` operator.#### fn add(self, rhs: T) -> Self Performs the `+` operation. #### fn clone(&self) -> Bytes Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(pages: Pages) -> Self Converts to this type from the input type.### impl From<u32> for Bytes #### fn from(other: u32) -> Self Converts to this type from the input type.### impl From<usize> for Bytes #### fn from(other: usize) -> Self Converts to this type from the input type.### impl Hash for Bytes #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Bytes) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Bytes) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Bytes> for Bytes #### fn partial_cmp(&self, other: &Bytes) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. T: Into<Self>, #### type Output = Bytes The resulting type after applying the `-` operator.#### fn sub(self, rhs: T) -> Self Performs the `-` operation. #### type Error = PageCountOutOfRange The type returned in the event of a conversion error.#### fn try_from(bytes: Bytes) -> Result<Self, Self::ErrorPerforms the conversion.### impl Copy for Bytes ### impl Eq for Bytes ### impl StructuralEq for Bytes ### impl StructuralPartialEq for Bytes Auto Trait Implementations --- ### impl RefUnwindSafe for Bytes ### impl Send for Bytes ### impl Sync for Bytes ### impl Unpin for Bytes ### impl UnwindSafe for Bytes Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::CustomSectionIndex === ``` pub struct CustomSectionIndex(/* private fields */); ``` Index type of a custom section inside a WebAssembly module. Implementations --- ### impl CustomSectionIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for CustomSectionIndexwhere u32: Archive, #### type Archived = CustomSectionIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> CustomSectionIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<CustomSectionIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for CustomSectionIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for CustomSectionIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &CustomSectionIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &CustomSectionIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<CustomSectionIndex> for CustomSectionIndex #### fn partial_cmp(&self, other: &CustomSectionIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> CustomSectionIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for CustomSectionIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for CustomSectionIndex ### impl Eq for CustomSectionIndex ### impl StructuralEq for CustomSectionIndex ### impl StructuralPartialEq for CustomSectionIndex Auto Trait Implementations --- ### impl RefUnwindSafe for CustomSectionIndex ### impl Send for CustomSectionIndex ### impl Sync for CustomSectionIndex ### impl Unpin for CustomSectionIndex ### impl UnwindSafe for CustomSectionIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::DataIndex === ``` pub struct DataIndex(/* private fields */); ``` Index type of a passive data segment inside the WebAssembly module. Implementations --- ### impl DataIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for DataIndexwhere u32: Archive, #### type Archived = DataIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> DataIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<DataIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for DataIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for DataIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &DataIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &DataIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<DataIndex> for DataIndex #### fn partial_cmp(&self, other: &DataIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> DataIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for DataIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for DataIndex ### impl Eq for DataIndex ### impl StructuralEq for DataIndex ### impl StructuralPartialEq for DataIndex Auto Trait Implementations --- ### impl RefUnwindSafe for DataIndex ### impl Send for DataIndex ### impl Sync for DataIndex ### impl Unpin for DataIndex ### impl UnwindSafe for DataIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::DataInitializer === ``` pub struct DataInitializer<'data> { pub location: DataInitializerLocation, pub data: &'data [u8], } ``` A data initializer for linear memory. Fields --- `location: DataInitializerLocation`The location where the initialization is to be performed. `data: &'data [u8]`The initialization data. Trait Implementations --- ### impl<'data> Debug for DataInitializer<'data#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl<'data> RefUnwindSafe for DataInitializer<'data### impl<'data> Send for DataInitializer<'data### impl<'data> Sync for DataInitializer<'data### impl<'data> Unpin for DataInitializer<'data### impl<'data> UnwindSafe for DataInitializer<'dataBlanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ElemIndex === ``` pub struct ElemIndex(/* private fields */); ``` Index type of a passive element segment inside the WebAssembly module. Implementations --- ### impl ElemIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for ElemIndexwhere u32: Archive, #### type Archived = ElemIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> ElemIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<ElemIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for ElemIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for ElemIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &ElemIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &ElemIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<ElemIndex> for ElemIndex #### fn partial_cmp(&self, other: &ElemIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> ElemIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for ElemIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for ElemIndex ### impl Eq for ElemIndex ### impl StructuralEq for ElemIndex ### impl StructuralPartialEq for ElemIndex Auto Trait Implementations --- ### impl RefUnwindSafe for ElemIndex ### impl Send for ElemIndex ### impl Sync for ElemIndex ### impl Unpin for ElemIndex ### impl UnwindSafe for ElemIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ExportType === ``` pub struct ExportType<T = ExternType> { /* private fields */ } ``` A descriptor for an exported WebAssembly value. This type is primarily accessed from the `Module::exports` accessor and describes what names are exported from a wasm module and the type of the item that is exported. The `<T>` refefers to `ExternType`, however it can also refer to use `MemoryType`, `TableType`, `FunctionType` and `GlobalType` for ease of use. Implementations --- ### impl<T> ExportType<T#### pub fn new(name: &str, ty: T) -> Self Creates a new export which is exported with the given `name` and has the given `ty`. #### pub fn name(&self) -> &str Returns the name by which this export is known by. #### pub fn ty(&self) -> &T Returns the type of this export. Trait Implementations --- ### impl<T: Clone> Clone for ExportType<T#### fn clone(&self) -> ExportType<TReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<T: Eq> Eq for ExportType<T### impl<T> StructuralEq for ExportType<T### impl<T> StructuralPartialEq for ExportType<TAuto Trait Implementations --- ### impl<T> RefUnwindSafe for ExportType<T>where T: RefUnwindSafe, ### impl<T> Send for ExportType<T>where T: Send, ### impl<T> Sync for ExportType<T>where T: Sync, ### impl<T> Unpin for ExportType<T>where T: Unpin, ### impl<T> UnwindSafe for ExportType<T>where T: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ExportsIterator === ``` pub struct ExportsIterator<I: Iterator<Item = ExportType> + Sized> { /* private fields */ } ``` This iterator allows us to iterate over the exports and offer nice API ergonomics over it. Implementations --- ### impl<I: Iterator<Item = ExportType> + Sized> ExportsIterator<I#### pub fn new(iter: I, size: usize) -> Self Create a new `ExportsIterator` for a given iterator and size ### impl<I: Iterator<Item = ExportType> + Sized> ExportsIterator<I#### pub fn functions(self) -> impl Iterator<Item = ExportType<FunctionType>> + Sized Get only the functions #### pub fn memories(self) -> impl Iterator<Item = ExportType<MemoryType>> + Sized Get only the memories #### pub fn tables(self) -> impl Iterator<Item = ExportType<TableType>> + Sized Get only the tables #### pub fn globals(self) -> impl Iterator<Item = ExportType<GlobalType>> + Sized Get only the globals Trait Implementations --- ### impl<I: Iterator<Item = ExportType> + Sized> ExactSizeIterator for ExportsIterator<I#### fn len(&self) -> usize Returns the exact remaining length of the iterator. 🔬This is a nightly-only experimental API. (`exact_size_is_empty`)Returns `true` if the iterator is empty. &mut self ) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where Self: Sized, 🔬This is a nightly-only experimental API. (`iter_next_chunk`)Advances the iterator and returns an array containing the next `N` values. Read more1.0.0 · source#### fn size_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. Read more1.0.0 · source#### fn count(self) -> usizewhere Self: Sized, Consumes the iterator, counting the number of iterations and returning it. Read more1.0.0 · source#### fn last(self) -> Option<Self::Item>where Self: Sized, Consumes the iterator, returning the last element. Self: Sized, Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more1.0.0 · source#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> where Self: Sized, U: IntoIterator<Item = Self::Item>, Takes two iterators and creates a new iterator over both in sequence. Read more1.0.0 · source#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> where Self: Sized, U: IntoIterator, ‘Zips up’ two iterators into a single iterator of pairs. Self: Sized, G: FnMut() -> Self::Item, 🔬This is a nightly-only experimental API. (`iter_intersperse`)Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. Read more1.0.0 · source#### fn map<B, F>(self, f: F) -> Map<Self, F> where Self: Sized, F: FnMut(Self::Item) -> B, Takes a closure and creates an iterator which calls that closure on each element. Read more1.21.0 · source#### fn for_each<F>(self, f: F)where Self: Sized, F: FnMut(Self::Item), Calls a closure on each element of an iterator. Read more1.0.0 · source#### fn filter<P>(self, predicate: P) -> Filter<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator which uses a closure to determine if an element should be yielded. Read more1.0.0 · source#### fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Creates an iterator that both filters and maps. Read more1.0.0 · source#### fn enumerate(self) -> Enumerate<Self> where Self: Sized, Creates an iterator which gives the current iteration count as well as the next value. Read more1.0.0 · source#### fn peekable(self) -> Peekable<Self> where Self: Sized, Creates an iterator which can use the `peek` and `peek_mut` methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more1.0.0 · source#### fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that `skip`s elements based on a predicate. Read more1.0.0 · source#### fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that yields elements based on a predicate. Read more1.57.0 · source#### fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> where Self: Sized, P: FnMut(Self::Item) -> Option<B>, Creates an iterator that both yields elements based on a predicate and maps. Read more1.0.0 · source#### fn skip(self, n: usize) -> Skip<Self> where Self: Sized, Creates an iterator that skips the first `n` elements. Read more1.0.0 · source#### fn take(self, n: usize) -> Take<Self> where Self: Sized, Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. Read more1.0.0 · source#### fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>, An iterator adapter which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. Read more1.0.0 · source#### fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, Creates an iterator that works like map, but flattens nested structure. Self: Sized, F: FnMut(&[Self::Item; N]) -> R, 🔬This is a nightly-only experimental API. (`iter_map_windows`)Calls the given function `f` for each contiguous window of size `N` over `self` and returns an iterator over the outputs of `f`. Like `slice::windows()`, the windows during mapping overlap as well. Read more1.0.0 · source#### fn fuse(self) -> Fuse<Self> where Self: Sized, Creates an iterator which ends after the first `None`. Read more1.0.0 · source#### fn inspect<F>(self, f: F) -> Inspect<Self, F> where Self: Sized, F: FnMut(&Self::Item), Does something with each element of an iterator, passing the value on. Read more1.0.0 · source#### fn by_ref(&mut self) -> &mut Selfwhere Self: Sized, Borrows an iterator, rather than consuming it. Read more1.0.0 · source#### fn collect<B>(self) -> Bwhere B: FromIterator<Self::Item>, Self: Sized, Transforms an iterator into a collection. E: Extend<Self::Item>, Self: Sized, 🔬This is a nightly-only experimental API. (`iter_collect_into`)Collects all the items from an iterator into a collection. Read more1.0.0 · source#### fn partition<B, F>(self, f: F) -> (B, B)where Self: Sized, B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool, Consumes an iterator, creating two collections from it. Self: Sized, P: FnMut(Self::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_is_partitioned`)Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. Read more1.27.0 · source#### fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more1.27.0 · source#### fn try_for_each<F, R>(&mut self, f: F) -> Rwhere Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Output = ()>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more1.0.0 · source#### fn fold<B, F>(self, init: B, f: F) -> Bwhere Self: Sized, F: FnMut(B, Self::Item) -> B, Folds every element into an accumulator by applying an operation, returning the final result. Read more1.51.0 · source#### fn reduce<F>(self, f: F) -> Option<Self::Item>where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item, Reduces the elements to a single one, by repeatedly applying a reducing operation. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere Self: Sized, F: FnMut(Self::Item, Self::Item) -> R, R: Try<Output = Self::Item>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce`)Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more1.0.0 · source#### fn all<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if every element of the iterator matches a predicate. Read more1.0.0 · source#### fn any<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if any element of the iterator matches a predicate. Read more1.0.0 · source#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where Self: Sized, P: FnMut(&Self::Item) -> bool, Searches for an element of an iterator that satisfies a predicate. Read more1.30.0 · source#### fn find_map<B, F>(&mut self, f: F) -> Option<B>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Applies function to the elements of iterator and returns the first non-none result. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere Self: Sized, F: FnMut(&Self::Item) -> R, R: Try<Output = bool>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`try_find`)Applies function to the elements of iterator and returns the first true result or the first error. Read more1.0.0 · source#### fn position<P>(&mut self, predicate: P) -> Option<usize>where Self: Sized, P: FnMut(Self::Item) -> bool, Searches for an element in an iterator, returning its index. Read more1.6.0 · source#### fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the maximum value from the specified function. Read more1.15.0 · source#### fn max_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the maximum value with respect to the specified comparison function. Read more1.6.0 · source#### fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the minimum value from the specified function. Read more1.15.0 · source#### fn min_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the minimum value with respect to the specified comparison function. Read more1.0.0 · source#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Iterator<Item = (A, B)>, Converts an iterator of pairs into a pair of containers. Read more1.36.0 · source#### fn copied<'a, T>(self) -> Copied<Self> where T: 'a + Copy, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which copies all of its elements. Read more1.0.0 · source#### fn cloned<'a, T>(self) -> Cloned<Self> where T: 'a + Clone, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which `clone`s all of its elements. Self: Sized, 🔬This is a nightly-only experimental API. (`iter_array_chunks`)Returns an iterator over `N` elements of the iterator at a time. Read more1.11.0 · source#### fn sum<S>(self) -> Swhere Self: Sized, S: Sum<Self::Item>, Sums the elements of an iterator. Read more1.11.0 · source#### fn product<P>(self) -> Pwhere Self: Sized, P: Product<Self::Item>, Iterates over the entire iterator, multiplying all the elements Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn partial_cmp<I>(self, other: I) -> Option<Ordering>where I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Lexicographically compares the `PartialOrd` elements of this `Iterator` with those of another. The comparison works like short-circuit evaluation, returning a result without comparing the remaining elements. As soon as an order can be determined, the evaluation stops and a result is returned. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn eq<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are equal to those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_order_by`)Determines if the elements of this `Iterator` are equal to those of another with respect to the specified equality function. Read more1.5.0 · source#### fn ne<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are not equal to those of another. Read more1.5.0 · source#### fn lt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less than those of another. Read more1.5.0 · source#### fn le<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less or equal to those of another. Read more1.5.0 · source#### fn gt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than those of another. Read more1.5.0 · source#### fn ge<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than or equal to those of another. Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given comparator function. Self: Sized, F: FnMut(Self::Item) -> K, K: PartialOrd<K>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given key extraction function. Read moreAuto Trait Implementations --- ### impl<I> RefUnwindSafe for ExportsIterator<I>where I: RefUnwindSafe, ### impl<I> Send for ExportsIterator<I>where I: Send, ### impl<I> Sync for ExportsIterator<I>where I: Sync, ### impl<I> Unpin for ExportsIterator<I>where I: Unpin, ### impl<I> UnwindSafe for ExportsIterator<I>where I: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<I> IntoIterator for Iwhere I: Iterator, #### type Item = <I as Iterator>::Item The type of the elements being iterated over.#### type IntoIter = I Which kind of iterator are we turning this into?const: unstable · source#### fn into_iter(self) -> I Creates an iterator from a value. #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"ArrayChunks<Self, N>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.ArrayChunks.html\" title=\"struct wasmer_types::lib::std::iter::ArrayChunks\">ArrayChunks</a>&lt;I, N&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, const N: <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.ArrayChunks.html\" title=\"struct wasmer_types::lib::std::iter::ArrayChunks\">ArrayChunks</a>&lt;I, N&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = [&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.array.html\">N</a>];</span>","Chain<Self, <U as IntoIterator>::IntoIter>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Chain.html\" title=\"struct wasmer_types::lib::std::iter::Chain\">Chain</a>&lt;A, B&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A, B&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Chain.html\" title=\"struct wasmer_types::lib::std::iter::Chain\">Chain</a>&lt;A, B&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n B: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = &lt;A as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;A as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Cloned<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Cloned.html\" title=\"struct wasmer_types::lib::std::iter::Cloned\">Cloned</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, I, T&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Cloned.html\" title=\"struct wasmer_types::lib::std::iter::Cloned\">Cloned</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n T: 'a + <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html\" title=\"trait core::clone::Clone\">Clone</a>,\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = T;</span>","Copied<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Copied.html\" title=\"struct wasmer_types::lib::std::iter::Copied\">Copied</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, I, T&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Copied.html\" title=\"struct wasmer_types::lib::std::iter::Copied\">Copied</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n T: 'a + <a class=\"trait\" href=\"lib/std/marker/trait.Copy.html\" title=\"trait wasmer_types::lib::std::marker::Copy\">Copy</a>,\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = T;</span>","Enumerate<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Enumerate.html\" title=\"struct wasmer_types::lib::std::iter::Enumerate\">Enumerate</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Enumerate.html\" title=\"struct wasmer_types::lib::std::iter::Enumerate\">Enumerate</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>, &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>);</span>","Filter<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Filter.html\" title=\"struct wasmer_types::lib::std::iter::Filter\">Filter</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Filter.html\" title=\"struct wasmer_types::lib::std::iter::Filter\">Filter</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","FilterMap<Self, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.FilterMap.html\" title=\"struct wasmer_types::lib::std::iter::FilterMap\">FilterMap</a>&lt;I, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.FilterMap.html\" title=\"struct wasmer_types::lib::std::iter::FilterMap\">FilterMap</a>&lt;I, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/option/enum.Option.html\" title=\"enum core::option::Option\">Option</a>&lt;B&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","FlatMap<Self, U, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.FlatMap.html\" title=\"struct wasmer_types::lib::std::iter::FlatMap\">FlatMap</a>&lt;I, U, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, U, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.FlatMap.html\" title=\"struct wasmer_types::lib::std::iter::FlatMap\">FlatMap</a>&lt;I, U, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n U: <a class=\"trait\" href=\"lib/std/iter/trait.IntoIterator.html\" title=\"trait wasmer_types::lib::std::iter::IntoIterator\">IntoIterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; U,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;U as <a class=\"trait\" href=\"lib/std/iter/trait.IntoIterator.html\" title=\"trait wasmer_types::lib::std::iter::IntoIterator\">IntoIterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.IntoIterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::IntoIterator::Item\">Item</a>;</span>","Fuse<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Fuse.html\" title=\"struct wasmer_types::lib::std::iter::Fuse\">Fuse</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Fuse.html\" title=\"struct wasmer_types::lib::std::iter::Fuse\">Fuse</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Inspect<Self, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Inspect.html\" title=\"struct wasmer_types::lib::std::iter::Inspect\">Inspect</a>&lt;I, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Inspect.html\" title=\"struct wasmer_types::lib::std::iter::Inspect\">Inspect</a>&lt;I, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>),</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","IntersperseWith<Self, G>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.IntersperseWith.html\" title=\"struct wasmer_types::lib::std::iter::IntersperseWith\">IntersperseWith</a>&lt;I, G&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, G&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.IntersperseWith.html\" title=\"struct wasmer_types::lib::std::iter::IntersperseWith\">IntersperseWith</a>&lt;I, G&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n G: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>() -&gt; &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Map<Self, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Map.html\" title=\"struct wasmer_types::lib::std::iter::Map\">Map</a>&lt;I, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Map.html\" title=\"struct wasmer_types::lib::std::iter::Map\">Map</a>&lt;I, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; B,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","MapWhile<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.MapWhile.html\" title=\"struct wasmer_types::lib::std::iter::MapWhile\">MapWhile</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.MapWhile.html\" title=\"struct wasmer_types::lib::std::iter::MapWhile\">MapWhile</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/option/enum.Option.html\" title=\"enum core::option::Option\">Option</a>&lt;B&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","MapWindows<Self, F, N>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.MapWindows.html\" title=\"struct wasmer_types::lib::std::iter::MapWindows\">MapWindows</a>&lt;I, F, N&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, F, R, const N: <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.MapWindows.html\" title=\"struct wasmer_types::lib::std::iter::MapWindows\">MapWindows</a>&lt;I, F, N&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;[&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.array.html\">N</a>]) -&gt; R,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = R;</span>","Peekable<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Peekable.html\" title=\"struct wasmer_types::lib::std::iter::Peekable\">Peekable</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Peekable.html\" title=\"struct wasmer_types::lib::std::iter::Peekable\">Peekable</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Scan<Self, St, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Scan.html\" title=\"struct wasmer_types::lib::std::iter::Scan\">Scan</a>&lt;I, St, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, St, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Scan.html\" title=\"struct wasmer_types::lib::std::iter::Scan\">Scan</a>&lt;I, St, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;mut St</a>, &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/option/enum.Option.html\" title=\"enum core::option::Option\">Option</a>&lt;B&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","Skip<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Skip.html\" title=\"struct wasmer_types::lib::std::iter::Skip\">Skip</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Skip.html\" title=\"struct wasmer_types::lib::std::iter::Skip\">Skip</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","SkipWhile<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.SkipWhile.html\" title=\"struct wasmer_types::lib::std::iter::SkipWhile\">SkipWhile</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.SkipWhile.html\" title=\"struct wasmer_types::lib::std::iter::SkipWhile\">SkipWhile</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","StepBy<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.StepBy.html\" title=\"struct wasmer_types::lib::std::iter::StepBy\">StepBy</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.StepBy.html\" title=\"struct wasmer_types::lib::std::iter::StepBy\">StepBy</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Take<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Take.html\" title=\"struct wasmer_types::lib::std::iter::Take\">Take</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Take.html\" title=\"struct wasmer_types::lib::std::iter::Take\">Take</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","TakeWhile<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.TakeWhile.html\" title=\"struct wasmer_types::lib::std::iter::TakeWhile\">TakeWhile</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.TakeWhile.html\" title=\"struct wasmer_types::lib::std::iter::TakeWhile\">TakeWhile</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Zip<Self, <U as IntoIterator>::IntoIter>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Zip.html\" title=\"struct wasmer_types::lib::std::iter::Zip\">Zip</a>&lt;A, B&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A, B&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Zip.html\" title=\"struct wasmer_types::lib::std::iter::Zip\">Zip</a>&lt;A, B&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n B: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (&lt;A as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>, &lt;B as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>);</span>"} Struct wasmer_types::Features === ``` pub struct Features { pub threads: bool, pub reference_types: bool, pub simd: bool, pub bulk_memory: bool, pub multi_value: bool, pub tail_call: bool, pub module_linking: bool, pub multi_memory: bool, pub memory64: bool, pub exceptions: bool, pub relaxed_simd: bool, pub extended_const: bool, } ``` Controls which experimental features will be enabled. Features usually have a corresponding WebAssembly proposal. Fields --- `threads: bool`Threads proposal should be enabled `reference_types: bool`Reference Types proposal should be enabled `simd: bool`SIMD proposal should be enabled `bulk_memory: bool`Bulk Memory proposal should be enabled `multi_value: bool`Multi Value proposal should be enabled `tail_call: bool`Tail call proposal should be enabled `module_linking: bool`Module Linking proposal should be enabled `multi_memory: bool`Multi Memory proposal should be enabled `memory64: bool`64-bit Memory proposal should be enabled `exceptions: bool`Wasm exceptions proposal should be enabled `relaxed_simd: bool`Relaxed SIMD proposal should be enabled `extended_const: bool`Extended constant expressions proposal should be enabled Implementations --- ### impl Features #### pub fn new() -> Self Create a new feature #### pub fn threads(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly threads proposal will be enabled. The WebAssembly threads proposal is not currently fully standardized and is undergoing development. Support for this feature can be enabled through this method for appropriate WebAssembly modules. This feature gates items such as shared memories and atomic instructions. This is `false` by default. #### pub fn reference_types(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly reference types proposal will be enabled. The WebAssembly reference types proposal is now fully standardized and enabled by default. This feature gates items such as the `externref` type and multiple tables being in a module. Note that enabling the reference types feature will also enable the bulk memory feature. This is `true` by default. #### pub fn simd(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly SIMD proposal will be enabled. The WebAssembly SIMD proposal is not currently fully standardized and is undergoing development. Support for this feature can be enabled through this method for appropriate WebAssembly modules. This feature gates items such as the `v128` type and all of its operators being in a module. This is `false` by default. #### pub fn bulk_memory(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly bulk memory operations proposal will be enabled. The WebAssembly bulk memory operations proposal is now fully standardized and enabled by default. This feature gates items such as the `memory.copy` instruction, passive data/table segments, etc, being in a module. This is `true` by default. #### pub fn multi_value(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly multi-value proposal will be enabled. The WebAssembly multi-value proposal is now fully standardized and enabled by default, except with the singlepass compiler which does not support it. This feature gates functions and blocks returning multiple values in a module, for example. This is `true` by default. #### pub fn tail_call(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly tail-call proposal will be enabled. The WebAssembly tail-call proposal is not currently fully standardized and is undergoing development. Support for this feature can be enabled through this method for appropriate WebAssembly modules. This feature gates tail-call functions in WebAssembly. This is `false` by default. #### pub fn module_linking(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly module linking proposal will be enabled. The WebAssembly module linking proposal is not currently fully standardized and is undergoing development. Support for this feature can be enabled through this method for appropriate WebAssembly modules. This feature allows WebAssembly modules to define, import and export modules and instances. This is `false` by default. #### pub fn multi_memory(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly multi-memory proposal will be enabled. The WebAssembly multi-memory proposal is not currently fully standardized and is undergoing development. Support for this feature can be enabled through this method for appropriate WebAssembly modules. This feature adds the ability to use multiple memories within a single Wasm module. This is `false` by default. #### pub fn memory64(&mut self, enable: bool) -> &mut Self Configures whether the WebAssembly 64-bit memory proposal will be enabled. The WebAssembly 64-bit memory proposal is not currently fully standardized and is undergoing development. Support for this feature can be enabled through this method for appropriate WebAssembly modules. This feature gates support for linear memory of sizes larger than 2^32 bits. This is `false` by default. Trait Implementations --- ### impl Archive for Featureswhere bool: Archive, #### type Archived = Features The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. bool: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> Features Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Self Returns the “default value” for a type. bool: Archive, Archived<bool>: Deserialize<bool, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<Features, __D::ErrorDeserializes using the given deserializer### impl PartialEq<Features> for Features #### fn eq(&self, other: &Features) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for Featureswhere bool: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for Features ### impl StructuralEq for Features ### impl StructuralPartialEq for Features Auto Trait Implementations --- ### impl RefUnwindSafe for Features ### impl Send for Features ### impl Sync for Features ### impl Unpin for Features ### impl UnwindSafe for Features Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::FrameInfo === ``` pub struct FrameInfo { /* private fields */ } ``` Description of a frame in a backtrace. Each runtime error includes a backtrace of the WebAssembly frames that led to the trap, and each frame is described by this structure. Implementations --- ### impl FrameInfo #### pub fn new( module_name: String, func_index: u32, function_name: Option<String>, func_start: SourceLoc, instr: SourceLoc ) -> Self Creates a new FrameInfo, useful for testing. #### pub fn func_index(&self) -> u32 Returns the WebAssembly function index for this frame. This function index is the index in the function index space of the WebAssembly module that this frame comes from. #### pub fn module_name(&self) -> &str Returns the identifer of the module that this frame is for. ModuleInfo identifiers are present in the `name` section of a WebAssembly binary, but this may not return the exact item in the `name` section. ModuleInfo names can be overwritten at construction time or perhaps inferred from file names. The primary purpose of this function is to assist in debugging and therefore may be tweaked over time. This function returns `None` when no name can be found or inferred. #### pub fn function_name(&self) -> Option<&strReturns a descriptive name of the function for this frame, if one is available. The name of this function may come from the `name` section of the WebAssembly binary, or wasmer may try to infer a better name for it if not available, for example the name of the export if it’s exported. This return value is primarily used for debugging and human-readable purposes for things like traps. Note that the exact return value may be tweaked over time here and isn’t guaranteed to be something in particular about a wasm module due to its primary purpose of assisting in debugging. This function returns `None` when no name could be inferred. #### pub fn module_offset(&self) -> usize Returns the offset within the original wasm module this frame’s program counter was at. The offset here is the offset from the beginning of the original wasm module to the instruction that this frame points to. #### pub fn func_offset(&self) -> usize Returns the offset from the original wasm module’s function to this frame’s program counter. The offset here is the offset from the beginning of the defining function of this frame (within the wasm module) to the instruction this frame points to. Trait Implementations --- ### impl Clone for FrameInfo #### fn clone(&self) -> FrameInfo Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for FrameInfo ### impl Send for FrameInfo ### impl Sync for FrameInfo ### impl Unpin for FrameInfo ### impl UnwindSafe for FrameInfo Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::FunctionIndex === ``` pub struct FunctionIndex(/* private fields */); ``` Index type of a function (imported or local) inside the WebAssembly module. Implementations --- ### impl FunctionIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for FunctionIndexwhere u32: Archive, #### type Archived = FunctionIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> FunctionIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<FunctionIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for FunctionIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for FunctionIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &FunctionIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &FunctionIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<FunctionIndex> for FunctionIndex #### fn partial_cmp(&self, other: &FunctionIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> FunctionIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for FunctionIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for FunctionIndex ### impl Eq for FunctionIndex ### impl StructuralEq for FunctionIndex ### impl StructuralPartialEq for FunctionIndex Auto Trait Implementations --- ### impl RefUnwindSafe for FunctionIndex ### impl Send for FunctionIndex ### impl Sync for FunctionIndex ### impl Unpin for FunctionIndex ### impl UnwindSafe for FunctionIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::FunctionType === ``` pub struct FunctionType { /* private fields */ } ``` The signature of a function that is either implemented in a Wasm module or exposed to Wasm by the host. WebAssembly functions can have 0 or more parameters and results. Implementations --- ### impl FunctionType #### pub fn new<Params, Returns>(params: Params, returns: Returns) -> Selfwhere Params: Into<Box<[Type]>>, Returns: Into<Box<[Type]>>, Creates a new Function Type with the given parameter and return types. #### pub fn params(&self) -> &[Type] Parameter types. #### pub fn results(&self) -> &[Type] Return types. Trait Implementations --- ### impl Archive for FunctionTypewhere Box<[Type]>: Archive, #### type Archived = ArchivedFunctionType The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> FunctionType Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Box<[Type]>: Archive, Archived<Box<[Type]>>: Deserialize<Box<[Type]>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<FunctionType, __D::ErrorDeserializes using the given deserializer### impl Display for FunctionType #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(as_ref: &Self) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 0], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 0], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 1], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 1], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 2], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 2], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 3], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 3], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 4], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 4], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 5], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 5], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 6], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 6], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 7], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 7], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 8], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 8], [Type; 9])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 0])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 0])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 1])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 1])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 2])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 2])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 3])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 3])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 4])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 4])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 5])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 5])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 6])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 6])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 7])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 7])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 8])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 8])) -> Self Converts to this type from the input type.### impl From<([Type; 9], [Type; 9])> for FunctionType #### fn from(pair: ([Type; 9], [Type; 9])) -> Self Converts to this type from the input type.### impl Hash for FunctionType #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &FunctionType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for FunctionTypewhere Box<[Type]>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for FunctionType ### impl StructuralEq for FunctionType ### impl StructuralPartialEq for FunctionType Auto Trait Implementations --- ### impl RefUnwindSafe for FunctionType ### impl Send for FunctionType ### impl Sync for FunctionType ### impl Unpin for FunctionType ### impl UnwindSafe for FunctionType Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::GlobalIndex === ``` pub struct GlobalIndex(/* private fields */); ``` Index type of a global variable (imported or local) inside the WebAssembly module. Implementations --- ### impl GlobalIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for GlobalIndexwhere u32: Archive, #### type Archived = GlobalIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> GlobalIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<GlobalIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for GlobalIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for GlobalIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &GlobalIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &GlobalIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<GlobalIndex> for GlobalIndex #### fn partial_cmp(&self, other: &GlobalIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> GlobalIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for GlobalIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for GlobalIndex ### impl Eq for GlobalIndex ### impl StructuralEq for GlobalIndex ### impl StructuralPartialEq for GlobalIndex Auto Trait Implementations --- ### impl RefUnwindSafe for GlobalIndex ### impl Send for GlobalIndex ### impl Sync for GlobalIndex ### impl Unpin for GlobalIndex ### impl UnwindSafe for GlobalIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::GlobalType === ``` pub struct GlobalType { pub ty: Type, pub mutability: Mutability, } ``` WebAssembly global. Fields --- `ty: Type`The type of the value stored in the global. `mutability: Mutability`A flag indicating whether the value may change at runtime. Implementations --- ### impl GlobalType A WebAssembly global descriptor. This type describes an instance of a global in a WebAssembly module. Globals are local to an `Instance` and are either immutable or mutable. #### pub fn new(ty: Type, mutability: Mutability) -> Self Create a new Global variable ##### Usage: ``` use wasmer_types::{GlobalType, Type, Mutability}; // An I32 constant global let global = GlobalType::new(Type::I32, Mutability::Const); // An I64 mutable global let global = GlobalType::new(Type::I64, Mutability::Var); ``` Trait Implementations --- ### impl Archive for GlobalTypewhere Type: Archive, Mutability: Archive, #### type Archived = GlobalType The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. Type: CheckBytes<__C>, Mutability: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> GlobalType Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Type: Archive, Archived<Type>: Deserialize<Type, __D>, Mutability: Archive, Archived<Mutability>: Deserialize<Mutability, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<GlobalType, __D::ErrorDeserializes using the given deserializer### impl Display for GlobalType #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &GlobalType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for GlobalTypewhere Type: Serialize<__S>, Mutability: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for GlobalType ### impl Eq for GlobalType ### impl StructuralEq for GlobalType ### impl StructuralPartialEq for GlobalType Auto Trait Implementations --- ### impl RefUnwindSafe for GlobalType ### impl Send for GlobalType ### impl Sync for GlobalType ### impl Unpin for GlobalType ### impl UnwindSafe for GlobalType Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ImportKey === ``` pub struct ImportKey { pub module: String, pub field: String, pub import_idx: u32, } ``` Hash key of an import Fields --- `module: String`Module name `field: String`Field name `import_idx: u32`Import index Trait Implementations --- ### impl Archive for ImportKeywhere String: Archive, u32: Archive, #### type Archived = ArchivedImportKey The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> ImportKey Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> ImportKey Returns the “default value” for a type. String: Archive, Archived<String>: Deserialize<String, __D>, u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<ImportKey, __D::ErrorDeserializes using the given deserializer### impl From<(String, String, u32)> for ImportKey #### fn from((module, field, import_idx): (String, String, u32)) -> Self Converts to this type from the input type.### impl Hash for ImportKey #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &ImportKey) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for ImportKeywhere String: Serialize<__S>, u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for ImportKey ### impl StructuralEq for ImportKey ### impl StructuralPartialEq for ImportKey Auto Trait Implementations --- ### impl RefUnwindSafe for ImportKey ### impl Send for ImportKey ### impl Sync for ImportKey ### impl Unpin for ImportKey ### impl UnwindSafe for ImportKey Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ImportType === ``` pub struct ImportType<T = ExternType> { /* private fields */ } ``` A descriptor for an imported value into a wasm module. This type is primarily accessed from the `Module::imports` API. Each `ImportType` describes an import into the wasm module with the module/name that it’s imported from as well as the type of item that’s being imported. Implementations --- ### impl<T> ImportType<T#### pub fn new(module: &str, name: &str, ty: T) -> Self Creates a new import descriptor which comes from `module` and `name` and is of type `ty`. #### pub fn module(&self) -> &str Returns the module name that this import is expected to come from. #### pub fn name(&self) -> &str Returns the field name of the module that this import is expected to come from. #### pub fn ty(&self) -> &T Returns the expected type of this import. Trait Implementations --- ### impl<T: Clone> Clone for ImportType<T#### fn clone(&self) -> ImportType<TReturns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Formats the value using the given formatter. Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<T: Eq> Eq for ImportType<T### impl<T> StructuralEq for ImportType<T### impl<T> StructuralPartialEq for ImportType<TAuto Trait Implementations --- ### impl<T> RefUnwindSafe for ImportType<T>where T: RefUnwindSafe, ### impl<T> Send for ImportType<T>where T: Send, ### impl<T> Sync for ImportType<T>where T: Sync, ### impl<T> Unpin for ImportType<T>where T: Unpin, ### impl<T> UnwindSafe for ImportType<T>where T: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ImportsIterator === ``` pub struct ImportsIterator<I: Iterator<Item = ImportType> + Sized> { /* private fields */ } ``` This iterator allows us to iterate over the imports and offer nice API ergonomics over it. Implementations --- ### impl<I: Iterator<Item = ImportType> + Sized> ImportsIterator<I#### pub fn new(iter: I, size: usize) -> Self Create a new `ImportsIterator` for a given iterator and size ### impl<I: Iterator<Item = ImportType> + Sized> ImportsIterator<I#### pub fn functions(self) -> impl Iterator<Item = ImportType<FunctionType>> + Sized Get only the functions #### pub fn memories(self) -> impl Iterator<Item = ImportType<MemoryType>> + Sized Get only the memories #### pub fn tables(self) -> impl Iterator<Item = ImportType<TableType>> + Sized Get only the tables #### pub fn globals(self) -> impl Iterator<Item = ImportType<GlobalType>> + Sized Get only the globals Trait Implementations --- ### impl<I: Iterator<Item = ImportType> + Sized> ExactSizeIterator for ImportsIterator<I#### fn len(&self) -> usize Returns the exact remaining length of the iterator. 🔬This is a nightly-only experimental API. (`exact_size_is_empty`)Returns `true` if the iterator is empty. &mut self ) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where Self: Sized, 🔬This is a nightly-only experimental API. (`iter_next_chunk`)Advances the iterator and returns an array containing the next `N` values. Read more1.0.0 · source#### fn size_hint(&self) -> (usize, Option<usize>) Returns the bounds on the remaining length of the iterator. Read more1.0.0 · source#### fn count(self) -> usizewhere Self: Sized, Consumes the iterator, counting the number of iterations and returning it. Read more1.0.0 · source#### fn last(self) -> Option<Self::Item>where Self: Sized, Consumes the iterator, returning the last element. Self: Sized, Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more1.0.0 · source#### fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter> where Self: Sized, U: IntoIterator<Item = Self::Item>, Takes two iterators and creates a new iterator over both in sequence. Read more1.0.0 · source#### fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter> where Self: Sized, U: IntoIterator, ‘Zips up’ two iterators into a single iterator of pairs. Self: Sized, G: FnMut() -> Self::Item, 🔬This is a nightly-only experimental API. (`iter_intersperse`)Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. Read more1.0.0 · source#### fn map<B, F>(self, f: F) -> Map<Self, F> where Self: Sized, F: FnMut(Self::Item) -> B, Takes a closure and creates an iterator which calls that closure on each element. Read more1.21.0 · source#### fn for_each<F>(self, f: F)where Self: Sized, F: FnMut(Self::Item), Calls a closure on each element of an iterator. Read more1.0.0 · source#### fn filter<P>(self, predicate: P) -> Filter<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator which uses a closure to determine if an element should be yielded. Read more1.0.0 · source#### fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Creates an iterator that both filters and maps. Read more1.0.0 · source#### fn enumerate(self) -> Enumerate<Self> where Self: Sized, Creates an iterator which gives the current iteration count as well as the next value. Read more1.0.0 · source#### fn peekable(self) -> Peekable<Self> where Self: Sized, Creates an iterator which can use the `peek` and `peek_mut` methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more1.0.0 · source#### fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that `skip`s elements based on a predicate. Read more1.0.0 · source#### fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, Creates an iterator that yields elements based on a predicate. Read more1.57.0 · source#### fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> where Self: Sized, P: FnMut(Self::Item) -> Option<B>, Creates an iterator that both yields elements based on a predicate and maps. Read more1.0.0 · source#### fn skip(self, n: usize) -> Skip<Self> where Self: Sized, Creates an iterator that skips the first `n` elements. Read more1.0.0 · source#### fn take(self, n: usize) -> Take<Self> where Self: Sized, Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. Read more1.0.0 · source#### fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>, An iterator adapter which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. Read more1.0.0 · source#### fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, Creates an iterator that works like map, but flattens nested structure. Self: Sized, F: FnMut(&[Self::Item; N]) -> R, 🔬This is a nightly-only experimental API. (`iter_map_windows`)Calls the given function `f` for each contiguous window of size `N` over `self` and returns an iterator over the outputs of `f`. Like `slice::windows()`, the windows during mapping overlap as well. Read more1.0.0 · source#### fn fuse(self) -> Fuse<Self> where Self: Sized, Creates an iterator which ends after the first `None`. Read more1.0.0 · source#### fn inspect<F>(self, f: F) -> Inspect<Self, F> where Self: Sized, F: FnMut(&Self::Item), Does something with each element of an iterator, passing the value on. Read more1.0.0 · source#### fn by_ref(&mut self) -> &mut Selfwhere Self: Sized, Borrows an iterator, rather than consuming it. Read more1.0.0 · source#### fn collect<B>(self) -> Bwhere B: FromIterator<Self::Item>, Self: Sized, Transforms an iterator into a collection. E: Extend<Self::Item>, Self: Sized, 🔬This is a nightly-only experimental API. (`iter_collect_into`)Collects all the items from an iterator into a collection. Read more1.0.0 · source#### fn partition<B, F>(self, f: F) -> (B, B)where Self: Sized, B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool, Consumes an iterator, creating two collections from it. Self: Sized, P: FnMut(Self::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_is_partitioned`)Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. Read more1.27.0 · source#### fn try_fold<B, F, R>(&mut self, init: B, f: F) -> Rwhere Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>, An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more1.27.0 · source#### fn try_for_each<F, R>(&mut self, f: F) -> Rwhere Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Output = ()>, An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more1.0.0 · source#### fn fold<B, F>(self, init: B, f: F) -> Bwhere Self: Sized, F: FnMut(B, Self::Item) -> B, Folds every element into an accumulator by applying an operation, returning the final result. Read more1.51.0 · source#### fn reduce<F>(self, f: F) -> Option<Self::Item>where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Self::Item, Reduces the elements to a single one, by repeatedly applying a reducing operation. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryTypewhere Self: Sized, F: FnMut(Self::Item, Self::Item) -> R, R: Try<Output = Self::Item>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`iterator_try_reduce`)Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more1.0.0 · source#### fn all<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if every element of the iterator matches a predicate. Read more1.0.0 · source#### fn any<F>(&mut self, f: F) -> boolwhere Self: Sized, F: FnMut(Self::Item) -> bool, Tests if any element of the iterator matches a predicate. Read more1.0.0 · source#### fn find<P>(&mut self, predicate: P) -> Option<Self::Item>where Self: Sized, P: FnMut(&Self::Item) -> bool, Searches for an element of an iterator that satisfies a predicate. Read more1.30.0 · source#### fn find_map<B, F>(&mut self, f: F) -> Option<B>where Self: Sized, F: FnMut(Self::Item) -> Option<B>, Applies function to the elements of iterator and returns the first non-none result. &mut self, f: F ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryTypewhere Self: Sized, F: FnMut(&Self::Item) -> R, R: Try<Output = bool>, <R as Try>::Residual: Residual<Option<Self::Item>>, 🔬This is a nightly-only experimental API. (`try_find`)Applies function to the elements of iterator and returns the first true result or the first error. Read more1.0.0 · source#### fn position<P>(&mut self, predicate: P) -> Option<usize>where Self: Sized, P: FnMut(Self::Item) -> bool, Searches for an element in an iterator, returning its index. Read more1.6.0 · source#### fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the maximum value from the specified function. Read more1.15.0 · source#### fn max_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the maximum value with respect to the specified comparison function. Read more1.6.0 · source#### fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>where B: Ord, Self: Sized, F: FnMut(&Self::Item) -> B, Returns the element that gives the minimum value from the specified function. Read more1.15.0 · source#### fn min_by<F>(self, compare: F) -> Option<Self::Item>where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, Returns the element that gives the minimum value with respect to the specified comparison function. Read more1.0.0 · source#### fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Iterator<Item = (A, B)>, Converts an iterator of pairs into a pair of containers. Read more1.36.0 · source#### fn copied<'a, T>(self) -> Copied<Self> where T: 'a + Copy, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which copies all of its elements. Read more1.0.0 · source#### fn cloned<'a, T>(self) -> Cloned<Self> where T: 'a + Clone, Self: Sized + Iterator<Item = &'a T>, Creates an iterator which `clone`s all of its elements. Self: Sized, 🔬This is a nightly-only experimental API. (`iter_array_chunks`)Returns an iterator over `N` elements of the iterator at a time. Read more1.11.0 · source#### fn sum<S>(self) -> Swhere Self: Sized, S: Sum<Self::Item>, Sums the elements of an iterator. Read more1.11.0 · source#### fn product<P>(self) -> Pwhere Self: Sized, P: Product<Self::Item>, Iterates over the entire iterator, multiplying all the elements Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn partial_cmp<I>(self, other: I) -> Option<Ordering>where I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Lexicographically compares the `PartialOrd` elements of this `Iterator` with those of another. The comparison works like short-circuit evaluation, returning a result without comparing the remaining elements. As soon as an order can be determined, the evaluation stops and a result is returned. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`iter_order_by`)Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more1.5.0 · source#### fn eq<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are equal to those of another. Self: Sized, I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool, 🔬This is a nightly-only experimental API. (`iter_order_by`)Determines if the elements of this `Iterator` are equal to those of another with respect to the specified equality function. Read more1.5.0 · source#### fn ne<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialEq<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are not equal to those of another. Read more1.5.0 · source#### fn lt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less than those of another. Read more1.5.0 · source#### fn le<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically less or equal to those of another. Read more1.5.0 · source#### fn gt<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than those of another. Read more1.5.0 · source#### fn ge<I>(self, other: I) -> boolwhere I: IntoIterator, Self::Item: PartialOrd<<I as IntoIterator>::Item>, Self: Sized, Determines if the elements of this `Iterator` are lexicographically greater than or equal to those of another. Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given comparator function. Self: Sized, F: FnMut(Self::Item) -> K, K: PartialOrd<K>, 🔬This is a nightly-only experimental API. (`is_sorted`)Checks if the elements of this iterator are sorted using the given key extraction function. Read moreAuto Trait Implementations --- ### impl<I> RefUnwindSafe for ImportsIterator<I>where I: RefUnwindSafe, ### impl<I> Send for ImportsIterator<I>where I: Send, ### impl<I> Sync for ImportsIterator<I>where I: Sync, ### impl<I> Unpin for ImportsIterator<I>where I: Unpin, ### impl<I> UnwindSafe for ImportsIterator<I>where I: UnwindSafe, Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<I> IntoIterator for Iwhere I: Iterator, #### type Item = <I as Iterator>::Item The type of the elements being iterated over.#### type IntoIter = I Which kind of iterator are we turning this into?const: unstable · source#### fn into_iter(self) -> I Creates an iterator from a value. #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"ArrayChunks<Self, N>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.ArrayChunks.html\" title=\"struct wasmer_types::lib::std::iter::ArrayChunks\">ArrayChunks</a>&lt;I, N&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, const N: <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.ArrayChunks.html\" title=\"struct wasmer_types::lib::std::iter::ArrayChunks\">ArrayChunks</a>&lt;I, N&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = [&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.array.html\">N</a>];</span>","Chain<Self, <U as IntoIterator>::IntoIter>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Chain.html\" title=\"struct wasmer_types::lib::std::iter::Chain\">Chain</a>&lt;A, B&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A, B&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Chain.html\" title=\"struct wasmer_types::lib::std::iter::Chain\">Chain</a>&lt;A, B&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n B: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = &lt;A as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;A as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Cloned<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Cloned.html\" title=\"struct wasmer_types::lib::std::iter::Cloned\">Cloned</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, I, T&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Cloned.html\" title=\"struct wasmer_types::lib::std::iter::Cloned\">Cloned</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n T: 'a + <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html\" title=\"trait core::clone::Clone\">Clone</a>,\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = T;</span>","Copied<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Copied.html\" title=\"struct wasmer_types::lib::std::iter::Copied\">Copied</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;'a, I, T&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Copied.html\" title=\"struct wasmer_types::lib::std::iter::Copied\">Copied</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n T: 'a + <a class=\"trait\" href=\"lib/std/marker/trait.Copy.html\" title=\"trait wasmer_types::lib::std::marker::Copy\">Copy</a>,\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;'a T</a>&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = T;</span>","Enumerate<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Enumerate.html\" title=\"struct wasmer_types::lib::std::iter::Enumerate\">Enumerate</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Enumerate.html\" title=\"struct wasmer_types::lib::std::iter::Enumerate\">Enumerate</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>, &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>);</span>","Filter<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Filter.html\" title=\"struct wasmer_types::lib::std::iter::Filter\">Filter</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Filter.html\" title=\"struct wasmer_types::lib::std::iter::Filter\">Filter</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","FilterMap<Self, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.FilterMap.html\" title=\"struct wasmer_types::lib::std::iter::FilterMap\">FilterMap</a>&lt;I, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.FilterMap.html\" title=\"struct wasmer_types::lib::std::iter::FilterMap\">FilterMap</a>&lt;I, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/option/enum.Option.html\" title=\"enum core::option::Option\">Option</a>&lt;B&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","FlatMap<Self, U, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.FlatMap.html\" title=\"struct wasmer_types::lib::std::iter::FlatMap\">FlatMap</a>&lt;I, U, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, U, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.FlatMap.html\" title=\"struct wasmer_types::lib::std::iter::FlatMap\">FlatMap</a>&lt;I, U, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n U: <a class=\"trait\" href=\"lib/std/iter/trait.IntoIterator.html\" title=\"trait wasmer_types::lib::std::iter::IntoIterator\">IntoIterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; U,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;U as <a class=\"trait\" href=\"lib/std/iter/trait.IntoIterator.html\" title=\"trait wasmer_types::lib::std::iter::IntoIterator\">IntoIterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.IntoIterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::IntoIterator::Item\">Item</a>;</span>","Fuse<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Fuse.html\" title=\"struct wasmer_types::lib::std::iter::Fuse\">Fuse</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Fuse.html\" title=\"struct wasmer_types::lib::std::iter::Fuse\">Fuse</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Inspect<Self, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Inspect.html\" title=\"struct wasmer_types::lib::std::iter::Inspect\">Inspect</a>&lt;I, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Inspect.html\" title=\"struct wasmer_types::lib::std::iter::Inspect\">Inspect</a>&lt;I, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>),</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","IntersperseWith<Self, G>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.IntersperseWith.html\" title=\"struct wasmer_types::lib::std::iter::IntersperseWith\">IntersperseWith</a>&lt;I, G&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, G&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.IntersperseWith.html\" title=\"struct wasmer_types::lib::std::iter::IntersperseWith\">IntersperseWith</a>&lt;I, G&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n G: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>() -&gt; &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Map<Self, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Map.html\" title=\"struct wasmer_types::lib::std::iter::Map\">Map</a>&lt;I, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Map.html\" title=\"struct wasmer_types::lib::std::iter::Map\">Map</a>&lt;I, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; B,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","MapWhile<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.MapWhile.html\" title=\"struct wasmer_types::lib::std::iter::MapWhile\">MapWhile</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.MapWhile.html\" title=\"struct wasmer_types::lib::std::iter::MapWhile\">MapWhile</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/option/enum.Option.html\" title=\"enum core::option::Option\">Option</a>&lt;B&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","MapWindows<Self, F, N>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.MapWindows.html\" title=\"struct wasmer_types::lib::std::iter::MapWindows\">MapWindows</a>&lt;I, F, N&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, F, R, const N: <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.usize.html\">usize</a>&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.MapWindows.html\" title=\"struct wasmer_types::lib::std::iter::MapWindows\">MapWindows</a>&lt;I, F, N&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;[&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.array.html\">N</a>]) -&gt; R,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = R;</span>","Peekable<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Peekable.html\" title=\"struct wasmer_types::lib::std::iter::Peekable\">Peekable</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Peekable.html\" title=\"struct wasmer_types::lib::std::iter::Peekable\">Peekable</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Scan<Self, St, F>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Scan.html\" title=\"struct wasmer_types::lib::std::iter::Scan\">Scan</a>&lt;I, St, F&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;B, I, St, F&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Scan.html\" title=\"struct wasmer_types::lib::std::iter::Scan\">Scan</a>&lt;I, St, F&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n F: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.reference.html\">&amp;mut St</a>, &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"enum\" href=\"https://doc.rust-lang.org/nightly/core/option/enum.Option.html\" title=\"enum core::option::Option\">Option</a>&lt;B&gt;,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = B;</span>","Skip<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Skip.html\" title=\"struct wasmer_types::lib::std::iter::Skip\">Skip</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Skip.html\" title=\"struct wasmer_types::lib::std::iter::Skip\">Skip</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","SkipWhile<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.SkipWhile.html\" title=\"struct wasmer_types::lib::std::iter::SkipWhile\">SkipWhile</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.SkipWhile.html\" title=\"struct wasmer_types::lib::std::iter::SkipWhile\">SkipWhile</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","StepBy<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.StepBy.html\" title=\"struct wasmer_types::lib::std::iter::StepBy\">StepBy</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.StepBy.html\" title=\"struct wasmer_types::lib::std::iter::StepBy\">StepBy</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Take<Self>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Take.html\" title=\"struct wasmer_types::lib::std::iter::Take\">Take</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Take.html\" title=\"struct wasmer_types::lib::std::iter::Take\">Take</a>&lt;I&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","TakeWhile<Self, P>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.TakeWhile.html\" title=\"struct wasmer_types::lib::std::iter::TakeWhile\">TakeWhile</a>&lt;I, P&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I, P&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.TakeWhile.html\" title=\"struct wasmer_types::lib::std::iter::TakeWhile\">TakeWhile</a>&lt;I, P&gt;<span class=\"where fmt-newline\">where\n I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n P: <a class=\"trait\" href=\"lib/std/ops/trait.FnMut.html\" title=\"trait wasmer_types::lib::std::ops::FnMut\">FnMut</a>(&amp;&lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>) -&gt; <a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.bool.html\">bool</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = &lt;I as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>;</span>","Zip<Self, <U as IntoIterator>::IntoIter>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/iter/struct.Zip.html\" title=\"struct wasmer_types::lib::std::iter::Zip\">Zip</a>&lt;A, B&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A, B&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"lib/std/iter/struct.Zip.html\" title=\"struct wasmer_types::lib::std::iter::Zip\">Zip</a>&lt;A, B&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,\n B: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>,</span></span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = (&lt;A as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>, &lt;B as <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&gt;::<a class=\"associatedtype\" href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" title=\"type wasmer_types::lib::std::iter::Iterator::Item\">Item</a>);</span>"} Struct wasmer_types::LocalFunctionIndex === ``` pub struct LocalFunctionIndex(/* private fields */); ``` Index type of a function defined locally inside the WebAssembly module. Implementations --- ### impl LocalFunctionIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for LocalFunctionIndexwhere u32: Archive, #### type Archived = LocalFunctionIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> LocalFunctionIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<LocalFunctionIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for LocalFunctionIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for LocalFunctionIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &LocalFunctionIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &LocalFunctionIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<LocalFunctionIndex> for LocalFunctionIndex #### fn partial_cmp(&self, other: &LocalFunctionIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> LocalFunctionIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for LocalFunctionIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for LocalFunctionIndex ### impl Eq for LocalFunctionIndex ### impl StructuralEq for LocalFunctionIndex ### impl StructuralPartialEq for LocalFunctionIndex Auto Trait Implementations --- ### impl RefUnwindSafe for LocalFunctionIndex ### impl Send for LocalFunctionIndex ### impl Sync for LocalFunctionIndex ### impl Unpin for LocalFunctionIndex ### impl UnwindSafe for LocalFunctionIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::LocalGlobalIndex === ``` pub struct LocalGlobalIndex(/* private fields */); ``` Index type of a global defined locally inside the WebAssembly module. Implementations --- ### impl LocalGlobalIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for LocalGlobalIndexwhere u32: Archive, #### type Archived = LocalGlobalIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> LocalGlobalIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<LocalGlobalIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for LocalGlobalIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for LocalGlobalIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &LocalGlobalIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &LocalGlobalIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<LocalGlobalIndex> for LocalGlobalIndex #### fn partial_cmp(&self, other: &LocalGlobalIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> LocalGlobalIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for LocalGlobalIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for LocalGlobalIndex ### impl Eq for LocalGlobalIndex ### impl StructuralEq for LocalGlobalIndex ### impl StructuralPartialEq for LocalGlobalIndex Auto Trait Implementations --- ### impl RefUnwindSafe for LocalGlobalIndex ### impl Send for LocalGlobalIndex ### impl Sync for LocalGlobalIndex ### impl Unpin for LocalGlobalIndex ### impl UnwindSafe for LocalGlobalIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::LocalMemoryIndex === ``` pub struct LocalMemoryIndex(/* private fields */); ``` Index type of a memory defined locally inside the WebAssembly module. Implementations --- ### impl LocalMemoryIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Clone for LocalMemoryIndex #### fn clone(&self) -> LocalMemoryIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for LocalMemoryIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &LocalMemoryIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &LocalMemoryIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<LocalMemoryIndex> for LocalMemoryIndex #### fn partial_cmp(&self, other: &LocalMemoryIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> LocalMemoryIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl Copy for LocalMemoryIndex ### impl Eq for LocalMemoryIndex ### impl StructuralEq for LocalMemoryIndex ### impl StructuralPartialEq for LocalMemoryIndex Auto Trait Implementations --- ### impl RefUnwindSafe for LocalMemoryIndex ### impl Send for LocalMemoryIndex ### impl Sync for LocalMemoryIndex ### impl Unpin for LocalMemoryIndex ### impl UnwindSafe for LocalMemoryIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::LocalTableIndex === ``` pub struct LocalTableIndex(/* private fields */); ``` Index type of a table defined locally inside the WebAssembly module. Implementations --- ### impl LocalTableIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Clone for LocalTableIndex #### fn clone(&self) -> LocalTableIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for LocalTableIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &LocalTableIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &LocalTableIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<LocalTableIndex> for LocalTableIndex #### fn partial_cmp(&self, other: &LocalTableIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> LocalTableIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl Copy for LocalTableIndex ### impl Eq for LocalTableIndex ### impl StructuralEq for LocalTableIndex ### impl StructuralPartialEq for LocalTableIndex Auto Trait Implementations --- ### impl RefUnwindSafe for LocalTableIndex ### impl Send for LocalTableIndex ### impl Sync for LocalTableIndex ### impl Unpin for LocalTableIndex ### impl UnwindSafe for LocalTableIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::Memory32 === ``` pub struct Memory32; ``` Marker trait for 32-bit memories. Trait Implementations --- ### impl Clone for Memory32 #### fn clone(&self) -> Memory32 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### type Offset = u32 Type used to represent an offset into a memory. This is `u32` or `u64`.#### type Native = i32 Type used to pass this value as an argument or return value for a Wasm function.#### const ZERO: Self::Offset = {transmute(0x00000000): <memory::Memory32 as memory::MemorySize>::Offset} Zero value used for `WasmPtr::is_null`.#### const ONE: Self::Offset = {transmute(0x00000001): <memory::Memory32 as memory::MemorySize>::Offset} One value used for counting.#### fn offset_to_native(offset: Self::Offset) -> Self::Native Convert an `Offset` to a `Native`.#### fn native_to_offset(native: Self::Native) -> Self::Offset Convert a `Native` to an `Offset`.#### fn is_64bit() -> bool True if the memory is 64-bit### impl NativeWasmType for Memory32 #### const WASM_TYPE: Type = <<Self as MemorySize>::Native as NativeWasmType>::WASM_TYPE Type for this `NativeWasmType`.#### type Abi = <<Memory32 as MemorySize>::Native as NativeWasmType>::Abi The ABI for this type (i32, i64, f32, f64)### impl Copy for Memory32 Auto Trait Implementations --- ### impl RefUnwindSafe for Memory32 ### impl Send for Memory32 ### impl Sync for Memory32 ### impl Unpin for Memory32 ### impl UnwindSafe for Memory32 Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::Memory64 === ``` pub struct Memory64; ``` Marker trait for 64-bit memories. Trait Implementations --- ### impl Clone for Memory64 #### fn clone(&self) -> Memory64 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### type Offset = u64 Type used to represent an offset into a memory. This is `u32` or `u64`.#### type Native = i64 Type used to pass this value as an argument or return value for a Wasm function.#### const ZERO: Self::Offset = {transmute(0x0000000000000000): <memory::Memory64 as memory::MemorySize>::Offset} Zero value used for `WasmPtr::is_null`.#### const ONE: Self::Offset = {transmute(0x0000000000000001): <memory::Memory64 as memory::MemorySize>::Offset} One value used for counting.#### fn offset_to_native(offset: Self::Offset) -> Self::Native Convert an `Offset` to a `Native`.#### fn native_to_offset(native: Self::Native) -> Self::Offset Convert a `Native` to an `Offset`.#### fn is_64bit() -> bool True if the memory is 64-bit### impl NativeWasmType for Memory64 #### const WASM_TYPE: Type = <<Self as MemorySize>::Native as NativeWasmType>::WASM_TYPE Type for this `NativeWasmType`.#### type Abi = <<Memory64 as MemorySize>::Native as NativeWasmType>::Abi The ABI for this type (i32, i64, f32, f64)### impl Copy for Memory64 Auto Trait Implementations --- ### impl RefUnwindSafe for Memory64 ### impl Send for Memory64 ### impl Sync for Memory64 ### impl Unpin for Memory64 ### impl UnwindSafe for Memory64 Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::MemoryIndex === ``` pub struct MemoryIndex(/* private fields */); ``` Index type of a linear memory (imported or local) inside the WebAssembly module. Implementations --- ### impl MemoryIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for MemoryIndexwhere u32: Archive, #### type Archived = MemoryIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> MemoryIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<MemoryIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for MemoryIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for MemoryIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &MemoryIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &MemoryIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<MemoryIndex> for MemoryIndex #### fn partial_cmp(&self, other: &MemoryIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> MemoryIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for MemoryIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for MemoryIndex ### impl Eq for MemoryIndex ### impl StructuralEq for MemoryIndex ### impl StructuralPartialEq for MemoryIndex Auto Trait Implementations --- ### impl RefUnwindSafe for MemoryIndex ### impl Send for MemoryIndex ### impl Sync for MemoryIndex ### impl Unpin for MemoryIndex ### impl UnwindSafe for MemoryIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::MemoryType === ``` pub struct MemoryType { pub minimum: Pages, pub maximum: Option<Pages>, pub shared: bool, } ``` A descriptor for a WebAssembly memory type. Memories are described in units of pages (64KB) and represent contiguous chunks of addressable memory. Fields --- `minimum: Pages`The minimum number of pages in the memory. `maximum: Option<Pages>`The maximum number of pages in the memory. `shared: bool`Whether the memory may be shared between multiple threads. Implementations --- ### impl MemoryType #### pub fn new<IntoPages>( minimum: IntoPages, maximum: Option<IntoPages>, shared: bool ) -> Selfwhere IntoPages: Into<Pages>, Creates a new descriptor for a WebAssembly memory given the specified limits of the memory. Trait Implementations --- ### impl Archive for MemoryTypewhere Pages: Archive, Option<Pages>: Archive, bool: Archive, #### type Archived = ArchivedMemoryType The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> MemoryType Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Pages: Archive, Archived<Pages>: Deserialize<Pages, __D>, Option<Pages>: Archive, Archived<Option<Pages>>: Deserialize<Option<Pages>, __D>, bool: Archive, Archived<bool>: Deserialize<bool, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<MemoryType, __D::ErrorDeserializes using the given deserializer### impl Display for MemoryType #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &MemoryType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for MemoryTypewhere Pages: Serialize<__S>, Option<Pages>: Serialize<__S>, bool: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for MemoryType ### impl Eq for MemoryType ### impl StructuralEq for MemoryType ### impl StructuralPartialEq for MemoryType Auto Trait Implementations --- ### impl RefUnwindSafe for MemoryType ### impl Send for MemoryType ### impl Sync for MemoryType ### impl Unpin for MemoryType ### impl UnwindSafe for MemoryType Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::MetadataHeader === ``` #[repr(C)]pub struct MetadataHeader { /* private fields */ } ``` Metadata header which holds an ABI version and the length of the remaining metadata. Implementations --- ### impl MetadataHeader #### pub const CURRENT_VERSION: u32 = 5u32 Current ABI version. Increment this any time breaking changes are made to the format of the serialized data. #### pub const LEN: usize = 16usize Length of the metadata header. #### pub const ALIGN: usize = 16usize Alignment of the metadata. #### pub fn new(len: usize) -> Self Creates a new header for metadata of the given length. #### pub fn into_bytes(self) -> [u8; 16] Convert the header into its bytes representation. #### pub fn parse(bytes: &[u8]) -> Result<usize, DeserializeErrorParses the header and returns the length of the metadata following it. Trait Implementations --- ### impl Clone for MetadataHeader #### fn clone(&self) -> MetadataHeader Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Auto Trait Implementations --- ### impl RefUnwindSafe for MetadataHeader ### impl Send for MetadataHeader ### impl Sync for MetadataHeader ### impl Unpin for MetadataHeader ### impl UnwindSafe for MetadataHeader Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::ModuleInfo === ``` pub struct ModuleInfo { pub id: ModuleId, pub name: Option<String>, pub imports: IndexMap<ImportKey, ImportIndex>, pub exports: IndexMap<String, ExportIndex>, pub start_function: Option<FunctionIndex>, pub table_initializers: Vec<TableInitializer>, pub passive_elements: HashMap<ElemIndex, Box<[FunctionIndex]>>, pub passive_data: HashMap<DataIndex, Box<[u8]>>, pub global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>, pub function_names: HashMap<FunctionIndex, String>, pub signatures: PrimaryMap<SignatureIndex, FunctionType>, pub functions: PrimaryMap<FunctionIndex, SignatureIndex>, pub tables: PrimaryMap<TableIndex, TableType>, pub memories: PrimaryMap<MemoryIndex, MemoryType>, pub globals: PrimaryMap<GlobalIndex, GlobalType>, pub custom_sections: IndexMap<String, CustomSectionIndex>, pub custom_sections_data: PrimaryMap<CustomSectionIndex, Box<[u8]>>, pub num_imported_functions: usize, pub num_imported_tables: usize, pub num_imported_memories: usize, pub num_imported_globals: usize, } ``` A translated WebAssembly module, excluding the function bodies and memory initializers. Fields --- `id: ModuleId`A unique identifier (within this process) for this module. We skip serialization/deserialization of this field, as it should be computed by the process. It’s not skipped in rkyv, but that is okay, because even though it’s skipped in bincode/serde it’s still deserialized back as a garbage number, and later override from computed by the process `name: Option<String>`The name of this wasm module, often found in the wasm file. `imports: IndexMap<ImportKey, ImportIndex>`Imported entities with the (module, field, index_of_the_import) Keeping the `index_of_the_import` is important, as there can be two same references to the same import, and we don’t want to confuse them. `exports: IndexMap<String, ExportIndex>`Exported entities. `start_function: Option<FunctionIndex>`The module “start” function, if present. `table_initializers: Vec<TableInitializer>`WebAssembly table initializers. `passive_elements: HashMap<ElemIndex, Box<[FunctionIndex]>>`WebAssembly passive elements. `passive_data: HashMap<DataIndex, Box<[u8]>>`WebAssembly passive data segments. `global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>`WebAssembly global initializers. `function_names: HashMap<FunctionIndex, String>`WebAssembly function names. `signatures: PrimaryMap<SignatureIndex, FunctionType>`WebAssembly function signatures. `functions: PrimaryMap<FunctionIndex, SignatureIndex>`WebAssembly functions (imported and local). `tables: PrimaryMap<TableIndex, TableType>`WebAssembly tables (imported and local). `memories: PrimaryMap<MemoryIndex, MemoryType>`WebAssembly linear memories (imported and local). `globals: PrimaryMap<GlobalIndex, GlobalType>`WebAssembly global variables (imported and local). `custom_sections: IndexMap<String, CustomSectionIndex>`Custom sections in the module. `custom_sections_data: PrimaryMap<CustomSectionIndex, Box<[u8]>>`The data for each CustomSection in the module. `num_imported_functions: usize`Number of imported functions in the module. `num_imported_tables: usize`Number of imported tables in the module. `num_imported_memories: usize`Number of imported memories in the module. `num_imported_globals: usize`Number of imported globals in the module. Implementations --- ### impl ModuleInfo #### pub fn new() -> Self Allocates the module data structures. #### pub fn get_passive_element(&self, index: ElemIndex) -> Option<&[FunctionIndex]Get the given passive element, if it exists. #### pub fn exported_signatures(&self) -> Vec<FunctionTypeGet the exported signatures of the module #### pub fn exports(&self) -> ExportsIterator<impl Iterator<Item = ExportType> + '_Get the export types of the module #### pub fn imports(&self) -> ImportsIterator<impl Iterator<Item = ImportType> + '_Get the import types of the module #### pub fn custom_sections<'a>( &'a self, name: &'a str ) -> impl Iterator<Item = Box<[u8]>> + 'a Get the custom sections of the module given a `name`. #### pub fn func_index(&self, local_func: LocalFunctionIndex) -> FunctionIndex Convert a `LocalFunctionIndex` into a `FunctionIndex`. #### pub fn local_func_index( &self, func: FunctionIndex ) -> Option<LocalFunctionIndexConvert a `FunctionIndex` into a `LocalFunctionIndex`. Returns None if the index is an imported function. #### pub fn is_imported_function(&self, index: FunctionIndex) -> bool Test whether the given function index is for an imported function. #### pub fn table_index(&self, local_table: LocalTableIndex) -> TableIndex Convert a `LocalTableIndex` into a `TableIndex`. #### pub fn local_table_index(&self, table: TableIndex) -> Option<LocalTableIndexConvert a `TableIndex` into a `LocalTableIndex`. Returns None if the index is an imported table. #### pub fn is_imported_table(&self, index: TableIndex) -> bool Test whether the given table index is for an imported table. #### pub fn memory_index(&self, local_memory: LocalMemoryIndex) -> MemoryIndex Convert a `LocalMemoryIndex` into a `MemoryIndex`. #### pub fn local_memory_index( &self, memory: MemoryIndex ) -> Option<LocalMemoryIndexConvert a `MemoryIndex` into a `LocalMemoryIndex`. Returns None if the index is an imported memory. #### pub fn is_imported_memory(&self, index: MemoryIndex) -> bool Test whether the given memory index is for an imported memory. #### pub fn global_index(&self, local_global: LocalGlobalIndex) -> GlobalIndex Convert a `LocalGlobalIndex` into a `GlobalIndex`. #### pub fn local_global_index( &self, global: GlobalIndex ) -> Option<LocalGlobalIndexConvert a `GlobalIndex` into a `LocalGlobalIndex`. Returns None if the index is an imported global. #### pub fn is_imported_global(&self, index: GlobalIndex) -> bool Test whether the given global index is for an imported global. #### pub fn name(&self) -> String Get the Module name #### pub fn imported_function_types(&self) -> impl Iterator<Item = FunctionType> + '_ Get the imported function types of the module. Trait Implementations --- ### impl Archive for ModuleInfo #### type Archived = <ArchivableModuleInfo as Archive>::Archived The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> ModuleInfo Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> ModuleInfo Returns the “default value” for a type. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn eq(&self, other: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<S: Serializer + SharedSerializeRegistry + ScratchSpace + ?Sized> Serialize<S> for ModuleInfo #### fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for ModuleInfo Auto Trait Implementations --- ### impl RefUnwindSafe for ModuleInfo ### impl Send for ModuleInfo ### impl Sync for ModuleInfo ### impl Unpin for ModuleInfo ### impl UnwindSafe for ModuleInfo Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"ExportsIterator<impl Iterator<Item = ExportType> + '_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.ExportsIterator.html\" title=\"struct wasmer_types::ExportsIterator\">ExportsIterator</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = <a class=\"struct\" href=\"struct.ExportType.html\" title=\"struct wasmer_types::ExportType\">ExportType</a>&gt; + <a class=\"trait\" href=\"lib/std/marker/trait.Sized.html\" title=\"trait wasmer_types::lib::std::marker::Sized\">Sized</a>&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"struct.ExportsIterator.html\" title=\"struct wasmer_types::ExportsIterator\">ExportsIterator</a>&lt;I&gt;</span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"struct\" href=\"struct.ExportType.html\" title=\"struct wasmer_types::ExportType\">ExportType</a>;</span>","ImportsIterator<impl Iterator<Item = ImportType> + '_>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.ImportsIterator.html\" title=\"struct wasmer_types::ImportsIterator\">ImportsIterator</a>&lt;I&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;I: <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a>&lt;Item = <a class=\"struct\" href=\"struct.ImportType.html\" title=\"struct wasmer_types::ImportType\">ImportType</a>&gt; + <a class=\"trait\" href=\"lib/std/marker/trait.Sized.html\" title=\"trait wasmer_types::lib::std::marker::Sized\">Sized</a>&gt; <a class=\"trait\" href=\"lib/std/iter/trait.Iterator.html\" title=\"trait wasmer_types::lib::std::iter::Iterator\">Iterator</a> for <a class=\"struct\" href=\"struct.ImportsIterator.html\" title=\"struct wasmer_types::ImportsIterator\">ImportsIterator</a>&lt;I&gt;</span><span class=\"where fmt-newline\"> type <a href=\"lib/std/iter/trait.Iterator.html#associatedtype.Item\" class=\"associatedtype\">Item</a> = <a class=\"struct\" href=\"struct.ImportType.html\" title=\"struct wasmer_types::ImportType\">ImportType</a>;</span>"} Struct wasmer_types::PageCountOutOfRange === ``` pub struct PageCountOutOfRange; ``` The only error that can happen when converting `Bytes` to `Pages` Trait Implementations --- ### impl Clone for PageCountOutOfRange #### fn clone(&self) -> PageCountOutOfRange Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn eq(&self, other: &PageCountOutOfRange) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for PageCountOutOfRange ### impl Eq for PageCountOutOfRange ### impl StructuralEq for PageCountOutOfRange ### impl StructuralPartialEq for PageCountOutOfRange Auto Trait Implementations --- ### impl RefUnwindSafe for PageCountOutOfRange ### impl Send for PageCountOutOfRange ### impl Sync for PageCountOutOfRange ### impl Unpin for PageCountOutOfRange ### impl UnwindSafe for PageCountOutOfRange Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::Pages === ``` pub struct Pages(pub u32); ``` Units of WebAssembly pages (as specified to be 65,536 bytes). Tuple Fields --- `0: u32`Implementations --- ### impl Pages #### pub const fn max_value() -> Self Returns the largest value that can be represented by the Pages type. This is defined by the WebAssembly standard as 65,536 pages. #### pub fn checked_add(self, rhs: Self) -> Option<SelfChecked addition. Computes `self + rhs`, returning `None` if overflow occurred. #### pub fn bytes(self) -> Bytes Calculate number of bytes from pages. Trait Implementations --- ### impl<T> Add<T> for Pageswhere T: Into<Self>, #### type Output = Pages The resulting type after applying the `+` operator.#### fn add(self, rhs: T) -> Self Performs the `+` operation. u32: Archive, #### type Archived = Pages The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> Pages Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<Pages, __D::ErrorDeserializes using the given deserializer### impl From<Pages> for Bytes #### fn from(pages: Pages) -> Self Converts to this type from the input type.### impl From<u32> for Pages #### fn from(other: u32) -> Self Converts to this type from the input type.### impl Hash for Pages #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &Pages) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &Pages) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<Pages> for Pages #### fn partial_cmp(&self, other: &Pages) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl<T> Sub<T> for Pageswhere T: Into<Self>, #### type Output = Pages The resulting type after applying the `-` operator.#### fn sub(self, rhs: T) -> Self Performs the `-` operation. #### type Error = PageCountOutOfRange The type returned in the event of a conversion error.#### fn try_from(bytes: Bytes) -> Result<Self, Self::ErrorPerforms the conversion.### impl Copy for Pages ### impl Eq for Pages ### impl StructuralEq for Pages ### impl StructuralPartialEq for Pages Auto Trait Implementations --- ### impl RefUnwindSafe for Pages ### impl Send for Pages ### impl Sync for Pages ### impl Unpin for Pages ### impl UnwindSafe for Pages Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::SignatureIndex === ``` pub struct SignatureIndex(/* private fields */); ``` Index type of a signature (imported or local) inside the WebAssembly module. Implementations --- ### impl SignatureIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for SignatureIndexwhere u32: Archive, #### type Archived = SignatureIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> SignatureIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<SignatureIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for SignatureIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for SignatureIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &SignatureIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &SignatureIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<SignatureIndex> for SignatureIndex #### fn partial_cmp(&self, other: &SignatureIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> SignatureIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for SignatureIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for SignatureIndex ### impl Eq for SignatureIndex ### impl StructuralEq for SignatureIndex ### impl StructuralPartialEq for SignatureIndex Auto Trait Implementations --- ### impl RefUnwindSafe for SignatureIndex ### impl Send for SignatureIndex ### impl Sync for SignatureIndex ### impl Unpin for SignatureIndex ### impl UnwindSafe for SignatureIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::SourceLoc === ``` #[repr(transparent)]pub struct SourceLoc(/* private fields */); ``` A source location. The default source location uses the all-ones bit pattern `!0`. It is used for instructions that can’t be given a real source location. Implementations --- ### impl SourceLoc #### pub fn new(bits: u32) -> Self Create a new source location with the given bits. #### pub fn is_default(self) -> bool Is this the default source location? #### pub fn bits(self) -> u32 Read the bits of this source location. Trait Implementations --- ### impl Archive for SourceLocwhere u32: Archive, #### type Archived = SourceLoc The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> SourceLoc Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Self Returns the “default value” for a type. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<SourceLoc, __D::ErrorDeserializes using the given deserializer### impl Display for SourceLoc #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn eq(&self, other: &SourceLoc) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for SourceLocwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for SourceLoc ### impl Eq for SourceLoc ### impl StructuralEq for SourceLoc ### impl StructuralPartialEq for SourceLoc Auto Trait Implementations --- ### impl RefUnwindSafe for SourceLoc ### impl Send for SourceLoc ### impl Sync for SourceLoc ### impl Unpin for SourceLoc ### impl UnwindSafe for SourceLoc Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::StoreId === ``` pub struct StoreId(/* private fields */); ``` Unique ID to identify a context. Every handle to an object managed by a context also contains the ID of the context. This is used to check that a handle is always used with the correct context. Trait Implementations --- ### impl Clone for StoreId #### fn clone(&self) -> StoreId Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Self Returns the “default value” for a type. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &StoreId) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for StoreId ### impl Eq for StoreId ### impl StructuralEq for StoreId ### impl StructuralPartialEq for StoreId Auto Trait Implementations --- ### impl RefUnwindSafe for StoreId ### impl Send for StoreId ### impl Sync for StoreId ### impl Unpin for StoreId ### impl UnwindSafe for StoreId Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::TableIndex === ``` pub struct TableIndex(/* private fields */); ``` Index type of a table (imported or local) inside the WebAssembly module. Implementations --- ### impl TableIndex #### pub fn from_u32(x: u32) -> Self Create a new instance from a `u32`. #### pub fn as_u32(self) -> u32 Return the underlying index value as a `u32`. Trait Implementations --- ### impl Archive for TableIndexwhere u32: Archive, #### type Archived = TableIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u32: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> TableIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u32: Archive, Archived<u32>: Deserialize<u32, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<TableIndex, __D::ErrorDeserializes using the given deserializer### impl EntityRef for TableIndex #### fn new(index: usize) -> Self Create a new entity reference from a small integer. This should crash if the requested index is not representable.#### fn index(self) -> usize Get the index that was used to create this entity reference.### impl Hash for TableIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &TableIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &TableIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<TableIndex> for TableIndex #### fn partial_cmp(&self, other: &TableIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### fn reserved_value() -> TableIndex Create an instance of the reserved value.#### fn is_reserved_value(&self) -> bool Checks whether value is the reserved one.### impl<__S: Fallible + ?Sized> Serialize<__S> for TableIndexwhere u32: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for TableIndex ### impl Eq for TableIndex ### impl StructuralEq for TableIndex ### impl StructuralPartialEq for TableIndex Auto Trait Implementations --- ### impl RefUnwindSafe for TableIndex ### impl Send for TableIndex ### impl Sync for TableIndex ### impl Unpin for TableIndex ### impl UnwindSafe for TableIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::TableInitializer === ``` pub struct TableInitializer { pub table_index: TableIndex, pub base: Option<GlobalIndex>, pub offset: usize, pub elements: Box<[FunctionIndex]>, } ``` A WebAssembly table initializer. Fields --- `table_index: TableIndex`The index of a table to initialize. `base: Option<GlobalIndex>`Optionally, a global variable giving a base index. `offset: usize`The offset to add to the base. `elements: Box<[FunctionIndex]>`The values to write into the table elements. Trait Implementations --- ### impl Archive for TableInitializerwhere TableIndex: Archive, Option<GlobalIndex>: Archive, usize: Archive, Box<[FunctionIndex]>: Archive, #### type Archived = ArchivedTableInitializer The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> TableInitializer Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. TableIndex: Archive, Archived<TableIndex>: Deserialize<TableIndex, __D>, Option<GlobalIndex>: Archive, Archived<Option<GlobalIndex>>: Deserialize<Option<GlobalIndex>, __D>, usize: Archive, Archived<usize>: Deserialize<usize, __D>, Box<[FunctionIndex]>: Archive, Archived<Box<[FunctionIndex]>>: Deserialize<Box<[FunctionIndex]>, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<TableInitializer, __D::ErrorDeserializes using the given deserializer### impl Hash for TableInitializer #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &TableInitializer) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for TableInitializerwhere TableIndex: Serialize<__S>, Option<GlobalIndex>: Serialize<__S>, usize: Serialize<__S>, Box<[FunctionIndex]>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for TableInitializer ### impl StructuralEq for TableInitializer ### impl StructuralPartialEq for TableInitializer Auto Trait Implementations --- ### impl RefUnwindSafe for TableInitializer ### impl Send for TableInitializer ### impl Sync for TableInitializer ### impl Unpin for TableInitializer ### impl UnwindSafe for TableInitializer Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::TableType === ``` pub struct TableType { pub ty: Type, pub minimum: u32, pub maximum: Option<u32>, } ``` A descriptor for a table in a WebAssembly module. Tables are contiguous chunks of a specific element, typically a `funcref` or an `externref`. The most common use for tables is a function table through which `call_indirect` can invoke other functions. Fields --- `ty: Type`The type of data stored in elements of the table. `minimum: u32`The minimum number of elements in the table. `maximum: Option<u32>`The maximum number of elements in the table. Implementations --- ### impl TableType #### pub fn new(ty: Type, minimum: u32, maximum: Option<u32>) -> Self Creates a new table descriptor which will contain the specified `element` and have the `limits` applied to its length. Trait Implementations --- ### impl Archive for TableTypewhere Type: Archive, u32: Archive, Option<u32>: Archive, #### type Archived = ArchivedTableType The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### fn clone(&self) -> TableType Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Type: Archive, Archived<Type>: Deserialize<Type, __D>, u32: Archive, Archived<u32>: Deserialize<u32, __D>, Option<u32>: Archive, Archived<Option<u32>>: Deserialize<Option<u32>, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<TableType, __D::ErrorDeserializes using the given deserializer### impl Display for TableType #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &TableType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for TableTypewhere Type: Serialize<__S>, u32: Serialize<__S>, Option<u32>: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for TableType ### impl Eq for TableType ### impl StructuralEq for TableType ### impl StructuralPartialEq for TableType Auto Trait Implementations --- ### impl RefUnwindSafe for TableType ### impl Send for TableType ### impl Sync for TableType ### impl Unpin for TableType ### impl UnwindSafe for TableType Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::TargetSharedSignatureIndex === ``` pub struct TargetSharedSignatureIndex(/* private fields */); ``` Target specific type for shared signature index. Implementations --- ### impl TargetSharedSignatureIndex #### pub const fn new(value: u32) -> Self Constructs `TargetSharedSignatureIndex`. #### pub const fn index(self) -> u32 Returns index value. Trait Implementations --- ### impl Clone for TargetSharedSignatureIndex #### fn clone(&self) -> TargetSharedSignatureIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Auto Trait Implementations --- ### impl RefUnwindSafe for TargetSharedSignatureIndex ### impl Send for TargetSharedSignatureIndex ### impl Sync for TargetSharedSignatureIndex ### impl Unpin for TargetSharedSignatureIndex ### impl UnwindSafe for TargetSharedSignatureIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::TrapInformation === ``` pub struct TrapInformation { pub code_offset: CodeOffset, pub trap_code: TrapCode, } ``` Information about trap. Fields --- `code_offset: CodeOffset`The offset of the trapping instruction in native code. It is relative to the beginning of the function. `trap_code: TrapCode`Code of the trap. Trait Implementations --- ### impl Archive for TrapInformationwhere CodeOffset: Archive, TrapCode: Archive, #### type Archived = TrapInformation The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. CodeOffset: CheckBytes<__C>, TrapCode: CheckBytes<__C>, #### type Error = StructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, StructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> TrapInformation Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. CodeOffset: Archive, Archived<CodeOffset>: Deserialize<CodeOffset, __D>, TrapCode: Archive, Archived<TrapCode>: Deserialize<TrapCode, __D>, #### fn deserialize( &self, deserializer: &mut __D ) -> Result<TrapInformation, __D::ErrorDeserializes using the given deserializer### impl PartialEq<TrapInformation> for TrapInformation #### fn eq(&self, other: &TrapInformation) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for TrapInformationwhere CodeOffset: Serialize<__S>, TrapCode: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for TrapInformation ### impl StructuralEq for TrapInformation ### impl StructuralPartialEq for TrapInformation Auto Trait Implementations --- ### impl RefUnwindSafe for TrapInformation ### impl Send for TrapInformation ### impl Sync for TrapInformation ### impl Unpin for TrapInformation ### impl UnwindSafe for TrapInformation Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::Triple === ``` pub struct Triple { pub architecture: Architecture, pub vendor: Vendor, pub operating_system: OperatingSystem, pub environment: Environment, pub binary_format: BinaryFormat, } ``` A target “triple”. Historically such things had three fields, though they’ve added additional fields over time. Note that `Triple` doesn’t implement `Default` itself. If you want a type which defaults to the host triple, or defaults to unknown-unknown-unknown, use `DefaultToHost` or `DefaultToUnknown`, respectively. Fields --- `architecture: Architecture`The “architecture” (and sometimes the subarchitecture). `vendor: Vendor`The “vendor” (whatever that means). `operating_system: OperatingSystem`The “operating system” (sometimes also the environment). `environment: Environment`The “environment” on top of the operating system (often omitted for operating systems with a single predominant environment). `binary_format: BinaryFormat`The “binary format” (rarely used). Implementations --- ### impl Triple #### pub const fn host() -> Triple Return the triple for the current host. ### impl Triple #### pub fn endianness(&self) -> Result<Endianness, ()Return the endianness of this target’s architecture. #### pub fn pointer_width(&self) -> Result<PointerWidth, ()Return the pointer width of this target’s architecture. #### pub fn default_calling_convention(&self) -> Result<CallingConvention, ()Return the default calling convention for the given target triple. #### pub fn data_model(&self) -> Result<CDataModel, ()The C data model for a given target. If the model is not known, returns `Err(())`. #### pub fn unknown() -> Triple Return a `Triple` with all unknown fields. Trait Implementations --- ### impl Clone for Triple #### fn clone(&self) -> Triple Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = ParseError The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Triple, <Triple as FromStr>::ErrParses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Triple) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for Triple ### impl StructuralEq for Triple ### impl StructuralPartialEq for Triple Auto Trait Implementations --- ### impl RefUnwindSafe for Triple ### impl Send for Triple ### impl Sync for Triple ### impl Unpin for Triple ### impl UnwindSafe for Triple Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::V128 === ``` pub struct V128(/* private fields */); ``` The WebAssembly V128 type Implementations --- ### impl V128 #### pub fn bytes(&self) -> &[u8; 16] Get the bytes corresponding to the V128 value #### pub fn iter(&self) -> impl Iterator<Item = &u8Iterate over the bytes in the constant. #### pub fn to_vec(self) -> Vec<u8Convert the immediate into a vector. #### pub fn as_slice(&self) -> &[u8] Convert the immediate into a slice. Trait Implementations --- ### impl Archive for V128where [u8; 16]: Archive, #### type Archived = V128 The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: Self::Resolver, out: *mutSelf::Archived ) Creates the archived version of this value at the given position and writes it to the given output. [u8; 16]: CheckBytes<__C>, #### type Error = TupleStructCheckError The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, TupleStructCheckErrorChecks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> V128 Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. [u8; 16]: Archive, Archived<[u8; 16]>: Deserialize<[u8; 16], __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<V128, __D::ErrorDeserializes using the given deserializer### impl From<&[u8]> for V128 #### fn from(slice: &[u8]) -> Self Converts to this type from the input type.### impl From<[u8; 16]> for V128 #### fn from(array: [u8; 16]) -> Self Converts to this type from the input type.### impl Hash for V128 #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &V128) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for V128where [u8; 16]: Serialize<__S>, #### fn serialize(&self, serializer: &mut __S) -> Result<Self::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for V128 ### impl Eq for V128 ### impl StructuralEq for V128 ### impl StructuralPartialEq for V128 Auto Trait Implementations --- ### impl RefUnwindSafe for V128 ### impl Send for V128 ### impl Sync for V128 ### impl Unpin for V128 ### impl UnwindSafe for V128 Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.{"&[u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>","Vec<u8>":"<h3>Notable traits for <code><a class=\"struct\" href=\"lib/std/vec/struct.Vec.html\" title=\"struct wasmer_types::lib::std::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;</code></h3><pre><code><span class=\"where fmt-newline\">impl&lt;A&gt; <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Write.html\" title=\"trait std::io::Write\">Write</a> for <a class=\"struct\" href=\"lib/std/vec/struct.Vec.html\" title=\"struct wasmer_types::lib::std::vec::Vec\">Vec</a>&lt;<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>, A&gt;<span class=\"where fmt-newline\">where\n A: <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/core/alloc/trait.Allocator.html\" title=\"trait core::alloc::Allocator\">Allocator</a>,</span></span>"} Struct wasmer_types::VMBuiltinFunctionIndex === ``` pub struct VMBuiltinFunctionIndex(/* private fields */); ``` An index type for builtin functions. Implementations --- ### impl VMBuiltinFunctionIndex #### pub const fn get_memory32_grow_index() -> Self Returns an index for wasm’s `memory.grow` builtin function. #### pub const fn get_imported_memory32_grow_index() -> Self Returns an index for wasm’s imported `memory.grow` builtin function. #### pub const fn get_memory32_size_index() -> Self Returns an index for wasm’s `memory.size` builtin function. #### pub const fn get_imported_memory32_size_index() -> Self Returns an index for wasm’s imported `memory.size` builtin function. #### pub const fn get_table_copy_index() -> Self Returns an index for wasm’s `table.copy` when both tables are locally defined. #### pub const fn get_table_init_index() -> Self Returns an index for wasm’s `table.init`. #### pub const fn get_elem_drop_index() -> Self Returns an index for wasm’s `elem.drop`. #### pub const fn get_memory_copy_index() -> Self Returns an index for wasm’s `memory.copy` for locally defined memories. #### pub const fn get_imported_memory_copy_index() -> Self Returns an index for wasm’s `memory.copy` for imported memories. #### pub const fn get_memory_fill_index() -> Self Returns an index for wasm’s `memory.fill` for locally defined memories. #### pub const fn get_imported_memory_fill_index() -> Self Returns an index for wasm’s `memory.fill` for imported memories. #### pub const fn get_memory_init_index() -> Self Returns an index for wasm’s `memory.init` instruction. #### pub const fn get_data_drop_index() -> Self Returns an index for wasm’s `data.drop` instruction. #### pub const fn get_raise_trap_index() -> Self Returns an index for wasm’s `raise_trap` instruction. #### pub const fn get_table_size_index() -> Self Returns an index for wasm’s `table.size` instruction for local tables. #### pub const fn get_imported_table_size_index() -> Self Returns an index for wasm’s `table.size` instruction for imported tables. #### pub const fn get_table_grow_index() -> Self Returns an index for wasm’s `table.grow` instruction for local tables. #### pub const fn get_imported_table_grow_index() -> Self Returns an index for wasm’s `table.grow` instruction for imported tables. #### pub const fn get_table_get_index() -> Self Returns an index for wasm’s `table.get` instruction for local tables. #### pub const fn get_imported_table_get_index() -> Self Returns an index for wasm’s `table.get` instruction for imported tables. #### pub const fn get_table_set_index() -> Self Returns an index for wasm’s `table.set` instruction for local tables. #### pub const fn get_imported_table_set_index() -> Self Returns an index for wasm’s `table.set` instruction for imported tables. #### pub const fn get_func_ref_index() -> Self Returns an index for wasm’s `func.ref` instruction. #### pub const fn get_table_fill_index() -> Self Returns an index for wasm’s `table.fill` instruction for local tables. #### pub const fn get_memory_atomic_wait32_index() -> Self Returns an index for wasm’s local `memory.atomic.wait32` builtin function. #### pub const fn get_imported_memory_atomic_wait32_index() -> Self Returns an index for wasm’s imported `memory.atomic.wait32` builtin function. #### pub const fn get_memory_atomic_wait64_index() -> Self Returns an index for wasm’s local `memory.atomic.wait64` builtin function. #### pub const fn get_imported_memory_atomic_wait64_index() -> Self Returns an index for wasm’s imported `memory.atomic.wait64` builtin function. #### pub const fn get_memory_atomic_notify_index() -> Self Returns an index for wasm’s local `memory.atomic.notify` builtin function. #### pub const fn get_imported_memory_atomic_notify_index() -> Self Returns an index for wasm’s imported `memory.atomic.notify` builtin function. #### pub const fn builtin_functions_total_number() -> u32 Returns the total number of builtin functions. #### pub const fn index(self) -> u32 Return the index as an u32 number. Trait Implementations --- ### impl Clone for VMBuiltinFunctionIndex #### fn clone(&self) -> VMBuiltinFunctionIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Auto Trait Implementations --- ### impl RefUnwindSafe for VMBuiltinFunctionIndex ### impl Send for VMBuiltinFunctionIndex ### impl Sync for VMBuiltinFunctionIndex ### impl Unpin for VMBuiltinFunctionIndex ### impl UnwindSafe for VMBuiltinFunctionIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct wasmer_types::VMOffsets === ``` pub struct VMOffsets { /* private fields */ } ``` This class computes offsets to fields within VMContext and other related structs that JIT code accesses directly. Implementations --- ### impl VMOffsets #### pub fn new(pointer_size: u8, module: &ModuleInfo) -> Self Return a new `VMOffsets` instance, for a given pointer size. #### pub fn new_for_trampolines(pointer_size: u8) -> Self Return a new `VMOffsets` instance, for a given pointer size skipping the `ModuleInfo`. Note: This should only when generating code for trampolines. #### pub fn num_local_tables(&self) -> u32 Number of local tables defined in the module #### pub fn num_local_memories(&self) -> u32 Number of local memories defined in the module ### impl VMOffsets Offsets for `VMFunctionImport`. #### pub const fn vmfunction_import_body(&self) -> u8 The offset of the `body` field. #### pub const fn vmfunction_import_vmctx(&self) -> u8 The offset of the `vmctx` field. #### pub const fn vmfunction_import_handle(&self) -> u8 The offset of the `handle` field. #### pub const fn size_of_vmfunction_import(&self) -> u8 Return the size of `VMFunctionImport`. ### impl VMOffsets Offsets for `VMDynamicFunctionContext`. #### pub const fn vmdynamicfunction_import_context_address(&self) -> u8 The offset of the `address` field. #### pub const fn vmdynamicfunction_import_context_ctx(&self) -> u8 The offset of the `ctx` field. #### pub const fn size_of_vmdynamicfunction_import_context(&self) -> u8 Return the size of `VMDynamicFunctionContext`. ### impl VMOffsets Offsets for `*const VMFunctionBody`. #### pub const fn size_of_vmfunction_body_ptr(&self) -> u8 The size of the `current_elements` field. ### impl VMOffsets Offsets for `VMTableImport`. #### pub const fn vmtable_import_definition(&self) -> u8 The offset of the `definition` field. #### pub const fn vmtable_import_handle(&self) -> u8 The offset of the `handle` field. #### pub const fn size_of_vmtable_import(&self) -> u8 Return the size of `VMTableImport`. ### impl VMOffsets Offsets for `VMTableDefinition`. #### pub const fn vmtable_definition_base(&self) -> u8 The offset of the `base` field. #### pub const fn vmtable_definition_current_elements(&self) -> u8 The offset of the `current_elements` field. #### pub const fn size_of_vmtable_definition_current_elements(&self) -> u8 The size of the `current_elements` field. #### pub const fn size_of_vmtable_definition(&self) -> u8 Return the size of `VMTableDefinition`. ### impl VMOffsets Offsets for `VMMemoryImport`. #### pub const fn vmmemory_import_definition(&self) -> u8 The offset of the `from` field. #### pub const fn vmmemory_import_handle(&self) -> u8 The offset of the `handle` field. #### pub const fn size_of_vmmemory_import(&self) -> u8 Return the size of `VMMemoryImport`. ### impl VMOffsets Offsets for `VMMemoryDefinition`. #### pub const fn vmmemory_definition_base(&self) -> u8 The offset of the `base` field. #### pub const fn vmmemory_definition_current_length(&self) -> u8 The offset of the `current_length` field. #### pub const fn size_of_vmmemory_definition_current_length(&self) -> u8 The size of the `current_length` field. #### pub const fn size_of_vmmemory_definition(&self) -> u8 Return the size of `VMMemoryDefinition`. ### impl VMOffsets Offsets for `VMGlobalImport`. #### pub const fn vmglobal_import_definition(&self) -> u8 The offset of the `definition` field. #### pub const fn vmglobal_import_handle(&self) -> u8 The offset of the `handle` field. #### pub const fn size_of_vmglobal_import(&self) -> u8 Return the size of `VMGlobalImport`. ### impl VMOffsets Offsets for a non-null pointer to a `VMGlobalDefinition` used as a local global. #### pub const fn size_of_vmglobal_local(&self) -> u8 Return the size of a pointer to a `VMGlobalDefinition`; The underlying global itself is the size of the largest value type (i.e. a V128), however the size of this type is just the size of a pointer. ### impl VMOffsets Offsets for `VMSharedSignatureIndex`. #### pub const fn size_of_vmshared_signature_index(&self) -> u8 Return the size of `VMSharedSignatureIndex`. ### impl VMOffsets Offsets for `VMCallerCheckedAnyfunc`. #### pub const fn vmcaller_checked_anyfunc_func_ptr(&self) -> u8 The offset of the `func_ptr` field. #### pub const fn vmcaller_checked_anyfunc_type_index(&self) -> u8 The offset of the `type_index` field. #### pub const fn vmcaller_checked_anyfunc_vmctx(&self) -> u8 The offset of the `vmctx` field. #### pub const fn vmcaller_checked_anyfunc_call_trampoline(&self) -> u8 The offset of the `call_trampoline` field. #### pub const fn size_of_vmcaller_checked_anyfunc(&self) -> u8 Return the size of `VMCallerCheckedAnyfunc`. ### impl VMOffsets Offsets for `VMFuncRef`. #### pub const fn vm_funcref_anyfunc_ptr(&self) -> u8 The offset to the pointer to the anyfunc inside the ref. #### pub const fn size_of_vm_funcref(&self) -> u8 Return the size of `VMFuncRef`. ### impl VMOffsets Offsets for `VMContext`. #### pub fn vmctx_signature_ids_begin(&self) -> u32 The offset of the `signature_ids` array. #### pub fn vmctx_imported_functions_begin(&self) -> u32 The offset of the `tables` array. #### pub fn vmctx_imported_tables_begin(&self) -> u32 The offset of the `tables` array. #### pub fn vmctx_imported_memories_begin(&self) -> u32 The offset of the `memories` array. #### pub fn vmctx_imported_globals_begin(&self) -> u32 The offset of the `globals` array. #### pub fn vmctx_tables_begin(&self) -> u32 The offset of the `tables` array. #### pub fn vmctx_memories_begin(&self) -> u32 The offset of the `memories` array. #### pub fn vmctx_globals_begin(&self) -> u32 The offset of the `globals` array. #### pub fn vmctx_builtin_functions_begin(&self) -> u32 The offset of the builtin functions array. #### pub fn size_of_vmctx(&self) -> u32 Return the size of the `VMContext` allocation. #### pub fn vmctx_vmshared_signature_id(&self, index: SignatureIndex) -> u32 Return the offset to `VMSharedSignatureIndex` index `index`. #### pub fn vmctx_vmfunction_import(&self, index: FunctionIndex) -> u32 Return the offset to `VMFunctionImport` index `index`. #### pub fn vmctx_vmtable_import(&self, index: TableIndex) -> u32 Return the offset to `VMTableImport` index `index`. #### pub fn vmctx_vmmemory_import(&self, index: MemoryIndex) -> u32 Return the offset to `VMMemoryImport` index `index`. #### pub fn vmctx_vmglobal_import(&self, index: GlobalIndex) -> u32 Return the offset to `VMGlobalImport` index `index`. #### pub fn vmctx_vmtable_definition(&self, index: LocalTableIndex) -> u32 Return the offset to `VMTableDefinition` index `index`. #### pub fn vmctx_vmmemory_definition(&self, index: LocalMemoryIndex) -> u32 Return the offset to `VMMemoryDefinition` index `index`. #### pub fn vmctx_vmglobal_definition(&self, index: LocalGlobalIndex) -> u32 Return the offset to the `VMGlobalDefinition` index `index`. #### pub fn vmctx_vmfunction_import_body(&self, index: FunctionIndex) -> u32 Return the offset to the `body` field in `*const VMFunctionBody` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmfunction_import_vmctx(&self, index: FunctionIndex) -> u32 Return the offset to the `vmctx` field in `*const VMFunctionBody` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmtable_import_definition(&self, index: TableIndex) -> u32 Return the offset to the `definition` field in `VMTableImport` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmtable_definition_base(&self, index: LocalTableIndex) -> u32 Return the offset to the `base` field in `VMTableDefinition` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmtable_definition_current_elements( &self, index: LocalTableIndex ) -> u32 Return the offset to the `current_elements` field in `VMTableDefinition` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmmemory_import_definition(&self, index: MemoryIndex) -> u32 Return the offset to the `from` field in `VMMemoryImport` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmmemory_import_handle(&self, index: MemoryIndex) -> u32 Return the offset to the `vmctx` field in `VMMemoryImport` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmmemory_definition_base(&self, index: LocalMemoryIndex) -> u32 Return the offset to the `base` field in `VMMemoryDefinition` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmmemory_definition_current_length( &self, index: LocalMemoryIndex ) -> u32 Return the offset to the `current_length` field in `VMMemoryDefinition` index `index`. Remember updating precompute upon changes #### pub fn vmctx_vmglobal_import_definition(&self, index: GlobalIndex) -> u32 Return the offset to the `from` field in `VMGlobalImport` index `index`. Remember updating precompute upon changes #### pub fn vmctx_builtin_function(&self, index: VMBuiltinFunctionIndex) -> u32 Return the offset to builtin function in `VMBuiltinFunctionsArray` index `index`. Remember updating precompute upon changes Trait Implementations --- ### impl Clone for VMOffsets #### fn clone(&self) -> VMOffsets Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for VMOffsets ### impl Send for VMOffsets ### impl Sync for VMOffsets ### impl Unpin for VMOffsets ### impl UnwindSafe for VMOffsets Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::Aarch64Architecture === ``` pub enum Aarch64Architecture { Aarch64, Aarch64be, } ``` Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### Aarch64 ### Aarch64be Implementations --- ### impl Aarch64Architecture #### pub fn is_thumb(self) -> bool Test if this architecture uses the Thumb instruction set. #### pub fn pointer_width(self) -> PointerWidth Return the pointer bit width of this target’s architecture. #### pub fn endianness(self) -> Endianness Return the endianness of this architecture. #### pub fn into_str(self) -> Cow<'static, strConvert into a string Trait Implementations --- ### impl Clone for Aarch64Architecture #### fn clone(&self) -> Aarch64Architecture Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = () The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Aarch64Architecture, ()Parses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Aarch64Architecture) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for Aarch64Architecture ### impl Eq for Aarch64Architecture ### impl StructuralEq for Aarch64Architecture ### impl StructuralPartialEq for Aarch64Architecture Auto Trait Implementations --- ### impl RefUnwindSafe for Aarch64Architecture ### impl Send for Aarch64Architecture ### impl Sync for Aarch64Architecture ### impl Unpin for Aarch64Architecture ### impl UnwindSafe for Aarch64Architecture Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::Architecture === ``` pub enum Architecture { Unknown, Arm(ArmArchitecture), AmdGcn, Aarch64(Aarch64Architecture), Asmjs, Avr, Bpfeb, Bpfel, Hexagon, X86_32(X86_32Architecture), M68k, LoongArch64, Mips32(Mips32Architecture), Mips64(Mips64Architecture), Msp430, Nvptx64, Powerpc, Powerpc64, Powerpc64le, Riscv32(Riscv32Architecture), Riscv64(Riscv64Architecture), S390x, Sparc, Sparc64, Sparcv9, Wasm32, Wasm64, X86_64, X86_64h, XTensa, Clever(CleverArchitecture), } ``` The “architecture” field, which in some cases also specifies a specific subarchitecture. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### Unknown ### Arm(ArmArchitecture) ### AmdGcn ### Aarch64(Aarch64Architecture) ### Asmjs ### Avr ### Bpfeb ### Bpfel ### Hexagon ### X86_32(X86_32Architecture) ### M68k ### LoongArch64 ### Mips32(Mips32Architecture) ### Mips64(Mips64Architecture) ### Msp430 ### Nvptx64 ### Powerpc ### Powerpc64 ### Powerpc64le ### Riscv32(Riscv32Architecture) ### Riscv64(Riscv64Architecture) ### S390x ### Sparc ### Sparc64 ### Sparcv9 ### Wasm32 ### Wasm64 ### X86_64 ### X86_64h x86_64 target that only supports Haswell-compatible Intel chips. ### XTensa ### Clever(CleverArchitecture) Implementations --- ### impl Architecture #### pub const fn host() -> Architecture Return the architecture for the current host. ### impl Architecture #### pub fn endianness(self) -> Result<Endianness, ()Return the endianness of this architecture. #### pub fn pointer_width(self) -> Result<PointerWidth, ()Return the pointer bit width of this target’s architecture. #### pub fn is_clever(&self) -> bool Checks if this Architecture is some variant of Clever-ISA #### pub fn into_str(self) -> Cow<'static, strConvert into a string Trait Implementations --- ### impl Clone for Architecture #### fn clone(&self) -> Architecture Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = () The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Architecture, ()Parses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Architecture) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for Architecture ### impl Eq for Architecture ### impl StructuralEq for Architecture ### impl StructuralPartialEq for Architecture Auto Trait Implementations --- ### impl RefUnwindSafe for Architecture ### impl Send for Architecture ### impl Sync for Architecture ### impl Unpin for Architecture ### impl UnwindSafe for Architecture Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::BinaryFormat === ``` pub enum BinaryFormat { Unknown, Elf, Coff, Macho, Wasm, Xcoff, } ``` The “binary format” field, which is usually omitted, and the binary format is implied by the other fields. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### Unknown ### Elf ### Coff ### Macho ### Wasm ### Xcoff Implementations --- ### impl BinaryFormat #### pub const fn host() -> BinaryFormat Return the binary format for the current host. ### impl BinaryFormat #### pub fn into_str(self) -> Cow<'static, strConvert into a string Trait Implementations --- ### impl Clone for BinaryFormat #### fn clone(&self) -> BinaryFormat Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = () The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<BinaryFormat, ()Parses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &BinaryFormat) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for BinaryFormat ### impl Eq for BinaryFormat ### impl StructuralEq for BinaryFormat ### impl StructuralPartialEq for BinaryFormat Auto Trait Implementations --- ### impl RefUnwindSafe for BinaryFormat ### impl Send for BinaryFormat ### impl Sync for BinaryFormat ### impl Unpin for BinaryFormat ### impl UnwindSafe for BinaryFormat Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::CallingConvention === ``` pub enum CallingConvention { SystemV, WasmBasicCAbi, WindowsFastcall, AppleAarch64, } ``` The calling convention, which specifies things like which registers are used for passing arguments, which registers are callee-saved, and so on. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### SystemV “System V”, which is used on most Unix-like platfoms. Note that the specific conventions vary between hardware architectures; for example, x86-32’s “System V” is entirely different from x86-64’s “System V”. ### WasmBasicCAbi The WebAssembly C ABI. https://github.com/WebAssembly/tool-conventions/blob/master/BasicCABI.md ### WindowsFastcall “Windows Fastcall”, which is used on Windows. Note that like “System V”, this varies between hardware architectures. On x86-32 it describes what Windows documentation calls “fastcall”, and on x86-64 it describes what Windows documentation often just calls the Windows x64 calling convention (though the compiler still recognizes “fastcall” as an alias for it). ### AppleAarch64 Apple Aarch64 platforms use their own variant of the common Aarch64 calling convention. https://developer.apple.com/documentation/xcode/writing_arm64_code_for_apple_platforms Trait Implementations --- ### impl Clone for CallingConvention #### fn clone(&self) -> CallingConvention Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &CallingConvention) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for CallingConvention ### impl Eq for CallingConvention ### impl StructuralEq for CallingConvention ### impl StructuralPartialEq for CallingConvention Auto Trait Implementations --- ### impl RefUnwindSafe for CallingConvention ### impl Send for CallingConvention ### impl Sync for CallingConvention ### impl Unpin for CallingConvention ### impl UnwindSafe for CallingConvention Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::Endianness === ``` pub enum Endianness { Little, Big, } ``` The target memory endianness. Variants --- ### Little ### Big Trait Implementations --- ### impl Clone for Endianness #### fn clone(&self) -> Endianness Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Endianness) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for Endianness ### impl Eq for Endianness ### impl StructuralEq for Endianness ### impl StructuralPartialEq for Endianness Auto Trait Implementations --- ### impl RefUnwindSafe for Endianness ### impl Send for Endianness ### impl Sync for Endianness ### impl Unpin for Endianness ### impl UnwindSafe for Endianness Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::Environment === ``` pub enum Environment { Unknown, AmdGiz, Android, Androideabi, Eabi, Eabihf, Gnu, Gnuabi64, Gnueabi, Gnueabihf, Gnuspe, Gnux32, GnuIlp32, GnuLlvm, HermitKernel, LinuxKernel, Macabi, Musl, Musleabi, Musleabihf, Muslabi64, Msvc, Newlib, Kernel, Uclibc, Uclibceabi, Uclibceabihf, Sgx, Sim, Softfloat, Spe, } ``` The “environment” field, which specifies an ABI environment on top of the operating system. In many configurations, this field is omitted, and the environment is implied by the operating system. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### Unknown ### AmdGiz ### Android ### Androideabi ### Eabi ### Eabihf ### Gnu ### Gnuabi64 ### Gnueabi ### Gnueabihf ### Gnuspe ### Gnux32 ### GnuIlp32 ### GnuLlvm ### HermitKernel ### LinuxKernel ### Macabi ### Musl ### Musleabi ### Musleabihf ### Muslabi64 ### Msvc ### Newlib ### Kernel ### Uclibc ### Uclibceabi ### Uclibceabihf ### Sgx ### Sim ### Softfloat ### Spe Implementations --- ### impl Environment #### pub const fn host() -> Environment Return the environment for the current host. ### impl Environment #### pub fn into_str(self) -> Cow<'static, strConvert into a string Trait Implementations --- ### impl Clone for Environment #### fn clone(&self) -> Environment Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = () The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Environment, ()Parses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Environment) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for Environment ### impl Eq for Environment ### impl StructuralEq for Environment ### impl StructuralPartialEq for Environment Auto Trait Implementations --- ### impl RefUnwindSafe for Environment ### impl Send for Environment ### impl Sync for Environment ### impl Unpin for Environment ### impl UnwindSafe for Environment Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::ExportIndex === ``` #[repr(u8)]pub enum ExportIndex { Function(FunctionIndex), Table(TableIndex), Memory(MemoryIndex), Global(GlobalIndex), } ``` An entity to export. Variants --- ### Function(FunctionIndex) Function export. ### Table(TableIndex) Table export. ### Memory(MemoryIndex) Memory export. ### Global(GlobalIndex) Global export. Trait Implementations --- ### impl Archive for ExportIndexwhere FunctionIndex: Archive, TableIndex: Archive, MemoryIndex: Archive, GlobalIndex: Archive, #### type Archived = ExportIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. FunctionIndex: CheckBytes<__C>, TableIndex: CheckBytes<__C>, MemoryIndex: CheckBytes<__C>, GlobalIndex: CheckBytes<__C>, #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> ExportIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. FunctionIndex: Archive, Archived<FunctionIndex>: Deserialize<FunctionIndex, __D>, TableIndex: Archive, Archived<TableIndex>: Deserialize<TableIndex, __D>, MemoryIndex: Archive, Archived<MemoryIndex>: Deserialize<MemoryIndex, __D>, GlobalIndex: Archive, Archived<GlobalIndex>: Deserialize<GlobalIndex, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<ExportIndex, __D::ErrorDeserializes using the given deserializer### impl Hash for ExportIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &ExportIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &ExportIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<ExportIndex> for ExportIndex #### fn partial_cmp(&self, other: &ExportIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. FunctionIndex: Serialize<__S>, TableIndex: Serialize<__S>, MemoryIndex: Serialize<__S>, GlobalIndex: Serialize<__S>, #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for ExportIndex ### impl Eq for ExportIndex ### impl StructuralEq for ExportIndex ### impl StructuralPartialEq for ExportIndex Auto Trait Implementations --- ### impl RefUnwindSafe for ExportIndex ### impl Send for ExportIndex ### impl Sync for ExportIndex ### impl Unpin for ExportIndex ### impl UnwindSafe for ExportIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::ExternType === ``` pub enum ExternType { Function(FunctionType), Global(GlobalType), Table(TableType), Memory(MemoryType), } ``` A list of all possible types which can be externally referenced from a WebAssembly module. This list can be found in `ImportType` or `ExportType`, so these types can either be imported or exported. Variants --- ### Function(FunctionType) This external type is the type of a WebAssembly function. ### Global(GlobalType) This external type is the type of a WebAssembly global. ### Table(TableType) This external type is the type of a WebAssembly table. ### Memory(MemoryType) This external type is the type of a WebAssembly memory. Implementations --- ### impl ExternType #### pub fn func(&self) -> Option<&FunctionTypeAttempt to return the underlying type of this external type, returning `None` if it is a different type. #### pub fn unwrap_func(&self) -> &FunctionType Returns the underlying descriptor of this `ExternType`, panicking if it is a different type. ##### Panics Panics if `self` is not of the right type. #### pub fn global(&self) -> Option<&GlobalTypeAttempt to return the underlying type of this external type, returning `None` if it is a different type. #### pub fn unwrap_global(&self) -> &GlobalType Returns the underlying descriptor of this `ExternType`, panicking if it is a different type. ##### Panics Panics if `self` is not of the right type. #### pub fn table(&self) -> Option<&TableTypeAttempt to return the underlying type of this external type, returning `None` if it is a different type. #### pub fn unwrap_table(&self) -> &TableType Returns the underlying descriptor of this `ExternType`, panicking if it is a different type. ##### Panics Panics if `self` is not of the right type. #### pub fn memory(&self) -> Option<&MemoryTypeAttempt to return the underlying type of this external type, returning `None` if it is a different type. #### pub fn unwrap_memory(&self) -> &MemoryType Returns the underlying descriptor of this `ExternType`, panicking if it is a different type. ##### Panics Panics if `self` is not of the right type. #### pub fn is_compatible_with( &self, other: &Self, runtime_size: Option<u32> ) -> bool Check if two externs are compatible Trait Implementations --- ### impl Clone for ExternType #### fn clone(&self) -> ExternType Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &ExternType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for ExternType ### impl StructuralEq for ExternType ### impl StructuralPartialEq for ExternType Auto Trait Implementations --- ### impl RefUnwindSafe for ExternType ### impl Send for ExternType ### impl Sync for ExternType ### impl Unpin for ExternType ### impl UnwindSafe for ExternType Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::GlobalInit === ``` #[repr(u8)]pub enum GlobalInit { I32Const(i32), I64Const(i64), F32Const(f32), F64Const(f64), V128Const(V128), GetGlobal(GlobalIndex), RefNullConst, RefFunc(FunctionIndex), } ``` Globals are initialized via the `const` operators or by referring to another import. Variants --- ### I32Const(i32) An `i32.const`. ### I64Const(i64) An `i64.const`. ### F32Const(f32) An `f32.const`. ### F64Const(f64) An `f64.const`. ### V128Const(V128) A `v128.const`. ### GetGlobal(GlobalIndex) A `global.get` of another global. ### RefNullConst A `ref.null`. ### RefFunc(FunctionIndex) A `ref.func <index>`. Trait Implementations --- ### impl Archive for GlobalInitwhere i32: Archive, i64: Archive, f32: Archive, f64: Archive, V128: Archive, GlobalIndex: Archive, FunctionIndex: Archive, #### type Archived = GlobalInit The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. i32: CheckBytes<__C>, i64: CheckBytes<__C>, f32: CheckBytes<__C>, f64: CheckBytes<__C>, V128: CheckBytes<__C>, GlobalIndex: CheckBytes<__C>, FunctionIndex: CheckBytes<__C>, #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> GlobalInit Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. i32: Archive, Archived<i32>: Deserialize<i32, __D>, i64: Archive, Archived<i64>: Deserialize<i64, __D>, f32: Archive, Archived<f32>: Deserialize<f32, __D>, f64: Archive, Archived<f64>: Deserialize<f64, __D>, V128: Archive, Archived<V128>: Deserialize<V128, __D>, GlobalIndex: Archive, Archived<GlobalIndex>: Deserialize<GlobalIndex, __D>, FunctionIndex: Archive, Archived<FunctionIndex>: Deserialize<FunctionIndex, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<GlobalInit, __D::ErrorDeserializes using the given deserializer### impl PartialEq<GlobalInit> for GlobalInit #### fn eq(&self, other: &GlobalInit) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for GlobalInitwhere i32: Serialize<__S>, i64: Serialize<__S>, f32: Serialize<__S>, f64: Serialize<__S>, V128: Serialize<__S>, GlobalIndex: Serialize<__S>, FunctionIndex: Serialize<__S>, #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for GlobalInit ### impl StructuralPartialEq for GlobalInit Auto Trait Implementations --- ### impl RefUnwindSafe for GlobalInit ### impl Send for GlobalInit ### impl Sync for GlobalInit ### impl Unpin for GlobalInit ### impl UnwindSafe for GlobalInit Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::ImportIndex === ``` #[repr(u8)]pub enum ImportIndex { Function(FunctionIndex), Table(TableIndex), Memory(MemoryIndex), Global(GlobalIndex), } ``` An entity to import. Variants --- ### Function(FunctionIndex) Function import. ### Table(TableIndex) Table import. ### Memory(MemoryIndex) Memory import. ### Global(GlobalIndex) Global import. Trait Implementations --- ### impl Archive for ImportIndexwhere FunctionIndex: Archive, TableIndex: Archive, MemoryIndex: Archive, GlobalIndex: Archive, #### type Archived = ImportIndex The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. FunctionIndex: CheckBytes<__C>, TableIndex: CheckBytes<__C>, MemoryIndex: CheckBytes<__C>, GlobalIndex: CheckBytes<__C>, #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> ImportIndex Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. FunctionIndex: Archive, Archived<FunctionIndex>: Deserialize<FunctionIndex, __D>, TableIndex: Archive, Archived<TableIndex>: Deserialize<TableIndex, __D>, MemoryIndex: Archive, Archived<MemoryIndex>: Deserialize<MemoryIndex, __D>, GlobalIndex: Archive, Archived<GlobalIndex>: Deserialize<GlobalIndex, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<ImportIndex, __D::ErrorDeserializes using the given deserializer### impl Hash for ImportIndex #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn cmp(&self, other: &ImportIndex) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &ImportIndex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialOrd<ImportIndex> for ImportIndex #### fn partial_cmp(&self, other: &ImportIndex) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. Read more1.0.0 · source#### fn lt(&self, other: &Rhs) -> bool This method tests less than (for `self` and `other`) and is used by the `<` operator. Read more1.0.0 · source#### fn le(&self, other: &Rhs) -> bool This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. Read more1.0.0 · source#### fn gt(&self, other: &Rhs) -> bool This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.0.0 · source#### fn ge(&self, other: &Rhs) -> bool This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. FunctionIndex: Serialize<__S>, TableIndex: Serialize<__S>, MemoryIndex: Serialize<__S>, GlobalIndex: Serialize<__S>, #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for ImportIndex ### impl StructuralEq for ImportIndex ### impl StructuralPartialEq for ImportIndex Auto Trait Implementations --- ### impl RefUnwindSafe for ImportIndex ### impl Send for ImportIndex ### impl Sync for ImportIndex ### impl Unpin for ImportIndex ### impl UnwindSafe for ImportIndex Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::LibCall === ``` #[repr(u16)]pub enum LibCall { CeilF32, CeilF64, FloorF32, FloorF64, NearestF32, NearestF64, TruncF32, TruncF64, Memory32Size, ImportedMemory32Size, TableCopy, TableInit, TableFill, TableSize, ImportedTableSize, TableGet, ImportedTableGet, TableSet, ImportedTableSet, TableGrow, ImportedTableGrow, FuncRef, ElemDrop, Memory32Copy, ImportedMemory32Copy, Memory32Fill, ImportedMemory32Fill, Memory32Init, DataDrop, RaiseTrap, Probestack, Memory32AtomicWait32, ImportedMemory32AtomicWait32, Memory32AtomicWait64, ImportedMemory32AtomicWait64, Memory32AtomicNotify, ImportedMemory32AtomicNotify, } ``` The name of a runtime library routine. This list is likely to grow over time. Variants --- ### CeilF32 ceil.f32 ### CeilF64 ceil.f64 ### FloorF32 floor.f32 ### FloorF64 floor.f64 ### NearestF32 nearest.f32 ### NearestF64 nearest.f64 ### TruncF32 trunc.f32 ### TruncF64 trunc.f64 ### Memory32Size memory.size for local functions ### ImportedMemory32Size memory.size for imported functions ### TableCopy table.copy ### TableInit table.init ### TableFill table.fill ### TableSize table.size for local tables ### ImportedTableSize table.size for imported tables ### TableGet table.get for local tables ### ImportedTableGet table.get for imported tables ### TableSet table.set for local tables ### ImportedTableSet table.set for imported tables ### TableGrow table.grow for local tables ### ImportedTableGrow table.grow for imported tables ### FuncRef ref.func ### ElemDrop elem.drop ### Memory32Copy memory.copy for local memories ### ImportedMemory32Copy memory.copy for imported memories ### Memory32Fill memory.fill for local memories ### ImportedMemory32Fill memory.fill for imported memories ### Memory32Init memory.init ### DataDrop data.drop ### RaiseTrap A custom trap ### Probestack probe for stack overflow. These are emitted for functions which need when the `enable_probestack` setting is true. ### Memory32AtomicWait32 memory.atomic.wait32 for local memories ### ImportedMemory32AtomicWait32 memory.atomic.wait32 for imported memories ### Memory32AtomicWait64 memory.atomic.wait64 for local memories ### ImportedMemory32AtomicWait64 memory.atomic.wait64 for imported memories ### Memory32AtomicNotify memory.atomic.notify for local memories ### ImportedMemory32AtomicNotify memory.atomic.botify for imported memories Implementations --- ### impl LibCall #### pub fn to_function_name(&self) -> &str Return the function name associated to the libcall. Trait Implementations --- ### impl Archive for LibCall #### type Archived = LibCall The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### type Error = EnumCheckError<u16The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u16>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> LibCall Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Iterator = LibCallEnumIterator Type of the iterator over the variants.#### const VARIANT_COUNT: usize = 37usize Number of variants.#### fn into_enum_iter() -> Self::Iterator Returns an iterator over the variants. #### fn eq(&self, other: &LibCall) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for LibCall #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for LibCall ### impl Eq for LibCall ### impl StructuralEq for LibCall ### impl StructuralPartialEq for LibCall Auto Trait Implementations --- ### impl RefUnwindSafe for LibCall ### impl Send for LibCall ### impl Sync for LibCall ### impl Unpin for LibCall ### impl UnwindSafe for LibCall Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::MemoryStyle === ``` #[repr(u8)]pub enum MemoryStyle { Dynamic { offset_guard_size: u64, }, Static { bound: Pages, offset_guard_size: u64, }, } ``` Implementation styles for WebAssembly linear memory. Variants --- ### Dynamic #### Fields `offset_guard_size: u64`Our chosen offset-guard size. It represents the size in bytes of extra guard pages after the end to optimize loads and stores with constant offsets. The actual memory can be resized and moved. ### Static #### Fields `bound: Pages`The number of mapped and unmapped pages. `offset_guard_size: u64`Our chosen offset-guard size. It represents the size in bytes of extra guard pages after the end to optimize loads and stores with constant offsets. Address space is allocated up front. Implementations --- ### impl MemoryStyle #### pub fn offset_guard_size(&self) -> u64 Returns the offset-guard size Trait Implementations --- ### impl Archive for MemoryStylewhere u64: Archive, Pages: Archive, #### type Archived = MemoryStyle The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. u64: CheckBytes<__C>, Pages: CheckBytes<__C>, #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> MemoryStyle Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. u64: Archive, Archived<u64>: Deserialize<u64, __D>, Pages: Archive, Archived<Pages>: Deserialize<Pages, __D>, #### fn deserialize(&self, deserializer: &mut __D) -> Result<MemoryStyle, __D::ErrorDeserializes using the given deserializer### impl Hash for MemoryStyle #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &MemoryStyle) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for MemoryStylewhere u64: Serialize<__S>, Pages: Serialize<__S>, #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for MemoryStyle ### impl Eq for MemoryStyle ### impl StructuralEq for MemoryStyle ### impl StructuralPartialEq for MemoryStyle Auto Trait Implementations --- ### impl RefUnwindSafe for MemoryStyle ### impl Send for MemoryStyle ### impl Sync for MemoryStyle ### impl Unpin for MemoryStyle ### impl UnwindSafe for MemoryStyle Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::Mutability === ``` #[repr(u8)]pub enum Mutability { Const, Var, } ``` Indicator of whether a global is mutable or not Variants --- ### Const The global is constant and its value does not change ### Var The value of the global can change over time Implementations --- ### impl Mutability #### pub fn is_mutable(self) -> bool Returns a boolean indicating if the enum is set to mutable. Trait Implementations --- ### impl Archive for Mutability #### type Archived = Mutability The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> Mutability Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(value: Mutability) -> Self Converts to this type from the input type.### impl From<bool> for Mutability #### fn from(value: bool) -> Self Converts to this type from the input type.### impl Hash for Mutability #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Mutability) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for Mutability #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for Mutability ### impl Eq for Mutability ### impl StructuralEq for Mutability ### impl StructuralPartialEq for Mutability Auto Trait Implementations --- ### impl RefUnwindSafe for Mutability ### impl Send for Mutability ### impl Sync for Mutability ### impl Unpin for Mutability ### impl UnwindSafe for Mutability Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::OnCalledAction === ``` pub enum OnCalledAction { InvokeAgain, Finish, Trap(Box<dyn Error + Send + Sync>), } ``` After the stack is unwound via asyncify what should the call loop do next Variants --- ### InvokeAgain Will call the function again ### Finish Will return the result of the invocation ### Trap(Box<dyn Error + Send + Sync>) Traps with an error Trait Implementations --- ### impl Debug for OnCalledAction #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl !RefUnwindSafe for OnCalledAction ### impl Send for OnCalledAction ### impl Sync for OnCalledAction ### impl Unpin for OnCalledAction ### impl !UnwindSafe for OnCalledAction Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::OperatingSystem === ``` pub enum OperatingSystem { Unknown, Aix, AmdHsa, Bitrig, Cloudabi, Cuda, Darwin, Dragonfly, Emscripten, Espidf, Freebsd, Fuchsia, Haiku, Hermit, Horizon, Illumos, Ios, L4re, Linux, MacOSX { major: u16, minor: u16, patch: u16, }, Nebulet, Netbsd, None_, Openbsd, Psp, Redox, Solaris, SolidAsp3, Tvos, Uefi, VxWorks, Wasi, Watchos, Windows, } ``` The “operating system” field, which sometimes implies an environment, and sometimes isn’t an actual operating system. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### Unknown ### Aix ### AmdHsa ### Bitrig ### Cloudabi ### Cuda ### Darwin ### Dragonfly ### Emscripten ### Espidf ### Freebsd ### Fuchsia ### Haiku ### Hermit ### Horizon ### Illumos ### Ios ### L4re ### Linux ### MacOSX #### Fields `major: u16``minor: u16``patch: u16`### Nebulet ### Netbsd ### None_ ### Openbsd ### Psp ### Redox ### Solaris ### SolidAsp3 ### Tvos ### Uefi ### VxWorks ### Wasi ### Watchos ### Windows Implementations --- ### impl OperatingSystem #### pub const fn host() -> OperatingSystem Return the operating system for the current host. ### impl OperatingSystem #### pub fn into_str(self) -> Cow<'static, strConvert into a string Trait Implementations --- ### impl Clone for OperatingSystem #### fn clone(&self) -> OperatingSystem Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = () The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<OperatingSystem, ()Parses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &OperatingSystem) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for OperatingSystem ### impl Eq for OperatingSystem ### impl StructuralEq for OperatingSystem ### impl StructuralPartialEq for OperatingSystem Auto Trait Implementations --- ### impl RefUnwindSafe for OperatingSystem ### impl Send for OperatingSystem ### impl Sync for OperatingSystem ### impl Unpin for OperatingSystem ### impl UnwindSafe for OperatingSystem Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::PointerWidth === ``` pub enum PointerWidth { U16, U32, U64, } ``` The width of a pointer (in the default address space). Variants --- ### U16 ### U32 ### U64 Implementations --- ### impl PointerWidth #### pub fn bits(self) -> u8 Return the number of bits in a pointer. #### pub fn bytes(self) -> u8 Return the number of bytes in a pointer. For these purposes, there are 8 bits in a byte. Trait Implementations --- ### impl Clone for PointerWidth #### fn clone(&self) -> PointerWidth Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &PointerWidth) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for PointerWidth ### impl Eq for PointerWidth ### impl StructuralEq for PointerWidth ### impl StructuralPartialEq for PointerWidth Auto Trait Implementations --- ### impl RefUnwindSafe for PointerWidth ### impl Send for PointerWidth ### impl Sync for PointerWidth ### impl Unpin for PointerWidth ### impl UnwindSafe for PointerWidth Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::TableStyle === ``` #[repr(u8)]pub enum TableStyle { CallerChecksSignature, } ``` Implementation styles for WebAssembly tables. Variants --- ### CallerChecksSignature Signatures are stored in the table and checked in the caller. Trait Implementations --- ### impl Archive for TableStyle #### type Archived = TableStyle The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> TableStyle Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &TableStyle) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for TableStyle #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Eq for TableStyle ### impl StructuralEq for TableStyle ### impl StructuralPartialEq for TableStyle Auto Trait Implementations --- ### impl RefUnwindSafe for TableStyle ### impl Send for TableStyle ### impl Sync for TableStyle ### impl Unpin for TableStyle ### impl UnwindSafe for TableStyle Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::TrapCode === ``` #[repr(u32)]pub enum TrapCode { StackOverflow, HeapAccessOutOfBounds, HeapMisaligned, TableAccessOutOfBounds, IndirectCallToNull, BadSignature, IntegerOverflow, IntegerDivisionByZero, BadConversionToInteger, UnreachableCodeReached, UnalignedAtomic, } ``` A trap code describing the reason for a trap. All trap instructions have an explicit trap code. Variants --- ### StackOverflow The current stack space was exhausted. On some platforms, a stack overflow may also be indicated by a segmentation fault from the stack guard page. ### HeapAccessOutOfBounds A `heap_addr` instruction detected an out-of-bounds error. Note that not all out-of-bounds heap accesses are reported this way; some are detected by a segmentation fault on the heap unmapped or offset-guard pages. ### HeapMisaligned A `heap_addr` instruction was misaligned. ### TableAccessOutOfBounds A `table_addr` instruction detected an out-of-bounds error. ### IndirectCallToNull Indirect call to a null table entry. ### BadSignature Signature mismatch on indirect call. ### IntegerOverflow An integer arithmetic operation caused an overflow. ### IntegerDivisionByZero An integer division by zero. ### BadConversionToInteger Failed float-to-int conversion. ### UnreachableCodeReached Code that was supposed to have been unreachable was reached. ### UnalignedAtomic An atomic memory access was attempted with an unaligned pointer. Implementations --- ### impl TrapCode #### pub fn message(&self) -> &str Gets the message for this trap code Trait Implementations --- ### impl Archive for TrapCode #### type Archived = TrapCode The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### type Error = EnumCheckError<u32The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u32>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> TrapCode Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, request: &mut Request<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### type Err = () The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Self, Self::ErrParses a string `s` to return a value of this type. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &TrapCode) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for TrapCode #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for TrapCode ### impl Eq for TrapCode ### impl StructuralEq for TrapCode ### impl StructuralPartialEq for TrapCode Auto Trait Implementations --- ### impl RefUnwindSafe for TrapCode ### impl Send for TrapCode ### impl Sync for TrapCode ### impl Unpin for TrapCode ### impl UnwindSafe for TrapCode Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> Error for Twhere T: Error + 'static, #### fn as_error(&self) -> &(dyn Error + 'static) Gets this error as an `std::error::Error`.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::Type === ``` #[repr(u8)]pub enum Type { I32, I64, F32, F64, V128, ExternRef, FuncRef, } ``` A list of all possible value types in WebAssembly. Variants --- ### I32 Signed 32 bit integer. ### I64 Signed 64 bit integer. ### F32 Floating point 32 bit integer. ### F64 Floating point 64 bit integer. ### V128 A 128 bit number. ### ExternRef A reference to opaque data in the Wasm instance. ### FuncRef A reference to a Wasm function. Implementations --- ### impl Type #### pub fn is_num(self) -> bool Returns true if `Type` matches any of the numeric types. (e.g. `I32`, `I64`, `F32`, `F64`, `V128`). #### pub fn is_ref(self) -> bool Returns true if `Type` matches either of the reference types. Trait Implementations --- ### impl Archive for Type #### type Archived = Type The archived representation of this type. The resolver for this type. It must contain all the additional information from serializing needed to make the archived type from the normal type.#### unsafe fn resolve( &self, pos: usize, resolver: <Self as Archive>::Resolver, out: *mut<Self as Archive>::Archived ) Creates the archived version of this value at the given position and writes it to the given output. #### type Error = EnumCheckError<u8The error that may result from checking the type.#### unsafe fn check_bytes<'__bytecheck>( value: *const Self, context: &mut __C ) -> Result<&'__bytecheck Self, EnumCheckError<u8>Checks whether the given pointer points to a valid value within the given context. #### fn clone(&self) -> Type Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn hash<__H: Hasher>(&self, state: &mut __H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Type) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl<__S: Fallible + ?Sized> Serialize<__S> for Type #### fn serialize( &self, serializer: &mut __S ) -> Result<<Self as Archive>::Resolver, __S::ErrorWrites the dependencies for the object and returns a resolver that can create the archived type.### impl Copy for Type ### impl Eq for Type ### impl StructuralEq for Type ### impl StructuralPartialEq for Type Auto Trait Implementations --- ### impl RefUnwindSafe for Type ### impl Send for Type ### impl Sync for Type ### impl Unpin for Type ### impl UnwindSafe for Type Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> ArchiveUnsized for Twhere T: Archive, #### type Archived = <T as Archive>::Archived The archived counterpart of this type. Unlike `Archive`, it may be unsized. The resolver for the metadata of this type. &self, _: usize, _: <T as ArchiveUnsized>::MetadataResolver, _: *mut<<T as ArchiveUnsized>::Archived as ArchivePointee>::ArchivedMetadata ) Creates the archived version of the metadata for this value at the given position and writes it to the given output. &self, from: usize, to: usize, resolver: Self::MetadataResolver, out: *mutRelPtr<Self::Archived, <isize as Archive>::Archived> ) Resolves a relative pointer to this value with the given `from` and `to` and writes it to the given output. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T, S> SerializeUnsized<S> for Twhere T: Serialize<S>, S: Serializer + ?Sized, #### fn serialize_unsized( &self, serializer: &mut S ) -> Result<usize, <S as Fallible>::ErrorWrites the object and returns the position of the archived type.#### fn serialize_metadata(&self, _: &mut S) -> Result<(), <S as Fallible>::ErrorSerializes the metadata for the given type.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum wasmer_types::Vendor === ``` pub enum Vendor { Unknown, Amd, Apple, Espressif, Experimental, Fortanix, Ibm, Kmc, Nintendo, Nvidia, Pc, Rumprun, Sun, Uwp, Wrs, Custom(CustomVendor), } ``` The “vendor” field, which in practice is little more than an arbitrary modifier. Variants (Non-exhaustive) --- Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.### Unknown ### Amd ### Apple ### Espressif ### Experimental ### Fortanix ### Ibm ### Kmc ### Nintendo ### Nvidia ### Pc ### Rumprun ### Sun ### Uwp ### Wrs ### Custom(CustomVendor) A custom vendor. “Custom” in this context means that the vendor is not specifically recognized by upstream Autotools, LLVM, Rust, or other relevant authorities on triple naming. It’s useful for people building and using locally patched toolchains. Outside of such patched environments, users of `target-lexicon` should treat `Custom` the same as `Unknown` and ignore the string. Implementations --- ### impl Vendor #### pub const fn host() -> Vendor Return the vendor for the current host. ### impl Vendor #### pub fn as_str(&self) -> &str Extracts a string slice. Trait Implementations --- ### impl Clone for Vendor #### fn clone(&self) -> Vendor Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = () The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Vendor, ()Parses a string `s` to return a value of this type. #### fn hash<__H>(&self, state: &mut __H)where __H: Hasher, Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized, Feeds a slice of this type into the given `Hasher`. #### fn eq(&self, other: &Vendor) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Eq for Vendor ### impl StructuralEq for Vendor ### impl StructuralPartialEq for Vendor Auto Trait Implementations --- ### impl RefUnwindSafe for Vendor ### impl Send for Vendor ### impl Sync for Vendor ### impl Unpin for Vendor ### impl UnwindSafe for Vendor Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. T: Hash + ?Sized, #### default fn get_hash<H, B>(value: &H, build_hasher: &B) -> u64where H: Hash + ?Sized, B: BuildHasher, ### impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized, #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal.### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Constant wasmer_types::VERSION === ``` pub const VERSION: &str = env!("CARGO_PKG_VERSION"); ``` Version number of this crate. Constant wasmer_types::WASM_MAX_PAGES === ``` pub const WASM_MAX_PAGES: u32 = 0x10000; ``` The number of pages we can have before we run out of byte index space. Constant wasmer_types::WASM_MIN_PAGES === ``` pub const WASM_MIN_PAGES: u32 = 0x100; ``` The minimum number of pages allowed. Constant wasmer_types::WASM_PAGE_SIZE === ``` pub const WASM_PAGE_SIZE: usize = 0x10000; ``` WebAssembly page sizes are fixed to be 64KiB. Note: large page support may be added in an opt-in manner in the future. Trait wasmer_types::DataInitializerLike === ``` pub trait DataInitializerLike<'a> { type Location: DataInitializerLocationLike + Copy + 'a; // Required methods fn location(&self) -> Self::Location; fn data(&self) -> &'a [u8] ; } ``` Any struct that acts like a `DataInitializer`. Required Associated Types --- #### type Location: DataInitializerLocationLike + Copy + 'a Required Methods --- #### fn location(&self) -> Self::Location #### fn data(&self) -> &'a [u8] Implementors --- ### impl<'a> DataInitializerLike<'a> for &'a ArchivedOwnedDataInitializer #### type Location = &'a ArchivedDataInitializerLocation ### impl<'a> DataInitializerLike<'a> for &'a OwnedDataInitializer #### type Location = &'a DataInitializerLocation {"&'a [u8]":"<h3>Notable traits for <code>&amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</code></h3><pre><code><span class=\"where fmt-newline\">impl <a class=\"trait\" href=\"https://doc.rust-lang.org/nightly/std/io/trait.Read.html\" title=\"trait std::io::Read\">Read</a> for &amp;[<a class=\"primitive\" href=\"https://doc.rust-lang.org/nightly/std/primitive.u8.html\">u8</a>]</span>"} Trait wasmer_types::DataInitializerLocationLike === ``` pub trait DataInitializerLocationLike { // Required methods fn memory_index(&self) -> MemoryIndex; fn base(&self) -> Option<GlobalIndex>; fn offset(&self) -> usize; } ``` Any struct that acts like a `DataInitializerLocation`. Required Methods --- #### fn memory_index(&self) -> MemoryIndex #### fn base(&self) -> Option<GlobalIndex#### fn offset(&self) -> usize Implementors --- ### impl DataInitializerLocationLike for &ArchivedDataInitializerLocation ### impl DataInitializerLocationLike for &DataInitializerLocation Trait wasmer_types::MemorySize === ``` pub unsafe trait MemorySize: Copy { type Offset: Default + Debug + Display + Eq + Ord + PartialEq<Self::Offset> + PartialOrd<Self::Offset> + Clone + Copy + Sync + Send + ValueType + Into<u64> + From<u32> + From<u16> + From<u8> + TryFrom<u64> + TryFrom<u32> + TryFrom<u16> + TryFrom<u8> + TryFrom<i32> + TryInto<usize> + TryInto<u64> + TryInto<u32> + TryInto<u16> + TryInto<u8> + TryInto<i32> + TryFrom<usize> + Add<Self::Offset> + Sum<Self::Offset> + AddAssign<Self::Offset> + 'static; type Native: NativeWasmType; const ZERO: Self::Offset; const ONE: Self::Offset; // Required methods fn offset_to_native(offset: Self::Offset) -> Self::Native; fn native_to_offset(native: Self::Native) -> Self::Offset; fn is_64bit() -> bool; } ``` Trait for the `Memory32` and `Memory64` marker types. This allows code to be generic over 32-bit and 64-bit memories. Safety --- Direct memory access is unsafe Required Associated Types --- #### type Offset: Default + Debug + Display + Eq + Ord + PartialEq<Self::Offset> + PartialOrd<Self::Offset> + Clone + Copy + Sync + Send + ValueType + Into<u64> + From<u32> + From<u16> + From<u8> + TryFrom<u64> + TryFrom<u32> + TryFrom<u16> + TryFrom<u8> + TryFrom<i32> + TryInto<usize> + TryInto<u64> + TryInto<u32> + TryInto<u16> + TryInto<u8> + TryInto<i32> + TryFrom<usize> + Add<Self::Offset> + Sum<Self::Offset> + AddAssign<Self::Offset> + 'static Type used to represent an offset into a memory. This is `u32` or `u64`. #### type Native: NativeWasmType Type used to pass this value as an argument or return value for a Wasm function. Required Associated Constants --- #### const ZERO: Self::Offset Zero value used for `WasmPtr::is_null`. #### const ONE: Self::Offset One value used for counting. Required Methods --- #### fn offset_to_native(offset: Self::Offset) -> Self::Native Convert an `Offset` to a `Native`. #### fn native_to_offset(native: Self::Native) -> Self::Offset Convert a `Native` to an `Offset`. #### fn is_64bit() -> bool True if the memory is 64-bit Implementors --- ### impl MemorySize for Memory32 #### type Offset = u32 #### type Native = i32 #### const ZERO: Self::Offset = {transmute(0x00000000): <memory::Memory32 as memory::MemorySize>::Offset} #### const ONE: Self::Offset = {transmute(0x00000001): <memory::Memory32 as memory::MemorySize>::Offset} ### impl MemorySize for Memory64 #### type Offset = u64 #### type Native = i64 #### const ZERO: Self::Offset = {transmute(0x0000000000000000): <memory::Memory64 as memory::MemorySize>::Offset} #### const ONE: Self::Offset = {transmute(0x0000000000000001): <memory::Memory64 as memory::MemorySize>::Offset} Trait wasmer_types::NativeWasmType === ``` pub trait NativeWasmType: Sized { type Abi: Copy + Debug; const WASM_TYPE: Type; } ``` `NativeWasmType` represents a Wasm type that has a direct representation on the host (hence the “native” term). It uses the Rust Type system to automatically detect the Wasm type associated with a native Rust type. ``` use wasmer_types::{NativeWasmType, Type}; let wasm_type = i32::WASM_TYPE; assert_eq!(wasm_type, Type::I32); ``` > Note: This strategy will be needed later to > automatically detect the signature of a Rust function. Required Associated Types --- #### type Abi: Copy + Debug The ABI for this type (i32, i64, f32, f64) Required Associated Constants --- #### const WASM_TYPE: Type Type for this `NativeWasmType`. Implementations on Foreign Types --- ### impl NativeWasmType for u128 #### const WASM_TYPE: Type = Type::V128 #### type Abi = u128 ### impl NativeWasmType for f32 #### const WASM_TYPE: Type = Type::F32 #### type Abi = f32 ### impl NativeWasmType for u32 #### const WASM_TYPE: Type = Type::I32 #### type Abi = u32 ### impl NativeWasmType for i64 #### const WASM_TYPE: Type = Type::I64 #### type Abi = i64 ### impl NativeWasmType for u64 #### const WASM_TYPE: Type = Type::I64 #### type Abi = u64 ### impl NativeWasmType for f64 #### const WASM_TYPE: Type = Type::F64 #### type Abi = f64 ### impl<T: NativeWasmType> NativeWasmType for Option<T#### const WASM_TYPE: Type = T::WASM_TYPE #### type Abi = <T as NativeWasmType>::Abi ### impl NativeWasmType for i32 #### const WASM_TYPE: Type = Type::I32 #### type Abi = i32 Implementors --- ### impl NativeWasmType for Memory32 #### const WASM_TYPE: Type = <<Self as MemorySize>::Native as NativeWasmType>::WASM_TYPE #### type Abi = <<Memory32 as MemorySize>::Native as NativeWasmType>::Abi ### impl NativeWasmType for Memory64 #### const WASM_TYPE: Type = <<Self as MemorySize>::Native as NativeWasmType>::WASM_TYPE #### type Abi = <<Memory64 as MemorySize>::Native as NativeWasmType>::Abi Trait wasmer_types::ValueType === ``` pub unsafe trait ValueType: Copy { // Required method fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit<u8>]); } ``` Trait for a Value type. A Value type is a type that is always valid and may be safely copied. Safety --- To maintain safety, types which implement this trait must be valid for all bit patterns. This means that it cannot contain enums, `bool`, references, etc. Concretely a `u32` is a Value type because every combination of 32 bits is a valid `u32`. However a `bool` is *not* a Value type because any bit patterns other than `0` and `1` are invalid in Rust and may cause undefined behavior if a `bool` is constructed from those bytes. Additionally this trait has a method which zeros out any uninitializes bytes prior to writing them to Wasm memory, which prevents information leaks into the sandbox. Required Methods --- #### fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit<u8>]) This method is passed a byte slice which contains the byte representation of `self`. It must zero out any bytes which are uninitialized (e.g. padding bytes). Implementations on Foreign Types --- ### impl ValueType for u8 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [i16; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [i128; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [i32; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [f64; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for f32 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for u64 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [u8; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for isize #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for u32 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [u32; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [bool; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for bool #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [i8; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [i64; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [u64; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [f32; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [u128; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for i64 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for i16 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for usize #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for f64 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for u16 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for i32 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [isize; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for i128 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for u128 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl ValueType for i8 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [usize; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) ### impl<const N: usize> ValueType for [u16; N] #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) Implementors --- ### impl<T: ?Sized> ValueType for PhantomData<TFunction wasmer_types::is_wasm === ``` pub fn is_wasm(bytes: impl AsRef<[u8]>) -> bool ``` Check if the provided bytes are wasm-like Type Alias wasmer_types::Addend === ``` pub type Addend = i64; ``` Addend to add to the symbol value. Trait Implementations --- ### impl Add<&BigEndian<i64>> for i64 #### type Output = i64 The resulting type after applying the `+` operator.#### fn add(self, other: &BigEndian<i64>) -> <i64 as Add<&BigEndian<i64>>>::Output Performs the `+` operation. #### type Output = i64 The resulting type after applying the `+` operator.#### fn add( self, other: &LittleEndian<i64> ) -> <i64 as Add<&LittleEndian<i64>>>::Output Performs the `+` operation. #### type Output = i64 The resulting type after applying the `+` operator.#### fn add( self, other: &NativeEndian<i64> ) -> <i64 as Add<&NativeEndian<i64>>>::Output Performs the `+` operation. Read more1.0.0 · source### impl Add<&i64> for i64 #### type Output = <i64 as Add<i64>>::Output The resulting type after applying the `+` operator.#### fn add(self, other: &i64) -> <i64 as Add<i64>>::Output Performs the `+` operation. #### type Output = i64 The resulting type after applying the `+` operator.#### fn add(self, other: BigEndian<i64>) -> <i64 as Add<BigEndian<i64>>>::Output Performs the `+` operation. #### type Output = i64 The resulting type after applying the `+` operator.#### fn add( self, other: LittleEndian<i64> ) -> <i64 as Add<LittleEndian<i64>>>::Output Performs the `+` operation. #### type Output = i64 The resulting type after applying the `+` operator.#### fn add( self, other: NativeEndian<i64> ) -> <i64 as Add<NativeEndian<i64>>>::Output Performs the `+` operation. Read more1.0.0 · source### impl Add<i64> for i64 #### type Output = i64 The resulting type after applying the `+` operator.#### fn add(self, other: i64) -> i64 Performs the `+` operation. Read more1.22.0 · source### impl AddAssign<&i64> for i64 #### fn add_assign(&mut self, other: &i64) Performs the `+=` operation. Read more1.8.0 · source### impl AddAssign<i64> for i64 #### fn add_assign(&mut self, other: i64) Performs the `+=` operation. Read more1.0.0 · source### impl Binary for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl BitAnd<&BigEndian<i64>> for i64 #### type Output = i64 The resulting type after applying the `&` operator.#### fn bitand( self, other: &BigEndian<i64> ) -> <i64 as BitAnd<&BigEndian<i64>>>::Output Performs the `&` operation. #### type Output = i64 The resulting type after applying the `&` operator.#### fn bitand( self, other: &LittleEndian<i64> ) -> <i64 as BitAnd<&LittleEndian<i64>>>::Output Performs the `&` operation. #### type Output = i64 The resulting type after applying the `&` operator.#### fn bitand( self, other: &NativeEndian<i64> ) -> <i64 as BitAnd<&NativeEndian<i64>>>::Output Performs the `&` operation. Read more1.0.0 · source### impl BitAnd<&i64> for i64 #### type Output = <i64 as BitAnd<i64>>::Output The resulting type after applying the `&` operator.#### fn bitand(self, other: &i64) -> <i64 as BitAnd<i64>>::Output Performs the `&` operation. #### type Output = i64 The resulting type after applying the `&` operator.#### fn bitand( self, other: BigEndian<i64> ) -> <i64 as BitAnd<BigEndian<i64>>>::Output Performs the `&` operation. #### type Output = i64 The resulting type after applying the `&` operator.#### fn bitand( self, other: LittleEndian<i64> ) -> <i64 as BitAnd<LittleEndian<i64>>>::Output Performs the `&` operation. #### type Output = i64 The resulting type after applying the `&` operator.#### fn bitand( self, other: NativeEndian<i64> ) -> <i64 as BitAnd<NativeEndian<i64>>>::Output Performs the `&` operation. Read more1.0.0 · source### impl BitAnd<i64> for i64 #### type Output = i64 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: i64) -> i64 Performs the `&` operation. Read more1.22.0 · source### impl BitAndAssign<&i64> for i64 #### fn bitand_assign(&mut self, other: &i64) Performs the `&=` operation. Read more1.8.0 · source### impl BitAndAssign<i64> for i64 #### fn bitand_assign(&mut self, other: i64) Performs the `&=` operation. #### type Output = i64 The resulting type after applying the `|` operator.#### fn bitor( self, other: &BigEndian<i64> ) -> <i64 as BitOr<&BigEndian<i64>>>::Output Performs the `|` operation. #### type Output = i64 The resulting type after applying the `|` operator.#### fn bitor( self, other: &LittleEndian<i64> ) -> <i64 as BitOr<&LittleEndian<i64>>>::Output Performs the `|` operation. #### type Output = i64 The resulting type after applying the `|` operator.#### fn bitor( self, other: &NativeEndian<i64> ) -> <i64 as BitOr<&NativeEndian<i64>>>::Output Performs the `|` operation. Read more1.0.0 · source### impl BitOr<&i64> for i64 #### type Output = <i64 as BitOr<i64>>::Output The resulting type after applying the `|` operator.#### fn bitor(self, other: &i64) -> <i64 as BitOr<i64>>::Output Performs the `|` operation. #### type Output = i64 The resulting type after applying the `|` operator.#### fn bitor(self, other: BigEndian<i64>) -> <i64 as BitOr<BigEndian<i64>>>::Output Performs the `|` operation. #### type Output = i64 The resulting type after applying the `|` operator.#### fn bitor( self, other: LittleEndian<i64> ) -> <i64 as BitOr<LittleEndian<i64>>>::Output Performs the `|` operation. #### type Output = i64 The resulting type after applying the `|` operator.#### fn bitor( self, other: NativeEndian<i64> ) -> <i64 as BitOr<NativeEndian<i64>>>::Output Performs the `|` operation. Read more1.45.0 · source### impl BitOr<NonZeroI64> for i64 #### type Output = NonZeroI64 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: NonZeroI64) -> <i64 as BitOr<NonZeroI64>>::Output Performs the `|` operation. Read more1.0.0 · source### impl BitOr<i64> for i64 #### type Output = i64 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: i64) -> i64 Performs the `|` operation. Read more1.22.0 · source### impl BitOrAssign<&i64> for i64 #### fn bitor_assign(&mut self, other: &i64) Performs the `|=` operation. Read more1.8.0 · source### impl BitOrAssign<i64> for i64 #### fn bitor_assign(&mut self, other: i64) Performs the `|=` operation. #### type Output = i64 The resulting type after applying the `^` operator.#### fn bitxor( self, other: &BigEndian<i64> ) -> <i64 as BitXor<&BigEndian<i64>>>::Output Performs the `^` operation. #### type Output = i64 The resulting type after applying the `^` operator.#### fn bitxor( self, other: &LittleEndian<i64> ) -> <i64 as BitXor<&LittleEndian<i64>>>::Output Performs the `^` operation. #### type Output = i64 The resulting type after applying the `^` operator.#### fn bitxor( self, other: &NativeEndian<i64> ) -> <i64 as BitXor<&NativeEndian<i64>>>::Output Performs the `^` operation. Read more1.0.0 · source### impl BitXor<&i64> for i64 #### type Output = <i64 as BitXor<i64>>::Output The resulting type after applying the `^` operator.#### fn bitxor(self, other: &i64) -> <i64 as BitXor<i64>>::Output Performs the `^` operation. #### type Output = i64 The resulting type after applying the `^` operator.#### fn bitxor( self, other: BigEndian<i64> ) -> <i64 as BitXor<BigEndian<i64>>>::Output Performs the `^` operation. #### type Output = i64 The resulting type after applying the `^` operator.#### fn bitxor( self, other: LittleEndian<i64> ) -> <i64 as BitXor<LittleEndian<i64>>>::Output Performs the `^` operation. #### type Output = i64 The resulting type after applying the `^` operator.#### fn bitxor( self, other: NativeEndian<i64> ) -> <i64 as BitXor<NativeEndian<i64>>>::Output Performs the `^` operation. Read more1.0.0 · source### impl BitXor<i64> for i64 #### type Output = i64 The resulting type after applying the `^` operator.#### fn bitxor(self, other: i64) -> i64 Performs the `^` operation. Read more1.22.0 · source### impl BitXorAssign<&i64> for i64 #### fn bitxor_assign(&mut self, other: &i64) Performs the `^=` operation. Read more1.8.0 · source### impl BitXorAssign<i64> for i64 #### fn bitxor_assign(&mut self, other: i64) Performs the `^=` operation. Read more1.0.0 · source### impl Debug for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. Read more1.0.0 · source### impl Display for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Output = i64 The resulting type after applying the `/` operator.#### fn div(self, other: &BigEndian<i64>) -> <i64 as Div<&BigEndian<i64>>>::Output Performs the `/` operation. #### type Output = i64 The resulting type after applying the `/` operator.#### fn div( self, other: &LittleEndian<i64> ) -> <i64 as Div<&LittleEndian<i64>>>::Output Performs the `/` operation. #### type Output = i64 The resulting type after applying the `/` operator.#### fn div( self, other: &NativeEndian<i64> ) -> <i64 as Div<&NativeEndian<i64>>>::Output Performs the `/` operation. Read more1.0.0 · source### impl Div<&i64> for i64 #### type Output = <i64 as Div<i64>>::Output The resulting type after applying the `/` operator.#### fn div(self, other: &i64) -> <i64 as Div<i64>>::Output Performs the `/` operation. #### type Output = i64 The resulting type after applying the `/` operator.#### fn div(self, other: BigEndian<i64>) -> <i64 as Div<BigEndian<i64>>>::Output Performs the `/` operation. #### type Output = i64 The resulting type after applying the `/` operator.#### fn div( self, other: LittleEndian<i64> ) -> <i64 as Div<LittleEndian<i64>>>::Output Performs the `/` operation. #### type Output = i64 The resulting type after applying the `/` operator.#### fn div( self, other: NativeEndian<i64> ) -> <i64 as Div<NativeEndian<i64>>>::Output Performs the `/` operation. Read more1.0.0 · source### impl Div<i64> for i64 This operation rounds towards zero, truncating any fractional part of the exact result. #### Panics This operation will panic if `other == 0` or the division results in overflow. #### type Output = i64 The resulting type after applying the `/` operator.#### fn div(self, other: i64) -> i64 Performs the `/` operation. Read more1.22.0 · source### impl DivAssign<&i64> for i64 #### fn div_assign(&mut self, other: &i64) Performs the `/=` operation. Read more1.8.0 · source### impl DivAssign<i64> for i64 #### fn div_assign(&mut self, other: i64) Performs the `/=` operation. #### fn from(value: &'a BigEndian<i64>) -> i64 Converts to this type from the input type.### impl<'a> From<&'a LittleEndian<i64>> for i64 #### fn from(value: &'a LittleEndian<i64>) -> i64 Converts to this type from the input type.### impl<'a> From<&'a NativeEndian<i64>> for i64 #### fn from(value: &'a NativeEndian<i64>) -> i64 Converts to this type from the input type.### impl From<BigEndian<i64>> for i64 #### fn from(value: BigEndian<i64>) -> i64 Converts to this type from the input type.### impl From<LittleEndian<i64>> for i64 #### fn from(value: LittleEndian<i64>) -> i64 Converts to this type from the input type.### impl From<NativeEndian<i64>> for i64 #### fn from(value: NativeEndian<i64>) -> i64 Converts to this type from the input type.1.31.0 · source### impl From<NonZeroI64> for i64 #### fn from(nonzero: NonZeroI64) -> i64 Converts a `NonZeroI64` into an `i64` 1.28.0 · source### impl From<bool> for i64 #### fn from(small: bool) -> i64 Converts a `bool` to a `i64`. The resulting value is `0` for `false` and `1` for `true` values. ##### Examples ``` assert_eq!(i64::from(true), 1); assert_eq!(i64::from(false), 0); ``` 1.5.0 · source### impl From<i16> for i64 #### fn from(small: i16) -> i64 Converts `i16` to `i64` losslessly. 1.5.0 · source### impl From<i32> for i64 #### fn from(small: i32) -> i64 Converts `i32` to `i64` losslessly. 1.5.0 · source### impl From<i8> for i64 #### fn from(small: i8) -> i64 Converts `i8` to `i64` losslessly. 1.5.0 · source### impl From<u16> for i64 #### fn from(small: u16) -> i64 Converts `u16` to `i64` losslessly. 1.5.0 · source### impl From<u32> for i64 #### fn from(small: u32) -> i64 Converts `u32` to `i64` losslessly. 1.5.0 · source### impl From<u8> for i64 #### fn from(small: u8) -> i64 Converts `u8` to `i64` losslessly. 1.0.0 · source### impl Hash for i64 #### fn hash<H>(&self, state: &mut H)where H: Hasher, Feeds this value into the given `Hasher`. H: Hasher, Feeds a slice of this type into the given `Hasher`. Read more1.42.0 · source### impl LowerExp for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl LowerHex for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Mul<&BigEndian<i64>> for i64 #### type Output = i64 The resulting type after applying the `*` operator.#### fn mul(self, other: &BigEndian<i64>) -> <i64 as Mul<&BigEndian<i64>>>::Output Performs the `*` operation. #### type Output = i64 The resulting type after applying the `*` operator.#### fn mul( self, other: &LittleEndian<i64> ) -> <i64 as Mul<&LittleEndian<i64>>>::Output Performs the `*` operation. #### type Output = i64 The resulting type after applying the `*` operator.#### fn mul( self, other: &NativeEndian<i64> ) -> <i64 as Mul<&NativeEndian<i64>>>::Output Performs the `*` operation. Read more1.0.0 · source### impl Mul<&i64> for i64 #### type Output = <i64 as Mul<i64>>::Output The resulting type after applying the `*` operator.#### fn mul(self, other: &i64) -> <i64 as Mul<i64>>::Output Performs the `*` operation. #### type Output = i64 The resulting type after applying the `*` operator.#### fn mul(self, other: BigEndian<i64>) -> <i64 as Mul<BigEndian<i64>>>::Output Performs the `*` operation. #### type Output = i64 The resulting type after applying the `*` operator.#### fn mul( self, other: LittleEndian<i64> ) -> <i64 as Mul<LittleEndian<i64>>>::Output Performs the `*` operation. #### type Output = i64 The resulting type after applying the `*` operator.#### fn mul( self, other: NativeEndian<i64> ) -> <i64 as Mul<NativeEndian<i64>>>::Output Performs the `*` operation. Read more1.0.0 · source### impl Mul<i64> for i64 #### type Output = i64 The resulting type after applying the `*` operator.#### fn mul(self, other: i64) -> i64 Performs the `*` operation. Read more1.22.0 · source### impl MulAssign<&i64> for i64 #### fn mul_assign(&mut self, other: &i64) Performs the `*=` operation. Read more1.8.0 · source### impl MulAssign<i64> for i64 #### fn mul_assign(&mut self, other: i64) Performs the `*=` operation. #### const WASM_TYPE: Type = Type::I64 Type for this `NativeWasmType`.#### type Abi = i64 The ABI for this type (i32, i64, f32, f64)1.0.0 · source### impl Neg for i64 #### type Output = i64 The resulting type after applying the `-` operator.#### fn neg(self) -> i64 Performs the unary `-` operation. Read more1.0.0 · source### impl Not for i64 #### type Output = i64 The resulting type after applying the `!` operator.#### fn not(self) -> i64 Performs the unary `!` operation. Read more1.0.0 · source### impl Octal for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl Ord for i64 #### fn cmp(&self, other: &i64) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &BigEndian<i64>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<LittleEndian<i64>> for i64 #### fn eq(&self, other: &LittleEndian<i64>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<NativeEndian<i64>> for i64 #### fn eq(&self, other: &NativeEndian<i64>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl PartialEq<i64> for i64 #### fn eq(&self, other: &i64) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.#### fn ne(&self, other: &i64) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl PartialOrd<i64> for i64 #### fn partial_cmp(&self, other: &i64) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. This method tests less than (for `self` and `other`) and is used by the `<` operator. This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.12.0 · source### impl<'a> Product<&'a i64> for i64 #### fn product<I>(iter: I) -> i64where I: Iterator<Item = &'a i64>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.1.12.0 · source### impl Product<i64> for i64 #### fn product<I>(iter: I) -> i64where I: Iterator<Item = i64>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.### impl Rem<&BigEndian<i64>> for i64 #### type Output = i64 The resulting type after applying the `%` operator.#### fn rem(self, other: &BigEndian<i64>) -> <i64 as Rem<&BigEndian<i64>>>::Output Performs the `%` operation. #### type Output = i64 The resulting type after applying the `%` operator.#### fn rem( self, other: &LittleEndian<i64> ) -> <i64 as Rem<&LittleEndian<i64>>>::Output Performs the `%` operation. #### type Output = i64 The resulting type after applying the `%` operator.#### fn rem( self, other: &NativeEndian<i64> ) -> <i64 as Rem<&NativeEndian<i64>>>::Output Performs the `%` operation. Read more1.0.0 · source### impl Rem<&i64> for i64 #### type Output = <i64 as Rem<i64>>::Output The resulting type after applying the `%` operator.#### fn rem(self, other: &i64) -> <i64 as Rem<i64>>::Output Performs the `%` operation. #### type Output = i64 The resulting type after applying the `%` operator.#### fn rem(self, other: BigEndian<i64>) -> <i64 as Rem<BigEndian<i64>>>::Output Performs the `%` operation. #### type Output = i64 The resulting type after applying the `%` operator.#### fn rem( self, other: LittleEndian<i64> ) -> <i64 as Rem<LittleEndian<i64>>>::Output Performs the `%` operation. #### type Output = i64 The resulting type after applying the `%` operator.#### fn rem( self, other: NativeEndian<i64> ) -> <i64 as Rem<NativeEndian<i64>>>::Output Performs the `%` operation. Read more1.0.0 · source### impl Rem<i64> for i64 This operation satisfies `n % d == n - (n / d) * d`. The result has the same sign as the left operand. #### Panics This operation will panic if `other == 0` or if `self / other` results in overflow. #### type Output = i64 The resulting type after applying the `%` operator.#### fn rem(self, other: i64) -> i64 Performs the `%` operation. Read more1.22.0 · source### impl RemAssign<&i64> for i64 #### fn rem_assign(&mut self, other: &i64) Performs the `%=` operation. Read more1.8.0 · source### impl RemAssign<i64> for i64 #### fn rem_assign(&mut self, other: i64) Performs the `%=` operation. #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: &BigEndian<i64>) -> <i64 as Shl<&BigEndian<i64>>>::Output Performs the `<<` operation. #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl( self, other: &LittleEndian<i64> ) -> <i64 as Shl<&LittleEndian<i64>>>::Output Performs the `<<` operation. #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl( self, other: &NativeEndian<i64> ) -> <i64 as Shl<&NativeEndian<i64>>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i128> for i64 #### type Output = <i64 as Shl<i128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i128) -> <i64 as Shl<i128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i16> for i64 #### type Output = <i64 as Shl<i16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i16) -> <i64 as Shl<i16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i32> for i64 #### type Output = <i64 as Shl<i32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i32) -> <i64 as Shl<i32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i64> for i64 #### type Output = <i64 as Shl<i64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i64) -> <i64 as Shl<i64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i8> for i64 #### type Output = <i64 as Shl<i8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i8) -> <i64 as Shl<i8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&isize> for i64 #### type Output = <i64 as Shl<isize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &isize) -> <i64 as Shl<isize>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u128> for i64 #### type Output = <i64 as Shl<u128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u128) -> <i64 as Shl<u128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u16> for i64 #### type Output = <i64 as Shl<u16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u16) -> <i64 as Shl<u16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u32> for i64 #### type Output = <i64 as Shl<u32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u32) -> <i64 as Shl<u32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u64> for i64 #### type Output = <i64 as Shl<u64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u64) -> <i64 as Shl<u64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u8> for i64 #### type Output = <i64 as Shl<u8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u8) -> <i64 as Shl<u8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&usize> for i64 #### type Output = <i64 as Shl<usize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &usize) -> <i64 as Shl<usize>>::Output Performs the `<<` operation. #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: BigEndian<i64>) -> <i64 as Shl<BigEndian<i64>>>::Output Performs the `<<` operation. #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl( self, other: LittleEndian<i64> ) -> <i64 as Shl<LittleEndian<i64>>>::Output Performs the `<<` operation. #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl( self, other: NativeEndian<i64> ) -> <i64 as Shl<NativeEndian<i64>>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i128> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: i128) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i16> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: i16) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i32> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: i32) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i64> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: i64) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i8> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: i8) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<isize> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: isize) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u128> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: u128) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u16> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: u16) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u32> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: u32) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u64> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: u64) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u8> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: u8) -> i64 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<usize> for i64 #### type Output = i64 The resulting type after applying the `<<` operator.#### fn shl(self, other: usize) -> i64 Performs the `<<` operation. Read more1.22.0 · source### impl ShlAssign<&i128> for i64 #### fn shl_assign(&mut self, other: &i128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i16> for i64 #### fn shl_assign(&mut self, other: &i16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i32> for i64 #### fn shl_assign(&mut self, other: &i32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i64> for i64 #### fn shl_assign(&mut self, other: &i64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i8> for i64 #### fn shl_assign(&mut self, other: &i8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&isize> for i64 #### fn shl_assign(&mut self, other: &isize) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u128> for i64 #### fn shl_assign(&mut self, other: &u128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u16> for i64 #### fn shl_assign(&mut self, other: &u16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u32> for i64 #### fn shl_assign(&mut self, other: &u32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u64> for i64 #### fn shl_assign(&mut self, other: &u64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u8> for i64 #### fn shl_assign(&mut self, other: &u8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&usize> for i64 #### fn shl_assign(&mut self, other: &usize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i128> for i64 #### fn shl_assign(&mut self, other: i128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i16> for i64 #### fn shl_assign(&mut self, other: i16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i32> for i64 #### fn shl_assign(&mut self, other: i32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i64> for i64 #### fn shl_assign(&mut self, other: i64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i8> for i64 #### fn shl_assign(&mut self, other: i8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<isize> for i64 #### fn shl_assign(&mut self, other: isize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u128> for i64 #### fn shl_assign(&mut self, other: u128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u16> for i64 #### fn shl_assign(&mut self, other: u16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u32> for i64 #### fn shl_assign(&mut self, other: u32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u64> for i64 #### fn shl_assign(&mut self, other: u64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u8> for i64 #### fn shl_assign(&mut self, other: u8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<usize> for i64 #### fn shl_assign(&mut self, other: usize) Performs the `<<=` operation. #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: &BigEndian<i64>) -> <i64 as Shr<&BigEndian<i64>>>::Output Performs the `>>` operation. #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr( self, other: &LittleEndian<i64> ) -> <i64 as Shr<&LittleEndian<i64>>>::Output Performs the `>>` operation. #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr( self, other: &NativeEndian<i64> ) -> <i64 as Shr<&NativeEndian<i64>>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i128> for i64 #### type Output = <i64 as Shr<i128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i128) -> <i64 as Shr<i128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i16> for i64 #### type Output = <i64 as Shr<i16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i16) -> <i64 as Shr<i16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i32> for i64 #### type Output = <i64 as Shr<i32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i32) -> <i64 as Shr<i32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i64> for i64 #### type Output = <i64 as Shr<i64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i64) -> <i64 as Shr<i64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i8> for i64 #### type Output = <i64 as Shr<i8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i8) -> <i64 as Shr<i8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&isize> for i64 #### type Output = <i64 as Shr<isize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &isize) -> <i64 as Shr<isize>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u128> for i64 #### type Output = <i64 as Shr<u128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u128) -> <i64 as Shr<u128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u16> for i64 #### type Output = <i64 as Shr<u16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u16) -> <i64 as Shr<u16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u32> for i64 #### type Output = <i64 as Shr<u32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u32) -> <i64 as Shr<u32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u64> for i64 #### type Output = <i64 as Shr<u64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u64) -> <i64 as Shr<u64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u8> for i64 #### type Output = <i64 as Shr<u8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u8) -> <i64 as Shr<u8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&usize> for i64 #### type Output = <i64 as Shr<usize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &usize) -> <i64 as Shr<usize>>::Output Performs the `>>` operation. #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: BigEndian<i64>) -> <i64 as Shr<BigEndian<i64>>>::Output Performs the `>>` operation. #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr( self, other: LittleEndian<i64> ) -> <i64 as Shr<LittleEndian<i64>>>::Output Performs the `>>` operation. #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr( self, other: NativeEndian<i64> ) -> <i64 as Shr<NativeEndian<i64>>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i128> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: i128) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i16> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: i16) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i32> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: i32) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i64> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: i64) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i8> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: i8) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<isize> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: isize) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u128> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: u128) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u16> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: u16) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u32> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: u32) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u64> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: u64) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u8> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: u8) -> i64 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<usize> for i64 #### type Output = i64 The resulting type after applying the `>>` operator.#### fn shr(self, other: usize) -> i64 Performs the `>>` operation. Read more1.22.0 · source### impl ShrAssign<&i128> for i64 #### fn shr_assign(&mut self, other: &i128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i16> for i64 #### fn shr_assign(&mut self, other: &i16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i32> for i64 #### fn shr_assign(&mut self, other: &i32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i64> for i64 #### fn shr_assign(&mut self, other: &i64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i8> for i64 #### fn shr_assign(&mut self, other: &i8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&isize> for i64 #### fn shr_assign(&mut self, other: &isize) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u128> for i64 #### fn shr_assign(&mut self, other: &u128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u16> for i64 #### fn shr_assign(&mut self, other: &u16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u32> for i64 #### fn shr_assign(&mut self, other: &u32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u64> for i64 #### fn shr_assign(&mut self, other: &u64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u8> for i64 #### fn shr_assign(&mut self, other: &u8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&usize> for i64 #### fn shr_assign(&mut self, other: &usize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i128> for i64 #### fn shr_assign(&mut self, other: i128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i16> for i64 #### fn shr_assign(&mut self, other: i16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i32> for i64 #### fn shr_assign(&mut self, other: i32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i64> for i64 #### fn shr_assign(&mut self, other: i64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i8> for i64 #### fn shr_assign(&mut self, other: i8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<isize> for i64 #### fn shr_assign(&mut self, other: isize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u128> for i64 #### fn shr_assign(&mut self, other: u128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u16> for i64 #### fn shr_assign(&mut self, other: u16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u32> for i64 #### fn shr_assign(&mut self, other: u32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u64> for i64 #### fn shr_assign(&mut self, other: u64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u8> for i64 #### fn shr_assign(&mut self, other: u8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<usize> for i64 #### fn shr_assign(&mut self, other: usize) Performs the `>>=` operation. #### unsafe fn forward_unchecked(start: i64, n: usize) -> i64 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. of `self` `count` times. of `self` `count` times. #### type Output = i64 The resulting type after applying the `-` operator.#### fn sub(self, other: &BigEndian<i64>) -> <i64 as Sub<&BigEndian<i64>>>::Output Performs the `-` operation. #### type Output = i64 The resulting type after applying the `-` operator.#### fn sub( self, other: &LittleEndian<i64> ) -> <i64 as Sub<&LittleEndian<i64>>>::Output Performs the `-` operation. #### type Output = i64 The resulting type after applying the `-` operator.#### fn sub( self, other: &NativeEndian<i64> ) -> <i64 as Sub<&NativeEndian<i64>>>::Output Performs the `-` operation. Read more1.0.0 · source### impl Sub<&i64> for i64 #### type Output = <i64 as Sub<i64>>::Output The resulting type after applying the `-` operator.#### fn sub(self, other: &i64) -> <i64 as Sub<i64>>::Output Performs the `-` operation. #### type Output = i64 The resulting type after applying the `-` operator.#### fn sub(self, other: BigEndian<i64>) -> <i64 as Sub<BigEndian<i64>>>::Output Performs the `-` operation. #### type Output = i64 The resulting type after applying the `-` operator.#### fn sub( self, other: LittleEndian<i64> ) -> <i64 as Sub<LittleEndian<i64>>>::Output Performs the `-` operation. #### type Output = i64 The resulting type after applying the `-` operator.#### fn sub( self, other: NativeEndian<i64> ) -> <i64 as Sub<NativeEndian<i64>>>::Output Performs the `-` operation. Read more1.0.0 · source### impl Sub<i64> for i64 #### type Output = i64 The resulting type after applying the `-` operator.#### fn sub(self, other: i64) -> i64 Performs the `-` operation. Read more1.22.0 · source### impl SubAssign<&i64> for i64 #### fn sub_assign(&mut self, other: &i64) Performs the `-=` operation. Read more1.8.0 · source### impl SubAssign<i64> for i64 #### fn sub_assign(&mut self, other: i64) Performs the `-=` operation. Read more1.12.0 · source### impl<'a> Sum<&'a i64> for i64 #### fn sum<I>(iter: I) -> i64where I: Iterator<Item = &'a i64>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.12.0 · source### impl Sum<i64> for i64 #### fn sum<I>(iter: I) -> i64where I: Iterator<Item = i64>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.34.0 · source### impl TryFrom<i128> for i64 #### fn try_from(u: i128) -> Result<i64, <i64 as TryFrom<i128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<isize> for i64 #### fn try_from(value: isize) -> Result<i64, <i64 as TryFrom<isize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u128> for i64 #### fn try_from(u: u128) -> Result<i64, <i64 as TryFrom<u128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u64> for i64 #### fn try_from(u: u64) -> Result<i64, <i64 as TryFrom<u64>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<usize> for i64 #### fn try_from(u: usize) -> Result<i64, <i64 as TryFrom<usize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.42.0 · source### impl UpperExp for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl UpperHex for i64 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl ValueType for i64 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) This method is passed a byte slice which contains the byte representation of `self`. It must zero out any bytes which are uninitialized (e.g. padding bytes).### impl ConstParamTy for i64 1.0.0 · source### impl Copy for i64 1.0.0 · source### impl Eq for i64 ### impl StructuralEq for i64 ### impl StructuralPartialEq for i64 ### impl TrustedStep for i64 Type Alias wasmer_types::CodeOffset === ``` pub type CodeOffset = u32; ``` Offset in bytes from the beginning of the function. Trait Implementations --- ### impl Add<&BigEndian<u32>> for u32 #### type Output = u32 The resulting type after applying the `+` operator.#### fn add(self, other: &BigEndian<u32>) -> <u32 as Add<&BigEndian<u32>>>::Output Performs the `+` operation. #### type Output = u32 The resulting type after applying the `+` operator.#### fn add( self, other: &LittleEndian<u32> ) -> <u32 as Add<&LittleEndian<u32>>>::Output Performs the `+` operation. #### type Output = u32 The resulting type after applying the `+` operator.#### fn add( self, other: &NativeEndian<u32> ) -> <u32 as Add<&NativeEndian<u32>>>::Output Performs the `+` operation. Read more1.0.0 · source### impl Add<&u32> for u32 #### type Output = <u32 as Add<u32>>::Output The resulting type after applying the `+` operator.#### fn add(self, other: &u32) -> <u32 as Add<u32>>::Output Performs the `+` operation. #### type Output = u32 The resulting type after applying the `+` operator.#### fn add(self, other: BigEndian<u32>) -> <u32 as Add<BigEndian<u32>>>::Output Performs the `+` operation. #### type Output = u32 The resulting type after applying the `+` operator.#### fn add( self, other: LittleEndian<u32> ) -> <u32 as Add<LittleEndian<u32>>>::Output Performs the `+` operation. #### type Output = u32 The resulting type after applying the `+` operator.#### fn add( self, other: NativeEndian<u32> ) -> <u32 as Add<NativeEndian<u32>>>::Output Performs the `+` operation. Read more1.0.0 · source### impl Add<u32> for u32 #### type Output = u32 The resulting type after applying the `+` operator.#### fn add(self, other: u32) -> u32 Performs the `+` operation. Read more1.22.0 · source### impl AddAssign<&u32> for u32 #### fn add_assign(&mut self, other: &u32) Performs the `+=` operation. Read more1.8.0 · source### impl AddAssign<u32> for u32 #### fn add_assign(&mut self, other: u32) Performs the `+=` operation. Read more1.0.0 · source### impl Binary for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl BitAnd<&BigEndian<u32>> for u32 #### type Output = u32 The resulting type after applying the `&` operator.#### fn bitand( self, other: &BigEndian<u32> ) -> <u32 as BitAnd<&BigEndian<u32>>>::Output Performs the `&` operation. #### type Output = u32 The resulting type after applying the `&` operator.#### fn bitand( self, other: &LittleEndian<u32> ) -> <u32 as BitAnd<&LittleEndian<u32>>>::Output Performs the `&` operation. #### type Output = u32 The resulting type after applying the `&` operator.#### fn bitand( self, other: &NativeEndian<u32> ) -> <u32 as BitAnd<&NativeEndian<u32>>>::Output Performs the `&` operation. Read more1.0.0 · source### impl BitAnd<&u32> for u32 #### type Output = <u32 as BitAnd<u32>>::Output The resulting type after applying the `&` operator.#### fn bitand(self, other: &u32) -> <u32 as BitAnd<u32>>::Output Performs the `&` operation. #### type Output = u32 The resulting type after applying the `&` operator.#### fn bitand( self, other: BigEndian<u32> ) -> <u32 as BitAnd<BigEndian<u32>>>::Output Performs the `&` operation. #### type Output = u32 The resulting type after applying the `&` operator.#### fn bitand( self, other: LittleEndian<u32> ) -> <u32 as BitAnd<LittleEndian<u32>>>::Output Performs the `&` operation. #### type Output = u32 The resulting type after applying the `&` operator.#### fn bitand( self, other: NativeEndian<u32> ) -> <u32 as BitAnd<NativeEndian<u32>>>::Output Performs the `&` operation. Read more1.0.0 · source### impl BitAnd<u32> for u32 #### type Output = u32 The resulting type after applying the `&` operator.#### fn bitand(self, rhs: u32) -> u32 Performs the `&` operation. Read more1.22.0 · source### impl BitAndAssign<&u32> for u32 #### fn bitand_assign(&mut self, other: &u32) Performs the `&=` operation. Read more1.8.0 · source### impl BitAndAssign<u32> for u32 #### fn bitand_assign(&mut self, other: u32) Performs the `&=` operation. #### type Output = u32 The resulting type after applying the `|` operator.#### fn bitor( self, other: &BigEndian<u32> ) -> <u32 as BitOr<&BigEndian<u32>>>::Output Performs the `|` operation. #### type Output = u32 The resulting type after applying the `|` operator.#### fn bitor( self, other: &LittleEndian<u32> ) -> <u32 as BitOr<&LittleEndian<u32>>>::Output Performs the `|` operation. #### type Output = u32 The resulting type after applying the `|` operator.#### fn bitor( self, other: &NativeEndian<u32> ) -> <u32 as BitOr<&NativeEndian<u32>>>::Output Performs the `|` operation. Read more1.0.0 · source### impl BitOr<&u32> for u32 #### type Output = <u32 as BitOr<u32>>::Output The resulting type after applying the `|` operator.#### fn bitor(self, other: &u32) -> <u32 as BitOr<u32>>::Output Performs the `|` operation. #### type Output = u32 The resulting type after applying the `|` operator.#### fn bitor(self, other: BigEndian<u32>) -> <u32 as BitOr<BigEndian<u32>>>::Output Performs the `|` operation. #### type Output = u32 The resulting type after applying the `|` operator.#### fn bitor( self, other: LittleEndian<u32> ) -> <u32 as BitOr<LittleEndian<u32>>>::Output Performs the `|` operation. #### type Output = u32 The resulting type after applying the `|` operator.#### fn bitor( self, other: NativeEndian<u32> ) -> <u32 as BitOr<NativeEndian<u32>>>::Output Performs the `|` operation. Read more1.45.0 · source### impl BitOr<NonZeroU32> for u32 #### type Output = NonZeroU32 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: NonZeroU32) -> <u32 as BitOr<NonZeroU32>>::Output Performs the `|` operation. Read more1.0.0 · source### impl BitOr<u32> for u32 #### type Output = u32 The resulting type after applying the `|` operator.#### fn bitor(self, rhs: u32) -> u32 Performs the `|` operation. Read more1.22.0 · source### impl BitOrAssign<&u32> for u32 #### fn bitor_assign(&mut self, other: &u32) Performs the `|=` operation. Read more1.8.0 · source### impl BitOrAssign<u32> for u32 #### fn bitor_assign(&mut self, other: u32) Performs the `|=` operation. #### type Output = u32 The resulting type after applying the `^` operator.#### fn bitxor( self, other: &BigEndian<u32> ) -> <u32 as BitXor<&BigEndian<u32>>>::Output Performs the `^` operation. #### type Output = u32 The resulting type after applying the `^` operator.#### fn bitxor( self, other: &LittleEndian<u32> ) -> <u32 as BitXor<&LittleEndian<u32>>>::Output Performs the `^` operation. #### type Output = u32 The resulting type after applying the `^` operator.#### fn bitxor( self, other: &NativeEndian<u32> ) -> <u32 as BitXor<&NativeEndian<u32>>>::Output Performs the `^` operation. Read more1.0.0 · source### impl BitXor<&u32> for u32 #### type Output = <u32 as BitXor<u32>>::Output The resulting type after applying the `^` operator.#### fn bitxor(self, other: &u32) -> <u32 as BitXor<u32>>::Output Performs the `^` operation. #### type Output = u32 The resulting type after applying the `^` operator.#### fn bitxor( self, other: BigEndian<u32> ) -> <u32 as BitXor<BigEndian<u32>>>::Output Performs the `^` operation. #### type Output = u32 The resulting type after applying the `^` operator.#### fn bitxor( self, other: LittleEndian<u32> ) -> <u32 as BitXor<LittleEndian<u32>>>::Output Performs the `^` operation. #### type Output = u32 The resulting type after applying the `^` operator.#### fn bitxor( self, other: NativeEndian<u32> ) -> <u32 as BitXor<NativeEndian<u32>>>::Output Performs the `^` operation. Read more1.0.0 · source### impl BitXor<u32> for u32 #### type Output = u32 The resulting type after applying the `^` operator.#### fn bitxor(self, other: u32) -> u32 Performs the `^` operation. Read more1.22.0 · source### impl BitXorAssign<&u32> for u32 #### fn bitxor_assign(&mut self, other: &u32) Performs the `^=` operation. Read more1.8.0 · source### impl BitXorAssign<u32> for u32 #### fn bitxor_assign(&mut self, other: u32) Performs the `^=` operation. Read more1.0.0 · source### impl Debug for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. Read more1.0.0 · source### impl Display for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Output = u32 The resulting type after applying the `/` operator.#### fn div(self, other: &BigEndian<u32>) -> <u32 as Div<&BigEndian<u32>>>::Output Performs the `/` operation. #### type Output = u32 The resulting type after applying the `/` operator.#### fn div( self, other: &LittleEndian<u32> ) -> <u32 as Div<&LittleEndian<u32>>>::Output Performs the `/` operation. #### type Output = u32 The resulting type after applying the `/` operator.#### fn div( self, other: &NativeEndian<u32> ) -> <u32 as Div<&NativeEndian<u32>>>::Output Performs the `/` operation. Read more1.0.0 · source### impl Div<&u32> for u32 #### type Output = <u32 as Div<u32>>::Output The resulting type after applying the `/` operator.#### fn div(self, other: &u32) -> <u32 as Div<u32>>::Output Performs the `/` operation. #### type Output = u32 The resulting type after applying the `/` operator.#### fn div(self, other: BigEndian<u32>) -> <u32 as Div<BigEndian<u32>>>::Output Performs the `/` operation. #### type Output = u32 The resulting type after applying the `/` operator.#### fn div( self, other: LittleEndian<u32> ) -> <u32 as Div<LittleEndian<u32>>>::Output Performs the `/` operation. #### type Output = u32 The resulting type after applying the `/` operator.#### fn div( self, other: NativeEndian<u32> ) -> <u32 as Div<NativeEndian<u32>>>::Output Performs the `/` operation. Read more1.51.0 · source### impl Div<NonZeroU32> for u32 #### fn div(self, other: NonZeroU32) -> u32 This operation rounds towards zero, truncating any fractional part of the exact result, and cannot panic. #### type Output = u32 The resulting type after applying the `/` operator.1.0.0 · source### impl Div<u32> for u32 This operation rounds towards zero, truncating any fractional part of the exact result. #### Panics This operation will panic if `other == 0`. #### type Output = u32 The resulting type after applying the `/` operator.#### fn div(self, other: u32) -> u32 Performs the `/` operation. Read more1.22.0 · source### impl DivAssign<&u32> for u32 #### fn div_assign(&mut self, other: &u32) Performs the `/=` operation. Read more1.8.0 · source### impl DivAssign<u32> for u32 #### fn div_assign(&mut self, other: u32) Performs the `/=` operation. #### fn from(value: &'a BigEndian<u32>) -> u32 Converts to this type from the input type.### impl<'a> From<&'a LittleEndian<u32>> for u32 #### fn from(value: &'a LittleEndian<u32>) -> u32 Converts to this type from the input type.### impl<'a> From<&'a NativeEndian<u32>> for u32 #### fn from(value: &'a NativeEndian<u32>) -> u32 Converts to this type from the input type.### impl From<BigEndian<u32>> for u32 #### fn from(value: BigEndian<u32>) -> u32 Converts to this type from the input type.1.1.0 · source### impl From<Ipv4Addr> for u32 #### fn from(ip: Ipv4Addr) -> u32 Uses `Ipv4Addr::to_bits` to convert an IPv4 address to a host byte order `u32`. ### impl From<LittleEndian<u32>> for u32 #### fn from(value: LittleEndian<u32>) -> u32 Converts to this type from the input type.### impl From<NativeEndian<u32>> for u32 #### fn from(value: NativeEndian<u32>) -> u32 Converts to this type from the input type.1.31.0 · source### impl From<NonZeroU32> for u32 #### fn from(nonzero: NonZeroU32) -> u32 Converts a `NonZeroU32` into an `u32` 1.28.0 · source### impl From<bool> for u32 #### fn from(small: bool) -> u32 Converts a `bool` to a `u32`. The resulting value is `0` for `false` and `1` for `true` values. ##### Examples ``` assert_eq!(u32::from(true), 1); assert_eq!(u32::from(false), 0); ``` 1.13.0 · source### impl From<char> for u32 #### fn from(c: char) -> u32 Converts a `char` into a `u32`. ##### Examples ``` use std::mem; let c = 'c'; let u = u32::from(c); assert!(4 == mem::size_of_val(&u)) ``` 1.5.0 · source### impl From<u16> for u32 #### fn from(small: u16) -> u32 Converts `u16` to `u32` losslessly. 1.5.0 · source### impl From<u8> for u32 #### fn from(small: u8) -> u32 Converts `u8` to `u32` losslessly. 1.0.0 · source### impl Hash for u32 #### fn hash<H>(&self, state: &mut H)where H: Hasher, Feeds this value into the given `Hasher`. H: Hasher, Feeds a slice of this type into the given `Hasher`. Read more1.42.0 · source### impl LowerExp for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl LowerHex for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl Mul<&BigEndian<u32>> for u32 #### type Output = u32 The resulting type after applying the `*` operator.#### fn mul(self, other: &BigEndian<u32>) -> <u32 as Mul<&BigEndian<u32>>>::Output Performs the `*` operation. #### type Output = u32 The resulting type after applying the `*` operator.#### fn mul( self, other: &LittleEndian<u32> ) -> <u32 as Mul<&LittleEndian<u32>>>::Output Performs the `*` operation. #### type Output = u32 The resulting type after applying the `*` operator.#### fn mul( self, other: &NativeEndian<u32> ) -> <u32 as Mul<&NativeEndian<u32>>>::Output Performs the `*` operation. Read more1.0.0 · source### impl Mul<&u32> for u32 #### type Output = <u32 as Mul<u32>>::Output The resulting type after applying the `*` operator.#### fn mul(self, other: &u32) -> <u32 as Mul<u32>>::Output Performs the `*` operation. #### type Output = u32 The resulting type after applying the `*` operator.#### fn mul(self, other: BigEndian<u32>) -> <u32 as Mul<BigEndian<u32>>>::Output Performs the `*` operation. Read more1.31.0 · source### impl Mul<Duration> for u32 #### type Output = Duration The resulting type after applying the `*` operator.#### fn mul(self, rhs: Duration) -> Duration Performs the `*` operation. #### type Output = u32 The resulting type after applying the `*` operator.#### fn mul( self, other: LittleEndian<u32> ) -> <u32 as Mul<LittleEndian<u32>>>::Output Performs the `*` operation. #### type Output = u32 The resulting type after applying the `*` operator.#### fn mul( self, other: NativeEndian<u32> ) -> <u32 as Mul<NativeEndian<u32>>>::Output Performs the `*` operation. Read more1.0.0 · source### impl Mul<u32> for u32 #### type Output = u32 The resulting type after applying the `*` operator.#### fn mul(self, other: u32) -> u32 Performs the `*` operation. Read more1.22.0 · source### impl MulAssign<&u32> for u32 #### fn mul_assign(&mut self, other: &u32) Performs the `*=` operation. Read more1.8.0 · source### impl MulAssign<u32> for u32 #### fn mul_assign(&mut self, other: u32) Performs the `*=` operation. #### const WASM_TYPE: Type = Type::I32 Type for this `NativeWasmType`.#### type Abi = u32 The ABI for this type (i32, i64, f32, f64)1.0.0 · source### impl Not for u32 #### type Output = u32 The resulting type after applying the `!` operator.#### fn not(self) -> u32 Performs the unary `!` operation. Read more1.0.0 · source### impl Octal for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl Ord for u32 #### fn cmp(&self, other: &u32) -> Ordering This method returns an `Ordering` between `self` and `other`. Read more1.21.0 · source#### fn max(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the maximum of two values. Read more1.21.0 · source#### fn min(self, other: Self) -> Selfwhere Self: Sized, Compares and returns the minimum of two values. Read more1.50.0 · source#### fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>, Restrict a value to a certain interval. #### fn eq(&self, other: &BigEndian<u32>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<LittleEndian<u32>> for u32 #### fn eq(&self, other: &LittleEndian<u32>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<NativeEndian<u32>> for u32 #### fn eq(&self, other: &NativeEndian<u32>) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl PartialEq<u32> for u32 #### fn eq(&self, other: &u32) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.#### fn ne(&self, other: &u32) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.1.0.0 · source### impl PartialOrd<u32> for u32 #### fn partial_cmp(&self, other: &u32) -> Option<OrderingThis method returns an ordering between `self` and `other` values if one exists. This method tests less than (for `self` and `other`) and is used by the `<` operator. This method tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. This method tests greater than (for `self` and `other`) and is used by the `>` operator. Read more1.12.0 · source### impl<'a> Product<&'a u32> for u32 #### fn product<I>(iter: I) -> u32where I: Iterator<Item = &'a u32>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.1.12.0 · source### impl Product<u32> for u32 #### fn product<I>(iter: I) -> u32where I: Iterator<Item = u32>, Method which takes an iterator and generates `Self` from the elements by multiplying the items.### impl Rem<&BigEndian<u32>> for u32 #### type Output = u32 The resulting type after applying the `%` operator.#### fn rem(self, other: &BigEndian<u32>) -> <u32 as Rem<&BigEndian<u32>>>::Output Performs the `%` operation. #### type Output = u32 The resulting type after applying the `%` operator.#### fn rem( self, other: &LittleEndian<u32> ) -> <u32 as Rem<&LittleEndian<u32>>>::Output Performs the `%` operation. #### type Output = u32 The resulting type after applying the `%` operator.#### fn rem( self, other: &NativeEndian<u32> ) -> <u32 as Rem<&NativeEndian<u32>>>::Output Performs the `%` operation. Read more1.0.0 · source### impl Rem<&u32> for u32 #### type Output = <u32 as Rem<u32>>::Output The resulting type after applying the `%` operator.#### fn rem(self, other: &u32) -> <u32 as Rem<u32>>::Output Performs the `%` operation. #### type Output = u32 The resulting type after applying the `%` operator.#### fn rem(self, other: BigEndian<u32>) -> <u32 as Rem<BigEndian<u32>>>::Output Performs the `%` operation. #### type Output = u32 The resulting type after applying the `%` operator.#### fn rem( self, other: LittleEndian<u32> ) -> <u32 as Rem<LittleEndian<u32>>>::Output Performs the `%` operation. #### type Output = u32 The resulting type after applying the `%` operator.#### fn rem( self, other: NativeEndian<u32> ) -> <u32 as Rem<NativeEndian<u32>>>::Output Performs the `%` operation. Read more1.51.0 · source### impl Rem<NonZeroU32> for u32 #### fn rem(self, other: NonZeroU32) -> u32 This operation satisfies `n % d == n - (n / d) * d`, and cannot panic. #### type Output = u32 The resulting type after applying the `%` operator.1.0.0 · source### impl Rem<u32> for u32 This operation satisfies `n % d == n - (n / d) * d`. The result has the same sign as the left operand. #### Panics This operation will panic if `other == 0`. #### type Output = u32 The resulting type after applying the `%` operator.#### fn rem(self, other: u32) -> u32 Performs the `%` operation. Read more1.22.0 · source### impl RemAssign<&u32> for u32 #### fn rem_assign(&mut self, other: &u32) Performs the `%=` operation. Read more1.8.0 · source### impl RemAssign<u32> for u32 #### fn rem_assign(&mut self, other: u32) Performs the `%=` operation. #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: &BigEndian<u32>) -> <u32 as Shl<&BigEndian<u32>>>::Output Performs the `<<` operation. #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl( self, other: &LittleEndian<u32> ) -> <u32 as Shl<&LittleEndian<u32>>>::Output Performs the `<<` operation. #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl( self, other: &NativeEndian<u32> ) -> <u32 as Shl<&NativeEndian<u32>>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i128> for u32 #### type Output = <u32 as Shl<i128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i128) -> <u32 as Shl<i128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i16> for u32 #### type Output = <u32 as Shl<i16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i16) -> <u32 as Shl<i16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i32> for u32 #### type Output = <u32 as Shl<i32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i32) -> <u32 as Shl<i32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i64> for u32 #### type Output = <u32 as Shl<i64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i64) -> <u32 as Shl<i64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&i8> for u32 #### type Output = <u32 as Shl<i8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &i8) -> <u32 as Shl<i8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&isize> for u32 #### type Output = <u32 as Shl<isize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &isize) -> <u32 as Shl<isize>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u128> for u32 #### type Output = <u32 as Shl<u128>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u128) -> <u32 as Shl<u128>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u16> for u32 #### type Output = <u32 as Shl<u16>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u16) -> <u32 as Shl<u16>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u32> for u32 #### type Output = <u32 as Shl<u32>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u32) -> <u32 as Shl<u32>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u64> for u32 #### type Output = <u32 as Shl<u64>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u64) -> <u32 as Shl<u64>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&u8> for u32 #### type Output = <u32 as Shl<u8>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &u8) -> <u32 as Shl<u8>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<&usize> for u32 #### type Output = <u32 as Shl<usize>>::Output The resulting type after applying the `<<` operator.#### fn shl(self, other: &usize) -> <u32 as Shl<usize>>::Output Performs the `<<` operation. #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: BigEndian<u32>) -> <u32 as Shl<BigEndian<u32>>>::Output Performs the `<<` operation. #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl( self, other: LittleEndian<u32> ) -> <u32 as Shl<LittleEndian<u32>>>::Output Performs the `<<` operation. #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl( self, other: NativeEndian<u32> ) -> <u32 as Shl<NativeEndian<u32>>>::Output Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i128> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i128) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i16> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i16) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i32> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i32) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i64> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i64) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<i8> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: i8) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<isize> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: isize) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u128> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u128) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u16> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u16) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u32> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u32) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u64> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u64) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<u8> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: u8) -> u32 Performs the `<<` operation. Read more1.0.0 · source### impl Shl<usize> for u32 #### type Output = u32 The resulting type after applying the `<<` operator.#### fn shl(self, other: usize) -> u32 Performs the `<<` operation. Read more1.22.0 · source### impl ShlAssign<&i128> for u32 #### fn shl_assign(&mut self, other: &i128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i16> for u32 #### fn shl_assign(&mut self, other: &i16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i32> for u32 #### fn shl_assign(&mut self, other: &i32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i64> for u32 #### fn shl_assign(&mut self, other: &i64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&i8> for u32 #### fn shl_assign(&mut self, other: &i8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&isize> for u32 #### fn shl_assign(&mut self, other: &isize) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u128> for u32 #### fn shl_assign(&mut self, other: &u128) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u16> for u32 #### fn shl_assign(&mut self, other: &u16) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u32> for u32 #### fn shl_assign(&mut self, other: &u32) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u64> for u32 #### fn shl_assign(&mut self, other: &u64) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&u8> for u32 #### fn shl_assign(&mut self, other: &u8) Performs the `<<=` operation. Read more1.22.0 · source### impl ShlAssign<&usize> for u32 #### fn shl_assign(&mut self, other: &usize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i128> for u32 #### fn shl_assign(&mut self, other: i128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i16> for u32 #### fn shl_assign(&mut self, other: i16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i32> for u32 #### fn shl_assign(&mut self, other: i32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i64> for u32 #### fn shl_assign(&mut self, other: i64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<i8> for u32 #### fn shl_assign(&mut self, other: i8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<isize> for u32 #### fn shl_assign(&mut self, other: isize) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u128> for u32 #### fn shl_assign(&mut self, other: u128) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u16> for u32 #### fn shl_assign(&mut self, other: u16) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u32> for u32 #### fn shl_assign(&mut self, other: u32) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u64> for u32 #### fn shl_assign(&mut self, other: u64) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<u8> for u32 #### fn shl_assign(&mut self, other: u8) Performs the `<<=` operation. Read more1.8.0 · source### impl ShlAssign<usize> for u32 #### fn shl_assign(&mut self, other: usize) Performs the `<<=` operation. #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: &BigEndian<u32>) -> <u32 as Shr<&BigEndian<u32>>>::Output Performs the `>>` operation. #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr( self, other: &LittleEndian<u32> ) -> <u32 as Shr<&LittleEndian<u32>>>::Output Performs the `>>` operation. #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr( self, other: &NativeEndian<u32> ) -> <u32 as Shr<&NativeEndian<u32>>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i128> for u32 #### type Output = <u32 as Shr<i128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i128) -> <u32 as Shr<i128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i16> for u32 #### type Output = <u32 as Shr<i16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i16) -> <u32 as Shr<i16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i32> for u32 #### type Output = <u32 as Shr<i32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i32) -> <u32 as Shr<i32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i64> for u32 #### type Output = <u32 as Shr<i64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i64) -> <u32 as Shr<i64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&i8> for u32 #### type Output = <u32 as Shr<i8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &i8) -> <u32 as Shr<i8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&isize> for u32 #### type Output = <u32 as Shr<isize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &isize) -> <u32 as Shr<isize>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u128> for u32 #### type Output = <u32 as Shr<u128>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u128) -> <u32 as Shr<u128>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u16> for u32 #### type Output = <u32 as Shr<u16>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u16) -> <u32 as Shr<u16>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u32> for u32 #### type Output = <u32 as Shr<u32>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u32) -> <u32 as Shr<u32>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u64> for u32 #### type Output = <u32 as Shr<u64>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u64) -> <u32 as Shr<u64>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&u8> for u32 #### type Output = <u32 as Shr<u8>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &u8) -> <u32 as Shr<u8>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<&usize> for u32 #### type Output = <u32 as Shr<usize>>::Output The resulting type after applying the `>>` operator.#### fn shr(self, other: &usize) -> <u32 as Shr<usize>>::Output Performs the `>>` operation. #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: BigEndian<u32>) -> <u32 as Shr<BigEndian<u32>>>::Output Performs the `>>` operation. #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr( self, other: LittleEndian<u32> ) -> <u32 as Shr<LittleEndian<u32>>>::Output Performs the `>>` operation. #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr( self, other: NativeEndian<u32> ) -> <u32 as Shr<NativeEndian<u32>>>::Output Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i128> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i128) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i16> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i16) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i32> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i32) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i64> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i64) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<i8> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: i8) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<isize> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: isize) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u128> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u128) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u16> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u16) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u32> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u32) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u64> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u64) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<u8> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: u8) -> u32 Performs the `>>` operation. Read more1.0.0 · source### impl Shr<usize> for u32 #### type Output = u32 The resulting type after applying the `>>` operator.#### fn shr(self, other: usize) -> u32 Performs the `>>` operation. Read more1.22.0 · source### impl ShrAssign<&i128> for u32 #### fn shr_assign(&mut self, other: &i128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i16> for u32 #### fn shr_assign(&mut self, other: &i16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i32> for u32 #### fn shr_assign(&mut self, other: &i32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i64> for u32 #### fn shr_assign(&mut self, other: &i64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&i8> for u32 #### fn shr_assign(&mut self, other: &i8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&isize> for u32 #### fn shr_assign(&mut self, other: &isize) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u128> for u32 #### fn shr_assign(&mut self, other: &u128) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u16> for u32 #### fn shr_assign(&mut self, other: &u16) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u32> for u32 #### fn shr_assign(&mut self, other: &u32) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u64> for u32 #### fn shr_assign(&mut self, other: &u64) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&u8> for u32 #### fn shr_assign(&mut self, other: &u8) Performs the `>>=` operation. Read more1.22.0 · source### impl ShrAssign<&usize> for u32 #### fn shr_assign(&mut self, other: &usize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i128> for u32 #### fn shr_assign(&mut self, other: i128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i16> for u32 #### fn shr_assign(&mut self, other: i16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i32> for u32 #### fn shr_assign(&mut self, other: i32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i64> for u32 #### fn shr_assign(&mut self, other: i64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<i8> for u32 #### fn shr_assign(&mut self, other: i8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<isize> for u32 #### fn shr_assign(&mut self, other: isize) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u128> for u32 #### fn shr_assign(&mut self, other: u128) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u16> for u32 #### fn shr_assign(&mut self, other: u16) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u32> for u32 #### fn shr_assign(&mut self, other: u32) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u64> for u32 #### fn shr_assign(&mut self, other: u64) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<u8> for u32 #### fn shr_assign(&mut self, other: u8) Performs the `>>=` operation. Read more1.8.0 · source### impl ShrAssign<usize> for u32 #### fn shr_assign(&mut self, other: usize) Performs the `>>=` operation. #### unsafe fn forward_unchecked(start: u32, n: usize) -> u32 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *successor* of `self` `count` times. 🔬This is a nightly-only experimental API. (`step_trait`)Returns the value that would be obtained by taking the *predecessor* of `self` `count` times. of `self` `count` times. of `self` `count` times. #### type Output = u32 The resulting type after applying the `-` operator.#### fn sub(self, other: &BigEndian<u32>) -> <u32 as Sub<&BigEndian<u32>>>::Output Performs the `-` operation. #### type Output = u32 The resulting type after applying the `-` operator.#### fn sub( self, other: &LittleEndian<u32> ) -> <u32 as Sub<&LittleEndian<u32>>>::Output Performs the `-` operation. #### type Output = u32 The resulting type after applying the `-` operator.#### fn sub( self, other: &NativeEndian<u32> ) -> <u32 as Sub<&NativeEndian<u32>>>::Output Performs the `-` operation. Read more1.0.0 · source### impl Sub<&u32> for u32 #### type Output = <u32 as Sub<u32>>::Output The resulting type after applying the `-` operator.#### fn sub(self, other: &u32) -> <u32 as Sub<u32>>::Output Performs the `-` operation. #### type Output = u32 The resulting type after applying the `-` operator.#### fn sub(self, other: BigEndian<u32>) -> <u32 as Sub<BigEndian<u32>>>::Output Performs the `-` operation. #### type Output = u32 The resulting type after applying the `-` operator.#### fn sub( self, other: LittleEndian<u32> ) -> <u32 as Sub<LittleEndian<u32>>>::Output Performs the `-` operation. #### type Output = u32 The resulting type after applying the `-` operator.#### fn sub( self, other: NativeEndian<u32> ) -> <u32 as Sub<NativeEndian<u32>>>::Output Performs the `-` operation. Read more1.0.0 · source### impl Sub<u32> for u32 #### type Output = u32 The resulting type after applying the `-` operator.#### fn sub(self, other: u32) -> u32 Performs the `-` operation. Read more1.22.0 · source### impl SubAssign<&u32> for u32 #### fn sub_assign(&mut self, other: &u32) Performs the `-=` operation. Read more1.8.0 · source### impl SubAssign<u32> for u32 #### fn sub_assign(&mut self, other: u32) Performs the `-=` operation. Read more1.12.0 · source### impl<'a> Sum<&'a u32> for u32 #### fn sum<I>(iter: I) -> u32where I: Iterator<Item = &'a u32>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.12.0 · source### impl Sum<u32> for u32 #### fn sum<I>(iter: I) -> u32where I: Iterator<Item = u32>, Method which takes an iterator and generates `Self` from the elements by “summing up” the items.1.34.0 · source### impl TryFrom<i128> for u32 #### fn try_from(u: i128) -> Result<u32, <u32 as TryFrom<i128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i16> for u32 #### fn try_from(u: i16) -> Result<u32, <u32 as TryFrom<i16>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i32> for u32 #### fn try_from(u: i32) -> Result<u32, <u32 as TryFrom<i32>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i64> for u32 #### fn try_from(u: i64) -> Result<u32, <u32 as TryFrom<i64>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<i8> for u32 #### fn try_from(u: i8) -> Result<u32, <u32 as TryFrom<i8>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<isize> for u32 #### fn try_from(u: isize) -> Result<u32, <u32 as TryFrom<isize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u128> for u32 #### fn try_from(u: u128) -> Result<u32, <u32 as TryFrom<u128>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<u64> for u32 #### fn try_from(u: u64) -> Result<u32, <u32 as TryFrom<u64>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.34.0 · source### impl TryFrom<usize> for u32 #### fn try_from(u: usize) -> Result<u32, <u32 as TryFrom<usize>>::ErrorTry to create the target number type from a source number type. This returns an error if the source value is outside of the range of the target type. #### type Error = TryFromIntError The type returned in the event of a conversion error.1.42.0 · source### impl UpperExp for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.1.0.0 · source### impl UpperHex for u32 #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter.### impl ValueType for u32 #### fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit<u8>]) This method is passed a byte slice which contains the byte representation of `self`. It must zero out any bytes which are uninitialized (e.g. padding bytes).### impl ConstParamTy for u32 1.0.0 · source### impl Copy for u32 1.0.0 · source### impl Eq for u32 ### impl StructuralEq for u32 ### impl StructuralPartialEq for u32 ### impl TrustedStep for u32 Union wasmer_types::RawValue === ``` #[repr(C)] pub union RawValue { pub i32: i32, pub i64: i64, pub u32: u32, pub u64: u64, pub f32: f32, pub f64: f64, pub i128: i128, pub u128: u128, pub funcref: usize, pub externref: usize, pub bytes: [u8; 16], } ``` Raw representation of a WebAssembly value. In most cases you will want to use the type-safe `Value` wrapper instead. Fields --- `i32: i32``i64: i64``u32: u32``u64: u64``f32: f32``f64: f64``i128: i128``u128: u128``funcref: usize``externref: usize``bytes: [u8; 16]`Trait Implementations --- ### impl Clone for RawValue #### fn clone(&self) -> RawValue Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Self Returns the “default value” for a type. #### fn from(value: f32) -> Self Converts to this type from the input type.### impl From<f64> for RawValue #### fn from(value: f64) -> Self Converts to this type from the input type.### impl From<i32> for RawValue #### fn from(value: i32) -> Self Converts to this type from the input type.### impl From<i64> for RawValue #### fn from(value: i64) -> Self Converts to this type from the input type.### impl PartialEq<RawValue> for RawValue #### fn eq(&self, o: &Self) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<f32> for RawValue #### fn eq(&self, o: &f32) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<f64> for RawValue #### fn eq(&self, o: &f64) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<i128> for RawValue #### fn eq(&self, o: &i128) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<i32> for RawValue #### fn eq(&self, o: &i32) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<i64> for RawValue #### fn eq(&self, o: &i64) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<u128> for RawValue #### fn eq(&self, o: &u128) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<u32> for RawValue #### fn eq(&self, o: &u32) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl PartialEq<u64> for RawValue #### fn eq(&self, o: &u64) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Copy for RawValue Auto Trait Implementations --- ### impl RefUnwindSafe for RawValue ### impl Send for RawValue ### impl Sync for RawValue ### impl Unpin for RawValue ### impl UnwindSafe for RawValue Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### type ArchivedMetadata = () The archived version of the pointer metadata for this type.#### fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata Converts some archived metadata to the pointer metadata for itself.### impl<T> Borrow<T> for Twhere T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized, #### fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::ErrorDeserializes using the given deserializer### impl<T> From<T> for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> LayoutRaw for T #### fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutErrorGets the layout of the type.### impl<T> Pointee for T #### type Metadata = () The type for metadata in pointers and references to `Self`.### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.
equivalence
cran
R
Package ‘equivalence’ October 13, 2022 Type Package Title Provides Tests and Graphics for Assessing Tests of Equivalence Version 0.7.2 Date 2016-05-10 Author <NAME> <<EMAIL>> Maintainer <NAME> <<EMAIL>> Depends lattice, boot, PairedData Imports grid Description Provides statistical tests and graphics for assessing tests of equivalence. Such tests have similarity as the alternative hypothesis instead of the null. Sample data sets are included. License GPL-2 NeedsCompilation yes Repository CRAN Date/Publication 2016-05-14 00:10:45 R topics documented: equiv.boo... 2 equiv.... 3 equivalenc... 5 equivalence-deprecate... 6 equivalence.xyplo... 6 pref.4P... 9 pref.LA... 10 print.tos... 11 ptte.dat... 12 ptte.sta... 13 rtos... 15 tos... 16 tost.sta... 18 uf... 20 equiv.boot Regression-based TOST using bootstrap Description This function wraps the regression-based TOST equivalence test inside a bootstrap, extracts and reports the useful quantities, and reports the outcome of the test. The function was written for vali- dating models, and requires paired data points. To use it for this purpose, pass the model predictions as the predictor variable, and the observations (which the predictions are intended to match) as the response variable. Usage equiv.boot(x, y, alpha = 0.05, b0.ii = 0.25, b1.ii = 0.25, reps = 100, b0.ii.absolute = FALSE) Arguments x the predictor variable (commonly predictions) y the response variable (commonly observations) alpha the size of the test b0.ii the half-length of the region of similarity for the intercept, expressed as a pro- portion of the estimate or in the same units as the estimate (see b0.ii.absolute). b1.ii the half-length of the region of similarity for the slope, expressed as a proportion of the estimate. reps the number of bootstrap replicates required b0.ii.absolute option to express b0.ii in the same units as the estimate of the intercept. Details In each case, if the two one-sided confidence interval is inside the region of similarity then the null hypothesis of dissimilarity is rejected. Value A list of length 10, comprising n The effective (non-missing) sample size ci.b0 The intercept TOST confidence interval rs.b0 The intercept region of similarity q.b0 The proportions of simulations below, within, and above, the intercept region of similarity Test.b0 The outcome of the test of the null hypothesis of dissimilarity for the intercept (Reject/Not Reject) ci.b1 The slope TOST confidence interval rs.b1 The slope region of similarity q.b1 The proportions of simulations below, within, and above, the slope region of similarity Test.b1 The outcome of the test of the null hypothesis of dissimilarity for the slope (Reject/Not Reject) eff.alpha The corrected alpha for each of the two independent tests. Acknowledgements Feedback from Mohammad Al-Ahmadi has been very useful for this function. Author(s) <NAME> <<EMAIL>> References Robinson, A.P., <NAME>, and <NAME>. 2005. A regression-based equivalence test for model validation: shifting the burden of proof. Tree Physiology 25, 903-913. See Also lm, boot, tost Examples # Approximately reproduces the first row from Table 2 of Robinson et al. (2005) data(pref.4PG) equiv.boot(pref.4PG$volinc4PG, pref.4PG$stemvolinc) equiv.p Inverts the regression-based TOST equivalence test Description This function generates the TOST intervals for the intercept and the slope of the regression of y on x, and determines the smallest region of indifference in each case that would reject the null hypothesis of dissimilarity. Usage equiv.p(x, y, alpha = 0.05) Arguments x The predictor variable - perhaps the model predictions y The response variable - perhaps the observations alpha The size of the test Details The generated confidence intervals are corrected for experiment-level size of alpha using Bonfer- roni. Value A list of two items: Intercept The smallest half-length of the interval that leads to rejection of the null hypoth- esis of dissimilarity for the intercept, in the units of y. Slope The smallest half-length of the interval that leads to rejection of the null hypoth- esis of dissimilarity for the slope, in the units of the slope. Note The accuracy of the output of this function is contingent on the usual regression assumptions, which are not checked here. Caveat emptor! Author(s) <NAME> <<EMAIL>> References <NAME>., and <NAME>. 2004. Model validation using equivalence tests. Ecological Modelling 176, 349–358. <NAME>., <NAME>, and <NAME>. 2005. A regression-based equivalence test for model validation: shifting the burden of proof. Tree Physiology 25, 903-913. See Also tost.data Examples data(ufc) equiv.p(ufc$Height.m.p, ufc$Height.m) equivalence Equivalence Tests Description This package provides tools to perform several equivalence tests. Note Recent changes: the tost.data function is deprecated as of version 0.5.0; please use tost, which provides more functionality. Author(s) <NAME> <<EMAIL>> References <NAME>. 1981. On hypothesis testing to determine if the mean of a normal distribution is contained in a known interval. Biometrics 37 617. <NAME>., and <NAME>. 2004. Model validation using equivalence tests. Ecological Modelling 176, 349–358. <NAME>. 2003. Testing statistical hypotheses of equivalence. Chapman and Hall/CRC. 284 pp. West<NAME>. 1981. Response to T.B.L. Kirkwood: bioequivalence testing - a need to rethink. Biometrics 37, 589-594. Examples data(ufc) ### Tost tost(ufc$Height.m.p, ufc$Height.m, epsilon = 1) ### equivalence plot ufc.ht <- ufc[!is.na(ufc$Height),] equivalence.xyplot(ufc.ht$Height.m ~ ufc.ht$Height.m.p, alpha=0.05, b0.ii=0.1, b1.ii=0.2, xlab="Predicted height (m)", ylab="Measured height (m)") equivalence-deprecated Deprecated Functions in Equivalence package Description These functions are provided for compatibility with older versions of R only, and may be defunct as soon as the next release. Usage tost.data(x, null = 0, alpha = 0.05, Epsilon = 0.36, absolute = FALSE) Arguments x the sample of paired differences null the value of the parameter in the null hypothesis alpha test size Epsilon magnitude of region of similarity absolute choose units: absolute (TRUE) or relative to the standard deviation (FALSE). Details The original help page for these functions is available at help("oldName-deprecated") (note the quotes). Functions in packages other than the base package are listed in help("pkg-deprecated"). tost.data is superceded by tost. See Also Deprecated equivalence.xyplot Constructs graphical regression-based tests of equivalence inside a lattice coplot Description Implements regression-based tests of equivalence within lattice graphics. Usage equivalence.xyplot(formula, alpha, b0.ii, b1.ii, add.smooth=FALSE, b0.absolute=FALSE, ...) Arguments formula a formula describing the form of conditioning plot. See the manual entry for xyplot for more details. alpha the size of the test b0.ii the half-length of the region of similarity for the intercept, can be relative or absolute (see below). b1.ii the half-length of the region of similarity for the slope. add.smooth adds a loess smooth to the graph. b0.absolute is b0.ii in absolute or relative units? ... extra arguments passed on to xyplot Details The graphic created by this function was proposed by Robinson et al. (2005) as a visual summary of the regression-based TOST. At first glance the graph will look messy; interpretation eases with practice. The following points should be noted. • LS line:A black, solid line of best fit is added. • Mean:A grey vertical bar indicates the mean of x and the TOST confidence interval for the intercept. • b0 R.S.:A shaded polygon is the region of similarity of the intercept, to test the model bias. • Test b0:If the grey vertical bar is within the shaded polygon then reject the null hypothesis of dissimilarity. This is a test of bias. • ...1 -If the region is too low then the predictions are too low. • ...2 -If the region is too high then the predictions are too high. • ...3 -If the region is too narrow then the predictions are too variable. • b1 C.I.:A black vertical bar undermeath the grey bar represents a confidence interval for the slope of the line of best fit. • b1 R.S.:Two black dashed lines are added representing the region of similarity. • Test b1:If the black bar is within the angle described by the dashed black lines then the slope of the observed/predicted regression is significantly similar to 1. This is a test of proportionality. • ...1 -If the bar is too high then the slope is too high; the model over-predicts the higher obser- vations and under-predicts the lower observations. • ...2 -If the bar is too low then the slope is too low; the model underpredicts the higher obser- vations and overpredicts the lower observations (analogous to regression to the mean). • ...3 -If the bar is too narrow then the predictions are too variable. The implementation in Robinson et al. (2005) required shifting so that the predictor has 0 mean. This hack has been removed here so that the basic graph object is a plot of the two variables being compared. Value Run for its side effect of producing a lattice plot object. Warning The accuracy of the output of this function is contingent on the usual regression assumptions, which are not checked here. Caveat emptor! Consider using equiv.boot() for a bootstrap-based solution. Transforming either variable will probably complicate the analysis considerably. Acknowledgements Feedback from <NAME> has been very useful for this function. Note This version produces a regression-based TOST for each level of the conditioning factor. There may be an argument for pooling the test across these levels, in which case some prepanel computations will be helpful. The TOST requires only estimates and standard errors from the data. Therefore the linear model used in the panel function can be replaced by any model that will produce suitable estimates. For example, in applying this function to hierarchical data we have had success using lme() instead. I’m not entirely convinced that all these lines on one image are a good idea. It’s straightforward to remove some, or change the colours. Recommendations for graphics that are visually cleaner are welcome. Author(s) <NAME> <<EMAIL>> References Robinson, A.P., <NAME>, and <NAME>. 2005. A regression-based equivalence test for model validation: shifting the burden of proof. Tree Physiology 25, 903-913. See Also tost.stat, xyplot, equiv.boot Examples data(pref.4PG) equivalence.xyplot(pref.4PG$stemvolinc ~ pref.4PG$volinc4PG, alpha=0.05, b0.ii=0.25, b1.ii=0.25, add.smooth=TRUE, xlab=expression(paste("4PG decadal volume growth (", m^3, ha^-1, decade^-1, ")", sep="")), ylab=expression(paste("Measured decadal volume growth (", m^3, ha^-1, decade^-1, ")", sep=""))) data(pref.LAI) equivalence.xyplot(pref.LAI$lai.pa ~ pref.LAI$lai.bl, alpha=0.05, b0.ii=0.25, b1.ii=0.25, xlab=expression(paste("LAI Beer-Lambert (", m^2, m^-2, ")", sep="")), ylab=expression(paste("LAI Ceptometer (", m^2, m^-2, ")", sep=""))) data(ufc) ufc.ht <- ufc[!is.na(ufc$Height),] equivalence.xyplot(ufc.ht$Height.m ~ ufc.ht$Height.m.p, alpha=0.05, b0.ii=0.1, b1.ii=0.2, xlab="Predicted height (m)", ylab="Measured height (m)") equivalence.xyplot(ufc.ht$Height.m ~ ufc.ht$Height.m.p | ufc.ht$Species, alpha=0.05, b0.ii=0.1, b1.ii=0.2, xlab="Predicted height (m)", ylab="Measured height (m)", subset=ufc.ht$Species %in% levels(ufc.ht$Species)[table(ufc.ht$Species)>5]) pref.4PG Measured and simulated data from PREF, northern Idaho, USA, and 4-PG Description These data are the juxtaposition of model output and field measurements for the Priest River Ex- perimental Forest in northern Idaho, USA. The model was a process-based aspatial forest stand model called 4-PG, developed from 3-PG by Duursma (2004). The data were used to demonstrate a regression-based TOST in Robinson et al (2005). Usage data(pref.4PG) Format A dataset with 35 observations on 33 variables, of which the following two were used for the model validation exercise. stemvolinc measured decadal stem growth in $m^3/ha$ volinc4PG predicted decadal stem growth in $m^3/ha$ Details Nothing in particular. Devil’s club (Oplopanax horridus) is very painful. Source The data are documented in Duursma (2004) and Robinson et al (2005). References <NAME>. 2004. A simple process-based model of forest growth, and a test for the Priest River Experimental Forest. Ph.D. Thesis, University of Idaho, 169 p. <NAME>., <NAME>, and <NAME>. 2005. A regression-based equivalence test for model validation: shifting the burden of proof. Tree Physiology 25, 903-913 Examples data(pref.4PG) pref.LAI Measured Leaf Area Index data from PREF, northern Idaho, USA Description These data are the juxtaposition of model output and field measurements for 36 forest plots in the Priest River Experimental Forest in northern Idaho, USA. The model was based on the Beer- Lambert model (Duursma et al. 2003). The data were used to demonstrate a regression-based TOST in Robinson et al (2005). Usage data(pref.LAI) Format A dataset with 36 observations on 8 variables, the following two of which were used for the test of equivalence: lai.pa LAI as estimated using allometric functions applied to measurements of trees within the sample plot. lai.bl LAI as estimated using the Beer-Lambert model from measurements of interception using a hand-held ceptometer. Details Nothing in particular. PREF, and northern Idaho, are very attractive. Source The data are documented in Duursma et al. (2003) and Robinson et al (2005). References <NAME>., <NAME>, and <NAME>. 2003. Leaf area index inferred from solar beam transmission in mixed conifer forests on complex terrain. Agricultural and Forest Meteorology 118, 221-236. <NAME>., <NAME>, and <NAME>. 2005. A regression-based equivalence test for model validation: shifting the burden of proof. Tree Physiology 25, 903-913. Examples data(pref.LAI) print.tost Print methods for TOST objects Description Printing objects of class ’"tost"’ by simple ’print’ methods. Usage ## S3 method for class 'tost' print(x, ...) Arguments x object of class ’"tost"’ ... arguments to be passed to other functions. Details The function inherits infrastructure from R’s print.htest, so a number of elements have been copied from the help file of that function. Value the argument ’x’, invisibly, as for all ’print’ methods. Author(s) <NAME> <<EMAIL>> See Also tost Examples data(ufc) tost(ufc$Height.m.p, ufc$Height.m, epsilon = 1, paired = TRUE) ptte.data Computes a paired t-test for equivalence from a single sample of a normally-distributed population Description This function computes the test and key test quantities for the paired t-test for equivalence, as doc- umented in Wellek (2003, pp 77-80). This function computes the test from a sample of a normally- distributed population. Usage ptte.data(x, alpha = 0.05, Epsilon = 0.25) Arguments x paired differences alpha test size Epsilon magnitude of region of similarity Details This test requires the assumption of normality of the population. Under that assumption the test is the uniformly most powerful invariant test (Wellek, 2003, pp. 78-79). The function as documented by Wellek (2003) uses units relative to the standard deviation, noting (p. 12) that 0.25 corresponds to a strict test and 0.5 to a liberal test. Value A list with the following components Dissimilarity the outcome of the test of the null hypothesis of dissimilarity Mean the mean of the sample StdDev the standard deviation of the sample n the sample size alpha the size of the test missing the number of observations missing Epsilon the magnitude of the region of similarity cutoff the critical value Tstat the test statistic; if Tstat < cutoff then the null hypothesis is rejected. Power the power of the test evaluated at the observed value Note This test requires the assumption of normality of the population. Under that assumption the test is the uniformly most powerful invariant test (Wellek, 2003, pp. 78-79). The exposition in Robinson and Froese (2004) mistakenly omits the square root of the F-quantile. Author(s) <NAME><<EMAIL>> References <NAME>., and <NAME>ese. 2004. Model validation using equivalence tests. Ecological Modelling 176, 349–358. Wellek, S. 2003. Testing statistical hypotheses of equivalence. Chapman and Hall/CRC. 284 pp. See Also ptte.stat, tost.data Examples data(ufc) ptte.data(ufc$Height.m.p - ufc$Height.m) ptte.stat Computes a paired t-test for equivalence from the mean and standard deviation of a sample from a normally-distributed population Description This function computes the test and key test quantities for the paired t-test for equivalence, as doc- umented in Wellek (2003, pp 77-80). This function computes the test from the mean and standard deviation of a sample of paired differences from a normally-distributed population. Usage ptte.stat(mean, std, n, alpha = 0.05, Epsilon = 0.25) Arguments mean the sample mean std the sample standard deviation n sample size alpha test size Epsilon magnitude of region of similarity Details This test requires the assumption of normality of the population. Under that assumption the test is the uniformly most powerful invariant test (Wellek, 2003, pp. 78-79). This version of the test can be applied post-hoc to any testing situation in which you have the mean, standard deviation, and sample size, and are confident that the sample is drawn from a normally-distributed population. The function as documented by Wellek (2003) uses units relative to the standard deviation, noting (p. 12) that 0.25 corresponds to a strict test and 0.5 to a liberal test. Value A list with the following components Dissimilarity the outcome of the test of the null hypothesis of dissimilarity Mean the mean of the sample StdDev the standard deviation of the sample n the sample size alpha the size of the test Epsilon the magnitude of the region of similarity cutoff the critical value Tstat the test statistic; if Tstat < cutoff then the null hypothesis is rejected. Power the power of the test evaluated at the observed value Note The exposition in Robinson and Froese (2004) mistakenly omits the square root of the F-quantile. Author(s) <NAME> <<EMAIL>> References <NAME>., and <NAME>. 2004. Model validation using equivalence tests. Ecological Modelling 176, 349–358. <NAME>. 2003. Testing statistical hypotheses of equivalence. Chapman and Hall/CRC. 284 pp. See Also ptte.data, tost.stat Examples data(ufc) ptte.stat(mean(ufc$Height.m.p - ufc$Height.m, na.rm=TRUE), sd(ufc$Height.m.p - ufc$Height.m, na.rm=TRUE), sum(!is.na(ufc$Height.m.p - ufc$Height.m))) rtost Computes a robust TOST for equivalence from paired or unpaired data Description This function computes the TOST and key TOST quantities for the two one-sided test for equiva- lence [Schuirmann (1981) and Westlake (1981)], using the robust t-test of Yuen [Yuen and Dixon (1973), Yuen (1974)] in place of the standard Welch t test (t.test stats). The yuen t test makes no as- sumption of normality. The function computes the robust TOST for a sample of paired differences or for two samples. The function performs almost as well as the Welch t test when the population distribution is normal and is more robust than the Welch t test in the face of non-normality (e.g., dis- tributions that are long-tailed, heteroscedastic, or contaminated by outliers)[Yuen and Dixon (1973), Yuen (1974)]. Usage rtost(x, y = NULL, alpha = 0.05, epsilon = 0.31, tr = 0.2, ...) Arguments x the first (or only) sample y the second sample alpha test size tr the proportion (percent/100) of the data set to be trimmed epsilon magnitude of region of similarity ... arguments to be passed to yuen.t.test Details The rtost function is wrapped around the yuen PairedData t test, a robust variant of the t test using trimmed means and winsorized variances. It provides tosts for the same range of designs, accepts the same arguments, and handles missing values the same way as tost equivalence. For the tost, the user must set epsilon, which is the magnitude of region similarity. Warning: with tr > 0.25 type I error control might be poor. Value A list with the following components mean.diff the mean of the difference se.diff the standard error of the difference alpha the size of the test ci.diff the 1-alpha confidence interval for the difference df the degrees of freedom used for the confidence interval epsilon the magnitude of the region of similarity result the outcome of the test of the null hypothesis of dissimilarity p.value the p-value of the significance test check.me the confidence interval corresponding to the p-value Note This test is the tost for equivalence (tost equivalence) wrapped around the robust, trimmed mean, winsorized variance yuen.t.test (yuen PairedData). Author(s) <NAME> <<EMAIL>> References <NAME>. 1981. On hypothesis testing to determine if the mean of a normal distribution is contained in a known interval. Biometrics 37, 617. <NAME>., and <NAME>. 2004. Model validation using equivalence tests. Ecological Modelling 176, 349–358. <NAME>. 2003. Testing statistical hypotheses of equivalence. Chapman and Hall/CRC. 284 pp. Westlake, W.J. 1981. Response to T.B.L. Kirkwood: bioequivalence testing - a need to rethink. Biometrics 37, 589-594. <NAME>. (1974) The two-sample trimmed t for unequal population variances. Biometrika, 61, 165-170. <NAME>., and <NAME>. (1973) The approximate behavior and performance of the two-sample trimmed t. Biometrika, 60, 369-374. See Also tost, yuen.t.test Examples data(ufc) rtost(ufc$Height.m.p, ufc$Height.m, epsilon = 1, tr = 0.2) tost Computes a TOST for equivalence from paired or unpaired data Description This function computes the test and key test quantities for the two one-sided test for equivalence, as documented in Schuirmann (1981) and Westlake (1981). The function computes the test for a sample of paired differences or two samples, assumed to be from a normally-distributed population. Much code in the function has been copied and adapted from R’s t.test.default function. Usage tost(x, y = NULL, epsilon = 1, paired = FALSE, var.equal = FALSE, conf.level = 0.95, alpha = NULL, ...) Arguments x the first (or only) sample y the second sample epsilon magnitude of region of similarity paired a logical indicating whether you want a paired tost var.equal a logical variable indicating whether to treat the two variances as being equal. If ’TRUE’ then the pooled variance is used to estimate the variance otherwise the Welch (or Satterthwaite) approximation to the degrees of freedom is used. conf.level confidence level of the interval alpha test size (for backwards-compatibility, overrides conf.level) ... arguments to be passed to other functions. Details The function inherits infrastructure from R’s t.test.default, so a number of elements have been copied from the help file of that function. This test requires the assumption of normality of the population, or an invocation of large-sample theory. The function wraps around the t.test function, so it provides tosts for the same range of designs, accepts the same arguments, and handles missing values the same way. If ’paired’ is ’TRUE’ then both ’x’ and ’y’ must be specified and they must be the same length. Missing values are silently removed (in pairs if ’paired’ is ’TRUE’). If ’var.equal’ is ’TRUE’ then the pooled estimate of the variance is used. By default, if ’var.equal’ is ’FALSE’ then the variance is estimated separately for both groups and the Welch modification to the degrees of freedom is used. Value A list with the following components estimate the mean of the difference se.diff the standard error of the difference alpha the size of the test data.name a character string giving the name(s) of the data ci.diff the 1-alpha confidence interval for the difference parameter the degrees of freedom used for the confidence interval epsilon the magnitude of the region of similarity result the outcome of the test of the null hypothesis of dissimilarity method a character string indicating what type of t-test was performed null.value the specified hypothesized value of the mean or mean difference depending on whether it was a one-sample tost or a two-sample tost. tost.p.value the p-value of the tost significance test tost.interval the two one-sided confidence interval corresponding to the test. Note This test requires the assumption of normality of the population. The components of the test are t-based confidence intervals, so the Central Limit Theorem and Slutsky’s Theorem may be relevant to its application in large samples. Author(s) <NAME> <<EMAIL>> References <NAME>. 1981. On hypothesis testing to determine if the mean of a normal distribution is contained in a known interval. Biometrics 37 617. <NAME>., and <NAME>. 2004. Model validation using equivalence tests. Ecological Modelling 176, 349–358. <NAME>. 2003. Testing statistical hypotheses of equivalence. Chapman and Hall/CRC. 284 pp. Westlake, W.J. 1981. Response to T.<NAME>: bioequivalence testing - a need to rethink. Biometrics 37, 589-594. See Also tost.stat, ptte.data Examples data(ufc) tost(ufc$Height.m.p, ufc$Height.m, epsilon = 1, paired = TRUE) tost.stat Computes a TOST for equivalence from sample statistics Description This function computes the test and key test quantities for the two one-sided test for equivalence, as documented in Schuirmann (1981) and Westlake (1981). This function computes the test from the statistics of a sample of paired differences of a normally-distributed population. Usage tost.stat(mean, std, n, null = 0, alpha = 0.05, Epsilon = 0.36) Arguments mean sample mean std sample standard deviation n sample size null the value of the parameter in the null hypothesis alpha test size Epsilon magnitude of region of similarity Details This test requires the assumption of normality of the population. Value A list with the following components Dissimilarity the outcome of the test of the null hypothesis of dissimilarity Mean the mean of the sample StdDev the standard deviation of the sample n the non-missing sample size alpha the size of the test Epsilon the magnitude of the region of similarity Interval the half-length of the two one-sided interval Note This test requires the assumption of normality of the population. The components of the test are t-based confidence intervals, so the Central Limit Theorem and Slutsky’s Theorem may be relevant to its application in large samples. Author(s) <NAME> <<EMAIL>> References Schuirmann, D.L. 1981. On hypothesis testing to determine if the mean of a normal distribution is contained in a known interval. Biometrics 37 617. Wellek, S. 2003. Testing statistical hypotheses of equivalence. Chapman and Hall/CRC. 284 pp. Westlake, W.J. 1981. Response to T.B.L. Kirkwood: bioequivalence testing - a need to rethink. Biometrics 37, 589-594. See Also tost.data, ptte.stat Examples data(ufc) tost.stat(mean(ufc$Height.m.p - ufc$Height.m, na.rm=TRUE), sd(ufc$Height.m.p - ufc$Height.m, na.rm=TRUE), sum(!is.na(ufc$Height.m.p - ufc$Height.m))) ufc Upper Flat Creek cruise data Description These are forest measurement data from the Upper Flat Creek unit of the University of Idaho Ex- perimental Forest, measured in 1991. The inventory was based on variable radius plots with 6.43 sq. m. per ha. BAF (Basal Area Factor). The forest stand was 121.5 ha. Usage data(ufc) Format A data frame with 633 observations on the following 12 variables. Plot plot label Tree tree label Species species kbd Dbh tree diameter at 1.37 m. from the ground, measured in millimetres. Height tree height measured in decimetres Height.ft tree height converted to feet Dbh.in tree diameter converted to inches Height.ft.p predicted tree height in feet Height.m tree height in metres Height.m.p predicted tree height in metres Details Plots that were measured with no trees are signified in the dataset by lines that have blank species codes and missing DBH. Source The data are provided courtesy of <NAME> and <NAME> of the University of Idaho Experimental Forest. The predicted height comes from the height/diameter model documented in Wykoff et al. (1982). The data and model were used in Robinson et al. (2005). References <NAME>., <NAME>, and <NAME>. 2005. A regression-based equivalence test for model validation: shifting the burden of proof. Tree Physiology 25, 903-913. Wykoff,W.R., <NAME>, and <NAME>. 1982. User’s guide to the stand Prognosis model. GTR-INT 133, USDA Forest Service, Intermountain Research Station, Ogden, UT, 113 p. Examples data(ufc)
atomic_lib
rust
Rust
Crate atomic_lib === `atomic_lib` helps you to get, store, serialize, parse and validate Atomic Data. See the Atomic Data Docs for more information. ### Features * Two stores for Atomic Data: + **In-memory** Store for getting / setting data. Useful for client applications. + **On disk** [Db], powered by Sled. Useful for applications that persist Atomic Data, such as `atomic-server`. * serialize and parse tools for JSON-AD, plain JSON, RDF, Turtle, N-Triples and JSON-LD. * Resource with getters, setters and a `.save` function that creates Commits. * Value converts Atomic Data to Rust native types * Validate Atomic Schema * Commits (transactions / delta’s / changes / updates / versioning / history). * [plugins] system (although not very mature) * collections (pagination, sorting, filtering) * Querying (using triple pattern fragments) (see storelike::Query) * [plugins::invite] for sharing * hierarchy for authorization * [crate::endpoints::Endpoint] for custom API endpoints * [config::Config] files. ### Getting started ``` // Import the `Storelike` trait to get access to most functions use atomic_lib::Storelike; // Start with initializing the in-memory store let store = atomic_lib::Store::init().unwrap(); // Pre-load the default Atomic Data Atoms (from atomicdata.dev), // this is not necessary, but will probably make your project a bit faster store.populate().unwrap(); // We can create a new Resource, linked to the store. // Note that since this store only exists in memory, it's data cannot be accessed from the internet. // Let's make a new Property instance! Let's create "age". let mut new_property = atomic_lib::Resource::new_instance("https://atomicdata.dev/classes/Property", &store).unwrap(); // And add a description for that Property new_property.set_propval_shortname("description", "the age of a person", &store).unwrap(); // A subject URL for the new resource has been created automatically. let subject = new_property.get_subject().clone(); // Now we need to make sure these changes are also applied to the store. // In order to change things in the store, we should use Commits, // which are signed pieces of data that contain state changes. // Because these are signed, we need an Agent, which has a private key to sign Commits. let agent = store.create_agent(Some("my_agent")).unwrap(); store.set_default_agent(agent); let _fails = new_property.save_locally(&store); // But.. when we commit, we get an error! // Because we haven't set all the properties required for the Property class. // We still need to set `shortname` and `datatype`. new_property.set_propval_shortname("shortname", "age", &store).unwrap(); new_property.set_propval_shortname("datatype", atomic_lib::urls::INTEGER, &store).unwrap(); new_property.save_locally(&store).unwrap(); // Now the changes to the resource applied to the store, and we can fetch the newly created resource! let fetched_new_resource = store.get_resource(&subject).unwrap(); assert!(fetched_new_resource.get_shortname("description", &store).unwrap().to_string() == "the age of a person"); ``` Re-exports --- * `pub use atoms::Atom;` * `pub use commit::Commit;` * `pub use errors::AtomicError;` * `pub use errors::AtomicErrorType;` * `pub use resources::Resource;` * `pub use store::Store;` * `pub use storelike::Storelike;` * `pub use values::Value;` Modules --- * agentsLogic for Agents Agents are actors (such as users) that can edit content. https://docs.atomicdata.dev/commits/concepts.html * atomsThe smallest units of data, consisting of a Subject, a Property and a Value * authenticationCheck signatures in authentication headers, find the correct agent. Authorization is done in Hierarchies * clientFunctions for interacting with an Atomic Server * collectionsCollections are dynamic resources that refer to multiple resources. They are constructed using a Query * commitDescribe changes / mutations to data * datatypeDataTypes constrain values of Atoms * errorsMostly contains implementations for Error types. * hierarchyThe Hierarchy model describes how Resources are structured in a tree-like shape. It deals with authorization (read / write permissions, rights, grants) See * mappingBecause writing full URLs is error prone and time consuming, we map URLs to shortnames. These are often user-specific. This section provides tools to store, share and resolve these Mappings. * parseParsing / deserialization / decoding * populatePopulating a Store means adding resources to it. Some of these are the core Atomic Data resources, such as the Property class. These base models are required for having a functioning store. Other populate methods help to set up an Atomic Server, by creating a basic file hierarcy and creating default collections. * resourcesA Resource is a set of Atoms that share a URL. Has methods for saving resources and getting properties inside them. * schemaStructs and models at the core of Atomic Schema (Class, Property, Datatype). * serializeSerialization / formatting / encoding (JSON, RDF, N-Triples) * storeIn-memory store of Atomic data. This provides many methods for finding, changing, serializing and parsing Atomic Data. * storelikeThe Storelike Trait contains many useful methods for maniupulting / retrieving data. * urlsContains some of the most important Atomic Data URLs. * utilsHelper functions for dealing with URLs * validateValidate the Store and create a ValidationReport. Might be deprecated soon, as Validation hasn’t been necessary since parsing has built-in data validation. * valuesA value is the part of an Atom that contains the actual information. Crate atomic_lib === `atomic_lib` helps you to get, store, serialize, parse and validate Atomic Data. See the Atomic Data Docs for more information. ### Features * Two stores for Atomic Data: + **In-memory** Store for getting / setting data. Useful for client applications. + **On disk** [Db], powered by Sled. Useful for applications that persist Atomic Data, such as `atomic-server`. * serialize and parse tools for JSON-AD, plain JSON, RDF, Turtle, N-Triples and JSON-LD. * Resource with getters, setters and a `.save` function that creates Commits. * Value converts Atomic Data to Rust native types * Validate Atomic Schema * Commits (transactions / delta’s / changes / updates / versioning / history). * [plugins] system (although not very mature) * collections (pagination, sorting, filtering) * Querying (using triple pattern fragments) (see storelike::Query) * [plugins::invite] for sharing * hierarchy for authorization * [crate::endpoints::Endpoint] for custom API endpoints * [config::Config] files. ### Getting started ``` // Import the `Storelike` trait to get access to most functions use atomic_lib::Storelike; // Start with initializing the in-memory store let store = atomic_lib::Store::init().unwrap(); // Pre-load the default Atomic Data Atoms (from atomicdata.dev), // this is not necessary, but will probably make your project a bit faster store.populate().unwrap(); // We can create a new Resource, linked to the store. // Note that since this store only exists in memory, it's data cannot be accessed from the internet. // Let's make a new Property instance! Let's create "age". let mut new_property = atomic_lib::Resource::new_instance("https://atomicdata.dev/classes/Property", &store).unwrap(); // And add a description for that Property new_property.set_propval_shortname("description", "the age of a person", &store).unwrap(); // A subject URL for the new resource has been created automatically. let subject = new_property.get_subject().clone(); // Now we need to make sure these changes are also applied to the store. // In order to change things in the store, we should use Commits, // which are signed pieces of data that contain state changes. // Because these are signed, we need an Agent, which has a private key to sign Commits. let agent = store.create_agent(Some("my_agent")).unwrap(); store.set_default_agent(agent); let _fails = new_property.save_locally(&store); // But.. when we commit, we get an error! // Because we haven't set all the properties required for the Property class. // We still need to set `shortname` and `datatype`. new_property.set_propval_shortname("shortname", "age", &store).unwrap(); new_property.set_propval_shortname("datatype", atomic_lib::urls::INTEGER, &store).unwrap(); new_property.save_locally(&store).unwrap(); // Now the changes to the resource applied to the store, and we can fetch the newly created resource! let fetched_new_resource = store.get_resource(&subject).unwrap(); assert!(fetched_new_resource.get_shortname("description", &store).unwrap().to_string() == "the age of a person"); ``` Re-exports --- * `pub use atoms::Atom;` * `pub use commit::Commit;` * `pub use errors::AtomicError;` * `pub use errors::AtomicErrorType;` * `pub use resources::Resource;` * `pub use store::Store;` * `pub use storelike::Storelike;` * `pub use values::Value;` Modules --- * agentsLogic for Agents Agents are actors (such as users) that can edit content. https://docs.atomicdata.dev/commits/concepts.html * atomsThe smallest units of data, consisting of a Subject, a Property and a Value * authenticationCheck signatures in authentication headers, find the correct agent. Authorization is done in Hierarchies * clientFunctions for interacting with an Atomic Server * collectionsCollections are dynamic resources that refer to multiple resources. They are constructed using a Query * commitDescribe changes / mutations to data * datatypeDataTypes constrain values of Atoms * errorsMostly contains implementations for Error types. * hierarchyThe Hierarchy model describes how Resources are structured in a tree-like shape. It deals with authorization (read / write permissions, rights, grants) See * mappingBecause writing full URLs is error prone and time consuming, we map URLs to shortnames. These are often user-specific. This section provides tools to store, share and resolve these Mappings. * parseParsing / deserialization / decoding * populatePopulating a Store means adding resources to it. Some of these are the core Atomic Data resources, such as the Property class. These base models are required for having a functioning store. Other populate methods help to set up an Atomic Server, by creating a basic file hierarcy and creating default collections. * resourcesA Resource is a set of Atoms that share a URL. Has methods for saving resources and getting properties inside them. * schemaStructs and models at the core of Atomic Schema (Class, Property, Datatype). * serializeSerialization / formatting / encoding (JSON, RDF, N-Triples) * storeIn-memory store of Atomic data. This provides many methods for finding, changing, serializing and parsing Atomic Data. * storelikeThe Storelike Trait contains many useful methods for maniupulting / retrieving data. * urlsContains some of the most important Atomic Data URLs. * utilsHelper functions for dealing with URLs * validateValidate the Store and create a ValidationReport. Might be deprecated soon, as Validation hasn’t been necessary since parsing has built-in data validation. * valuesA value is the part of an Atom that contains the actual information. Struct atomic_lib::store::Store === ``` pub struct Store { /* private fields */ } ``` The in-memory store of data, containing the Resources, Properties and Classes Implementations --- ### impl Store #### pub fn init() -> AtomicResult<StoreCreates an empty Store. Run `.populate()` to get useful standard models loaded into your store. Trait Implementations --- ### impl Clone for Store #### fn clone(&self) -> Store Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn add_atoms(&self, atoms: Vec<Atom>) -> AtomicResult<()👎Deprecated since 0.28.0: The atoms abstraction has been deprecated in favor of ResourcesAdds Atoms to the store. Will replace existing Atoms that share Subject / Property combination. Validates datatypes and required props presence.#### fn add_resource_opts( &self, resource: &Resource, check_required_props: bool, update_index: bool, overwrite_existing: bool ) -> AtomicResult<()Adds a Resource to the store. Replaces existing resource with the contents. Does not do any validations.#### fn all_resources( &self, _include_external: bool ) -> Box<dyn Iterator<Item = Resource>Returns an iterator that iterates over all resources in the store. If Include_external is false, this is filtered by selecting only resoureces that match the `self` URL of the store.#### fn get_server_url(&self) -> &str Returns the base URL where the default store is. E.g. `https://example.com` This is where deltas should be sent to. Also useful for Subject URL generation.#### fn get_self_url(&self) -> Option<StringReturns the root URL where this instance of the store is hosted. Should return `None` if this is simply a client and not a server. E.g. `https://example.com`#### fn get_default_agent(&self) -> AtomicResult<AgentReturns the default Agent for applying commits.#### fn get_resource(&self, subject: &str) -> AtomicResult<ResourceReturns a full Resource with native Values. Note that this does *not* construct dynamic Resources, such as collections. If you’re not sure what to use, use `get_resource_extended`.#### fn remove_resource(&self, subject: &str) -> AtomicResult<()Removes a resource from the store. Errors if not present.#### fn set_default_agent(&self, agent: Agent) Sets the default Agent for applying commits.#### fn query(&self, q: &Query) -> AtomicResult<QueryResultSearch the Store, returns the matching subjects.#### fn add_atom_to_index( &self, _atom: &Atom, _resource: &Resource ) -> AtomicResult<()Adds an Atom to the PropSubjectMap. Overwrites if already present. The default implementation for this does not do anything, so overwrite it if your store needs indexing.#### fn add_resource(&self, resource: &Resource) -> AtomicResult<()Adds a Resource to the store. Replaces existing resource with the contents. Updates the index. Validates the fields (checks required props). In most cases, you should use `resource.save()` instead, which uses Commits.#### fn build_index(&self, include_external: bool) -> AtomicResult<()Constructs the value index from all resources in the store. Could take a while.#### fn get_value(&self, subject: &str, property: &str) -> AtomicResult<ValueReturns a single Value from a Resource#### fn create_agent(&self, name: Option<&str>) -> AtomicResult<AgentCreate an Agent, storing its public key. An Agent is required for signing Commits. Returns a tuple of (subject, private_key). Make sure to store the private_key somewhere safe! Does not create a Commit - the recommended way is to use `agent.to_resource().save_locally()`.#### fn export(&self, include_external: bool) -> AtomicResult<StringExports the store to a big JSON-AD file. Sorts the export by first exporting Property Resources, which makes importing faster and more dependent.#### fn fetch_resource(&self, subject: &str) -> AtomicResult<ResourceFetches a resource, makes sure its subject matches. Uses the default agent to sign the request. Save to the store.#### fn get_resource_new(&self, subject: &str) -> Resource Returns an existing resource, or creates a new one with the given Subject#### fn get_class(&self, subject: &str) -> AtomicResult<ClassRetrieves a Class from the store by subject URL and converts it into a Class useful for forms#### fn get_classes_for_subject(&self, subject: &str) -> AtomicResult<Vec<Class>Finds all classes (isA) for any subject. Returns an empty vector if there are none.#### fn get_property(&self, subject: &str) -> AtomicResult<PropertyFetches a property by URL, returns a Property instance#### fn get_resource_extended( &self, subject: &str, skip_dynamic: bool, for_agent: &ForAgent ) -> AtomicResult<ResourceGet’s the resource, parses the Query parameters and calculates dynamic properties. Defaults to get_resource if store doesn’t support extended resources If `for_agent` is None, no authorization checks will be done, and all resources will return. If you want public only resurces, pass `Some(crate::authentication::public_agent)` as the agent. This function is called whenever a Commit is applied. Implement this if you want to have custom handlers for Commits.#### fn handle_not_found( &self, subject: &str, error: AtomicError ) -> AtomicResult<Resource#### fn import(&self, string: &str, parse_opts: &ParseOpts) -> AtomicResult<usizeImports a JSON-AD string, returns the amount of imported resources.#### fn get_path( &self, atomic_path: &str, mapping: Option<&Mapping>, for_agent: &ForAgent ) -> AtomicResult<PathReturnAccepts an Atomic Path string, returns the result value (resource or property value) E.g. `https://example.com description` or `thing isa 0` https://docs.atomicdata.dev/core/paths.html The `for_agent` argument is used to check if the user has rights to the resource. You can pass `None` if you don’t care about the rights (e.g. in client side apps) If you want to perform read rights checks, pass Some `for_agent` subject#### fn post_resource( &self, _subject: &str, _body: Vec<u8>, _for_agent: &ForAgent ) -> AtomicResult<ResourceHandles a HTTP POST request to the store. This is where [crate::endpoints::Endpoint] are used.#### fn populate(&self) -> AtomicResult<()Loads the default store. For DBs it also adds default Collections and Endpoints.#### fn remove_atom_from_index( &self, _atom: &Atom, _resource: &Resource ) -> AtomicResult<()Removes an Atom from the PropSubjectMap.#### fn validate(&self) -> ValidationReport Performs a light validation, without fetching external dataAuto Trait Implementations --- ### impl RefUnwindSafe for Store ### impl Send for Store ### impl Sync for Store ### impl Unpin for Store ### impl UnwindSafe for Store Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Module atomic_lib::serialize === Serialization / formatting / encoding (JSON, RDF, N-Triples) Enums --- * FormatShould list all the supported serialization formats Functions --- * propvals_to_json_ad_mapSerializes a Resource to a Serde JSON Map according to the JSON-AD spec. https://docs.atomicdata.dev/core/json-ad.html * propvals_to_json_ldSerializes a Resource to a Serde JSON Map. Supports both JSON and JSON-LD. If you opt in for JSON-LD, an @context object is created mapping the shortnames to URLs. https://docs.atomicdata.dev/interoperability/json.html#from-atomic-data-to-json-ld * resources_to_json_adSerializes a vector or Resources to a JSON-AD string * serialize_json_array Module atomic_lib::parse === Parsing / deserialization / decoding Structs --- * ParseOptsOptions for parsing (JSON-AD) resources. Many of these are related to rights, as parsing often implies overwriting / setting resources. Enums --- * SaveOpts Constants --- * JSON_AD_MIME Functions --- * parse_json_ad_commit_resourceParse a single Json AD string that represents an incoming Commit. WARNING: Does not match all props to datatypes (in Nested Resources), so it could result in invalid data, if the input data does not match the required datatypes. * parse_json_ad_resourceParse a single Json AD string, convert to Atoms WARNING: Does not match all props to datatypes (in Nested Resources), so it could result in invalid data, if the input data does not match the required datatypes. * parse_json_ad_stringParses JSON-AD string. Accepts an array containing multiple objects, or one single object. * parse_json_array Struct atomic_lib::resources::Resource === ``` pub struct Resource { /* private fields */ } ``` A Resource is a set of Atoms that shares a single Subject. A Resource only contains valid Values, but it *might* lack required properties. All changes to the Resource are applied after committing them (e.g. by using). Implementations --- ### impl Resource #### pub fn check_required_props(&self, store: &impl Storelike) -> AtomicResult<()Fetches all ‘required’ properties. Returns an error if any are missing in this Resource. #### pub fn destroy( &mut self, store: &impl Storelike ) -> AtomicResult<CommitResponseRemoves / deletes the resource from the store by performing a Commit. Recursively deletes the resource’s children. #### pub fn get_children( &self, store: &impl Storelike ) -> AtomicResult<Vec<Resource>Gets the children of this resource. #### pub fn from_propvals(propvals: PropVals, subject: String) -> Resource #### pub fn get(&self, property_url: &str) -> AtomicResult<&ValueGet a value by property URL #### pub fn get_commit_builder(&self) -> &CommitBuilder #### pub fn get_classes(&self, store: &impl Storelike) -> AtomicResult<Vec<Class>Checks if the classes are there, if not, fetches them. Returns an empty vector if there are no classes found. #### pub fn get_main_class(&self) -> AtomicResult<StringReturns the first item of the is_ array #### pub fn get_parent(&self, store: &impl Storelike) -> AtomicResult<ResourceReturns the `Parent` of this Resource. Throws in case of recursion #### pub fn get_parent_tree( &self, store: &impl Storelike ) -> AtomicResult<Vec<Resource>Walks the parent tree upwards until there is no parent, then returns them as a vector. #### pub fn get_propvals(&self) -> &PropVals Returns all PropVals. Useful if you want to iterate over all Atoms / Properties. #### pub fn get_shortname( &self, shortname: &str, store: &impl Storelike ) -> AtomicResult<&ValueGets a value by its property shortname or property URL. #### pub fn get_subject(&self) -> &String #### pub fn has_parent(&self, store: &impl Storelike, parent: &str) -> bool checks if a resouce has a specific parent. iterates over all parents. #### pub fn into_propvals(self) -> PropVals Returns all PropVals. #### pub fn new(subject: String) -> Resource Create a new, empty Resource. #### pub fn new_generate_subject(store: &impl Storelike) -> Resource Create a new resource with a generated Subject #### pub fn new_instance( class_url: &str, store: &impl Storelike ) -> AtomicResult<ResourceCreate a new instance of some Class. The subject is generated, but can be changed. Does not save the resource to the store. #### pub fn push_propval( &mut self, property: &str, value: SubResource, skip_existing: bool ) -> AtomicResult<()Appends a Resource to a specific property through the commitbuilder. Useful if you want to have compact Commits that add things to existing ResourceArrays. #### pub fn remove_propval(&mut self, property_url: &str) Remove a propval from a resource by property URL. #### pub fn remove_propval_shortname( &mut self, property_shortname: &str, store: &impl Storelike ) -> AtomicResult<()Remove a propval from a resource by property URL or shortname. Returns error if propval does not exist in this resource or its class. #### pub fn resolve_shortname_to_property( &self, shortname: &str, store: &impl Storelike ) -> AtomicResult<PropertyTries to resolve the shortname of a Property to a Property. Currently only tries the shortnames for linked classes - not for other properties. #### pub fn reset_commit_builder(&mut self) #### pub fn save(&mut self, store: &impl Storelike) -> AtomicResult<CommitResponseSaves the resource (with all the changes) to the store by creating a Commit. Uses default Agent to sign the Commit. Stores changes on the Subject’s Server by sending a Commit. Returns the generated Commit, the new Resource and the old Resource. #### pub fn save_locally( &mut self, store: &impl Storelike ) -> AtomicResult<CommitResponseSaves the resource (with all the changes) to the store by creating a Commit. Uses default Agent to sign the Commit. Returns the generated Commit and the new Resource. Does not validate rights / hierarchy. Does not store these changes on the server of the Subject - the Commit will be lost, unless you handle it manually. #### pub fn set_class(&mut self, is_a: &str) Overwrites the is_a (Class) of the Resource. #### pub fn set_propval_string( &mut self, property_url: String, value: &str, store: &impl Storelike ) -> AtomicResult<()Insert a Property/Value combination. Overwrites existing Property/Value. Validates the datatype. #### pub fn set_propval( &mut self, property: String, value: Value, store: &impl Storelike ) -> AtomicResult<()Inserts a Property/Value combination. Checks datatype. Overwrites existing. Adds the change to the commit builder’s `set` map. #### pub fn set_propval_unsafe(&mut self, property: String, value: Value) Does not validate property / datatype combination. Inserts a Property/Value combination. Overwrites existing. Adds it to the CommitBuilder. #### pub fn set_propval_shortname( &mut self, property: &str, value: &str, store: &impl Storelike ) -> AtomicResult<()Sets a property / value combination. Property can be a shortname (e.g. ‘description’ instead of the full URL). Returns error if propval does not exist in this resource or its class. #### pub fn set_propvals_unsafe(&mut self, propvals: PropVals) Overwrites all current PropVals. Does not perform validation. #### pub fn set_subject(&mut self, url: String) Changes the subject of the Resource. Does not ‘move’ the Resource See https://github.com/atomicdata-dev/atomic-server/issues/44 #### pub fn to_json_ad(&self) -> AtomicResult<StringConverts Resource to JSON-AD string. #### pub fn to_json(&self, store: &impl Storelike) -> AtomicResult<StringConverts Resource to plain JSON string. #### pub fn to_json_ld(&self, store: &impl Storelike) -> AtomicResult<StringConverts Resource to JSON-LD string, with @context object and RDF compatibility. #### pub fn to_atoms(&self) -> Vec<AtomTrait Implementations --- ### impl Clone for Resource #### fn clone(&self) -> Resource Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn from(val: Resource) -> Self Converts to this type from the input type.### impl From<Resource> for Value #### fn from(val: Resource) -> Self Converts to this type from the input type.### impl Serialize for Resource #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Resource ### impl Send for Resource ### impl Sync for Resource ### impl Unpin for Resource ### impl UnwindSafe for Resource Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. T: for<'de> Deserialize<'de>, Enum atomic_lib::values::Value === ``` pub enum Value { AtomicUrl(String), Date(String), Integer(i64), Float(f64), Markdown(String), ResourceArray(Vec<SubResource>), Slug(String), String(String), Timestamp(i64), NestedResource(SubResource), Resource(Box<Resource>), Boolean(bool), Unsupported(UnsupportedValue), } ``` An individual Value in an Atom. Note that creating values using `Value::from` might result in the wrong Datatype, as the from conversion makes assumptions (e.g. integers are Integers, not Timestamps). Use `Value::SomeDataType()` for explicit creation. Variants --- ### AtomicUrl(String) ### Date(String) ### Integer(i64) ### Float(f64) ### Markdown(String) ### ResourceArray(Vec<SubResource>) ### Slug(String) ### String(String) ### Timestamp(i64) Unix Epoch datetime in milliseconds ### NestedResource(SubResource) ### Resource(Box<Resource>) ### Boolean(bool) ### Unsupported(UnsupportedValue) Implementations --- ### impl Value #### pub fn contains_value(&self, q_val: &Value) -> bool Check if the value `q_val` is present in `val` #### pub fn datatype(&self) -> DataType Returns the datatype for the value #### pub fn new(value: &str, datatype: &DataType) -> AtomicResult<ValueCreates a new Value from an explicit DataType. Fails if the input string does not convert. #### pub fn new_from_string(value: &str, datatype: &str) -> AtomicResult<ValueReturns a new Value, accepts a datatype string #### pub fn to_subjects( &self, parent_path: Option<String> ) -> AtomicResult<Vec<String>Turns the value into a Vector of subject strings. Works for resource arrays with nested resources, full resources, single resources. Returns a path for for Anonymous Nested Resources, which is why you need to pass a parent_path e.g. `http://example.com/foo/bar https://atomicdata.dev/properties/children`. #### pub fn to_bool(&self) -> AtomicResult<bool#### pub fn to_int(&self) -> AtomicResult<i64Returns an Integer, if the Atom is one. #### pub fn to_nested(&self) -> AtomicResult<&PropValsReturns a PropVals Hashmap, if the Atom is a NestedResource #### pub fn to_sortable_string(&self) -> SortableValue Returns a Lexicographically sortable string representation of the value #### pub fn to_reference_index_strings(&self) -> Option<Vec<ReferenceString>Converts one Value to a bunch of indexable items. Returns None for unsupported types. Trait Implementations --- ### impl Clone for Value #### fn clone(&self) -> Value Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn from(val: Box<Resource>) -> Self Converts to this type from the input type.### impl From<HashMap<String, Value, RandomState>> for Value #### fn from(val: PropVals) -> Self Converts to this type from the input type.### impl From<Resource> for Value #### fn from(val: Resource) -> Self Converts to this type from the input type.### impl From<String> for Value #### fn from(val: String) -> Self Converts to this type from the input type.### impl From<SubResource> for Value #### fn from(val: SubResource) -> Self Converts to this type from the input type.### impl From<Vec<&str, Global>> for Value #### fn from(val: Vec<&str>) -> Self Converts to this type from the input type.### impl From<Vec<Resource, Global>> for Value #### fn from(val: Vec<Resource>) -> Self Converts to this type from the input type.### impl From<Vec<String, Global>> for Value #### fn from(val: Vec<String>) -> Self Converts to this type from the input type.### impl From<Vec<SubResource, Global>> for Value #### fn from(val: Vec<SubResource>) -> Self Converts to this type from the input type.### impl From<bool> for Value #### fn from(val: bool) -> Self Converts to this type from the input type.### impl From<f64> for Value #### fn from(val: f64) -> Self Converts to this type from the input type.### impl From<i32> for Value #### fn from(val: i32) -> Self Converts to this type from the input type.### impl From<usize> for Value #### fn from(val: usize) -> Self Converts to this type from the input type.### impl Serialize for Value #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Value ### impl Send for Value ### impl Sync for Value ### impl Unpin for Value ### impl UnwindSafe for Value Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. T: for<'de> Deserialize<'de>, Struct atomic_lib::commit::Commit === ``` pub struct Commit { pub subject: String, pub created_at: i64, pub signer: String, pub set: Option<HashMap<String, Value>>, pub remove: Option<Vec<String>>, pub destroy: Option<bool>, pub signature: Option<String>, pub push: Option<HashMap<String, Value>>, pub previous_commit: Option<String>, pub url: Option<String>, } ``` A Commit is a set of changes to a Resource. Use CommitBuilder if you’re programmatically constructing a Delta. Fields --- `subject: String`The subject URL that is to be modified by this Delta `created_at: i64`The date it was created, as a unix timestamp `signer: String`The URL of the one signing this Commit `set: Option<HashMap<String, Value>>`The set of PropVals that need to be added. Overwrites existing values `remove: Option<Vec<String>>`The set of property URLs that need to be removed `destroy: Option<bool>`If set to true, deletes the entire resource `signature: Option<String>`Base64 encoded signature of the JSON serialized Commit `push: Option<HashMap<String, Value>>`List of Properties and Arrays to be appended to them `previous_commit: Option<String>`The previously applied commit to this Resource. `url: Option<String>`The URL of the Commit Implementations --- ### impl Commit #### pub fn apply_opts( &self, store: &impl Storelike, opts: &CommitOpts ) -> AtomicResult<CommitResponseApply a single signed Commit to the store. Creates, edits or destroys a resource. Allows for control over which validations should be performed. Returns the generated Commit, the old Resource and the new Resource. #### pub fn apply_changes( &self, resource: Resource, store: &impl Storelike, update_index: bool ) -> AtomicResult<ResourceUpdates the values in the Resource according to the `set`, `remove`, `push`, and `destroy` attributes in the Commit. Optionally also updates the index in the Store. The Old Resource is only needed when `update_index` is true, and is used for checking #### pub fn apply_unsafe( &self, store: &impl Storelike ) -> AtomicResult<CommitResponseApplies a commit without performing authorization / signature / schema checks. Does not update the index. #### pub fn from_resource(resource: Resource) -> AtomicResult<CommitConverts a Resource of a Commit into a Commit #### pub fn into_resource(&self, store: &impl Storelike) -> AtomicResult<ResourceConverts the Commit into a Resource with Atomic Values. Creates an identifier using the server_url Works for both Signed and Unsigned Commits #### pub fn get_subject(&self) -> &str #### pub fn serialize_deterministically_json_ad( &self, store: &impl Storelike ) -> AtomicResult<StringGenerates a deterministic serialized JSON-AD representation of the Commit. Removes the signature from the object before serializing, since this function is used to check if the signature is correct. Trait Implementations --- ### impl Clone for Commit #### fn clone(&self) -> Commit Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Commit ### impl Send for Commit ### impl Sync for Commit ### impl Unpin for Commit ### impl UnwindSafe for Commit Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Module atomic_lib::collections === Collections are dynamic resources that refer to multiple resources. They are constructed using a Query Structs --- * CollectionDynamic resource used for ordering, filtering and querying content. Contains members / results. Use CollectionBuilder if you don’t (yet) need the results. Features pagination. * CollectionBuilderUsed to construct a Collection. Does not contain results / members. Has to be constructed using `Collection::new()` or `storelike.new_collection()`. Functions --- * construct_collection_from_paramsBuilds a collection from query params and the passed Collection resource. The query params are used to override the stored Collection resource properties. This also sets defaults for Collection properties when fields are missing * create_collection_resource_for_classCreates a Collection resource in the Store for a Class, for example `/documents`. Does not save it, though. * sort_resourcesSorts a vector or resources by some property. Struct atomic_lib::storelike::Query === ``` pub struct Query { pub property: Option<String>, pub value: Option<Value>, pub limit: Option<usize>, pub start_val: Option<Value>, pub end_val: Option<Value>, pub offset: usize, pub sort_by: Option<String>, pub sort_desc: bool, pub include_external: bool, pub include_nested: bool, pub for_agent: ForAgent, } ``` Use this to construct a list of Resources Fields --- `property: Option<String>`Filter by Property `value: Option<Value>`Filter by Value `limit: Option<usize>`Maximum of items to return, if none returns all items. `start_val: Option<Value>`Value at which to begin lexicographically sorting things. `end_val: Option<Value>`Value at which to stop lexicographically sorting things. `offset: usize`How many items to skip from the first one `sort_by: Option<String>`The Property URL that is used to sort the results `sort_desc: bool`Sort descending instead of ascending. `include_external: bool`Whether to include non-server resources `include_nested: bool`Whether to include full Resources in the result, if not, will add empty vector here. `for_agent: ForAgent`For which Agent the query is executed. Pass `None` if you want to skip permission checks. Implementations --- ### impl Query #### pub fn new() -> Self #### pub fn new_prop_val(prop: &str, val: &str) -> Self Search for a property-value combination #### pub fn new_class(class: &str) -> Self Search for instances of some Class Trait Implementations --- ### impl Debug for Query #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Self Returns the “default value” for a type. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Query ### impl Send for Query ### impl Sync for Query ### impl Unpin for Query ### impl UnwindSafe for Query Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Module atomic_lib::hierarchy === The Hierarchy model describes how Resources are structured in a tree-like shape. It deals with authorization (read / write permissions, rights, grants) See Enums --- * Right Functions --- * add_childrenLooks for children relations, adds to the resource. Performs a Query, might be expensive. * check_appendDoes the Agent have the right to *append* to its parent? This checks the `append` rights, and if that fails, checks the `write` right. Throws if not allowed. Returns string with explanation if allowed. * check_readDoes the Agent have the right to read / view the properties of the selected resource, or any of its parents? Throws if not allowed. Returns string with explanation if allowed. * check_rightsRecursively checks a Resource and its Parents for rights. Throws if not allowed. Returns string with explanation if allowed. * check_writeThrows if not allowed. Returns string with explanation if allowed. Struct atomic_lib::atoms::Atom === ``` pub struct Atom { pub subject: String, pub property: String, pub value: Value, } ``` The Atom is the smallest meaningful piece of data. It describes how one value relates to a subject. A [Resource] can be converted into a bunch of Atoms. Fields --- `subject: String`The URL where the resource is located `property: String``value: Value`Implementations --- ### impl Atom #### pub fn new(subject: String, property: String, value: Value) -> Self #### pub fn values_to_subjects(&self) -> AtomicResult<Vec<String>If the Atom’s Value is an Array, this will try to convert it into a set of Subjects. Used for indexing. #### pub fn to_indexable_atoms(&self) -> Vec<IndexAtomConverts one Atom to a series of stringified values that can be indexed. Trait Implementations --- ### impl Clone for Atom #### fn clone(&self) -> Atom Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, fmt: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for Atom ### impl Send for Atom ### impl Sync for Atom ### impl Unpin for Atom ### impl UnwindSafe for Atom Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Struct atomic_lib::errors::AtomicError === ``` pub struct AtomicError { pub message: String, pub error_type: AtomicErrorType, pub subject: Option<String>, } ``` Fields --- `message: String``error_type: AtomicErrorType``subject: Option<String>`Implementations --- ### impl AtomicError #### pub fn method_not_allowed(message: &str) -> AtomicError #### pub fn not_found(message: String) -> AtomicError A server will probably return a 404. #### pub fn unauthorized(message: String) -> AtomicError A server will probably return this error as a 403. #### pub fn other_error(message: String) -> AtomicError A server will probably return a 500. #### pub fn parse_error( message: &str, subject: Option<&str>, property: Option<&str> ) -> AtomicError #### pub fn into_resource(self, subject: String) -> Resource Converts the Error into a Resource. This helps clients to handle errors, such as show error messages in the right Form input fields. #### pub fn set_subject(self, subject: &str) -> Self Trait Implementations --- ### impl Clone for AtomicError #### fn clone(&self) -> AtomicError Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn description(&self) -> &str 👎Deprecated since 1.42.0: use the Display impl or to_string() Read more1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting#### fn provide<'a>(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. #### fn from(message: &str) -> Self Converts to this type from the input type.### impl From<Box<dyn Error, Global>> for AtomicError #### fn from(error: Box<dyn Error>) -> Self Converts to this type from the input type.### impl From<DecodeError> for AtomicError #### fn from(error: DecodeError) -> Self Converts to this type from the input type.### impl From<Error> for AtomicError #### fn from(error: Error) -> Self Converts to this type from the input type.### impl From<Error> for AtomicError #### fn from(error: Error) -> Self Converts to this type from the input type.### impl From<FromUtf8Error> for AtomicError #### fn from(error: FromUtf8Error) -> Self Converts to this type from the input type.### impl From<Infallible> for AtomicError #### fn from(error: Infallible) -> Self Converts to this type from the input type.### impl From<ParseBoolError> for AtomicError #### fn from(error: ParseBoolError) -> Self Converts to this type from the input type.### impl From<ParseError> for AtomicError #### fn from(error: ParseError) -> Self Converts to this type from the input type.### impl From<ParseFloatError> for AtomicError #### fn from(error: ParseFloatError) -> Self Converts to this type from the input type.### impl From<ParseIntError> for AtomicError #### fn from(error: ParseIntError) -> Self Converts to this type from the input type.### impl<T> From<PoisonError<T>> for AtomicError #### fn from(error: PoisonError<T>) -> Self Converts to this type from the input type.### impl From<String> for AtomicError #### fn from(message: String) -> Self Converts to this type from the input type.Auto Trait Implementations --- ### impl RefUnwindSafe for AtomicError ### impl Send for AtomicError ### impl Sync for AtomicError ### impl Unpin for AtomicError ### impl UnwindSafe for AtomicError Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<E> Provider for Ewhere E: Error + ?Sized, #### fn provide<'a>(&'a self, demand: &mut Demand<'a>) 🔬This is a nightly-only experimental API. (`provide_any`)Data providers should implement this method to provide *all* values they are able to provide by using `demand`. T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Enum atomic_lib::errors::AtomicErrorType === ``` pub enum AtomicErrorType { NotFoundError, UnauthorizedError, ParseError, OtherError, MethodNotAllowed, } ``` Variants --- ### NotFoundError ### UnauthorizedError ### ParseError ### OtherError ### MethodNotAllowed Trait Implementations --- ### impl Clone for AtomicErrorType #### fn clone(&self) -> AtomicErrorType Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreAuto Trait Implementations --- ### impl RefUnwindSafe for AtomicErrorType ### impl Send for AtomicErrorType ### impl Sync for AtomicErrorType ### impl Unpin for AtomicErrorType ### impl UnwindSafe for AtomicErrorType Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. Read more Trait atomic_lib::storelike::Storelike === ``` pub trait Storelike: Sized { // Required methods fn add_atoms(&self, atoms: Vec<Atom>) -> AtomicResult<()>; fn add_resource_opts( &self, resource: &Resource, check_required_props: bool, update_index: bool, overwrite_existing: bool ) -> AtomicResult<()>; fn all_resources( &self, include_external: bool ) -> Box<dyn Iterator<Item = Resource>>; fn get_server_url(&self) -> &str; fn get_resource(&self, subject: &str) -> AtomicResult<Resource>; fn remove_resource(&self, subject: &str) -> AtomicResult<()>; fn query(&self, q: &Query) -> AtomicResult<QueryResult>; fn set_default_agent(&self, agent: Agent); // Provided methods fn add_atom_to_index( &self, _atom: &Atom, _resource: &Resource ) -> AtomicResult<()> { ... } fn add_resource(&self, resource: &Resource) -> AtomicResult<()> { ... } fn build_index(&self, include_external: bool) -> AtomicResult<()> { ... } fn get_value(&self, subject: &str, property: &str) -> AtomicResult<Value> { ... } fn get_self_url(&self) -> Option<String> { ... } fn get_default_agent(&self) -> AtomicResult<Agent> { ... } fn create_agent(&self, name: Option<&str>) -> AtomicResult<Agent> { ... } fn export(&self, include_external: bool) -> AtomicResult<String> { ... } fn fetch_resource(&self, subject: &str) -> AtomicResult<Resource> { ... } fn get_resource_new(&self, subject: &str) -> Resource { ... } fn get_class(&self, subject: &str) -> AtomicResult<Class> { ... } fn get_classes_for_subject(&self, subject: &str) -> AtomicResult<Vec<Class>> { ... } fn get_property(&self, subject: &str) -> AtomicResult<Property> { ... } fn get_resource_extended( &self, subject: &str, skip_dynamic: bool, for_agent: &ForAgent ) -> AtomicResult<Resource> { ... } fn handle_commit(&self, _commit_response: &CommitResponse) { ... } fn handle_not_found( &self, subject: &str, error: AtomicError ) -> AtomicResult<Resource> { ... } fn import( &self, string: &str, parse_opts: &ParseOpts ) -> AtomicResult<usize> { ... } fn get_path( &self, atomic_path: &str, mapping: Option<&Mapping>, for_agent: &ForAgent ) -> AtomicResult<PathReturn> { ... } fn post_resource( &self, _subject: &str, _body: Vec<u8>, _for_agent: &ForAgent ) -> AtomicResult<Resource> { ... } fn populate(&self) -> AtomicResult<()> { ... } fn remove_atom_from_index( &self, _atom: &Atom, _resource: &Resource ) -> AtomicResult<()> { ... } fn validate(&self) -> ValidationReport { ... } } ``` Storelike provides many useful methods for interacting with an Atomic Store. It serves as a basic store Trait, agnostic of how it functions under the hood. This is useful, because we can create methods for Storelike that will work with either in-memory stores, as well as with persistent on-disk stores. Required Methods --- #### fn add_atoms(&self, atoms: Vec<Atom>) -> AtomicResult<()👎Deprecated since 0.28.0: The atoms abstraction has been deprecated in favor of ResourcesAdds Atoms to the store. Will replace existing Atoms that share Subject / Property combination. Validates datatypes and required props presence. #### fn add_resource_opts( &self, resource: &Resource, check_required_props: bool, update_index: bool, overwrite_existing: bool ) -> AtomicResult<()Adds a Resource to the store. Replaces existing resource with the contents. Does not do any validations. #### fn all_resources( &self, include_external: bool ) -> Box<dyn Iterator<Item = Resource>Returns an iterator that iterates over all resources in the store. If Include_external is false, this is filtered by selecting only resoureces that match the `self` URL of the store. #### fn get_server_url(&self) -> &str Returns the base URL where the default store is. E.g. `https://example.com` This is where deltas should be sent to. Also useful for Subject URL generation. #### fn get_resource(&self, subject: &str) -> AtomicResult<ResourceReturns a full Resource with native Values. Note that this does *not* construct dynamic Resources, such as collections. If you’re not sure what to use, use `get_resource_extended`. #### fn remove_resource(&self, subject: &str) -> AtomicResult<()Removes a resource from the store. Errors if not present. #### fn query(&self, q: &Query) -> AtomicResult<QueryResultSearch the Store, returns the matching subjects. #### fn set_default_agent(&self, agent: Agent) Sets the default Agent for applying commits. Provided Methods --- #### fn add_atom_to_index( &self, _atom: &Atom, _resource: &Resource ) -> AtomicResult<()Adds an Atom to the PropSubjectMap. Overwrites if already present. The default implementation for this does not do anything, so overwrite it if your store needs indexing. #### fn add_resource(&self, resource: &Resource) -> AtomicResult<()Adds a Resource to the store. Replaces existing resource with the contents. Updates the index. Validates the fields (checks required props). In most cases, you should use `resource.save()` instead, which uses Commits. #### fn build_index(&self, include_external: bool) -> AtomicResult<()Constructs the value index from all resources in the store. Could take a while. #### fn get_value(&self, subject: &str, property: &str) -> AtomicResult<ValueReturns a single Value from a Resource #### fn get_self_url(&self) -> Option<StringReturns the root URL where this instance of the store is hosted. Should return `None` if this is simply a client and not a server. E.g. `https://example.com` #### fn get_default_agent(&self) -> AtomicResult<AgentReturns the default Agent for applying commits. #### fn create_agent(&self, name: Option<&str>) -> AtomicResult<AgentCreate an Agent, storing its public key. An Agent is required for signing Commits. Returns a tuple of (subject, private_key). Make sure to store the private_key somewhere safe! Does not create a Commit - the recommended way is to use `agent.to_resource().save_locally()`. #### fn export(&self, include_external: bool) -> AtomicResult<StringExports the store to a big JSON-AD file. Sorts the export by first exporting Property Resources, which makes importing faster and more dependent. #### fn fetch_resource(&self, subject: &str) -> AtomicResult<ResourceFetches a resource, makes sure its subject matches. Uses the default agent to sign the request. Save to the store. #### fn get_resource_new(&self, subject: &str) -> Resource Returns an existing resource, or creates a new one with the given Subject #### fn get_class(&self, subject: &str) -> AtomicResult<ClassRetrieves a Class from the store by subject URL and converts it into a Class useful for forms #### fn get_classes_for_subject(&self, subject: &str) -> AtomicResult<Vec<Class>Finds all classes (isA) for any subject. Returns an empty vector if there are none. #### fn get_property(&self, subject: &str) -> AtomicResult<PropertyFetches a property by URL, returns a Property instance #### fn get_resource_extended( &self, subject: &str, skip_dynamic: bool, for_agent: &ForAgent ) -> AtomicResult<ResourceGet’s the resource, parses the Query parameters and calculates dynamic properties. Defaults to get_resource if store doesn’t support extended resources If `for_agent` is None, no authorization checks will be done, and all resources will return. If you want public only resurces, pass `Some(crate::authentication::public_agent)` as the agent. * *skip_dynamic* Does not calculte dynamic properties. Adds an `incomplete=true` property if the resource should have been dynamic. #### fn handle_commit(&self, _commit_response: &CommitResponse) This function is called whenever a Commit is applied. Implement this if you want to have custom handlers for Commits. #### fn handle_not_found( &self, subject: &str, error: AtomicError ) -> AtomicResult<Resource#### fn import(&self, string: &str, parse_opts: &ParseOpts) -> AtomicResult<usizeImports a JSON-AD string, returns the amount of imported resources. #### fn get_path( &self, atomic_path: &str, mapping: Option<&Mapping>, for_agent: &ForAgent ) -> AtomicResult<PathReturnAccepts an Atomic Path string, returns the result value (resource or property value) E.g. `https://example.com description` or `thing isa 0` https://docs.atomicdata.dev/core/paths.html The `for_agent` argument is used to check if the user has rights to the resource. You can pass `None` if you don’t care about the rights (e.g. in client side apps) If you want to perform read rights checks, pass Some `for_agent` subject #### fn post_resource( &self, _subject: &str, _body: Vec<u8>, _for_agent: &ForAgent ) -> AtomicResult<ResourceHandles a HTTP POST request to the store. This is where [crate::endpoints::Endpoint] are used. #### fn populate(&self) -> AtomicResult<()Loads the default store. For DBs it also adds default Collections and Endpoints. #### fn remove_atom_from_index( &self, _atom: &Atom, _resource: &Resource ) -> AtomicResult<()Removes an Atom from the PropSubjectMap. #### fn validate(&self) -> ValidationReport Performs a light validation, without fetching external data Implementors --- ### impl Storelike for Store Module atomic_lib::agents === Logic for Agents Agents are actors (such as users) that can edit content. https://docs.atomicdata.dev/commits/concepts.html Structs --- * Agent * Pairkeypair, serialized using base64 Enums --- * ForAgentNone represents no right checks will be performed, effectively SUDO mode. Functions --- * decode_base64 * encode_base64 * generate_public_keyReturns a Key Pair (including public key) from a private key, base64 encoded. * verify_public_keyChecks if the public key is a valid ED25519 base64 key. Not perfect - only checks byte length and parses base64. Module atomic_lib::atoms === The smallest units of data, consisting of a Subject, a Property and a Value Structs --- * AtomThe Atom is the smallest meaningful piece of data. It describes how one value relates to a subject. A [Resource] can be converted into a bunch of Atoms. * IndexAtomDiffers from a regular Atom, since the value here is always a string, and in the case of ResourceArrays, only a *single* subject is used for each atom. One IndexAtom for every member of the ResourceArray is created. Module atomic_lib::authentication === Check signatures in authentication headers, find the correct agent. Authorization is done in Hierarchies Structs --- * AuthValuesSet of values extracted from the request. Most are coming from headers. Functions --- * check_auth_signatureChecks if the signature is valid for this timestamp. Does not check if the agent has rights to access the subject. * get_agent_from_auth_values_and_checkGet the Agent’s subject from AuthValues Checks if the auth headers are correct, whether signature matches the public key, whether the timestamp is valid. by default, returns the public agent Module atomic_lib::client === Functions for interacting with an Atomic Server Functions --- * fetch_bodyFetches a URL, returns its body. Uses the store’s Agent agent (if set) to sign the request. * fetch_resourceFetches a resource, makes sure its subject matches. Checks the datatypes for the Values. Ignores all atoms where the subject is different. WARNING: Calls store methods, and is called by store methods, might get stuck in a loop! * get_authentication_headersReturns the various x-atomic authentication headers, includign agent signature * post_commitPosts a Commit to the endpoint of the Subject from the Commit * post_commit_custom_endpointPosts a Commit to an endpoint Default commit endpoint is `https://example.com/commit` Module atomic_lib::commit === Describe changes / mutations to data Structs --- * CommitA Commit is a set of changes to a Resource. Use CommitBuilder if you’re programmatically constructing a Delta. * CommitBuilderUse this for creating Commits. * CommitOptsDescribes options for applying a Commit. Skip the checks you don’t need to get better performance, or if you want to break the rules a little. * CommitResponseThe `resource_new`, `resource_old` and `commit_resource` fields are only created if the Commit is persisted. When the Db is only notifying other of changes (e.g. if a new Message was added to a ChatRoom), these fields are not created. When deleting a resource, the `resource_new` field is None. Functions --- * check_timestampChecks if the Commit has been created in the future or if it is expired. * sign_messageSigns a string using a base64 encoded ed25519 private key. Outputs a base64 encoded ed25519 signature. Module atomic_lib::datatype === DataTypes constrain values of Atoms Enums --- * DataType Functions --- * match_datatype Enum atomic_lib::datatype::DataType === ``` pub enum DataType { AtomicUrl, Boolean, Date, Integer, Float, Markdown, ResourceArray, Slug, String, Timestamp, Unsupported(String), } ``` Variants --- ### AtomicUrl Either a full Resource, a link to a resource (subject) or a Nested Anonymous Resource ### Boolean ### Date ### Integer ### Float ### Markdown ### ResourceArray ### Slug ### String ### Timestamp ### Unsupported(String) Trait Implementations --- ### impl Clone for DataType #### fn clone(&self) -> DataType Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### type Err = Infallible The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<Self, Self::ErrParses a string `s` to return a value of this type. #### fn eq(&self, other: &DataType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Serialize for DataType #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer, Serialize this value into the given Serde serializer. ### impl StructuralEq for DataType ### impl StructuralPartialEq for DataType Auto Trait Implementations --- ### impl RefUnwindSafe for DataType ### impl Send for DataType ### impl Sync for DataType ### impl Unpin for DataType ### impl UnwindSafe for DataType Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T> Instrument for T #### fn instrument(self, span: Span) -> Instrumented<SelfInstruments this type with the provided `Span`, returning an `Instrumented` wrapper. `Instrumented` wrapper. U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. T: Display + ?Sized, #### default fn to_string(&self) -> String Converts the given value to a `String`. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> WithSubscriber for T #### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. `WithDispatch` wrapper. T: for<'de> Deserialize<'de>, Module atomic_lib::errors === Mostly contains implementations for Error types. The AtomicError type should be returned from any function that may fail, although it is not returned everywhere at this moment. Structs --- * AtomicError Enums --- * AtomicErrorType Type Definitions --- * AtomicResultThe default Error type for all Atomic Lib Errors. Module atomic_lib::mapping === Because writing full URLs is error prone and time consuming, we map URLs to shortnames. These are often user-specific. This section provides tools to store, share and resolve these Mappings. Structs --- * MappingMaps shortanmes (bookmarks) to URLs Functions --- * is_urlCheck if something is a URL Module atomic_lib::populate === Populating a Store means adding resources to it. Some of these are the core Atomic Data resources, such as the Property class. These base models are required for having a functioning store. Other populate methods help to set up an Atomic Server, by creating a basic file hierarcy and creating default collections. Functions --- * create_driveCreates a Drive resource at the base URL. Does not set rights. Use set_drive_rights for that. * populate_base_modelsPopulates a store with some of the most fundamental Properties and Classes needed to bootstrap the whole. This is necessary to prevent a loop where Property X (like the `shortname` Property) cannot be added, because it’s Property Y (like `description`) has to be fetched before it can be added, which in turn has property Property X (`shortname`) which needs to be fetched before. https://github.com/atomicdata-dev/atomic-server/issues/60 * populate_collectionsGenerates collections for classes, such as `/agent` and `/collection`. Requires a `self_url` to be set in the store. * populate_default_storeImports the Atomic Data Core items (the entire atomicdata.dev Ontology / Vocabulary) * set_drive_rightsAdds rights to the default agent to the Drive resource (at the base URL). Optionally give Public Read rights. Module atomic_lib::resources === A Resource is a set of Atoms that share a URL. Has methods for saving resources and getting properties inside them. Structs --- * ResourceA Resource is a set of Atoms that shares a single Subject. A Resource only contains valid Values, but it *might* lack required properties. All changes to the Resource are applied after committing them (e.g. by using). Type Definitions --- * PropValsMaps Property URLs to their values Module atomic_lib::schema === Structs and models at the core of Atomic Schema (Class, Property, Datatype). Structs --- * Class * Property Module atomic_lib::store === In-memory store of Atomic data. This provides many methods for finding, changing, serializing and parsing Atomic Data. Structs --- * StoreThe in-memory store of data, containing the Resources, Properties and Classes Module atomic_lib::storelike === The Storelike Trait contains many useful methods for maniupulting / retrieving data. Structs --- * QueryUse this to construct a list of Resources * QueryResult Enums --- * PathReturn Traits --- * StorelikeStorelike provides many useful methods for interacting with an Atomic Store. It serves as a basic store Trait, agnostic of how it functions under the hood. This is useful, because we can create methods for Storelike that will work with either in-memory stores, as well as with persistent on-disk stores. Type Definitions --- * ResourceCollection Module atomic_lib::urls === Contains some of the most important Atomic Data URLs. Constants --- * AGENT * ALLOWS_ONLY * APPEND * ATOM * ATOMIC_URL * ATOM_PROPERTY * ATOM_SUBJECT * ATOM_VALUE * ATTACHMENTS * BOOKMARK * BOOLEAN * CHATROOM * CHECKSUM * CHILDREN * CLASS * CLASSTYPE_PROP * COLLECTION * COLLECTION_CURRENT_PAGE * COLLECTION_INCLUDE_EXTERNAL * COLLECTION_INCLUDE_NESTED * COLLECTION_MEMBERS * COLLECTION_MEMBER_COUNT * COLLECTION_PAGE_SIZE * COLLECTION_PROPERTY * COLLECTION_SORT_BY * COLLECTION_SORT_DESC * COLLECTION_TOTAL_PAGES * COLLECTION_VALUE * COMMIT * CREATED_AT * DATATYPE_CLASS * DATATYPE_PROP * DATE * DELETE * DESCRIPTION * DESTINATION * DESTROY * DOWNLOAD_URL * DRIVE * DRIVES * ENDPOINT * ENDPOINT_PARAMETERS * ENDPOINT_RESULTS * ERROR * EXPIRES_AT * FILE * FILENAME * FILESIZE * FLOAT * IMAGE_URL * IMPORTER * IMPORTER_JSON * IMPORTER_OVERWRITE_OUTSIDE * IMPORTER_PARENT * IMPORTER_URL * INCOMPLETE * INSERT * INTEGER * INTERNAL_ID * INVITE * INVITE_AGENT * INVITE_PUBKEY * IS_A * IS_DYNAMIC * IS_LOCKED * LAST_COMMIT * LOCAL_ID * MARKDOWN * MESSAGE * MESSAGES * MIMETYPE * NAME * NEXT_PAGE * PARAGRAPH * PARENT * PATH * PATH_FETCH_BOOKMARK * PATH_IMPORT * PATH_QUERY * PREVIEW * PREVIOUS_COMMIT * PROPERTY * PUBLIC_AGENT * PUBLIC_KEY * PUSH * READ * RECOMMENDS * REDIRECT * REDIRECT_AGENT * REMOVE * REQUIRES * RESOURCE_ARRAY * SEARCH_LIMIT * SEARCH_PROPERTY * SEARCH_QUERY * SET * SHORTNAME * SIGNATURE * SIGNER * SLUG * STRING * SUBJECT * SUBRESOURCES * SUDO_AGENT * TARGET * TIMESTAMP * URL * USAGES_LEFT * USED_BY * WRITE * WRITE_BOOL Functions --- * construct_path_import Module atomic_lib::utils === Helper functions for dealing with URLs Functions --- * check_valid_urlThrows an error if the URL is not a valid URL * nowReturns the current timestamp in milliseconds since UNIX epoch * random_stringGenerates a relatively short random string of n length * server_urlRemoves the path and query from a String, returns the base server URL Module atomic_lib::validate === Validate the Store and create a ValidationReport. Might be deprecated soon, as Validation hasn’t been necessary since parsing has built-in data validation. Structs --- * ValidationReport Functions --- * validate_storeChecks Atomic Data in the store for validity. Returns an Error if it is not valid. Module atomic_lib::values === A value is the part of an Atom that contains the actual information. Structs --- * UnsupportedValueWhen the Datatype of a Value is not handled by this library Enums --- * SubResourceA resource in a JSON-AD body can be any of these * ValueAn individual Value in an Atom. Note that creating values using `Value::from` might result in the wrong Datatype, as the from conversion makes assumptions (e.g. integers are Integers, not Timestamps). Use `Value::SomeDataType()` for explicit creation. Constants --- * DATE_REGEXYYYY-MM-DD * SLUG_REGEXOnly alphanumeric characters, no spaces Type Definitions --- * ReferenceStringA value that is meant for checking reference indexes. short. Vectors of subjects are turned into individual ReferenceStrings. * SortableValueString Value representing a lexicographically sortable string.
pythonwhat
readthedoc
SQL
This article lists some example solutions. For each of these solutions, an SCT is included, as well as some example student submissions that would pass and fail. In all of these, a submission that is identical to the solution will pass. These SCT examples are not golden bullets that are perfect for your situation. Depending on the exercise, you may want to focus on certain parts of a statement, or be more accepting for different alternative answers. ## Check object¶ ``` # solution x = 10 # sct Ex().check_object('x').has_equal_value() # passing submissions x = 5 + 5 x = 6 + 4 y = 4; x = y + 6 ``` ## Check function call¶ ``` # solution import pandas as pd pd.DataFrame([1, 2, 3], columns=['a']) # sct Ex().check_function('pandas.DataFrame')\ .multi( check_args('data').has_equal_value(), check_args('columns').has_equal_value() ) # passing submissions pd.DataFrame([1, 1+1, 3], columns=['a']) pd.DataFrame(data=[1, 2, 3], columns=['a']) pd.DataFrame(columns=['a'], data=[1, 2, 3]) ``` ## Check pandas chain (1)¶ ``` # solution import pandas as pd df = pd.DataFrame([1, 2, 3], columns=['a']) df.a.sum() # sct Ex().check_function("df.a.sum").has_equal_value() ``` ## Check pandas chain (2)¶ ``` # pec import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': ['x', 'x', 'y']}) # solution df.groupby('b').sum() # sct sig = sig_from_obj("df.groupby('b').sum") Ex().check_correct( # check if group by works check_function("df.groupby.sum", signature = sig).has_equal_value(), # check if group_by called correctly check_function("df.groupby").check_correct( has_equal_value(func = lambda x,y: x.keys == y.keys), check_args(0).has_equal_value() ) ) # passing submissions df.groupby('b').sum() df.groupby(['b']).sum() # failing submissions df # Did you call df.groupby()? df.groupby('a') # arg of groupby is incorrect df.groupby('b') # did you call df.groupby.sum()? ``` ## Check pandas plotting¶ ``` # pec import matplotlib.pyplot as plt import pandas as pd import numpy as np np.random.seed(42) df = pd.DataFrame({'val': np.random.rand(300) }) # solution df.val.plot(kind='hist') plt.title('my plot') plt.show() plt.clf() # sct Ex().check_or( multi( check_function('df.val.plot').check_args('kind').has_equal_value(), check_function('matplotlib.pyplot.title').check_args(0).has_equal_value() ), override("df.val.plot(kind='hist', title='my plot')").check_function('df.val.plot').multi( check_args('kind').has_equal_value(), check_args('title').has_equal_value() ), override("df['val'].plot(kind = 'hist'); plt.title('my plot')").multi( check_function('df.plot').check_args('kind').has_equal_value(), check_function('matplotlib.pyplot.title').check_args(0).has_equal_value() ), override("df['val'].plot(kind='hist', title='my plot')").check_function('df.plot').multi( check_args('kind').has_equal_value(), check_args('title').has_equal_value() ) ) Ex().check_function('matplotlib.pyplot.show') Ex().check_function('matplotlib.pyplot.clf') ``` ## Check object created through function call¶ ``` # pec import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) # solution result = np.mean(arr) # sct Ex().check_correct( check_object("result").has_equal_value(), check_function("numpy.mean").check_args("a").has_equal_value() ) # passing submissions result = np.mean(arr) result = np.sum(arr) / arr.size ``` ## Check DataFrame¶ ``` # solution import pandas as pd my_df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) # sct Ex().check_df("my_df").check_keys("a").has_equal_value() # passing submissions my_df = pd.DataFrame({"a": [1, 1 + 1, 3], "b": [4, 5, 6]}) my_df = pd.DataFrame({"b": [4, 5, 6], "a": [1, 2, 3]}) ``` ## Check printout¶ ``` # solution x = 3 print(x) # sct Ex().has_printout(0) # passing submissions print(3) print(1 + 1) x = 4; print(x - 1) ``` ## Check output¶ ``` # solution print("This is weird stuff") # sct Ex().has_output(r"This is \w* stuff") # passing submissions print("This is weird stuff") print("This is fancy stuff") print("This is cool stuff") # failing submissions print("this is weird stuff") print("Thisis weird stuff") ``` ## Check Multiple Choice¶ ``` # solution (implicit) # 3 is the correct answer # sct Ex().has_chosen(correct = 3, # 1-base indexed msgs = ["That's someone who makes soups.", "That's a clown who likes burgers.", "Correct! Head over to the next exercise!"]) ``` * `check_` functions typically ‘dive’ deeper into a part of the state it was passed. They are typically chained for further checking. * `has_` functions always return the state that they were intially passed and are used at the ‘end’ of a chain. ## Objects¶ * `check_object` (state, index, missing_msg=None, expand_msg=None, typestr='variable')¶ * Check object existence (and equality) Check whether an object is defined in the student’s process, and zoom in on its value in both student and solution process to inspect quality (with has_equal_value(). In `pythonbackend` , both the student’s submission as well as the solution code are executed, in separate processes. `check_object()` looks at these processes and checks if the referenced object is available in the student process. Next, you can use `has_equal_value()` to check whether the objects in the student and solution process correspond. b'Parameters:' * index (str) – the name of the object which value has to be checked. * missing_msg (str) – feedback message when the object is not defined in the student process. * expand_msg (str) – If specified, this overrides any messages that are prepended by previous SCT chains. b'Example:' Suppose you want the student to create a variable `x` , equal to 15: > x = 15 The following SCT will verify this: > Ex().check_object("x").has_equal_value() * `check_object()` will check if the variable `x` is defined in the student process. * `has_equal_value()` will check whether the value of `x` in the solution process is the same as in the student process. Note that `has_equal_value()` only looks at end result of a variable in the student process. In the example, how the object `x` came about in the student’s submission, does not matter. This means that all of the following submission will also pass the above SCT: > x = 15 x = 12 + 3 x = 3; x += 12 b'Example:' As the previous example mentioned, `has_equal_value()` only looks at the end result. If your exercise is first initializing and object and further down the script is updating the object, you can only look at the final value! Suppose you want the student to initialize and populate a list my_list as follows: > my_list = [] for i in range(20): if i % 3 == 0: my_list.append(i) There is no robust way to verify whether my_list = [0] was coded correctly in a separate way. The best SCT would look something like this: > msg = "Have you correctly initialized `my_list`?" Ex().check_correct( check_object('my_list').has_equal_value(), multi( # check initialization: [] or list() check_or( has_equal_ast(code = "[]", incorrect_msg = msg), check_function('list') ), check_for_loop().multi( check_iter().has_equal_value(), check_body().check_if_else().multi( check_test().multi( set_context(2).has_equal_value(), set_context(3).has_equal_value() ), check_body().set_context(3).\ set_env(my_list = [0]).\ has_equal_value(name = 'my_list') ) ) ) ) * `check_correct()` is used to robustly check whether `my_list` was built correctly. * If `my_list` is not correct, both the initialization and the population code are checked. b'Example:' Because checking object correctness incorrectly is such a common misconception, we’re adding another example: > import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) df['c'] = [7, 8, 9] The following SCT would be wrong, as it does not factor in the possibility that the ‘add column `c` ’ step could’ve been wrong: > Ex().check_correct( check_object('df').has_equal_value(), check_function('pandas.DataFrame').check_args(0).has_equal_value() ) The following SCT would be better, as it is specific to the steps: > # verify the df = pd.DataFrame(...) step Ex().check_correct( check_df('df').multi( check_keys('a').has_equal_value(), check_keys('b').has_equal_value() ), check_function('pandas.DataFrame').check_args(0).has_equal_value() ) # verify the df['c'] = [...] step Ex().check_df('df').check_keys('c').has_equal_value() b'Example:' pythonwhat compares the objects in the student and solution process with the `==` operator. For basic objects, this `==` is operator is properly implemented, so that the objects can be effectively compared. For more complex objects that are produced by third-party packages, however, it’s possible that this equality operator is not implemented in a way you’d expect. Often, for these object types the `==` will compare the actual object instances: > # pre exercise code class Number(): def __init__(self, n): self.n = n # solution x = Number(1) # sct that won't work Ex().check_object().has_equal_value() # sct Ex().check_object().has_equal_value(expr_code = 'x.n') # submissions that will pass this sct x = Number(1) x = Number(2 - 1) The basic SCT like in the previous example will notwork here. Notice how we used the `expr_code` argument to _override_ which value has_equal_value() is checking. Instead of checking whether x corresponds between student and solution process, it’s now executing the expression `x.n` and seeing if the result of running this expression in both student and solution process match. * `is_instance` (state, inst, not_instance_msg=None)¶ * Check whether an object is an instance of a certain class. `is_instance()` can currently only be used when chained from `check_object()` , the function that is used to ‘zoom in’ on the object of interest. b'Parameters:' * inst (class) – The class that the object should have. * not_instance_msg (str) – When specified, this overrides the automatically generated message in case the object does not have the expected class. * state (State) – The state that is passed in through the SCT chain (don’t specify this). b'Example:' SCT: > # Verify the class of arr import numpy Ex().check_object('arr').is_instance(numpy.ndarray) * `check_df` (state, index, missing_msg=None, not_instance_msg=None, expand_msg=None)¶ * Check whether a DataFrame was defined and it is the right type `check_df()` is a combo of `check_object()` and `is_instance()` that checks whether the specified object exists and whether the specified object is pandas DataFrame. You can continue checking the data frame with `check_keys()` function to ‘zoom in’ on a particular column in the pandas DataFrame: b'Parameters:' * index (str) – Name of the data frame to zoom in on. * missing_msg (str) – See `check_object()` . * not_instance_msg (str) – See `is_instance()` . * expand_msg (str) – If specified, this overrides any messages that are prepended by previous SCT chains. b'Example:' Suppose you want the student to create a DataFrame `my_df` with two columns. The column `a` should contain the numbers 1 to 3, while the contents of column `b` can be anything: > import pandas as pd my_df = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "n", "y"]}) The following SCT would robustly check that: > Ex().check_df("my_df").multi( check_keys("a").has_equal_value(), check_keys("b") ) * `check_df()` checks if `my_df` exists ( `check_object()` behind the scenes) and is a DataFrame ( `is_instance()` ) * `check_keys("a")` zooms in on the column `a` of the data frame, and `has_equal_value()` checks if the columns correspond between student and solution process. * `check_keys("b")` zooms in on hte column `b` of the data frame, but there’s no ‘equality checking’ happening The following submissions would pass the SCT above: > my_df = pd.DataFrame({"a": [1, 1 + 1, 3], "b": ["a", "l", "l"]}) my_df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) * `check_keys` (state, key, missing_msg=None, expand_msg=None)¶ * Check whether an object (dict, DataFrame, etc) has a key. `check_keys()` can currently only be used when chained from `check_object()` , the function that is used to ‘zoom in’ on the object of interest. b'Parameters:' * key (str) – Name of the key that the object should have. * missing_msg (str) – When specified, this overrides the automatically generated message in case the key does not exist. * expand_msg (str) – If specified, this overrides any messages that are prepended by previous SCT chains. * state (State) – The state that is passed in through the SCT chain (don’t specify this). b'Example:' Student code and solution code: > x = {'a': 2} SCT: > # Verify that x contains a key a Ex().check_object('x').check_keys('a') # Verify that x contains a key a and a is correct. Ex().check_object('x').check_keys('a').has_equal_value() ## Function calls¶ * `check_function` (state, name, index=0, missing_msg=None, params_not_matched_msg=None, expand_msg=None, signature=True)¶ * Check whether a particular function is called. `check_function()` is typically followed by: * `check_args()` to check whether the arguments were specified. In turn, `check_args()` can be followed by `has_equal_value()` or `has_equal_ast()` to assert that the arguments were correctly specified. * `has_equal_value()` to check whether rerunning the function call coded by the student gives the same result as calling the function call as in the solution. Checking function calls is a tricky topic. Please visit the dedicated article for more explanation, edge cases and best practices. b'Parameters:' * name (str) – the name of the function to be tested. When checking functions in packages, always use the ‘full path’ of the function. * index (int) – index of the function call to be checked. Defaults to 0. * missing_msg (str) – If specified, this overrides an automatically generated feedback message in case the student did not call the function correctly. * params_not_matched_msg (str) – If specified, this overrides an automatically generated feedback message in case the function parameters were not successfully matched. * expand_msg (str) – If specified, this overrides any messages that are prepended by previous SCT chains. * signature (Signature) – Normally, check_function() can figure out what the function signature is, but it might be necessary to use `sig_from_params()` to manually build a signature and pass this along. * state (State) – State object that is passed from the SCT Chain (don’t specify this). b'Examples:' SCT: > # Verify whether arr was correctly set in np.mean Ex().check_function('numpy.mean').check_args('a').has_equal_value() # Verify whether np.mean(arr) produced the same result Ex().check_function('numpy.mean').has_equal_value() * `check_args` (state, name, missing_msg=None)¶ * Check whether a function argument is specified. This function can follow `check_function()` in an SCT chain and verifies whether an argument is specified. If you want to go on and check whether the argument was correctly specified, you can can continue chaining with `has_equal_value()` (value-based check) or `has_equal_ast()` (AST-based check) This function can also follow `check_function_def()` or to see if arguments have been specified. b'Parameters:' * name (str) – the name of the argument for which you want to check if it is specified. This can also be a number, in which case it refers to the positional arguments. Named arguments take precedence. * missing_msg (str) – If specified, this overrides the automatically generated feedback message in case the student did specify the argument. * state (State) – State object that is passed from the SCT Chain (don’t specify this). b'Examples:' SCT: > # Verify whether arr was correctly set in np.mean # has_equal_value() checks the value of arr, used to set argument a Ex().check_function('numpy.mean').check_args('a').has_equal_value() # Verify whether arr was correctly set in np.mean # has_equal_ast() checks the expression used to set argument a Ex().check_function('numpy.mean').check_args('a').has_equal_ast() SCT: > Ex().check_function_def('my_power').multi( check_args('x') # will fail if student used y as arg check_args(0) # will still pass if student used y as arg ) ## Output¶ * `has_output` (state, text, pattern=True, no_output_msg=None)¶ * Search student output for a pattern. Among the student and solution process, the student submission and solution code as a string, the `Ex()` state also contains the output that a student generated with his or her submission. With `has_output()` , you can access this output and match it against a regular or fixed expression. b'Parameters:' * text (str) – the text that is searched for * pattern (bool) – if True (default), the text is treated as a pattern. If False, it is treated as plain text. * no_output_msg (str) – feedback message to be displayed if the output is not found. b'Example:' As an example, suppose we want a student to print out a sentence: > # Print the "This is some ... stuff" print("This is some weird stuff") The following SCT tests whether the student prints out ``` This is some weird stuff ``` : > # Using exact string matching Ex().has_output("This is some weird stuff", pattern = False) # Using a regular expression (more robust) # pattern = True is the default msg = "Print out ``This is some ... stuff`` to the output, " + \ "fill in ``...`` with a word you like." Ex().has_output(r"This is some \w* stuff", no_output_msg = msg) * `has_printout` (state, index, not_printed_msg=None, pre_code=None, name=None, copy=False)¶ * Check if the right printouts happened. `has_printout()` will look for the printout in the solution code that you specified with `index` (0 in this case), rerun the `print()` call in the solution process, capture its output, and verify whether the output is present in the output of the student. This is more robust as ``` Ex().check_function('print') ``` initiated chains as students can use as many printouts as they want, as long as they do the correct one somewhere. b'Parameters:' * index (int) – index of the `print()` call in the solution whose output you want to search for in the student output. * not_printed_msg (str) – if specified, this overrides the default message that is generated when the output is not found in the student output. * pre_code (str) – Python code as a string that is executed before running the targeted student call. This is the ideal place to set a random seed, for example. * copy (bool) – whether to try to deep copy objects in the environment, such as lists, that could accidentally be mutated. Disabled by default, which speeds up SCTs. * state (State) – state as passed by the SCT chain. Don’t specify this explicitly. b'Example:' Suppose you want somebody to print out 4: > print(1, 2, 3, 4) The following SCT would check that: > Ex().has_printout(0) All of the following SCTs would pass: > print(1, 2, 3, 4) print('1 2 3 4') print(1, 2, '3 4') print("random"); print(1, 2, 3, 4) b'Example:' Watch out: `has_printout()` will effectively rerun the `print()` call in the solution process after the entire solution script was executed. If your solution script updates the value of x after executing it, `has_printout()` will not work. Suppose you have the following solution: > x = 4 print(x) x = 6 The following SCT will not work: > Ex().has_printout(0) Why? When the `print(x)` call is executed, the value of `x` will be 6, and pythonwhat will look for the output ‘6’ in the output the student generated. In cases like these, `has_printout()` cannot be used. b'Example:' Inside a for loop `has_printout()` Suppose you have the following solution: > for i in range(5): print(i) The following SCT will not work: > Ex().check_for_loop().check_body().has_printout(0) The reason is that `has_printout()` can only be called from the root state. `Ex()` . If you want to check printouts done in e.g. a for loop, you have to use a check_function(‘print’) chain instead: > Ex().check_for_loop().check_body().\ set_context(0).check_function('print').\ check_args(0).has_equal_value() * index (int) – index of the * `has_no_error` (state, incorrect_msg='Have a look at the console: your code contains an error. Fix it and try again!')¶ * Check whether the submission did not generate a runtime error. If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check whether the student submission generated an error. This means it is not needed to use `has_no_error()` explicitly. However, in some cases, using `has_no_error()` explicitly somewhere throughout your SCT execution can be helpful: * If you want to make sure people didn’t write typos when writing a long function name. * If you want to first verify whether a function actually runs, before checking whether the arguments were specified correctly. * More generally, if, because of the content, it’s instrumental that the script runs without errors before doing any other verifications. b'Parameters:' incorrect_msg – if specified, this overrides the default message if the student code generated an error. b'Example:' Suppose you’re verifying an exercise about model training and validation: > # pre exercise code import numpy as np from sklearn.model_selection import train_test_split from sklearn import datasets from sklearn import svm iris = datasets.load_iris() iris.data.shape, iris.target.shape # solution X_train, X_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.4, random_state=0) If you want to make sure that `train_test_split()` ran without errors, which would check if the student typed the function without typos and used sensical arguments, you could use the following SCT: > Ex().has_no_error() Ex().check_function('sklearn.model_selection.train_test_split').multi( check_args(['arrays', 0]).has_equal_value(), check_args(['arrays', 0]).has_equal_value(), check_args(['options', 'test_size']).has_equal_value(), check_args(['options', 'random_state']).has_equal_value() ) If, on the other hand, you want to fall back onto pythonwhat’s built in behavior, that checks for an error before marking the exercise as correct, you can simply leave of the `has_no_error()` step. ## Code¶ * `has_code` (state, text, pattern=True, not_typed_msg=None)¶ * Test the student code. Tests if the student typed a (pattern of) text. It is advised to use `has_equal_ast()` instead of `has_code()` , as it is more robust to small syntactical differences that don’t change the code’s behavior. b'Parameters:' * text (str) – the text that is searched for * pattern (bool) – if True (the default), the text is treated as a pattern. If False, it is treated as plain text. * not_typed_msg (str) – feedback message to be displayed if the student did not type the text. b'Example:' Student code and solution code: > y = 1 + 2 + 3 SCT: > # Verify that student code contains pattern (not robust!!): Ex().has_code(r"1\s*\+2\s*\+3") * `has_import` (state, name, same_as=False, not_imported_msg='Did you import `{{pkg}}`?', incorrect_as_msg='Did you import `{{pkg}}` as `{{alias}}`?')¶ * Checks whether student imported a package or function correctly. Python features many ways to import packages. All of these different methods revolve around the `import` , `from` and `as` keywords. `has_import()` provides a robust way to check whether a student correctly imported a certain package. By default, `has_import()` allows for different ways of aliasing the imported package or function. If you want to make sure the correct alias was used to refer to the package or function that was imported, set `same_as=True` . b'Parameters:' * name (str) – the name of the package that has to be checked. * same_as (bool) – if True, the alias of the package or function has to be the same. Defaults to False. * not_imported_msg (str) – feedback message when the package is not imported. * incorrect_as_msg (str) – feedback message if the alias is wrong. b'Example:' Example 1, where aliases don’t matter (defaut): > # solution import matplotlib.pyplot as plt # sct Ex().has_import("matplotlib.pyplot") # passing submissions import matplotlib.pyplot as plt from matplotlib import pyplot as plt import matplotlib.pyplot as pltttt # failing submissions import matplotlib as mpl Example 2, where the SCT is coded so aliases do matter: > # solution import matplotlib.pyplot as plt # sct Ex().has_import("matplotlib.pyplot", same_as=True) # passing submissions import matplotlib.pyplot as plt from matplotlib import pyplot as plt # failing submissions import matplotlib.pyplot as pltttt ## has_equal_x¶ Run targeted student and solution code, and compare returned value. When called on an SCT chain, `has_equal_value()` will execute the student and solution code that is ‘zoomed in on’ and compare the returned values. b'Parameters:' or if you want to allow for different solutions other than the one coded up in the solution. b'Example:' SCT: > # Verify equality of arr: Ex().check_object('arr').has_equal_value() # Verify whether arr was correctly set in np.mean Ex().check_function('numpy.mean').check_args('a').has_equal_value() # Verify whether np.mean(arr) produced the same result Ex().check_function('numpy.mean').has_equal_value() * incorrect_msg (str) – feedback message if the returned value of the expression in the solution doesn’t match the one of the student. This feedback message will be expanded if it is used in the context of another check function, like Run targeted student and solution code, and compare output. When called on an SCT chain, `has_equal_output()` will execute the student and solution code that is ‘zoomed in on’ and compare the output. b'Parameters:' Run targeted student and solution code, and compare generated errors. When called on an SCT chain, `has_equal_error()` will execute the student and solution code that is ‘zoomed in on’ and compare the errors that they generate. b'Parameters:' * `has_equal_ast` (state, incorrect_msg=None, code=None, exact=True, append=None)¶ * Test whether abstract syntax trees match between the student and solution code. `has_equal_ast()` can be used in two ways: * As a robust version of `has_code()` . By setting `code` , you can look for the AST representation of `code` in the student’s submission. But be aware that `a` and `a = 1` won’t match, as reading and assigning are not the same in an AST. Use ``` ast.dump(ast.parse(code)) ``` to see an AST representation of `code` . * As an expression-based check when using more advanced SCT chain, e.g. to compare the equality of expressions to set function arguments. b'Parameters:' * incorrect_msg – message displayed when ASTs mismatch. When you specify `code` yourself, you have to specify this. * code – optional code to use instead of the solution AST. * exact – whether the representations must match exactly. If false, the solution AST only needs to be contained within the student AST (similar to using test student typed). Defaults to `True` , unless the `code` argument has been specified. b'Example:' Student and Solution Code: > dict(a = 'value').keys() SCT: > # all pass Ex().has_equal_ast() Ex().has_equal_ast(code = "dict(a = 'value').keys()") Ex().has_equal_ast(code = "dict(a = 'value')", exact = False) Student and Solution Code: > import numpy as np arr = np.array([1, 2, 3, 4, 5]) np.mean(arr) SCT: > # Check underlying value of arugment a of np.mean: Ex().check_function('numpy.mean').check_args('a').has_equal_ast() # Only check AST equality of expression used to specify argument a: Ex().check_function('numpy.mean').check_args('a').has_equal_ast() * As a robust version of ## Combining SCTs¶ * `multi` (state, *tests)¶ * Run multiple subtests. Return original state (for chaining). This function could be thought as an AND statement, since all tests it runs must pass b'Parameters:' The SCT below checks two has_code cases.. > Ex().multi(has_code('SELECT'), has_code('WHERE')) The SCT below uses `multi` to ‘branch out’ to check that the SELECT statement has both a WHERE and LIMIT clause.. > Ex().check_node('SelectStmt', 0).multi( check_edge('where_clause'), check_edge('limit_clause') ) b'Example:' Suppose we want to verify the following function call: > round(1.2345, ndigits=2) The following SCT would verify this, using `multi` to ‘branch out’ the state to two sub-SCTs: > Ex().check_function('round').multi( check_args(0).has_equal_value(), check_args('ndigits').has_equal_value() ) * `check_correct` (state, check, diagnose)¶ * Allows feedback from a diagnostic SCT, only if a check SCT fails. b'Parameters:' * state – State instance describing student and solution code. Can be omitted if used with Ex(). * check – An sct chain that must succeed. * diagnose – An sct chain to run if the check fails. b'Example:' The SCT below tests whether students query result is correct, before running diagnostic SCTs.. > Ex().check_correct( check_result(), check_node('SelectStmt') ) b'Example:' The SCT below tests whether an object is correct. Only if the object is not correct, will the function calling checks be executed > Ex().check_correct( check_object('x').has_equal_value(), check_function('round').check_args(0).has_equal_value() ) * `check_or` (state, *tests)¶ * Test whether at least one SCT passes. b'Parameters:' The SCT below tests that the student typed either ‘SELECT’ or ‘WHERE’ (or both).. > Ex().check_or( has_code('SELECT'), has_code('WHERE') ) The SCT below checks that a SELECT statement has at least a WHERE c or LIMIT clause.. > Ex().check_node('SelectStmt', 0).check_or( check_edge('where_clause'), check_edge('limit_clause') ) b'Example:' The SCT below tests that the student typed either ‘mean’ or ‘median’: > Ex().check_or( has_code('mean'), has_code('median') ) If the student didn’t type either, the feedback message generated by `has_code(mean)` , the first SCT, will be presented to the student. * `check_not` (state, *tests, msg)¶ * Run multiple subtests that should fail. If all subtests fail, returns original state (for chaining) * This function is currently only tested in working with `has_code()` in the subtests. * This function can be thought as a `NOT(x OR y OR ...)` statement, since all tests it runs must fail * This function can be considered a direct counterpart of multi. b'Parameters:' * state – State instance describing student and solution code, can be omitted if used with Ex() * *tests – one or more sub-SCTs to run * msg – feedback message that is shown in case not all tests specified in `*tests` fail. b'Example:' Thh SCT below runs two has_code cases.. > Ex().check_not( has_code('INNER'), has_code('OUTER'), incorrect_msg="Don't use `INNER` or `OUTER`!" ) If students use `INNER (JOIN)` or `OUTER (JOIN)` in their code, this test will fail. b'Example:' The SCT fails with feedback for a specific incorrect value, defined using an override: > Ex().check_object('result').multi( check_not( has_equal_value(override=100), msg='100 is incorrect for reason xyz.' ), has_equal_value() ) Notice that `check_not` comes before the `has_equal_value` test that checks if the student value is equal to the solution value. b'Example:' The SCT below runs two `has_code` cases: > Ex().check_not( has_code('mean'), has_code('median'), msg='Check your code' ) If students use `mean` or `median` anywhere in their code, this SCT will fail. Note * This function is not yet tested with all checks, please report unexpected behaviour. * This function can be thought as a NOT(x OR y OR …) statement, since all tests it runs must fail * This function can be considered a direct counterpart of multi. * This function is currently only tested in working with ## Function/Class/Lambda definitions¶ Check whether a function was defined and zoom in on it. Suppose you want a student to create a function `shout_echo()` : > def shout_echo(word1, echo=1): echo_word = word1 * echo shout_words = echo_word + '!!!' return shout_words The following SCT robustly checks this: > Ex().check_function_def('shout_echo').check_correct( multi( check_call("f('hey', 3)").has_equal_value(), check_call("f('hi', 2)").has_equal_value(), check_call("f('hi')").has_equal_value() ), check_body().set_context('test', 1).multi( has_equal_value(name = 'echo_word'), has_equal_value(name = 'shout_words') ) ) * `check_function_def()` zooms in on the function definition of `shout_echo` in both student and solution code (and process). * `check_correct()` is used to * First check whether the function gives the correct result when called in different ways (through `check_call()` ). * Only if these ‘function unit tests’ don’t pass, `check_correct()` will run the check_body() chain that dives deeper into the function definition body. This chain sets the context variables - `word1` and `echo` , the arguments of the function - to the values `'test'` and `1` respectively, again while being agnostic to the actual name of these context variables. * First check whether the function gives the correct result when called in different ways (through Notice how `check_correct()` is used to great effect here: why check the function definition internals if the I/O of the function works fine? Because of this construct, all the following submissions will pass the SCT: > # passing submission 1 def shout_echo(w, e=1): ew = w * e return ew + '!!!' # passing submission 2 def shout_echo(a, b=1): return a * b + '!!!' b'Example:' `check_args()` is most commonly used in combination with `check_function()` to verify the arguments of function calls, but it can also be used to verify the arguments specified in the signature of a function definition. We can extend the SCT for the previous example to explicitly verify the signature: > msg1 = "Make sure to specify 2 arguments!" msg2 = "don't specify default arg!" msg3 = "specify a default arg!" Ex().check_function_def('shout_echo').check_correct( multi( check_call("f('hey', 3)").has_equal_value(), check_call("f('hi', 2)").has_equal_value(), check_call("f('hi')").has_equal_value() ), multi( has_equal_part_len("args", unequal_msg=1), check_args(0).has_equal_part('is_default', msg=msg2), check_args('word1').has_equal_part('is_default', msg=msg2), check_args(1).\ has_equal_part('is_default', msg=msg3).has_equal_value(), check_args('echo').\ has_equal_part('is_default', msg=msg3).has_equal_value(), check_body().set_context('test', 1).multi( has_equal_value(name = 'echo_word'), has_equal_value(name = 'shout_words') ) ) ) ``` has_equal_part_len("args") ``` verifies whether student and solution function definition have the same number of arguments. * `check_args(0)` refers to the first argument in the signature by position, and the chain checks whether the student did not specify a default as in the solution. * An alternative for the `check_args(0)` chain is to use `check_args('word1')` to refer to the first argument. This is more restrictive, as the requires the student to use the exact same name. * `check_args(1)` refers to the second argument in the signature by position, and the chain checks whether the student specified a default, as in the solution, and whether the value of this default corresponds to the one in the solution. * The `check_args('echo')` chain is a more restrictive alternative for the `check_args(1)` chain. Notice that support for verifying arguments is not great yet: * A lot of work is needed to verify the number of arguments and whether or not defaults are set. * You have to specify custom messages because pythonwhat doesn’t automatically generate messages. We are working on it! * `has_equal_part_len` (state, name, unequal_msg)¶ * Verify that a part that is zoomed in on has equal length. Typically used in the context of `check_function_def()` b'Parameters:' * name (str) – name of the part for which to check the length to the corresponding part in the solution. * unequal_msg (str) – Message in case the lengths do not match. * state (State) – state as passed by the SCT chain. Don’t specify this explicitly. b'Examples:' Student and solution code: > def shout(word): return word + '!!!' SCT that checks number of arguments: > Ex().check_function_def('shout').has_equal_part_len('args', 'not enough args!') * `check_call` (state, callstr, argstr=None, expand_msg=None)¶ * When checking a function definition of lambda function, prepare has_equal_x for checking the call of a user-defined function. b'Parameters:' * callstr (str) – call string that specifies how the function should be called, e.g. f(1, a = 2). `check_call()` will replace `f` with the function/lambda you’re targeting. * argstr (str) – If specified, this overrides the way the function call is refered to in the expand message. * expand_msg (str) – If specified, this overrides any messages that are prepended by previous SCT chains. * state (State) – state object that is chained from. b'Example:' SCT: > Ex().check_function_def('my_power').multi( check_call("f(3)").has_equal_value() check_call("f(3)").has_equal_output() ) * callstr (str) – call string that specifies how the function should be called, e.g. f(1, a = 2). Check whether a class was defined and zoom in on its definition Can be chained with `check_bases()` and `check_body()` . b'Parameters:' Suppose you want to check whether a class was defined correctly: > class MyInt(int): def __init__(self, i): super().__init__(i + 1) The following SCT would verify this: > Ex().check_class_def('MyInt').multi( check_bases(0).has_equal_ast(), check_body().check_function_def('__init__').multi( check_args('self'), check_args('i'), check_body().set_context(i = 2).multi( check_function('super', signature=False), check_function('super.__init__').check_args(0).has_equal_value() ) ) ) * `check_class_def()` looks for the class definition itself. * With `check_bases()` , you can zoom in on the different basse classes that the class definition inherits from. * With `check_body()` , you zoom in on the class body, after which you can use other functions such as `check_function_def()` to look for class methods. * Of course, just like for other examples, you can use `check_correct()` where necessary, e.g. to verify whether class methods give the right behavior with `check_call()` before diving into the body of the method itself. ``` check_lambda_function ``` Suppose you want a student to create a lambda function that returns the length of an array times two: > lambda x: len(x)*2 The following SCT robustly checks this: > Ex().check_lambda_function().check_correct( multi( check_call("f([1])").has_equal_value(), check_call("f([1, 2])").has_equal_value() ), check_body().set_context([1, 2, 3]).has_equal_value() ) zooms in on the first lambda function in both student and solution code. * `check_correct()` is used to * First check whether the lambda function gives the correct result when called in different ways (through `check_call()` ). * Only if these ‘function unit tests’ don’t pass, `check_correct()` will run the check_body() chain that dives deeper into the lambda function’s body. This chain sets the context variable x, the argument of the function, to the values `[1, 2, 3]` , while being agnostic to the actual name the student used for this context variable. * First check whether the lambda function gives the correct result when called in different ways (through Notice how `check_correct()` is used to great effect here: why check the function definition internals if the I/O of the function works fine? Because of this construct, all the following submissions will pass the SCT: > # passing submission 1 lambda x: len(x) + len(x) # passing submission 2 lambda y, times=2: len(y) * times ## Control flow¶ Suppose you want students to print out a message if `x` is larger than 0: > x = 4 if x > 0: print("x is strictly positive") The following SCT would verify that: > Ex().check_if_else().multi( check_test().multi( set_env(x = -1).has_equal_value(), set_env(x = 1).has_equal_value(), set_env(x = 0).has_equal_value() ), check_body().check_function('print', 0).\ check_args('value').has_equal_value() ) * `check_if_else()` zooms in on the first if statement in the student and solution submission. * `check_test()` zooms in on the ‘test’ portion of the if statement, `x > 0` in case of the solution. `has_equal_value()` reruns this expression and the corresponding expression in the student code for different values of `x` (set with `set_env()` ) and compare there results. This way, you can robustly verify whether the if test was coded up correctly. If the student codes up the condition as `0 < x` , this would also be accepted. * `check_body()` zooms in on the ‘body’ portion of the if statement, `print("...")` in case of the solution. With a classical `check_function()` chain, it is verified whether the if statement contains a function `print()` and whether its argument is set correctly. b'Example:' In Python, when an if-else statement has an `elif` clause, it is held in the orelse part. In this sense, an if-elif-else statement is represented by python as nested if-elses. More specifically, this if-else statement: > if x > 0: print(x) elif y > 0: print(y) else: print('none') Is syntactically equivalent to: > if x > 0: print(x) else: if y > 0: print(y) else: print('none') The second representation has to be followed when writing the corresponding SCT: > Ex().check_if_else().multi( check_test(), # zoom in on x > 0 check_body(), # zoom in on print(x) check_orelse().check_if_else().multi( check_test(), # zoom in on y > 0 check_body(), # zoom in on print(y) check_orelse() # zoom in on print('none') ) ) Check whether a try except statement was coded zoom in on it. Can be chained with `check_body()` , `check_handlers()` , `check_orelse()` and `check_finalbody()` . b'Parameters:' Suppose you want to verify whether the student did a try-except statement properly: > do_dangerous_thing = lambda n: n try: x = do_dangerous_thing(n = 4) except ValueError as e: x = 'something wrong with inputs' except: x = 'something went wrong' finally: print('ciao!') The following SCT can be used to verify this: > Ex().check_try_except().multi( check_body().\ check_function('do_dangerous_thing').\ check_args('n').has_equal_value(), check_handlers('ValueError').\ has_equal_value(name = 'x'), check_handlers('all').\ has_equal_value(name = 'x'), check_finalbody().\ check_function('print').check_args(0).has_equal_value() ) * `check_if_exp` (state, index=0, typestr='{{ordinal}} node', missing_msg=None, expand_msg=None)¶ * This function works the exact same way as `check_if_else()` . * `check_with` (state, index=0, typestr='{{ordinal}} node', missing_msg=None, expand_msg=None)¶ * Check whether a with statement was coded zoom in on it. b'Parameters:' ## Loops¶ Can be chained with `check_iter()` and `check_body()` . b'Parameters:' Suppose you want a student to iterate over a predefined dictionary `my_dict` and do the appropriate printouts: > for key, value in my_dict.items(): print(key + " - " + str(value)) The following SCT would verify this: > Ex().check_for_loop().multi( check_iter().has_equal_value(), check_body().multi( set_context('a', 1).has_equal_output(), set_context('b', 2).has_equal_output() ) ) * `check_for_loop()` zooms in on the `for` loop, and makes its parts available for further checking. * `check_iter()` zooms in on the iterator part of the for loop, `my_dict.items()` in the solution. `has_equal_value()` re-executes the expressions specified by student and solution and compares their results. * `check_body()` zooms in on the body part of the for loop, ``` print(key + " - " + str(value)) ``` . For different values of `key` and `value` , the student’s body and solution’s body are executed again and the printouts are captured and compared to see if they are equal. Notice how you do not need to specify the variables by name in `set_context()` . pythonwhat can figure out the variable names used in both student and solution code, and can do the verification independent of that. That way, we can make the SCT robust against submissions that code the correct logic, but use different names for the context values. In other words, the following student submissions that would also pass the SCT: > # passing submission 1 my_dict = {'a': 1, 'b': 2} for k, v in my_dict.items(): print(k + " - " + str(v)) # passing submission 2 my_dict = {'a': 1, 'b': 2} for first, second in my_dict.items(): mess = first + " - " + str(second) print(mess) b'Example:' As another example, suppose you want the student to build a list of doubles as follows: > even = [] for i in range(10): even.append(2*i) The following SCT would robustly verify this: > Ex().check_correct( check_object('even').has_equal_value(), check_for_loop().multi( check_iter().has_equal_value(), check_body().set_context(2).set_env(even = []).\ has_equal_value(name = 'even') ) ) * `check_correct()` makes sure that we do not dive into the `for` loop if the array `even` is correctly populated in the end. * If `even` was not correctly populated, `check_for_loop()` will zoom in on the for loop. * The `check_iter()` chain verifies whether range(10) (or something equivalent) was used to iterate over. * `check_body()` zooms in on the body, and reruns the body ( `even.append(2*i)` in the solution) for `i` equal to 2, and even temporarily set to an empty array. Notice how we use `set_context()` to robustly set the context value (the student can use a different variable name), while we have to explicitly set `even` with `set_env()` . Also notice how we use ``` has_equal_value(name = 'even') ``` instead of the usual `check_object()` ; `check_object()` can only be called from the root state `Ex()` . b'Example:' As a follow-up example, suppose you want the student to build a list of doubles of the even numbers only: > even = [] for i in range(10): if i % 2 == 0: even.append(2*i) The following SCT would robustly verify this: > Ex().check_correct( check_object('even').has_equal_value(), check_for_loop().multi( check_iter().has_equal_value(), check_body().check_if_else().multi( check_test().multi( set_context(1).has_equal_value(), set_context(2).has_equal_value() ), check_body().set_context(2).\ set_env(even = []).has_equal_value(name = 'even') ) ) ) Check whether a while loop was coded and zoom in on it. Suppose you want a student to code a while loop that counts down a counter from 50 until a multilpe of 11 is found. If it is found, the value should be printed out. > i = 50 while i % 11 != 0: i -= 1 The following SCT robustly verifies this: > Ex().check_correct( check_object('i').has_equal_value(), check_while().multi( check_test().multi( set_env(i = 45).has_equal_value(), set_env(i = 44).has_equal_value() ), check_body().set_env(i = 3).has_equal_value(name = 'i') ) ) * `check_correct()` first checks whether the end result of `i` is correct. If it is, the entire chain that checks the `while` loop is skipped. * If `i` is not correctly calculated, `check_while_loop()` zooms in on the while loop. * `check_test()` zooms in on the condition of the `while` loop, `i % 11 != 0` in the solution, and verifies whether the expression gives the same results for different values of `i` , set through `set_env()` , when comparing student and solution. * `check_body()` zooms in on the body of the `while` loop, and `has_equal_value()` checks whether rerunning this body updates `i` as expected when `i` is temporarily set to 3 with `set_env()` . Suppose you expect students to create a list `my_list` as follows: > my_list = [ i*2 for i in range(0,10) if i>2 ] The following SCT would robustly verify this: > Ex().check_correct( check_object('my_list').has_equal_value(), check_list_comp().multi( check_iter().has_equal_value(), check_body().set_context(4).has_equal_value(), check_ifs(0).multi( set_context(0).has_equal_value(), set_context(3).has_equal_value(), set_context(5).has_equal_value() ) ) ) * With `check_correct()` , we’re making sure that the list comprehension checking is not executed if `my_list` was calculated properly. * If `my_list` is not correct, the ‘diagnose’ chain will run: `check_list_comp()` looks for the first list comprehension in the student’s submission. * Next, `check_iter()` zooms in on the iterator, `range(0, 10)` in the case of the solution. `has_equal_value()` verifies whether the expression that the student used evaluates to the same value as the expression that the solution used. * `check_body()` zooms in on the body, `i*2` in the case of the solution. `set_context()` sets the iterator to 4, allowing for the fact that the student used another name instead of `i` for this iterator. `has_equal_value()` reruns the body in the student and solution code with the iterator set to 4, and checks if the results are the same. * `check_ifs(0)` zooms in on the first `if` of the list comprehension, `i>2` in case of the solution. With a series of `set_context()` and `has_equal_value()` , it is verifies whether this condition evaluates to the same value in student and solution code for different values of the iterator (i in the case of the solution, whatever in the case of the student). Can be chained with `check_key()` , `check_value()` , and `check_ifs()` . b'Parameters:' Suppose you expect students to create a dictionary `my_dict` as follows: > my_dict = { m:len(m) for m in ['a', 'ab', 'abc'] } The following SCT would robustly verify this: > Ex().check_correct( check_object('my_dict').has_equal_value(), check_dict_comp().multi( check_iter().has_equal_value(), check_key().set_context('ab').has_equal_value(), check_value().set_context('ab').has_equal_value() ) ) * With `check_correct()` , we’re making sure that the dictionary comprehension checking is not executed if `my_dict` was created properly. * If `my_dict` is not correct, the ‘diagnose’ chain will run: `check_dict_comp()` looks for the first dictionary comprehension in the student’s submission. * Next, `check_iter()` zooms in on the iterator, `['a', 'ab', 'abc']` in the case of the solution. `has_equal_value()` verifies whether the expression that the student used evaluates to the same value as the expression that the solution used. * `check_key()` zooms in on the key of the comprehension, `m` in the case of the solution. `set_context()` temporaritly sets the iterator to `'ab'` , allowing for the fact that the student used another name instead of `m` for this iterator. `has_equal_value()` reruns the key expression in the student and solution code with the iterator set to `'ab'` , and checks if the results are the same. * `check_value()` zooms in on the value of the comprehension, `len(m)` in the case of the solution. `has_equal_value()` reruns the value expression in the student and solution code with the iterator set to `'ab'` , and checks if the results are the same. Check whether a generator expression was coded and zoom in on it. Suppose you expect students to create a generator `my_gen` as follows: > my_gen = ( i*2 for i in range(0,10) ) The following SCT would robustly verify this: > Ex().check_correct( check_object('my_gen').has_equal_value(), check_generator_exp().multi( check_iter().has_equal_value(), check_body().set_context(4).has_equal_value() ) ) Have a look at `check_list_comp` to understand what’s going on; it is very similar. ## State management¶ * `override` (state, solution)¶ * Override the solution code with something arbitrary. There might be cases in which you want to temporarily override the solution code so you can allow for alternative ways of solving an exercise. When you use `override()` in an SCT chain, the remainder of that SCT chain will run as if the solution code you specified is the only code that was in the solution. Check the glossary for an example (pandas plotting) b'Parameters:' * solution – solution code as a string that overrides the original solution code. * state – State instance describing student and solution code. Can be omitted if used with Ex(). * `disable_highlighting` (state)¶ * Disable highlighting in the remainder of the SCT chain. Include this function if you want to avoid that pythonwhat marks which part of the student submission is incorrect. b'Examples:' SCT that will mark the ‘number’ portion if it is incorrect: > Ex().check_function('round').check_args(0).has_equal_ast() SCT chains that will not mark certain mistakes. The earlier you put the function, the more types of mistakes will no longer be highlighted: > Ex().disable_highlighting().check_function('round').check_args(0).has_equal_ast() Ex().check_function('round').disable_highlighting().check_args(0).has_equal_ast() Ex().check_function('round').check_args(0).disable_highlighting().has_equal_ast() * `set_context` (state, *args, **kwargs)¶ * Update context values for student and solution environments. When `has_equal_x()` is used after this, the context values (in `for` loops and function definitions, for example) will have the values specified through his function. It is the function equivalent of the `context_vals` argument of the `has_equal_x()` functions. * Note 1: excess args and unmatched kwargs will be unused in the student environment. * Note 2: When you try to set context values that don’t match any target variables in the solution code, `set_context()` raises an exception that lists the ones available. * Note 3: positional arguments are more robust to the student using different names for context values. * Note 4: You have to specify arguments either by position, either by name. A combination is not possible. b'Example:' Solution code: > total = 0 for i in range(10): print(i ** 2) Student submission that will pass (different iterator, different calculation): > total = 0 for j in range(10): print(j * j) SCT: > # set_context is robust against different names of context values. Ex().check_for_loop().check_body().multi( set_context(1).has_equal_output(), set_context(2).has_equal_output(), set_context(3).has_equal_output() ) # equivalent SCT, by setting context_vals in has_equal_output() Ex().check_for_loop().check_body().\ multi([s.has_equal_output(context_vals=[i]) for i in range(1, 4)]) * `set_env` (state, **kwargs)¶ * Update/set environemnt variables for student and solution environments. When `has_equal_x()` is used after this, the variables specified through this function will be available in the student and solution process. Note that you will not see these variables in the student process of the state produced by this function: the values are saved on the state and are only added to the student and solution processes when `has_equal_ast()` is called. b'Example:' Student and Solution Code: > a = 1 if a > 4: print('pretty large') SCT: > # check if condition works with different values of a Ex().check_if_else().check_test().multi( set_env(a = 3).has_equal_value(), set_env(a = 4).has_equal_value(), set_env(a = 5).has_equal_value() ) # equivalent SCT, by setting extra_env in has_equal_value() Ex().check_if_else().check_test().\ multi([has_equal_value(extra_env={'a': i}) for i in range(3, 6)]) ## Checking files¶ * `check_file` (state: protowhat.State.State, path, missing_msg='Did you create the file `{}`?', is_dir_msg='Want to check the file `{}`, but found a directory.', parse=True, solution_code=None)¶ * Test whether file exists, and make its contents the student code. b'Parameters:' * state – State instance describing student and solution code. Can be omitted if used with Ex(). * path – expected location of the file * missing_msg – feedback message if no file is found in the expected location * is_dir_msg – feedback message if the path is a directory instead of a file * parse – If `True` (the default) the content of the file is interpreted as code in the main exercise technology. This enables more checks on the content of the file. * solution_code – this argument can be used to pass the expected code for the file so it can be used by subsequent checks. This SCT fails if the file is a directory. b'Example:' To check if a user created the file `my_output.txt` in the subdirectory `resources` of the directory where the exercise is run, use this SCT: > Ex().check_file("resources/my_output.txt", parse=False) * `has_dir` (state: protowhat.State.State, path, msg='Did you create a directory `{}`?')¶ * Test whether a directory exists. b'Parameters:' * state – State instance describing student and solution code. Can be omitted if used with Ex(). * path – expected location of the directory * msg – feedback message if no directory is found in the expected location b'Example:' To check if a user created the subdirectory `resources` in the directory where the exercise is run, use this SCT: > Ex().has_dir("resources") * `run` (state, relative_working_dir=None, solution_dir='../solution', run_solution=True)¶ * Run the focused student and solution code in the specified location This function can be used after `check_file` to execute student and solution code. The arguments allow configuring the correct context for execution. SCT functions chained after this one that execute pieces of code (custom expressions or the focused part of a file) execute in the same student and solution locations as the file. This function does not execute the file itself, but code in memory. This can have an impact when: * the solution code imports from a different file in the expected solution (code that is not installed) * using functionality depending on e.g. `__file__` and `inspect` When the expected code has imports from a different file that is part of the exercise, it can only work if the solution code provided earlier does not have these imports but instead has all that functionality inlined. b'Parameters:' * relative_working_dir (str) – if specified, this relative path is the subdirectory inside the student and solution context in which the code is executed * solution_dir (str) – a relative path, `solution` by default, that sets the root of the solution context, relative to that of the student execution context * state (State) – state as passed by the SCT chain. Don’t specify this explicitly. If `relative_working_dir` is not set, it will be the directory the file was loaded from by `check_file` and fall back to the root of the student execution context (the working directory pythonwhat runs in). The `solution_dir` helps to prevent solution side effects from conflicting with those of the student. If the set or derived value of `relative_working_dir` is an absolute path, `relative_working_dir` will not be used to form the solution execution working directory: the solution code will be executed in the root of the solution execution context. b'Example:' Suppose the student and solution have a file `script.py` in `/home/repl/` : > if True: a = 1 print("Hi!") We can check it with this SCT (with `file_content` containing the expected file content): > Ex().check_file( "script.py", solution_code=file_content ).run().multi( check_object("a").has_equal_value(), has_printout(0) ) ## Bash history checks¶ * `get_bash_history` (full_history=False, bash_history_path=None)¶ * Get the commands in the bash history b'Parameters:' * full_history (bool) – if true, returns all commands in the bash history, else only return the commands executed after the last bash history info update * bash_history_path (str | Path) – path to the bash history file b'Returns:' a list of commands (empty if the file is not found) Import from * `has_command` (state, pattern, msg, fixed=False, commands=None)¶ * Test whether the bash history has a command matching the pattern b'Parameters:' * state – State instance describing student and solution code. Can be omitted if used with Ex(). * pattern – text that command must contain (can be a regex pattern or a simple string) * msg – feedback message if no matching command is found * fixed – whether to match text exactly, rather than using regular expressions * commands – the bash history commands to check against. By default this will be all commands since the last bash history info update. Otherwise pass a list of commands to search through, created by calling the helper function `get_bash_history()` . Note The helper function ``` update_bash_history_info(bash_history_path=None) ``` needs to be called in the pre-exercise code in exercise types that don’t have built-in support for bash history features. Note If the bash history info is updated every time code is submitted (by using ``` update_bash_history_info() ``` in the pre-exercise code), it’s advised to only use this function as the second part of a `check_correct()` to help students debug the command they haven’t correctly run yet. Look at the examples to see what could go wrong. If bash history info is only updated at the start of an exercise, this can be used everywhere as the (cumulative) commands from all submissions are known. b'Example:' The goal of an exercise is to use `man` . If the exercise doesn’t have built-in support for bash history SCTs, update the bash history info in the pre-exercise code: > update_bash_history_info() In the SCT, check whether a command with `man` was used: > Ex().has_command("$man\s", "Your command should start with ``man ...``.") b'Example:' The goal of an exercise is to use `touch` to create two files. In the pre-exercise code, put: > update_bash_history_info() This SCT can cause problems: > Ex().has_command("touch.*file1", "Use `touch` to create `file1`") Ex().has_command("touch.*file2", "Use `touch` to create `file2`") If a student submits after running ``` touch file0 && touch file1 ``` in the console, they will get feedback to create `file2` . If they submit again after running `touch file2` in the console, they will get feedback to create `file1` , since the SCT only has access to commands after the last bash history info update (only the second command in this case). Only if they execute all required commands in a single submission the SCT will pass. A better SCT in this situation checks the outcome first and checks the command to help the student achieve it: > Ex().check_correct( check_file('file1', parse=False), has_command("touch.*file1", "Use `touch` to create `file1`") ) Ex().check_correct( check_file('file2', parse=False), has_command("touch.*file2", "Use `touch` to create `file2`") ) * `prepare_validation` (state: protowhat.State.State, commands: List[str], bash_history_path: Optional[str] = None) → protowhat.State.State¶ * Let the exercise validation know what shell commands are required to complete the exercise ``` from protowhat.checks import prepare_validation ``` . b'Parameters:' * state – State instance describing student and solution code. Can be omitted if used with Ex(). * commands – List of strings that a student is expected to execute * bash_history_path (str | Path) – path to the bash history file b'Example:' The goal of an exercise is to run a build and check the output. At the start of the SCT, put: > Ex().prepare_validation(["make", "cd build", "ls"]) Further down you can now use `has_command` . ``` update_bash_history_info ``` (bash_history_path=None)¶ * Store the current number of commands in the bash history `get_bash_history` can use this info later to get only newer commands. Depending on the wanted behaviour this function should be called at the start of the exercise or every time the exercise is submitted. ## Electives¶ * `has_chosen` (state, correct, msgs)¶ * Test multiple choice exercise. Test for a MultipleChoiceExercise. The correct answer (as an integer) and feedback messages are passed to this function. b'Parameters:' * correct (int) – the index of the correct answer (should be an instruction). Starts at 1. * msgs (list(str)) – a list containing all feedback messages belonging to each choice of the student. The list should have the same length as the number of options. * `success_msg` (message)¶ * Set the succes message of the sct. This message will be the feedback if all tests pass. :param message: A string containing the feedback message. :type message: str * `allow_errors` (state)¶ * Allow running the student code to generate errors. This has to be used only once for every time code is executed or a different xwhat library is used. In most exercises that means it should be used just once. b'Example:' The following SCT allows the student code to generate errors: > Ex().allow_errors() * `fail` (state, msg='fail')¶ * Always fails the SCT, with an optional msg. This function takes a single argument, `msg` , that is the feedback given to the student. Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs. For example, failing a test will highlight the code as if the previous test/check had failed. b'Example:' As a trivial SCT example, > Ex().check_for_loop().check_body().fail() This can also be helpful for debugging SCTs, as it can be used to stop testing as a given point. ## Basic functionality¶ Take the following example that checks whether a student used the `round()` function correctly: ``` # solution round(2.718282, ndigits = 3) # sct Ex().check_function("round").multi( check_args("number").has_equal_value(), check_args("ndigits").has_equal_value() ) # submissions that pass: round(2.718282, 3) round(2.718282, ndigits = 3 round(number=2.718282, ndigits=3) round(ndigits=3, number=2.718282) val=2.718282; dig=3; round(val, dig) val=2.718282; dig=3; round(number=val, dig) int_part = 2; dec_part = 0.718282; round(int_part + dec_part, 3) ``` * check_function() checks whether `round()` is called by the student, and parses all the arguments. * `check_args()` checks whether a certain argument was specified, and zooms in on the expression used to specify that argument. * `has_equal_value()` will rerun the expressions used to specify the arguments in both student and solution process, and compare the results. Note In `check_args()` you can refer to the argument of a function call both by argument name and by position. ### Customizations¶ If you only want to check the `number` parameter, just don’t include a second chain with ``` check_args("ndigits") ``` : ``` Ex().check_function("round").check_args("number").has_equal_value() ``` If you only want to check whether the `number` parameter was specified, but not that it was specified correctly, drop `has_equal_value()` : ``` Ex().check_function("round").check_args("number") ``` If you just want to check whether the function was called, drop `check_args()` : ``` Ex().check_function("round") ``` If you want to compare the ‘string versions’ of the expressions used to set the arguments instead of the evaluated result of these expressions, you can use `has_equal_ast()` instead of `has_equal_value()` : Now, the following submissions would fail: ``` val=2.718282; dig=3; round(val, dig) ``` – the string representation of `val` in the student code is compared to `2.718282` in the solution code. * ``` val=2.718282; dig=3; round(number=val, dig) ``` – same * ``` int_part = 2; dec_part = 0.718282; round(int_part + dec_part, 3) ``` – the string representation of `int_part + dec_part` in the student code is compered to `2.718282` in the solution code. As you can see, doing exact string comparison of arguments is not a good idea here, as it is very inflexible. There are cases, however, where it makes sense to use this, e.g. when there are very big objects passed to functions, and you don’t want to spend the processing power to fetch these objects from the student and solution processes. ## Functions in packages¶ If you’re testing whether function calls of particular packages are used correctly, you should always refer to these functions with their ‘full name’. Suppose you want to test whether the function `show` of `matplotlib.pyplot` was called, use this SCT: ``` Ex().check_function("matplotlib.pyplot.show") ``` `check_function()` can handle it when a student used aliases for the python packages (all `import` and `import * from *` calls are supported). If the student did not properly call the function, `check_function()` will automatically generate a feedback message that corresponds to how the student imported the modules/functions. ## has_equal_value? has_equal_ast?¶ In the customizations section above, you could already notice the difference between `has_equal_value()` and `has_equal_ast()` for checking whether arguments are correct. The former reruns the expression used to specify the argument in both student and solution process and compares their results, while the latter simply compares the expression’s AST representations. Clearly, the former is more robust, but there are some cases in which `has_equal_ast()` can be useful: * For better feedback. When using `has_equal_ast()` , the ‘expected x got y’ message that is automatically generated when the arguments don’t match up will use the actual expressions used. `has_equal_value()` will use string representations of the evaluations of the expressions, if they make sense, and this is typically less useful. * To avoid very expensive object comparisons. If you are 100% sure that the object people have to pass as an argument is already correct (because you checked it earlier in the SCT or because it was already specified in the pre exercise code) and doing an equality check on this object between student and solution project is likely going to be expensive, then you can safely use `has_equal_ast()` to speed things up. * If you want to save yourself the trouble of building exotic contexts. You’ll often find yourself checking function calls in e.g. a for loop. Typically, these function calls will use objects that were generated inside the loop. To easily unit test the body of a for loop, you’ll typically have to use `set_context()` and `set_env()` . For exotic for loops, this can become tricky, and it might be a quick fix to be a little more specific about the object names people should use, and just use `has_equal_ast()` for the argument comparison. That way, you’re bypassing the need to build up a context in the student/solution process and do object comparisions. ## Signatures¶ The `round()` example earlier in this article showed that a student can call the function in a multitude of ways, specifying arguments by position, by keyword or a mix of those. To be robust against this, pythonwhat uses the concept of argument binding. More specifically, each function has a function signature. Given this signature and the way the function was called, argument binding can map each parameter you specified to an argument. This small demo fetches the signature of the `open` function and tries to bind arguments that have been specified in two different ways. Notice how the resulting bound arguments are the same: >>> sig = inspect.signature(open) >>> sig <Signature (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)>>> sig.bind('my_file.txt', mode = 'r') <BoundArguments (file='my_file.txt', mode='r')>>> sig.bind(file = 'my_file.txt', mode = 'r') <BoundArguments (file='my_file.txt', mode='r')> ``` When you’re using `check_args()` you are actually selecting these bound arguments. This works fine for functions like `round()` and `open()` that have a list of named arguments, but things get tricky when dealing with functions that take `*args` and `*kwargs` . `*args` example¶ Python allows functions to take a variable number of unnamed arguments through `*args` , like this function: ``` def multiply(*args): res = 1 for num in args: res *= num return res ``` >>> inspect.signature(multiply) <Signature (*args)>>> sig = inspect.signature(multiply) >>> sig <Signature (*args)>>> sig.bind(1, 2) <BoundArguments (args=(1, 2))>>> sig.bind(3, 4, 5) <BoundArguments (args=(3, 4, 5))> ``` Notice how now the list of arguments is grouped under a tuple with the name `args` in the bound arguments. To be able to check each of these arguments individually, pythonwhat allows you to do repeated indexing in `check_args()` . Instead of specifying the name of an argument, you can specify a list of indices: ``` # solution to check against multiply(2, 3, 4) # corresponding SCT Ex().check_function("multiply").multi( check_args(["args", 0]).has_equal_value(), check_args(["args", 1]).has_equal_value(), check_args(["args", 2]).has_equal_value() ) ``` The `check_args()` subchains each zoom in on a particular tuple element of the bound `args` argument. `**kwargs` example¶ Python allows functions to take a variable number of named arguments through `**kwargs` , like this function: ``` def my_dict(**kwargs): return dict(**kwargs) ``` >>> sig = inspect.signature(my_dict) >>> sig.bind(a = 1, b = 2) <BoundArguments (kwargs={'b': 2, 'a': 1})>>> sig.bind(c = 2, b = 3) <BoundArguments (kwargs={'b': 3, 'c': 2})> ``` Notice how now the list of arguments is grouped under a dictionary name `kwargs` in the bound arguments. To be able to check each of these arguments individually, pythonwhat allows you to do repeated indexing in `check_args()` . Instead of specifying the name of an argument, you can specify a list of indices: ``` # solution to check against my_dict(a = 1, b = 2) # corresponding SCT Ex().check_function("my_dict").multi( check_args(["kwargs", "a"]).has_equal_value(), check_args(["kwargs", "b"]).has_equal_value() ) ``` The `check_args()` subchains each zoom in on a particular dictionary element of the bound `kwargs` argument. ### Manual signatures¶ Unfortunately for a lot of Python’s built-in functions no function signature is readily available because the function has been implemented in C code. To work around this, pythonwhat already includes manually specified signatures for functions such as `print()` , `str()` , `hasattr()` , etc, but it’s still possible that some signatures are missing. That’s why `check_function()` features a `signature` parameter, that is `True` by default. If pythonwhat can’t retrieve a signature for the function you want to test, you can pass an object of the class `inspect.Signature` to the `signature` parameter. Suppose, for the sake of example, that `check_function()` can’t find a signature for the `round()` function. In a real situation, you will be informed about a missing signature through a backend error. To be able to implement this SCT, you can use the `sig_from_params()` function: ``` sig = sig_from_params(param("number", param.POSITIONAL_OR_KEYWORD), param("ndigits", param.POSITIONAL_OR_KEYWORD, default=0)) Ex().check_function("round", signature=sig).multi( check_args("number").has_equal_value(), check_args("ndigits").has_equal_value() ) ``` You can pass `sig_from_params()` as many parameters as you want. `param` is an alias of the `Parameter` class that’s inside the `inspect` module. - The first argument of `param()` should be the name of the parameter, - The second argument should be the ‘kind’ of parameter. ``` param.POSITIONAL_OR_KEYWORD ``` tells `check_function` that the parameter can be specified either through a positional argument or through a keyword argument. Other common possibilities are ``` param.POSITIONAL_ONLY ``` and `param.KEYWORD_ONLY` (for a full list, refer to the docs). - The third optional argument allows you to specify a default value for the parameter. Note If you find vital Python functions that are used very often and that are not included in pythonwhat by default, you can let us know and we’ll add the function to our list of manual signatures. ## Multiple function calls¶ Inside `check_function()` the `index` argument ( `0` by default), becomes important when there are several calls of the same function. Suppose that your exercise requires the student to call the `round()` function twice: once on `pi` and once on Euler’s number: ``` # Call round on pi round(3.14159, 3) # Call round on e round(2.71828, 3) ``` To test both these function calls, you’ll need the following SCT: ``` Ex().check_function("round", 0).multi( check_args("number").has_equal_value() check_args("ndigits").has_equal_value() ) Ex().check_function("round", 1).multi( check_args("number").has_equal_value() check_args("ndigits").has_equal_value() ) ``` The first `check_function()` chain, where `index=0` , looks for the first call of `round()` in both student solution code, while `check_funtion()` with `index=1` will look for the second function call. After this, the rest of the SCT chain behaves as before. ## Methods¶ Methods are Python functions that are called on objects. For testing this, you can also use `check_function()` . Consider the following examples, that calculates the `mean()` of the column `a` in the pandas data frame `df` : ``` # pec import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3, 4] }) # solution df.a.mean() # sct Ex().check_function('df.a.mean').has_equal_value() ``` ``` The SCT is checking whether the method `df.a.mean` was called in the student code, and whether rerunning the call in both student and solution process is returning the same result. As a more advanced example, consider this example of chained method calls: # sct Ex().check_function('df.groupby').check_args(0).has_equal_value() Ex().check_function('df.groupby.mean', signature=sig_from_obj('df.mean')).has_equal_value() ``` * The first SCT is checking whether `df.groupby()` was called and whether the argument for `df.groupby()` was specified correctly to be `'type'` . * The second SCT is first checking whether `df.groupby.mean()` was called and whether calling it gives the right result. Notice several things: * We describe the entire chain of method calls, leaving out the parentheses and arguments used for method calls in between. * We use `sig_from_obj()` to manually specify a Python expression that pythonwhat can use to derive the signature from. If the string you use to describe the function to check evaluates to a method or function in the solution process, like for `'df.groupby'` , pythonwhat can figure out the signature. However, for `'df.groupby.mean'` will not evaluate to a method object in the solution process, so we need to manually specify a valid expression that will evaluate to a valid signature with `sig_from_obj()` . In this example, you are only checking whether the function is called and whether rerunning it gives the correct result. You are not checking the actual arguments, so there’s actually no point in trying to match the function call to its signature. In cases like this, you can set `signature=False` , which skips the fetching of a signature and the binding or arguments altogether: # sct Ex().check_function('df.groupby').check_args(0).has_equal_value() Ex().check_function('df.groupby.mean', signature=False).has_equal_value() ``` Warning Watch out with disabling signature binding as a one-stop solution to make your SCT run without errors. If there are arguments to check, argument binding makes sure that various ways of calling the function can all work. Setting `signature=False` will skip this binding, which can cause your SCT to mark perfectly valid student submissions as incorrect! Note You can also use the `sig_from_params()` function to manually build the signature from scratch, but this this more work than simply specifying the function object as a string from which to extract the signature.
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/nginx/armnginx/v2
go
Go
README [¶](#section-readme) --- ### Azure Nginx Module for Go [![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/nginx/armnginx/v2)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/nginx/armnginx/v2) The `armnginx` module provides operations for working with Azure Nginx. [Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/nginx/armnginx) ### Getting started #### Prerequisites * an [Azure subscription](https://azure.microsoft.com/free/) * Go 1.19 or above #### Install the package This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. Install the Azure Nginx module: ``` go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/nginx/armnginx/v2 ``` #### Authorization When creating a client, you will need to provide a credential for authenticating with Azure Nginx. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. ``` cred, err := azidentity.NewDefaultAzureCredential(nil) ``` For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). #### Client Factory Azure Nginx module consists of one or more clients. We provide a client factory which could be used to create any client in this module. ``` clientFactory, err := armnginx.NewClientFactory(<subscription ID>, cred, nil) ``` You can use `ClientOptions` in package `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` to set endpoint to connect with public and sovereign clouds as well as Azure Stack. For more information, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). ``` options := arm.ClientOptions { ClientOptions: azcore.ClientOptions { Cloud: cloud.AzureChina, }, } clientFactory, err := armnginx.NewClientFactory(<subscription ID>, cred, &options) ``` #### Clients A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. ``` client := clientFactory.NewDeploymentsClient() ``` #### Provide Feedback If you encounter bugs or have suggestions, please [open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Nginx` label. ### Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit <https://cla.microsoft.com>. When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [<EMAIL>](mailto:<EMAIL>) with any additional questions or comments. Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [type Certificate](#Certificate) * + [func (c Certificate) MarshalJSON() ([]byte, error)](#Certificate.MarshalJSON) + [func (c *Certificate) UnmarshalJSON(data []byte) error](#Certificate.UnmarshalJSON) * [type CertificateListResponse](#CertificateListResponse) * + [func (c CertificateListResponse) MarshalJSON() ([]byte, error)](#CertificateListResponse.MarshalJSON) + [func (c *CertificateListResponse) UnmarshalJSON(data []byte) error](#CertificateListResponse.UnmarshalJSON) * [type CertificateProperties](#CertificateProperties) * + [func (c CertificateProperties) MarshalJSON() ([]byte, error)](#CertificateProperties.MarshalJSON) + [func (c *CertificateProperties) UnmarshalJSON(data []byte) error](#CertificateProperties.UnmarshalJSON) * [type CertificatesClient](#CertificatesClient) * + [func NewCertificatesClient(subscriptionID string, credential azcore.TokenCredential, ...) (*CertificatesClient, error)](#NewCertificatesClient) * + [func (client *CertificatesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, deploymentName string, ...) (*runtime.Poller[CertificatesClientCreateOrUpdateResponse], error)](#CertificatesClient.BeginCreateOrUpdate) + [func (client *CertificatesClient) BeginDelete(ctx context.Context, resourceGroupName string, deploymentName string, ...) (*runtime.Poller[CertificatesClientDeleteResponse], error)](#CertificatesClient.BeginDelete) + [func (client *CertificatesClient) Get(ctx context.Context, resourceGroupName string, deploymentName string, ...) (CertificatesClientGetResponse, error)](#CertificatesClient.Get) + [func (client *CertificatesClient) NewListPager(resourceGroupName string, deploymentName string, ...) *runtime.Pager[CertificatesClientListResponse]](#CertificatesClient.NewListPager) * [type CertificatesClientBeginCreateOrUpdateOptions](#CertificatesClientBeginCreateOrUpdateOptions) * [type CertificatesClientBeginDeleteOptions](#CertificatesClientBeginDeleteOptions) * [type CertificatesClientCreateOrUpdateResponse](#CertificatesClientCreateOrUpdateResponse) * [type CertificatesClientDeleteResponse](#CertificatesClientDeleteResponse) * [type CertificatesClientGetOptions](#CertificatesClientGetOptions) * [type CertificatesClientGetResponse](#CertificatesClientGetResponse) * [type CertificatesClientListOptions](#CertificatesClientListOptions) * [type CertificatesClientListResponse](#CertificatesClientListResponse) * [type ClientFactory](#ClientFactory) * + [func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, ...) (*ClientFactory, error)](#NewClientFactory) * + [func (c *ClientFactory) NewCertificatesClient() *CertificatesClient](#ClientFactory.NewCertificatesClient) + [func (c *ClientFactory) NewConfigurationsClient() *ConfigurationsClient](#ClientFactory.NewConfigurationsClient) + [func (c *ClientFactory) NewDeploymentsClient() *DeploymentsClient](#ClientFactory.NewDeploymentsClient) + [func (c *ClientFactory) NewOperationsClient() *OperationsClient](#ClientFactory.NewOperationsClient) * [type Configuration](#Configuration) * + [func (c Configuration) MarshalJSON() ([]byte, error)](#Configuration.MarshalJSON) + [func (c *Configuration) UnmarshalJSON(data []byte) error](#Configuration.UnmarshalJSON) * [type ConfigurationFile](#ConfigurationFile) * + [func (c ConfigurationFile) MarshalJSON() ([]byte, error)](#ConfigurationFile.MarshalJSON) + [func (c *ConfigurationFile) UnmarshalJSON(data []byte) error](#ConfigurationFile.UnmarshalJSON) * [type ConfigurationListResponse](#ConfigurationListResponse) * + [func (c ConfigurationListResponse) MarshalJSON() ([]byte, error)](#ConfigurationListResponse.MarshalJSON) + [func (c *ConfigurationListResponse) UnmarshalJSON(data []byte) error](#ConfigurationListResponse.UnmarshalJSON) * [type ConfigurationPackage](#ConfigurationPackage) * + [func (c ConfigurationPackage) MarshalJSON() ([]byte, error)](#ConfigurationPackage.MarshalJSON) + [func (c *ConfigurationPackage) UnmarshalJSON(data []byte) error](#ConfigurationPackage.UnmarshalJSON) * [type ConfigurationProperties](#ConfigurationProperties) * + [func (c ConfigurationProperties) MarshalJSON() ([]byte, error)](#ConfigurationProperties.MarshalJSON) + [func (c *ConfigurationProperties) UnmarshalJSON(data []byte) error](#ConfigurationProperties.UnmarshalJSON) * [type ConfigurationsClient](#ConfigurationsClient) * + [func NewConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, ...) (*ConfigurationsClient, error)](#NewConfigurationsClient) * + [func (client *ConfigurationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, deploymentName string, ...) (*runtime.Poller[ConfigurationsClientCreateOrUpdateResponse], error)](#ConfigurationsClient.BeginCreateOrUpdate) + [func (client *ConfigurationsClient) BeginDelete(ctx context.Context, resourceGroupName string, deploymentName string, ...) (*runtime.Poller[ConfigurationsClientDeleteResponse], error)](#ConfigurationsClient.BeginDelete) + [func (client *ConfigurationsClient) Get(ctx context.Context, resourceGroupName string, deploymentName string, ...) (ConfigurationsClientGetResponse, error)](#ConfigurationsClient.Get) + [func (client *ConfigurationsClient) NewListPager(resourceGroupName string, deploymentName string, ...) *runtime.Pager[ConfigurationsClientListResponse]](#ConfigurationsClient.NewListPager) * [type ConfigurationsClientBeginCreateOrUpdateOptions](#ConfigurationsClientBeginCreateOrUpdateOptions) * [type ConfigurationsClientBeginDeleteOptions](#ConfigurationsClientBeginDeleteOptions) * [type ConfigurationsClientCreateOrUpdateResponse](#ConfigurationsClientCreateOrUpdateResponse) * [type ConfigurationsClientDeleteResponse](#ConfigurationsClientDeleteResponse) * [type ConfigurationsClientGetOptions](#ConfigurationsClientGetOptions) * [type ConfigurationsClientGetResponse](#ConfigurationsClientGetResponse) * [type ConfigurationsClientListOptions](#ConfigurationsClientListOptions) * [type ConfigurationsClientListResponse](#ConfigurationsClientListResponse) * [type CreatedByType](#CreatedByType) * + [func PossibleCreatedByTypeValues() []CreatedByType](#PossibleCreatedByTypeValues) * [type Deployment](#Deployment) * + [func (d Deployment) MarshalJSON() ([]byte, error)](#Deployment.MarshalJSON) + [func (d *Deployment) UnmarshalJSON(data []byte) error](#Deployment.UnmarshalJSON) * [type DeploymentListResponse](#DeploymentListResponse) * + [func (d DeploymentListResponse) MarshalJSON() ([]byte, error)](#DeploymentListResponse.MarshalJSON) + [func (d *DeploymentListResponse) UnmarshalJSON(data []byte) error](#DeploymentListResponse.UnmarshalJSON) * [type DeploymentProperties](#DeploymentProperties) * + [func (d DeploymentProperties) MarshalJSON() ([]byte, error)](#DeploymentProperties.MarshalJSON) + [func (d *DeploymentProperties) UnmarshalJSON(data []byte) error](#DeploymentProperties.UnmarshalJSON) * [type DeploymentUpdateParameters](#DeploymentUpdateParameters) * + [func (d DeploymentUpdateParameters) MarshalJSON() ([]byte, error)](#DeploymentUpdateParameters.MarshalJSON) + [func (d *DeploymentUpdateParameters) UnmarshalJSON(data []byte) error](#DeploymentUpdateParameters.UnmarshalJSON) * [type DeploymentUpdateProperties](#DeploymentUpdateProperties) * + [func (d DeploymentUpdateProperties) MarshalJSON() ([]byte, error)](#DeploymentUpdateProperties.MarshalJSON) + [func (d *DeploymentUpdateProperties) UnmarshalJSON(data []byte) error](#DeploymentUpdateProperties.UnmarshalJSON) * [type DeploymentsClient](#DeploymentsClient) * + [func NewDeploymentsClient(subscriptionID string, credential azcore.TokenCredential, ...) (*DeploymentsClient, error)](#NewDeploymentsClient) * + [func (client *DeploymentsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, deploymentName string, ...) (*runtime.Poller[DeploymentsClientCreateOrUpdateResponse], error)](#DeploymentsClient.BeginCreateOrUpdate) + [func (client *DeploymentsClient) BeginDelete(ctx context.Context, resourceGroupName string, deploymentName string, ...) (*runtime.Poller[DeploymentsClientDeleteResponse], error)](#DeploymentsClient.BeginDelete) + [func (client *DeploymentsClient) BeginUpdate(ctx context.Context, resourceGroupName string, deploymentName string, ...) (*runtime.Poller[DeploymentsClientUpdateResponse], error)](#DeploymentsClient.BeginUpdate) + [func (client *DeploymentsClient) Get(ctx context.Context, resourceGroupName string, deploymentName string, ...) (DeploymentsClientGetResponse, error)](#DeploymentsClient.Get) + [func (client *DeploymentsClient) NewListByResourceGroupPager(resourceGroupName string, options *DeploymentsClientListByResourceGroupOptions) *runtime.Pager[DeploymentsClientListByResourceGroupResponse]](#DeploymentsClient.NewListByResourceGroupPager) + [func (client *DeploymentsClient) NewListPager(options *DeploymentsClientListOptions) *runtime.Pager[DeploymentsClientListResponse]](#DeploymentsClient.NewListPager) * [type DeploymentsClientBeginCreateOrUpdateOptions](#DeploymentsClientBeginCreateOrUpdateOptions) * [type DeploymentsClientBeginDeleteOptions](#DeploymentsClientBeginDeleteOptions) * [type DeploymentsClientBeginUpdateOptions](#DeploymentsClientBeginUpdateOptions) * [type DeploymentsClientCreateOrUpdateResponse](#DeploymentsClientCreateOrUpdateResponse) * [type DeploymentsClientDeleteResponse](#DeploymentsClientDeleteResponse) * [type DeploymentsClientGetOptions](#DeploymentsClientGetOptions) * [type DeploymentsClientGetResponse](#DeploymentsClientGetResponse) * [type DeploymentsClientListByResourceGroupOptions](#DeploymentsClientListByResourceGroupOptions) * [type DeploymentsClientListByResourceGroupResponse](#DeploymentsClientListByResourceGroupResponse) * [type DeploymentsClientListOptions](#DeploymentsClientListOptions) * [type DeploymentsClientListResponse](#DeploymentsClientListResponse) * [type DeploymentsClientUpdateResponse](#DeploymentsClientUpdateResponse) * [type ErrorResponseBody](#ErrorResponseBody) * + [func (e ErrorResponseBody) MarshalJSON() ([]byte, error)](#ErrorResponseBody.MarshalJSON) + [func (e *ErrorResponseBody) UnmarshalJSON(data []byte) error](#ErrorResponseBody.UnmarshalJSON) * [type FrontendIPConfiguration](#FrontendIPConfiguration) * + [func (f FrontendIPConfiguration) MarshalJSON() ([]byte, error)](#FrontendIPConfiguration.MarshalJSON) + [func (f *FrontendIPConfiguration) UnmarshalJSON(data []byte) error](#FrontendIPConfiguration.UnmarshalJSON) * [type IdentityProperties](#IdentityProperties) * + [func (i IdentityProperties) MarshalJSON() ([]byte, error)](#IdentityProperties.MarshalJSON) + [func (i *IdentityProperties) UnmarshalJSON(data []byte) error](#IdentityProperties.UnmarshalJSON) * [type IdentityType](#IdentityType) * + [func PossibleIdentityTypeValues() []IdentityType](#PossibleIdentityTypeValues) * [type Logging](#Logging) * + [func (l Logging) MarshalJSON() ([]byte, error)](#Logging.MarshalJSON) + [func (l *Logging) UnmarshalJSON(data []byte) error](#Logging.UnmarshalJSON) * [type NetworkInterfaceConfiguration](#NetworkInterfaceConfiguration) * + [func (n NetworkInterfaceConfiguration) MarshalJSON() ([]byte, error)](#NetworkInterfaceConfiguration.MarshalJSON) + [func (n *NetworkInterfaceConfiguration) UnmarshalJSON(data []byte) error](#NetworkInterfaceConfiguration.UnmarshalJSON) * [type NetworkProfile](#NetworkProfile) * + [func (n NetworkProfile) MarshalJSON() ([]byte, error)](#NetworkProfile.MarshalJSON) + [func (n *NetworkProfile) UnmarshalJSON(data []byte) error](#NetworkProfile.UnmarshalJSON) * [type NginxPrivateIPAllocationMethod](#NginxPrivateIPAllocationMethod) * + [func PossibleNginxPrivateIPAllocationMethodValues() []NginxPrivateIPAllocationMethod](#PossibleNginxPrivateIPAllocationMethodValues) * [type OperationDisplay](#OperationDisplay) * + [func (o OperationDisplay) MarshalJSON() ([]byte, error)](#OperationDisplay.MarshalJSON) + [func (o *OperationDisplay) UnmarshalJSON(data []byte) error](#OperationDisplay.UnmarshalJSON) * [type OperationListResult](#OperationListResult) * + [func (o OperationListResult) MarshalJSON() ([]byte, error)](#OperationListResult.MarshalJSON) + [func (o *OperationListResult) UnmarshalJSON(data []byte) error](#OperationListResult.UnmarshalJSON) * [type OperationResult](#OperationResult) * + [func (o OperationResult) MarshalJSON() ([]byte, error)](#OperationResult.MarshalJSON) + [func (o *OperationResult) UnmarshalJSON(data []byte) error](#OperationResult.UnmarshalJSON) * [type OperationsClient](#OperationsClient) * + [func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error)](#NewOperationsClient) * + [func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse]](#OperationsClient.NewListPager) * [type OperationsClientListOptions](#OperationsClientListOptions) * [type OperationsClientListResponse](#OperationsClientListResponse) * [type PrivateIPAddress](#PrivateIPAddress) * + [func (p PrivateIPAddress) MarshalJSON() ([]byte, error)](#PrivateIPAddress.MarshalJSON) + [func (p *PrivateIPAddress) UnmarshalJSON(data []byte) error](#PrivateIPAddress.UnmarshalJSON) * [type ProvisioningState](#ProvisioningState) * + [func PossibleProvisioningStateValues() []ProvisioningState](#PossibleProvisioningStateValues) * [type PublicIPAddress](#PublicIPAddress) * + [func (p PublicIPAddress) MarshalJSON() ([]byte, error)](#PublicIPAddress.MarshalJSON) + [func (p *PublicIPAddress) UnmarshalJSON(data []byte) error](#PublicIPAddress.UnmarshalJSON) * [type ResourceProviderDefaultErrorResponse](#ResourceProviderDefaultErrorResponse) * + [func (r ResourceProviderDefaultErrorResponse) MarshalJSON() ([]byte, error)](#ResourceProviderDefaultErrorResponse.MarshalJSON) + [func (r *ResourceProviderDefaultErrorResponse) UnmarshalJSON(data []byte) error](#ResourceProviderDefaultErrorResponse.UnmarshalJSON) * [type ResourceSKU](#ResourceSKU) * + [func (r ResourceSKU) MarshalJSON() ([]byte, error)](#ResourceSKU.MarshalJSON) + [func (r *ResourceSKU) UnmarshalJSON(data []byte) error](#ResourceSKU.UnmarshalJSON) * [type StorageAccount](#StorageAccount) * + [func (s StorageAccount) MarshalJSON() ([]byte, error)](#StorageAccount.MarshalJSON) + [func (s *StorageAccount) UnmarshalJSON(data []byte) error](#StorageAccount.UnmarshalJSON) * [type SystemData](#SystemData) * + [func (s SystemData) MarshalJSON() ([]byte, error)](#SystemData.MarshalJSON) + [func (s *SystemData) UnmarshalJSON(data []byte) error](#SystemData.UnmarshalJSON) * [type UserIdentityProperties](#UserIdentityProperties) * + [func (u UserIdentityProperties) MarshalJSON() ([]byte, error)](#UserIdentityProperties.MarshalJSON) + [func (u *UserIdentityProperties) UnmarshalJSON(data []byte) error](#UserIdentityProperties.UnmarshalJSON) #### Examples [¶](#pkg-examples) * [CertificatesClient.BeginCreateOrUpdate](#example-CertificatesClient.BeginCreateOrUpdate) * [CertificatesClient.BeginDelete](#example-CertificatesClient.BeginDelete) * [CertificatesClient.Get](#example-CertificatesClient.Get) * [CertificatesClient.NewListPager](#example-CertificatesClient.NewListPager) * [ConfigurationsClient.BeginCreateOrUpdate](#example-ConfigurationsClient.BeginCreateOrUpdate) * [ConfigurationsClient.BeginDelete](#example-ConfigurationsClient.BeginDelete) * [ConfigurationsClient.Get](#example-ConfigurationsClient.Get) * [ConfigurationsClient.NewListPager](#example-ConfigurationsClient.NewListPager) * [DeploymentsClient.BeginCreateOrUpdate](#example-DeploymentsClient.BeginCreateOrUpdate) * [DeploymentsClient.BeginDelete](#example-DeploymentsClient.BeginDelete) * [DeploymentsClient.BeginUpdate](#example-DeploymentsClient.BeginUpdate) * [DeploymentsClient.Get](#example-DeploymentsClient.Get) * [DeploymentsClient.NewListByResourceGroupPager](#example-DeploymentsClient.NewListByResourceGroupPager) * [DeploymentsClient.NewListPager](#example-DeploymentsClient.NewListPager) * [OperationsClient.NewListPager](#example-OperationsClient.NewListPager) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) This section is empty. ### Functions [¶](#pkg-functions) This section is empty. ### Types [¶](#pkg-types) #### type [Certificate](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L14) [¶](#Certificate) ``` type Certificate struct { Location *[string](/builtin#string) `json:"location,omitempty"` Properties *[CertificateProperties](#CertificateProperties) `json:"properties,omitempty"` // Dictionary of Tags map[[string](/builtin#string)]*[string](/builtin#string) `json:"tags,omitempty"` // READ-ONLY ID *[string](/builtin#string) `json:"id,omitempty" azure:"ro"` // READ-ONLY Name *[string](/builtin#string) `json:"name,omitempty" azure:"ro"` // READ-ONLY; Metadata pertaining to creation and last modification of the resource. SystemData *[SystemData](#SystemData) `json:"systemData,omitempty" azure:"ro"` // READ-ONLY Type *[string](/builtin#string) `json:"type,omitempty" azure:"ro"` } ``` #### func (Certificate) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L20) [¶](#Certificate.MarshalJSON) ``` func (c [Certificate](#Certificate)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type Certificate. #### func (*Certificate) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L33) [¶](#Certificate.UnmarshalJSON) ``` func (c *[Certificate](#Certificate)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type Certificate. #### type [CertificateListResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L34) [¶](#CertificateListResponse) ``` type CertificateListResponse struct { NextLink *[string](/builtin#string) `json:"nextLink,omitempty"` Value []*[Certificate](#Certificate) `json:"value,omitempty"` } ``` #### func (CertificateListResponse) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L71) [¶](#CertificateListResponse.MarshalJSON) ``` func (c [CertificateListResponse](#CertificateListResponse)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type CertificateListResponse. #### func (*CertificateListResponse) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L79) [¶](#CertificateListResponse.UnmarshalJSON) ``` func (c *[CertificateListResponse](#CertificateListResponse)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type CertificateListResponse. #### type [CertificateProperties](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L39) [¶](#CertificateProperties) ``` type CertificateProperties struct { CertificateVirtualPath *[string](/builtin#string) `json:"certificateVirtualPath,omitempty"` KeyVaultSecretID *[string](/builtin#string) `json:"keyVaultSecretId,omitempty"` KeyVirtualPath *[string](/builtin#string) `json:"keyVirtualPath,omitempty"` // READ-ONLY ProvisioningState *[ProvisioningState](#ProvisioningState) `json:"provisioningState,omitempty" azure:"ro"` } ``` #### func (CertificateProperties) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L102) [¶](#CertificateProperties.MarshalJSON) ``` func (c [CertificateProperties](#CertificateProperties)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type CertificateProperties. #### func (*CertificateProperties) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L112) [¶](#CertificateProperties.UnmarshalJSON) ``` func (c *[CertificateProperties](#CertificateProperties)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type CertificateProperties. #### type [CertificatesClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/certificates_client.go#L26) [¶](#CertificatesClient) ``` type CertificatesClient struct { // contains filtered or unexported fields } ``` CertificatesClient contains the methods for the Certificates group. Don't use this type directly, use NewCertificatesClient() instead. #### func [NewCertificatesClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/certificates_client.go#L35) [¶](#NewCertificatesClient) ``` func NewCertificatesClient(subscriptionID [string](/builtin#string), credential [azcore](/github.com/Azure/azure-sdk-for-go/sdk/azcore).[TokenCredential](/github.com/Azure/azure-sdk-for-go/sdk/azcore#TokenCredential), options *[arm](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm).[ClientOptions](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm#ClientOptions)) (*[CertificatesClient](#CertificatesClient), [error](/builtin#error)) ``` NewCertificatesClient creates a new instance of CertificatesClient with the specified values. * subscriptionID - The ID of the target subscription. * credential - used to authorize requests. Usually a credential from azidentity. * options - pass nil to accept the default values. #### func (*CertificatesClient) [BeginCreateOrUpdate](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/certificates_client.go#L56) [¶](#CertificatesClient.BeginCreateOrUpdate) ``` func (client *[CertificatesClient](#CertificatesClient)) BeginCreateOrUpdate(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), certificateName [string](/builtin#string), options *[CertificatesClientBeginCreateOrUpdateOptions](#CertificatesClientBeginCreateOrUpdateOptions)) (*[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Poller](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Poller)[[CertificatesClientCreateOrUpdateResponse](#CertificatesClientCreateOrUpdateResponse)], [error](/builtin#error)) ``` BeginCreateOrUpdate - Create or update the Nginx certificates for given Nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * certificateName - The name of certificate * options - CertificatesClientBeginCreateOrUpdateOptions contains the optional parameters for the CertificatesClient.BeginCreateOrUpdate method. Example [¶](#example-CertificatesClient.BeginCreateOrUpdate) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Certificates_CreateOrUpdate.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewCertificatesClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myDeployment", "default", &armnginx.CertificatesClientBeginCreateOrUpdateOptions{Body: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } res, err := poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Certificate = armnginx.Certificate{ // Name: to.Ptr("default"), // Type: to.Ptr("nginx.nginxplus/nginxdeployments/certificates"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/NGINX.NGINXPLUS/nginxDeployments/myDeployment/certificates/default"), // Properties: &armnginx.CertificateProperties{ // CertificateVirtualPath: to.Ptr("/src/cert/somePath.cert"), // KeyVaultSecretID: to.Ptr("https://someKV.vault.azure.com/someSecretID"), // KeyVirtualPath: to.Ptr("/src/cert/somekey.key"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // } ``` ``` Output: ``` #### func (*CertificatesClient) [BeginDelete](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/certificates_client.go#L131) [¶](#CertificatesClient.BeginDelete) ``` func (client *[CertificatesClient](#CertificatesClient)) BeginDelete(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), certificateName [string](/builtin#string), options *[CertificatesClientBeginDeleteOptions](#CertificatesClientBeginDeleteOptions)) (*[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Poller](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Poller)[[CertificatesClientDeleteResponse](#CertificatesClientDeleteResponse)], [error](/builtin#error)) ``` BeginDelete - Deletes a certificate from the nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * certificateName - The name of certificate * options - CertificatesClientBeginDeleteOptions contains the optional parameters for the CertificatesClient.BeginDelete method. Example [¶](#example-CertificatesClient.BeginDelete) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Certificates_Delete.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewCertificatesClient().BeginDelete(ctx, "myResourceGroup", "myDeployment", "default", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } ``` ``` Output: ``` #### func (*CertificatesClient) [Get](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/certificates_client.go#L200) [¶](#CertificatesClient.Get) ``` func (client *[CertificatesClient](#CertificatesClient)) Get(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), certificateName [string](/builtin#string), options *[CertificatesClientGetOptions](#CertificatesClientGetOptions)) ([CertificatesClientGetResponse](#CertificatesClientGetResponse), [error](/builtin#error)) ``` Get - Get a certificate of given Nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * certificateName - The name of certificate * options - CertificatesClientGetOptions contains the optional parameters for the CertificatesClient.Get method. Example [¶](#example-CertificatesClient.Get) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Certificates_Get.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewCertificatesClient().Get(ctx, "myResourceGroup", "myDeployment", "default", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Certificate = armnginx.Certificate{ // Name: to.Ptr("default"), // Type: to.Ptr("nginx.nginxplus/nginxdeployments/certificates"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/NGINX.NGINXPLUS/nginxDeployments/myDeployment/certificates/default"), // Properties: &armnginx.CertificateProperties{ // CertificateVirtualPath: to.Ptr("/src/cert/somePath.cert"), // KeyVaultSecretID: to.Ptr("https://someKV.vault.azure.com/someSecretID"), // KeyVirtualPath: to.Ptr("/src/cert/somekey.key"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // } ``` ``` Output: ``` #### func (*CertificatesClient) [NewListPager](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/certificates_client.go#L260) [¶](#CertificatesClient.NewListPager) ``` func (client *[CertificatesClient](#CertificatesClient)) NewListPager(resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), options *[CertificatesClientListOptions](#CertificatesClientListOptions)) *[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Pager](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Pager)[[CertificatesClientListResponse](#CertificatesClientListResponse)] ``` NewListPager - List all certificates of given Nginx deployment Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * options - CertificatesClientListOptions contains the optional parameters for the CertificatesClient.NewListPager method. Example [¶](#example-CertificatesClient.NewListPager) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Certificates_List.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := clientFactory.NewCertificatesClient().NewListPager("myResourceGroup", "myDeployment", nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range page.Value { // You could use page here. We use blank identifier for just demo purposes. _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // page.CertificateListResponse = armnginx.CertificateListResponse{ // Value: []*armnginx.Certificate{ // { // Name: to.Ptr("cert1"), // Type: to.Ptr("nginx.nginxplus/nginxdeployments/certificates"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/NGINX.NGINXPLUS/nginxDeployments/myDeployment/certificates/cert1"), // Properties: &armnginx.CertificateProperties{ // CertificateVirtualPath: to.Ptr("/src/cert/somePath.cert"), // KeyVaultSecretID: to.Ptr("https://someKV.vault.azure.com/someSecretID"), // KeyVirtualPath: to.Ptr("/src/cert/somekey.key"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // }, // { // Name: to.Ptr("cert2"), // Type: to.Ptr("nginx.nginxplus/nginxdeployments/certificates"), // ID: to.Ptr("/subscritions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/NGINX.NGINXPLUS/nginxDeployments/myDeployment/certificates/cert2"), // Properties: &armnginx.CertificateProperties{ // CertificateVirtualPath: to.Ptr("/src/cert/somePath2.cert"), // KeyVaultSecretID: to.Ptr("https://someKV.vault.azure.com/someSecretID2"), // KeyVirtualPath: to.Ptr("/src/cert/somekey2.key"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // }}, // } } ``` ``` Output: ``` #### type [CertificatesClientBeginCreateOrUpdateOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L50) [¶](#CertificatesClientBeginCreateOrUpdateOptions) ``` type CertificatesClientBeginCreateOrUpdateOptions struct { // The certificate Body *[Certificate](#Certificate) // Resumes the LRO from the provided token. ResumeToken [string](/builtin#string) } ``` CertificatesClientBeginCreateOrUpdateOptions contains the optional parameters for the CertificatesClient.BeginCreateOrUpdate method. #### type [CertificatesClientBeginDeleteOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L58) [¶](#CertificatesClientBeginDeleteOptions) ``` type CertificatesClientBeginDeleteOptions struct { // Resumes the LRO from the provided token. ResumeToken [string](/builtin#string) } ``` CertificatesClientBeginDeleteOptions contains the optional parameters for the CertificatesClient.BeginDelete method. #### type [CertificatesClientCreateOrUpdateResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L13) [¶](#CertificatesClientCreateOrUpdateResponse) ``` type CertificatesClientCreateOrUpdateResponse struct { [Certificate](#Certificate) } ``` CertificatesClientCreateOrUpdateResponse contains the response from method CertificatesClient.BeginCreateOrUpdate. #### type [CertificatesClientDeleteResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L18) [¶](#CertificatesClientDeleteResponse) ``` type CertificatesClientDeleteResponse struct { } ``` CertificatesClientDeleteResponse contains the response from method CertificatesClient.BeginDelete. #### type [CertificatesClientGetOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L64) [¶](#CertificatesClientGetOptions) ``` type CertificatesClientGetOptions struct { } ``` CertificatesClientGetOptions contains the optional parameters for the CertificatesClient.Get method. #### type [CertificatesClientGetResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L23) [¶](#CertificatesClientGetResponse) ``` type CertificatesClientGetResponse struct { [Certificate](#Certificate) } ``` CertificatesClientGetResponse contains the response from method CertificatesClient.Get. #### type [CertificatesClientListOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L69) [¶](#CertificatesClientListOptions) ``` type CertificatesClientListOptions struct { } ``` CertificatesClientListOptions contains the optional parameters for the CertificatesClient.NewListPager method. #### type [CertificatesClientListResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L28) [¶](#CertificatesClientListResponse) ``` type CertificatesClientListResponse struct { [CertificateListResponse](#CertificateListResponse) } ``` CertificatesClientListResponse contains the response from method CertificatesClient.NewListPager. #### type [ClientFactory](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/client_factory.go#L19) [¶](#ClientFactory) added in v2.1.0 ``` type ClientFactory struct { // contains filtered or unexported fields } ``` ClientFactory is a client factory used to create any client in this module. Don't use this type directly, use NewClientFactory instead. #### func [NewClientFactory](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/client_factory.go#L30) [¶](#NewClientFactory) added in v2.1.0 ``` func NewClientFactory(subscriptionID [string](/builtin#string), credential [azcore](/github.com/Azure/azure-sdk-for-go/sdk/azcore).[TokenCredential](/github.com/Azure/azure-sdk-for-go/sdk/azcore#TokenCredential), options *[arm](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm).[ClientOptions](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm#ClientOptions)) (*[ClientFactory](#ClientFactory), [error](/builtin#error)) ``` NewClientFactory creates a new instance of ClientFactory with the specified values. The parameter values will be propagated to any client created from this factory. * subscriptionID - The ID of the target subscription. * credential - used to authorize requests. Usually a credential from azidentity. * options - pass nil to accept the default values. #### func (*ClientFactory) [NewCertificatesClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/client_factory.go#L41) [¶](#ClientFactory.NewCertificatesClient) added in v2.1.0 ``` func (c *[ClientFactory](#ClientFactory)) NewCertificatesClient() *[CertificatesClient](#CertificatesClient) ``` #### func (*ClientFactory) [NewConfigurationsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/client_factory.go#L46) [¶](#ClientFactory.NewConfigurationsClient) added in v2.1.0 ``` func (c *[ClientFactory](#ClientFactory)) NewConfigurationsClient() *[ConfigurationsClient](#ConfigurationsClient) ``` #### func (*ClientFactory) [NewDeploymentsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/client_factory.go#L51) [¶](#ClientFactory.NewDeploymentsClient) added in v2.1.0 ``` func (c *[ClientFactory](#ClientFactory)) NewDeploymentsClient() *[DeploymentsClient](#DeploymentsClient) ``` #### func (*ClientFactory) [NewOperationsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/client_factory.go#L56) [¶](#ClientFactory.NewOperationsClient) added in v2.1.0 ``` func (c *[ClientFactory](#ClientFactory)) NewOperationsClient() *[OperationsClient](#OperationsClient) ``` #### type [Configuration](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L73) [¶](#Configuration) ``` type Configuration struct { Location *[string](/builtin#string) `json:"location,omitempty"` Properties *[ConfigurationProperties](#ConfigurationProperties) `json:"properties,omitempty"` // Dictionary of Tags map[[string](/builtin#string)]*[string](/builtin#string) `json:"tags,omitempty"` // READ-ONLY ID *[string](/builtin#string) `json:"id,omitempty" azure:"ro"` // READ-ONLY Name *[string](/builtin#string) `json:"name,omitempty" azure:"ro"` // READ-ONLY; Metadata pertaining to creation and last modification of the resource. SystemData *[SystemData](#SystemData) `json:"systemData,omitempty" azure:"ro"` // READ-ONLY Type *[string](/builtin#string) `json:"type,omitempty" azure:"ro"` } ``` #### func (Configuration) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L141) [¶](#Configuration.MarshalJSON) ``` func (c [Configuration](#Configuration)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type Configuration. #### func (*Configuration) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L154) [¶](#Configuration.UnmarshalJSON) ``` func (c *[Configuration](#Configuration)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type Configuration. #### type [ConfigurationFile](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L93) [¶](#ConfigurationFile) ``` type ConfigurationFile struct { Content *[string](/builtin#string) `json:"content,omitempty"` VirtualPath *[string](/builtin#string) `json:"virtualPath,omitempty"` } ``` #### func (ConfigurationFile) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L192) [¶](#ConfigurationFile.MarshalJSON) ``` func (c [ConfigurationFile](#ConfigurationFile)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type ConfigurationFile. #### func (*ConfigurationFile) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L200) [¶](#ConfigurationFile.UnmarshalJSON) ``` func (c *[ConfigurationFile](#ConfigurationFile)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationFile. #### type [ConfigurationListResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L99) [¶](#ConfigurationListResponse) ``` type ConfigurationListResponse struct { // Link to the next set of results, if any. NextLink *[string](/builtin#string) `json:"nextLink,omitempty"` // Results of a list operation. Value []*[Configuration](#Configuration) `json:"value,omitempty"` } ``` ConfigurationListResponse - Response of a list operation. #### func (ConfigurationListResponse) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L223) [¶](#ConfigurationListResponse.MarshalJSON) ``` func (c [ConfigurationListResponse](#ConfigurationListResponse)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type ConfigurationListResponse. #### func (*ConfigurationListResponse) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L231) [¶](#ConfigurationListResponse.UnmarshalJSON) ``` func (c *[ConfigurationListResponse](#ConfigurationListResponse)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationListResponse. #### type [ConfigurationPackage](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L107) [¶](#ConfigurationPackage) ``` type ConfigurationPackage struct { Data *[string](/builtin#string) `json:"data,omitempty"` } ``` #### func (ConfigurationPackage) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L254) [¶](#ConfigurationPackage.MarshalJSON) ``` func (c [ConfigurationPackage](#ConfigurationPackage)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type ConfigurationPackage. #### func (*ConfigurationPackage) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L261) [¶](#ConfigurationPackage.UnmarshalJSON) ``` func (c *[ConfigurationPackage](#ConfigurationPackage)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationPackage. #### type [ConfigurationProperties](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L111) [¶](#ConfigurationProperties) ``` type ConfigurationProperties struct { Files []*[ConfigurationFile](#ConfigurationFile) `json:"files,omitempty"` Package *[ConfigurationPackage](#ConfigurationPackage) `json:"package,omitempty"` ProtectedFiles []*[ConfigurationFile](#ConfigurationFile) `json:"protectedFiles,omitempty"` RootFile *[string](/builtin#string) `json:"rootFile,omitempty"` // READ-ONLY ProvisioningState *[ProvisioningState](#ProvisioningState) `json:"provisioningState,omitempty" azure:"ro"` } ``` #### func (ConfigurationProperties) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L281) [¶](#ConfigurationProperties.MarshalJSON) ``` func (c [ConfigurationProperties](#ConfigurationProperties)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type ConfigurationProperties. #### func (*ConfigurationProperties) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L292) [¶](#ConfigurationProperties.UnmarshalJSON) ``` func (c *[ConfigurationProperties](#ConfigurationProperties)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationProperties. #### type [ConfigurationsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/configurations_client.go#L26) [¶](#ConfigurationsClient) ``` type ConfigurationsClient struct { // contains filtered or unexported fields } ``` ConfigurationsClient contains the methods for the Configurations group. Don't use this type directly, use NewConfigurationsClient() instead. #### func [NewConfigurationsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/configurations_client.go#L35) [¶](#NewConfigurationsClient) ``` func NewConfigurationsClient(subscriptionID [string](/builtin#string), credential [azcore](/github.com/Azure/azure-sdk-for-go/sdk/azcore).[TokenCredential](/github.com/Azure/azure-sdk-for-go/sdk/azcore#TokenCredential), options *[arm](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm).[ClientOptions](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm#ClientOptions)) (*[ConfigurationsClient](#ConfigurationsClient), [error](/builtin#error)) ``` NewConfigurationsClient creates a new instance of ConfigurationsClient with the specified values. * subscriptionID - The ID of the target subscription. * credential - used to authorize requests. Usually a credential from azidentity. * options - pass nil to accept the default values. #### func (*ConfigurationsClient) [BeginCreateOrUpdate](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/configurations_client.go#L56) [¶](#ConfigurationsClient.BeginCreateOrUpdate) ``` func (client *[ConfigurationsClient](#ConfigurationsClient)) BeginCreateOrUpdate(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), configurationName [string](/builtin#string), options *[ConfigurationsClientBeginCreateOrUpdateOptions](#ConfigurationsClientBeginCreateOrUpdateOptions)) (*[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Poller](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Poller)[[ConfigurationsClientCreateOrUpdateResponse](#ConfigurationsClientCreateOrUpdateResponse)], [error](/builtin#error)) ``` BeginCreateOrUpdate - Create or update the Nginx configuration for given Nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * configurationName - The name of configuration, only 'default' is supported value due to the singleton of Nginx conf * options - ConfigurationsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConfigurationsClient.BeginCreateOrUpdate method. Example [¶](#example-ConfigurationsClient.BeginCreateOrUpdate) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Configurations_CreateOrUpdate.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewConfigurationsClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myDeployment", "default", &armnginx.ConfigurationsClientBeginCreateOrUpdateOptions{Body: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } res, err := poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Configuration = armnginx.Configuration{ // Name: to.Ptr("default"), // Type: to.Ptr("nginx.nginxplus/nginxDeployments/configurations"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment/configurations/default"), // Properties: &armnginx.ConfigurationProperties{ // Files: []*armnginx.ConfigurationFile{ // { // Content: to.Ptr("ABCDEF=="), // VirtualPath: to.Ptr("/etc/nginx/nginx.conf"), // }}, // Package: &armnginx.ConfigurationPackage{ // }, // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // RootFile: to.Ptr("/etc/nginx/nginx.conf"), // }, // } ``` ``` Output: ``` #### func (*ConfigurationsClient) [BeginDelete](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/configurations_client.go#L131) [¶](#ConfigurationsClient.BeginDelete) ``` func (client *[ConfigurationsClient](#ConfigurationsClient)) BeginDelete(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), configurationName [string](/builtin#string), options *[ConfigurationsClientBeginDeleteOptions](#ConfigurationsClientBeginDeleteOptions)) (*[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Poller](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Poller)[[ConfigurationsClientDeleteResponse](#ConfigurationsClientDeleteResponse)], [error](/builtin#error)) ``` BeginDelete - Reset the Nginx configuration of given Nginx deployment to default If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * configurationName - The name of configuration, only 'default' is supported value due to the singleton of Nginx conf * options - ConfigurationsClientBeginDeleteOptions contains the optional parameters for the ConfigurationsClient.BeginDelete method. Example [¶](#example-ConfigurationsClient.BeginDelete) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Configurations_Delete.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewConfigurationsClient().BeginDelete(ctx, "myResourceGroup", "myDeployment", "default", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } ``` ``` Output: ``` #### func (*ConfigurationsClient) [Get](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/configurations_client.go#L200) [¶](#ConfigurationsClient.Get) ``` func (client *[ConfigurationsClient](#ConfigurationsClient)) Get(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), configurationName [string](/builtin#string), options *[ConfigurationsClientGetOptions](#ConfigurationsClientGetOptions)) ([ConfigurationsClientGetResponse](#ConfigurationsClientGetResponse), [error](/builtin#error)) ``` Get - Get the Nginx configuration of given Nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * configurationName - The name of configuration, only 'default' is supported value due to the singleton of Nginx conf * options - ConfigurationsClientGetOptions contains the optional parameters for the ConfigurationsClient.Get method. Example [¶](#example-ConfigurationsClient.Get) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Configurations_Get.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewConfigurationsClient().Get(ctx, "myResourceGroup", "myDeployment", "default", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Configuration = armnginx.Configuration{ // Name: to.Ptr("default"), // Type: to.Ptr("nginx.nginxplus/nginxDeployments/configurations"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment/configurations/default"), // Properties: &armnginx.ConfigurationProperties{ // Files: []*armnginx.ConfigurationFile{ // { // Content: to.Ptr("ABCDEF=="), // VirtualPath: to.Ptr("/etc/nginx/nginx.conf"), // }}, // Package: &armnginx.ConfigurationPackage{ // }, // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // RootFile: to.Ptr("/etc/nginx/nginx.conf"), // }, // } ``` ``` Output: ``` #### func (*ConfigurationsClient) [NewListPager](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/configurations_client.go#L260) [¶](#ConfigurationsClient.NewListPager) ``` func (client *[ConfigurationsClient](#ConfigurationsClient)) NewListPager(resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), options *[ConfigurationsClientListOptions](#ConfigurationsClientListOptions)) *[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Pager](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Pager)[[ConfigurationsClientListResponse](#ConfigurationsClientListResponse)] ``` NewListPager - List the Nginx configuration of given Nginx deployment. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * options - ConfigurationsClientListOptions contains the optional parameters for the ConfigurationsClient.NewListPager method. Example [¶](#example-ConfigurationsClient.NewListPager) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Configurations_List.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := clientFactory.NewConfigurationsClient().NewListPager("myResourceGroup", "myDeployment", nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range page.Value { // You could use page here. We use blank identifier for just demo purposes. _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // page.ConfigurationListResponse = armnginx.ConfigurationListResponse{ // Value: []*armnginx.Configuration{ // { // Name: to.Ptr("default"), // Type: to.Ptr("nginx.nginxplus/nginxDeployments/configurations"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment/configurations/default"), // Properties: &armnginx.ConfigurationProperties{ // Files: []*armnginx.ConfigurationFile{ // { // Content: to.Ptr("ABCDEF=="), // VirtualPath: to.Ptr("/etc/nginx/nginx.conf"), // }}, // Package: &armnginx.ConfigurationPackage{ // }, // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // RootFile: to.Ptr("/etc/nginx/nginx.conf"), // }, // }}, // } } ``` ``` Output: ``` #### type [ConfigurationsClientBeginCreateOrUpdateOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L123) [¶](#ConfigurationsClientBeginCreateOrUpdateOptions) ``` type ConfigurationsClientBeginCreateOrUpdateOptions struct { // The Nginx configuration Body *[Configuration](#Configuration) // Resumes the LRO from the provided token. ResumeToken [string](/builtin#string) } ``` ConfigurationsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConfigurationsClient.BeginCreateOrUpdate method. #### type [ConfigurationsClientBeginDeleteOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L131) [¶](#ConfigurationsClientBeginDeleteOptions) ``` type ConfigurationsClientBeginDeleteOptions struct { // Resumes the LRO from the provided token. ResumeToken [string](/builtin#string) } ``` ConfigurationsClientBeginDeleteOptions contains the optional parameters for the ConfigurationsClient.BeginDelete method. #### type [ConfigurationsClientCreateOrUpdateResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L33) [¶](#ConfigurationsClientCreateOrUpdateResponse) ``` type ConfigurationsClientCreateOrUpdateResponse struct { [Configuration](#Configuration) } ``` ConfigurationsClientCreateOrUpdateResponse contains the response from method ConfigurationsClient.BeginCreateOrUpdate. #### type [ConfigurationsClientDeleteResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L38) [¶](#ConfigurationsClientDeleteResponse) ``` type ConfigurationsClientDeleteResponse struct { } ``` ConfigurationsClientDeleteResponse contains the response from method ConfigurationsClient.BeginDelete. #### type [ConfigurationsClientGetOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L137) [¶](#ConfigurationsClientGetOptions) ``` type ConfigurationsClientGetOptions struct { } ``` ConfigurationsClientGetOptions contains the optional parameters for the ConfigurationsClient.Get method. #### type [ConfigurationsClientGetResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L43) [¶](#ConfigurationsClientGetResponse) ``` type ConfigurationsClientGetResponse struct { [Configuration](#Configuration) } ``` ConfigurationsClientGetResponse contains the response from method ConfigurationsClient.Get. #### type [ConfigurationsClientListOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L142) [¶](#ConfigurationsClientListOptions) ``` type ConfigurationsClientListOptions struct { } ``` ConfigurationsClientListOptions contains the optional parameters for the ConfigurationsClient.NewListPager method. #### type [ConfigurationsClientListResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L48) [¶](#ConfigurationsClientListResponse) ``` type ConfigurationsClientListResponse struct { [ConfigurationListResponse](#ConfigurationListResponse) } ``` ConfigurationsClientListResponse contains the response from method ConfigurationsClient.NewListPager. #### type [CreatedByType](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L18) [¶](#CreatedByType) ``` type CreatedByType [string](/builtin#string) ``` CreatedByType - The type of identity that created the resource. ``` const ( CreatedByTypeApplication [CreatedByType](#CreatedByType) = "Application" CreatedByTypeKey [CreatedByType](#CreatedByType) = "Key" CreatedByTypeManagedIdentity [CreatedByType](#CreatedByType) = "ManagedIdentity" CreatedByTypeUser [CreatedByType](#CreatedByType) = "User" ) ``` #### func [PossibleCreatedByTypeValues](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L28) [¶](#PossibleCreatedByTypeValues) ``` func PossibleCreatedByTypeValues() [][CreatedByType](#CreatedByType) ``` PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. #### type [Deployment](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L146) [¶](#Deployment) ``` type Deployment struct { Identity *[IdentityProperties](#IdentityProperties) `json:"identity,omitempty"` Location *[string](/builtin#string) `json:"location,omitempty"` Properties *[DeploymentProperties](#DeploymentProperties) `json:"properties,omitempty"` SKU *[ResourceSKU](#ResourceSKU) `json:"sku,omitempty"` // Dictionary of Tags map[[string](/builtin#string)]*[string](/builtin#string) `json:"tags,omitempty"` // READ-ONLY ID *[string](/builtin#string) `json:"id,omitempty" azure:"ro"` // READ-ONLY Name *[string](/builtin#string) `json:"name,omitempty" azure:"ro"` // READ-ONLY; Metadata pertaining to creation and last modification of the resource. SystemData *[SystemData](#SystemData) `json:"systemData,omitempty" azure:"ro"` // READ-ONLY Type *[string](/builtin#string) `json:"type,omitempty" azure:"ro"` } ``` #### func (Deployment) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L324) [¶](#Deployment.MarshalJSON) ``` func (d [Deployment](#Deployment)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type Deployment. #### func (*Deployment) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L339) [¶](#Deployment.UnmarshalJSON) ``` func (d *[Deployment](#Deployment)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type Deployment. #### type [DeploymentListResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L168) [¶](#DeploymentListResponse) ``` type DeploymentListResponse struct { NextLink *[string](/builtin#string) `json:"nextLink,omitempty"` Value []*[Deployment](#Deployment) `json:"value,omitempty"` } ``` #### func (DeploymentListResponse) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L383) [¶](#DeploymentListResponse.MarshalJSON) ``` func (d [DeploymentListResponse](#DeploymentListResponse)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type DeploymentListResponse. #### func (*DeploymentListResponse) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L391) [¶](#DeploymentListResponse.UnmarshalJSON) ``` func (d *[DeploymentListResponse](#DeploymentListResponse)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentListResponse. #### type [DeploymentProperties](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L173) [¶](#DeploymentProperties) ``` type DeploymentProperties struct { EnableDiagnosticsSupport *[bool](/builtin#bool) `json:"enableDiagnosticsSupport,omitempty"` Logging *[Logging](#Logging) `json:"logging,omitempty"` // The managed resource group to deploy VNet injection related network resources. ManagedResourceGroup *[string](/builtin#string) `json:"managedResourceGroup,omitempty"` NetworkProfile *[NetworkProfile](#NetworkProfile) `json:"networkProfile,omitempty"` // READ-ONLY; The IP address of the deployment. IPAddress *[string](/builtin#string) `json:"ipAddress,omitempty" azure:"ro"` // READ-ONLY NginxVersion *[string](/builtin#string) `json:"nginxVersion,omitempty" azure:"ro"` // READ-ONLY ProvisioningState *[ProvisioningState](#ProvisioningState) `json:"provisioningState,omitempty" azure:"ro"` } ``` #### func (DeploymentProperties) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L414) [¶](#DeploymentProperties.MarshalJSON) ``` func (d [DeploymentProperties](#DeploymentProperties)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type DeploymentProperties. #### func (*DeploymentProperties) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L427) [¶](#DeploymentProperties.UnmarshalJSON) ``` func (d *[DeploymentProperties](#DeploymentProperties)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentProperties. #### type [DeploymentUpdateParameters](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L191) [¶](#DeploymentUpdateParameters) ``` type DeploymentUpdateParameters struct { Identity *[IdentityProperties](#IdentityProperties) `json:"identity,omitempty"` Location *[string](/builtin#string) `json:"location,omitempty"` Properties *[DeploymentUpdateProperties](#DeploymentUpdateProperties) `json:"properties,omitempty"` SKU *[ResourceSKU](#ResourceSKU) `json:"sku,omitempty"` // Dictionary of Tags map[[string](/builtin#string)]*[string](/builtin#string) `json:"tags,omitempty"` } ``` #### func (DeploymentUpdateParameters) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L465) [¶](#DeploymentUpdateParameters.MarshalJSON) ``` func (d [DeploymentUpdateParameters](#DeploymentUpdateParameters)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type DeploymentUpdateParameters. #### func (*DeploymentUpdateParameters) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L476) [¶](#DeploymentUpdateParameters.UnmarshalJSON) ``` func (d *[DeploymentUpdateParameters](#DeploymentUpdateParameters)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentUpdateParameters. #### type [DeploymentUpdateProperties](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L201) [¶](#DeploymentUpdateProperties) ``` type DeploymentUpdateProperties struct { EnableDiagnosticsSupport *[bool](/builtin#bool) `json:"enableDiagnosticsSupport,omitempty"` Logging *[Logging](#Logging) `json:"logging,omitempty"` } ``` #### func (DeploymentUpdateProperties) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L508) [¶](#DeploymentUpdateProperties.MarshalJSON) ``` func (d [DeploymentUpdateProperties](#DeploymentUpdateProperties)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type DeploymentUpdateProperties. #### func (*DeploymentUpdateProperties) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L516) [¶](#DeploymentUpdateProperties.UnmarshalJSON) ``` func (d *[DeploymentUpdateProperties](#DeploymentUpdateProperties)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentUpdateProperties. #### type [DeploymentsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L26) [¶](#DeploymentsClient) ``` type DeploymentsClient struct { // contains filtered or unexported fields } ``` DeploymentsClient contains the methods for the Deployments group. Don't use this type directly, use NewDeploymentsClient() instead. #### func [NewDeploymentsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L35) [¶](#NewDeploymentsClient) ``` func NewDeploymentsClient(subscriptionID [string](/builtin#string), credential [azcore](/github.com/Azure/azure-sdk-for-go/sdk/azcore).[TokenCredential](/github.com/Azure/azure-sdk-for-go/sdk/azcore#TokenCredential), options *[arm](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm).[ClientOptions](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm#ClientOptions)) (*[DeploymentsClient](#DeploymentsClient), [error](/builtin#error)) ``` NewDeploymentsClient creates a new instance of DeploymentsClient with the specified values. * subscriptionID - The ID of the target subscription. * credential - used to authorize requests. Usually a credential from azidentity. * options - pass nil to accept the default values. #### func (*DeploymentsClient) [BeginCreateOrUpdate](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L55) [¶](#DeploymentsClient.BeginCreateOrUpdate) ``` func (client *[DeploymentsClient](#DeploymentsClient)) BeginCreateOrUpdate(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), options *[DeploymentsClientBeginCreateOrUpdateOptions](#DeploymentsClientBeginCreateOrUpdateOptions)) (*[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Poller](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Poller)[[DeploymentsClientCreateOrUpdateResponse](#DeploymentsClientCreateOrUpdateResponse)], [error](/builtin#error)) ``` BeginCreateOrUpdate - Create or update the Nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * options - DeploymentsClientBeginCreateOrUpdateOptions contains the optional parameters for the DeploymentsClient.BeginCreateOrUpdate method. Example [¶](#example-DeploymentsClient.BeginCreateOrUpdate) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Deployments_Create.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewDeploymentsClient().BeginCreateOrUpdate(ctx, "myResourceGroup", "myDeployment", &armnginx.DeploymentsClientBeginCreateOrUpdateOptions{Body: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } res, err := poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Deployment = armnginx.Deployment{ // Name: to.Ptr("myDeployment"), // Type: to.Ptr("nginx.nginxplus/deployments"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment"), // Location: to.Ptr("westus"), // Properties: &armnginx.DeploymentProperties{ // IPAddress: to.Ptr("1.1.1.1"), // ManagedResourceGroup: to.Ptr("myManagedResourceGroup"), // NetworkProfile: &armnginx.NetworkProfile{ // FrontEndIPConfiguration: &armnginx.FrontendIPConfiguration{ // PrivateIPAddresses: []*armnginx.PrivateIPAddress{ // { // PrivateIPAddress: to.Ptr("1.1.1.1"), // PrivateIPAllocationMethod: to.Ptr(armnginx.NginxPrivateIPAllocationMethodStatic), // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }}, // PublicIPAddresses: []*armnginx.PublicIPAddress{ // { // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/myPublicIPAddress"), // }}, // }, // NetworkInterfaceConfiguration: &armnginx.NetworkInterfaceConfiguration{ // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }, // }, // NginxVersion: to.Ptr("nginx-1.19.6"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // Tags: map[string]*string{ // "Environment": to.Ptr("Dev"), // }, // } ``` ``` Output: ``` #### func (*DeploymentsClient) [BeginDelete](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L124) [¶](#DeploymentsClient.BeginDelete) ``` func (client *[DeploymentsClient](#DeploymentsClient)) BeginDelete(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), options *[DeploymentsClientBeginDeleteOptions](#DeploymentsClientBeginDeleteOptions)) (*[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Poller](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Poller)[[DeploymentsClientDeleteResponse](#DeploymentsClientDeleteResponse)], [error](/builtin#error)) ``` BeginDelete - Delete the Nginx deployment resource If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * options - DeploymentsClientBeginDeleteOptions contains the optional parameters for the DeploymentsClient.BeginDelete method. Example [¶](#example-DeploymentsClient.BeginDelete) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Deployments_Delete.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewDeploymentsClient().BeginDelete(ctx, "myResourceGroup", "myDeployment", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } _, err = poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } ``` ``` Output: ``` #### func (*DeploymentsClient) [BeginUpdate](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L369) [¶](#DeploymentsClient.BeginUpdate) ``` func (client *[DeploymentsClient](#DeploymentsClient)) BeginUpdate(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), options *[DeploymentsClientBeginUpdateOptions](#DeploymentsClientBeginUpdateOptions)) (*[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Poller](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Poller)[[DeploymentsClientUpdateResponse](#DeploymentsClientUpdateResponse)], [error](/builtin#error)) ``` BeginUpdate - Update the Nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * options - DeploymentsClientBeginUpdateOptions contains the optional parameters for the DeploymentsClient.BeginUpdate method. Example [¶](#example-DeploymentsClient.BeginUpdate) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Deployments_Update.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } poller, err := clientFactory.NewDeploymentsClient().BeginUpdate(ctx, "myResourceGroup", "myDeployment", &armnginx.DeploymentsClientBeginUpdateOptions{Body: nil}) if err != nil { log.Fatalf("failed to finish the request: %v", err) } res, err := poller.PollUntilDone(ctx, nil) if err != nil { log.Fatalf("failed to pull the result: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Deployment = armnginx.Deployment{ // Name: to.Ptr("myDeployment"), // Type: to.Ptr("nginx.nginxplus/deployments"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment"), // Location: to.Ptr("westus"), // Properties: &armnginx.DeploymentProperties{ // IPAddress: to.Ptr("1.1.1.1"), // ManagedResourceGroup: to.Ptr("myManagedResourceGroup"), // NetworkProfile: &armnginx.NetworkProfile{ // FrontEndIPConfiguration: &armnginx.FrontendIPConfiguration{ // PrivateIPAddresses: []*armnginx.PrivateIPAddress{ // { // PrivateIPAddress: to.Ptr("1.1.1.1"), // PrivateIPAllocationMethod: to.Ptr(armnginx.NginxPrivateIPAllocationMethodStatic), // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }}, // PublicIPAddresses: []*armnginx.PublicIPAddress{ // { // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/myPublicIPAddress"), // }}, // }, // NetworkInterfaceConfiguration: &armnginx.NetworkInterfaceConfiguration{ // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }, // }, // NginxVersion: to.Ptr("nginx-1.19.6"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // Tags: map[string]*string{ // "Environment": to.Ptr("Dev"), // }, // } ``` ``` Output: ``` #### func (*DeploymentsClient) [Get](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L188) [¶](#DeploymentsClient.Get) ``` func (client *[DeploymentsClient](#DeploymentsClient)) Get(ctx [context](/context).[Context](/context#Context), resourceGroupName [string](/builtin#string), deploymentName [string](/builtin#string), options *[DeploymentsClientGetOptions](#DeploymentsClientGetOptions)) ([DeploymentsClientGetResponse](#DeploymentsClientGetResponse), [error](/builtin#error)) ``` Get - Get the Nginx deployment If the operation fails it returns an *azcore.ResponseError type. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * deploymentName - The name of targeted Nginx deployment * options - DeploymentsClientGetOptions contains the optional parameters for the DeploymentsClient.Get method. Example [¶](#example-DeploymentsClient.Get) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Deployments_Get.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewDeploymentsClient().Get(ctx, "myResourceGroup", "myDeployment", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.Deployment = armnginx.Deployment{ // Name: to.Ptr("myDeployment"), // Type: to.Ptr("nginx.nginxplus/deployments"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment"), // Location: to.Ptr("westus"), // Properties: &armnginx.DeploymentProperties{ // ManagedResourceGroup: to.Ptr("myManagedResourceGroup"), // NetworkProfile: &armnginx.NetworkProfile{ // FrontEndIPConfiguration: &armnginx.FrontendIPConfiguration{ // PrivateIPAddresses: []*armnginx.PrivateIPAddress{ // { // PrivateIPAddress: to.Ptr("1.1.1.1"), // PrivateIPAllocationMethod: to.Ptr(armnginx.NginxPrivateIPAllocationMethodStatic), // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }}, // PublicIPAddresses: []*armnginx.PublicIPAddress{ // { // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/myPublicIPAddress"), // }}, // }, // NetworkInterfaceConfiguration: &armnginx.NetworkInterfaceConfiguration{ // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }, // }, // NginxVersion: to.Ptr("nginx-1.19.6"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // } ``` ``` Output: ``` #### func (*DeploymentsClient) [NewListByResourceGroupPager](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L303) [¶](#DeploymentsClient.NewListByResourceGroupPager) ``` func (client *[DeploymentsClient](#DeploymentsClient)) NewListByResourceGroupPager(resourceGroupName [string](/builtin#string), options *[DeploymentsClientListByResourceGroupOptions](#DeploymentsClientListByResourceGroupOptions)) *[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Pager](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Pager)[[DeploymentsClientListByResourceGroupResponse](#DeploymentsClientListByResourceGroupResponse)] ``` NewListByResourceGroupPager - List all Nginx deployments under the specified resource group. Generated from API version 2022-08-01 * resourceGroupName - The name of the resource group. The name is case insensitive. * options - DeploymentsClientListByResourceGroupOptions contains the optional parameters for the DeploymentsClient.NewListByResourceGroupPager method. Example [¶](#example-DeploymentsClient.NewListByResourceGroupPager) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Deployments_ListByResourceGroup.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := clientFactory.NewDeploymentsClient().NewListByResourceGroupPager("myResourceGroup", nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range page.Value { // You could use page here. We use blank identifier for just demo purposes. _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // page.DeploymentListResponse = armnginx.DeploymentListResponse{ // Value: []*armnginx.Deployment{ // { // Name: to.Ptr("myDeployment"), // Type: to.Ptr("nginx.nginxplus/deployments"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment"), // Location: to.Ptr("westus"), // Properties: &armnginx.DeploymentProperties{ // IPAddress: to.Ptr("1.1.1.1"), // ManagedResourceGroup: to.Ptr("myManagedResourceGroup"), // NetworkProfile: &armnginx.NetworkProfile{ // FrontEndIPConfiguration: &armnginx.FrontendIPConfiguration{ // PrivateIPAddresses: []*armnginx.PrivateIPAddress{ // { // PrivateIPAddress: to.Ptr("1.1.1.1"), // PrivateIPAllocationMethod: to.Ptr(armnginx.NginxPrivateIPAllocationMethodStatic), // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }}, // PublicIPAddresses: []*armnginx.PublicIPAddress{ // { // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/myPublicIPAddress"), // }}, // }, // NetworkInterfaceConfiguration: &armnginx.NetworkInterfaceConfiguration{ // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }, // }, // NginxVersion: to.Ptr("nginx-1.19.6"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // }}, // } } ``` ``` Output: ``` #### func (*DeploymentsClient) [NewListPager](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/deployments_client.go#L242) [¶](#DeploymentsClient.NewListPager) ``` func (client *[DeploymentsClient](#DeploymentsClient)) NewListPager(options *[DeploymentsClientListOptions](#DeploymentsClientListOptions)) *[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Pager](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Pager)[[DeploymentsClientListResponse](#DeploymentsClientListResponse)] ``` NewListPager - List the Nginx deployments resources Generated from API version 2022-08-01 * options - DeploymentsClientListOptions contains the optional parameters for the DeploymentsClient.NewListPager method. Example [¶](#example-DeploymentsClient.NewListPager) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Deployments_List.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := clientFactory.NewDeploymentsClient().NewListPager(nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range page.Value { // You could use page here. We use blank identifier for just demo purposes. _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // page.DeploymentListResponse = armnginx.DeploymentListResponse{ // Value: []*armnginx.Deployment{ // { // Name: to.Ptr("myDeployment"), // Type: to.Ptr("nginx.nginxplus/deployments"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Nginx.NginxPlus/nginxDeployments/myDeployment"), // Location: to.Ptr("westus"), // Properties: &armnginx.DeploymentProperties{ // IPAddress: to.Ptr("1.1.1.1"), // ManagedResourceGroup: to.Ptr("myManagedResourceGroup"), // NetworkProfile: &armnginx.NetworkProfile{ // FrontEndIPConfiguration: &armnginx.FrontendIPConfiguration{ // PrivateIPAddresses: []*armnginx.PrivateIPAddress{ // { // PrivateIPAddress: to.Ptr("1.1.1.1"), // PrivateIPAllocationMethod: to.Ptr(armnginx.NginxPrivateIPAllocationMethodStatic), // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }}, // PublicIPAddresses: []*armnginx.PublicIPAddress{ // { // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/myPublicIPAddress"), // }}, // }, // NetworkInterfaceConfiguration: &armnginx.NetworkInterfaceConfiguration{ // SubnetID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"), // }, // }, // NginxVersion: to.Ptr("nginx-1.19.6"), // ProvisioningState: to.Ptr(armnginx.ProvisioningStateSucceeded), // }, // }}, // } } ``` ``` Output: ``` #### type [DeploymentsClientBeginCreateOrUpdateOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L208) [¶](#DeploymentsClientBeginCreateOrUpdateOptions) ``` type DeploymentsClientBeginCreateOrUpdateOptions struct { Body *[Deployment](#Deployment) // Resumes the LRO from the provided token. ResumeToken [string](/builtin#string) } ``` DeploymentsClientBeginCreateOrUpdateOptions contains the optional parameters for the DeploymentsClient.BeginCreateOrUpdate method. #### type [DeploymentsClientBeginDeleteOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L215) [¶](#DeploymentsClientBeginDeleteOptions) ``` type DeploymentsClientBeginDeleteOptions struct { // Resumes the LRO from the provided token. ResumeToken [string](/builtin#string) } ``` DeploymentsClientBeginDeleteOptions contains the optional parameters for the DeploymentsClient.BeginDelete method. #### type [DeploymentsClientBeginUpdateOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L221) [¶](#DeploymentsClientBeginUpdateOptions) ``` type DeploymentsClientBeginUpdateOptions struct { Body *[DeploymentUpdateParameters](#DeploymentUpdateParameters) // Resumes the LRO from the provided token. ResumeToken [string](/builtin#string) } ``` DeploymentsClientBeginUpdateOptions contains the optional parameters for the DeploymentsClient.BeginUpdate method. #### type [DeploymentsClientCreateOrUpdateResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L53) [¶](#DeploymentsClientCreateOrUpdateResponse) ``` type DeploymentsClientCreateOrUpdateResponse struct { [Deployment](#Deployment) } ``` DeploymentsClientCreateOrUpdateResponse contains the response from method DeploymentsClient.BeginCreateOrUpdate. #### type [DeploymentsClientDeleteResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L58) [¶](#DeploymentsClientDeleteResponse) ``` type DeploymentsClientDeleteResponse struct { } ``` DeploymentsClientDeleteResponse contains the response from method DeploymentsClient.BeginDelete. #### type [DeploymentsClientGetOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L228) [¶](#DeploymentsClientGetOptions) ``` type DeploymentsClientGetOptions struct { } ``` DeploymentsClientGetOptions contains the optional parameters for the DeploymentsClient.Get method. #### type [DeploymentsClientGetResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L63) [¶](#DeploymentsClientGetResponse) ``` type DeploymentsClientGetResponse struct { [Deployment](#Deployment) } ``` DeploymentsClientGetResponse contains the response from method DeploymentsClient.Get. #### type [DeploymentsClientListByResourceGroupOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L234) [¶](#DeploymentsClientListByResourceGroupOptions) ``` type DeploymentsClientListByResourceGroupOptions struct { } ``` DeploymentsClientListByResourceGroupOptions contains the optional parameters for the DeploymentsClient.NewListByResourceGroupPager method. #### type [DeploymentsClientListByResourceGroupResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L68) [¶](#DeploymentsClientListByResourceGroupResponse) ``` type DeploymentsClientListByResourceGroupResponse struct { [DeploymentListResponse](#DeploymentListResponse) } ``` DeploymentsClientListByResourceGroupResponse contains the response from method DeploymentsClient.NewListByResourceGroupPager. #### type [DeploymentsClientListOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L239) [¶](#DeploymentsClientListOptions) ``` type DeploymentsClientListOptions struct { } ``` DeploymentsClientListOptions contains the optional parameters for the DeploymentsClient.NewListPager method. #### type [DeploymentsClientListResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L73) [¶](#DeploymentsClientListResponse) ``` type DeploymentsClientListResponse struct { [DeploymentListResponse](#DeploymentListResponse) } ``` DeploymentsClientListResponse contains the response from method DeploymentsClient.NewListPager. #### type [DeploymentsClientUpdateResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L78) [¶](#DeploymentsClientUpdateResponse) ``` type DeploymentsClientUpdateResponse struct { [Deployment](#Deployment) } ``` DeploymentsClientUpdateResponse contains the response from method DeploymentsClient.BeginUpdate. #### type [ErrorResponseBody](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L243) [¶](#ErrorResponseBody) ``` type ErrorResponseBody struct { Code *[string](/builtin#string) `json:"code,omitempty"` Details []*[ErrorResponseBody](#ErrorResponseBody) `json:"details,omitempty"` Message *[string](/builtin#string) `json:"message,omitempty"` Target *[string](/builtin#string) `json:"target,omitempty"` } ``` #### func (ErrorResponseBody) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L539) [¶](#ErrorResponseBody.MarshalJSON) ``` func (e [ErrorResponseBody](#ErrorResponseBody)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type ErrorResponseBody. #### func (*ErrorResponseBody) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L549) [¶](#ErrorResponseBody.UnmarshalJSON) ``` func (e *[ErrorResponseBody](#ErrorResponseBody)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type ErrorResponseBody. #### type [FrontendIPConfiguration](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L250) [¶](#FrontendIPConfiguration) ``` type FrontendIPConfiguration struct { PrivateIPAddresses []*[PrivateIPAddress](#PrivateIPAddress) `json:"privateIPAddresses,omitempty"` PublicIPAddresses []*[PublicIPAddress](#PublicIPAddress) `json:"publicIPAddresses,omitempty"` } ``` #### func (FrontendIPConfiguration) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L578) [¶](#FrontendIPConfiguration.MarshalJSON) ``` func (f [FrontendIPConfiguration](#FrontendIPConfiguration)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type FrontendIPConfiguration. #### func (*FrontendIPConfiguration) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L586) [¶](#FrontendIPConfiguration.UnmarshalJSON) ``` func (f *[FrontendIPConfiguration](#FrontendIPConfiguration)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type FrontendIPConfiguration. #### type [IdentityProperties](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L255) [¶](#IdentityProperties) ``` type IdentityProperties struct { Type *[IdentityType](#IdentityType) `json:"type,omitempty"` // Dictionary of UserAssignedIdentities map[[string](/builtin#string)]*[UserIdentityProperties](#UserIdentityProperties) `json:"userAssignedIdentities,omitempty"` // READ-ONLY PrincipalID *[string](/builtin#string) `json:"principalId,omitempty" azure:"ro"` // READ-ONLY TenantID *[string](/builtin#string) `json:"tenantId,omitempty" azure:"ro"` } ``` #### func (IdentityProperties) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L609) [¶](#IdentityProperties.MarshalJSON) ``` func (i [IdentityProperties](#IdentityProperties)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type IdentityProperties. #### func (*IdentityProperties) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L619) [¶](#IdentityProperties.UnmarshalJSON) ``` func (i *[IdentityProperties](#IdentityProperties)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type IdentityProperties. #### type [IdentityType](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L37) [¶](#IdentityType) ``` type IdentityType [string](/builtin#string) ``` ``` const ( IdentityTypeNone [IdentityType](#IdentityType) = "None" IdentityTypeSystemAssigned [IdentityType](#IdentityType) = "SystemAssigned" IdentityTypeSystemAssignedUserAssigned [IdentityType](#IdentityType) = "SystemAssigned, UserAssigned" IdentityTypeUserAssigned [IdentityType](#IdentityType) = "UserAssigned" ) ``` #### func [PossibleIdentityTypeValues](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L47) [¶](#PossibleIdentityTypeValues) ``` func PossibleIdentityTypeValues() [][IdentityType](#IdentityType) ``` PossibleIdentityTypeValues returns the possible values for the IdentityType const type. #### type [Logging](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L268) [¶](#Logging) ``` type Logging struct { StorageAccount *[StorageAccount](#StorageAccount) `json:"storageAccount,omitempty"` } ``` #### func (Logging) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L648) [¶](#Logging.MarshalJSON) ``` func (l [Logging](#Logging)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type Logging. #### func (*Logging) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L655) [¶](#Logging.UnmarshalJSON) ``` func (l *[Logging](#Logging)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type Logging. #### type [NetworkInterfaceConfiguration](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L272) [¶](#NetworkInterfaceConfiguration) ``` type NetworkInterfaceConfiguration struct { SubnetID *[string](/builtin#string) `json:"subnetId,omitempty"` } ``` #### func (NetworkInterfaceConfiguration) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L675) [¶](#NetworkInterfaceConfiguration.MarshalJSON) ``` func (n [NetworkInterfaceConfiguration](#NetworkInterfaceConfiguration)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type NetworkInterfaceConfiguration. #### func (*NetworkInterfaceConfiguration) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L682) [¶](#NetworkInterfaceConfiguration.UnmarshalJSON) ``` func (n *[NetworkInterfaceConfiguration](#NetworkInterfaceConfiguration)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type NetworkInterfaceConfiguration. #### type [NetworkProfile](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L276) [¶](#NetworkProfile) ``` type NetworkProfile struct { FrontEndIPConfiguration *[FrontendIPConfiguration](#FrontendIPConfiguration) `json:"frontEndIPConfiguration,omitempty"` NetworkInterfaceConfiguration *[NetworkInterfaceConfiguration](#NetworkInterfaceConfiguration) `json:"networkInterfaceConfiguration,omitempty"` } ``` #### func (NetworkProfile) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L702) [¶](#NetworkProfile.MarshalJSON) ``` func (n [NetworkProfile](#NetworkProfile)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type NetworkProfile. #### func (*NetworkProfile) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L710) [¶](#NetworkProfile.UnmarshalJSON) ``` func (n *[NetworkProfile](#NetworkProfile)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type NetworkProfile. #### type [NginxPrivateIPAllocationMethod](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L56) [¶](#NginxPrivateIPAllocationMethod) ``` type NginxPrivateIPAllocationMethod [string](/builtin#string) ``` ``` const ( NginxPrivateIPAllocationMethodDynamic [NginxPrivateIPAllocationMethod](#NginxPrivateIPAllocationMethod) = "Dynamic" NginxPrivateIPAllocationMethodStatic [NginxPrivateIPAllocationMethod](#NginxPrivateIPAllocationMethod) = "Static" ) ``` #### func [PossibleNginxPrivateIPAllocationMethodValues](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L64) [¶](#PossibleNginxPrivateIPAllocationMethodValues) ``` func PossibleNginxPrivateIPAllocationMethodValues() [][NginxPrivateIPAllocationMethod](#NginxPrivateIPAllocationMethod) ``` PossibleNginxPrivateIPAllocationMethodValues returns the possible values for the NginxPrivateIPAllocationMethod const type. #### type [OperationDisplay](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L282) [¶](#OperationDisplay) ``` type OperationDisplay struct { // Description of the operation, e.g., 'Write deployments'. Description *[string](/builtin#string) `json:"description,omitempty"` // Operation type, e.g., read, write, delete, etc. Operation *[string](/builtin#string) `json:"operation,omitempty"` // Service provider: Nginx.NginxPlus Provider *[string](/builtin#string) `json:"provider,omitempty"` // Type on which the operation is performed, e.g., 'deployments'. Resource *[string](/builtin#string) `json:"resource,omitempty"` } ``` OperationDisplay - The object that represents the operation. #### func (OperationDisplay) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L733) [¶](#OperationDisplay.MarshalJSON) ``` func (o [OperationDisplay](#OperationDisplay)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type OperationDisplay. #### func (*OperationDisplay) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L743) [¶](#OperationDisplay.UnmarshalJSON) ``` func (o *[OperationDisplay](#OperationDisplay)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. #### type [OperationListResult](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L297) [¶](#OperationListResult) ``` type OperationListResult struct { // URL to get the next set of operation list results if there are any. NextLink *[string](/builtin#string) `json:"nextLink,omitempty"` // List of operations supported by the Nginx.NginxPlus provider. Value []*[OperationResult](#OperationResult) `json:"value,omitempty"` } ``` OperationListResult - Result of GET request to list Nginx.NginxPlus operations. #### func (OperationListResult) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L772) [¶](#OperationListResult.MarshalJSON) ``` func (o [OperationListResult](#OperationListResult)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type OperationListResult. #### func (*OperationListResult) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L780) [¶](#OperationListResult.UnmarshalJSON) ``` func (o *[OperationListResult](#OperationListResult)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. #### type [OperationResult](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L306) [¶](#OperationResult) ``` type OperationResult struct { // The object that represents the operation. Display *[OperationDisplay](#OperationDisplay) `json:"display,omitempty"` // Indicates whether the operation is a data action IsDataAction *[bool](/builtin#bool) `json:"isDataAction,omitempty"` // Operation name: {provider}/{resource}/{operation} Name *[string](/builtin#string) `json:"name,omitempty"` } ``` OperationResult - A Nginx.NginxPlus REST API operation. #### func (OperationResult) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L803) [¶](#OperationResult.MarshalJSON) ``` func (o [OperationResult](#OperationResult)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type OperationResult. #### func (*OperationResult) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L812) [¶](#OperationResult.UnmarshalJSON) ``` func (o *[OperationResult](#OperationResult)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type OperationResult. #### type [OperationsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/operations_client.go#L23) [¶](#OperationsClient) ``` type OperationsClient struct { // contains filtered or unexported fields } ``` OperationsClient contains the methods for the Operations group. Don't use this type directly, use NewOperationsClient() instead. #### func [NewOperationsClient](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/operations_client.go#L30) [¶](#NewOperationsClient) ``` func NewOperationsClient(credential [azcore](/github.com/Azure/azure-sdk-for-go/sdk/azcore).[TokenCredential](/github.com/Azure/azure-sdk-for-go/sdk/azcore#TokenCredential), options *[arm](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm).[ClientOptions](/github.com/Azure/azure-sdk-for-go/sdk/azcore/arm#ClientOptions)) (*[OperationsClient](#OperationsClient), [error](/builtin#error)) ``` NewOperationsClient creates a new instance of OperationsClient with the specified values. * credential - used to authorize requests. Usually a credential from azidentity. * options - pass nil to accept the default values. #### func (*OperationsClient) [NewListPager](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/operations_client.go#L45) [¶](#OperationsClient.NewListPager) ``` func (client *[OperationsClient](#OperationsClient)) NewListPager(options *[OperationsClientListOptions](#OperationsClientListOptions)) *[runtime](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime).[Pager](/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime#Pager)[[OperationsClientListResponse](#OperationsClientListResponse)] ``` NewListPager - List all operations provided by Nginx.NginxPlus for the 2022-08-01 api version. Generated from API version 2022-08-01 * options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. Example [¶](#example-OperationsClient.NewListPager) Generated from example definition: <https://github.com/Azure/azure-rest-api-specs/blob/c71a66dab813061f1d09982c2748a09317fe0860/specification/nginx/resource-manager/NGINX.NGINXPLUS/stable/2022-08-01/examples/Operations_List.json> ``` cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armnginx.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := clientFactory.NewOperationsClient().NewListPager(nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range page.Value { // You could use page here. We use blank identifier for just demo purposes. _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // page.OperationListResult = armnginx.OperationListResult{ // Value: []*armnginx.OperationResult{ // { // Name: to.Ptr("Nginx.NginxPlus/nginxDeployments/write"), // Display: &armnginx.OperationDisplay{ // Description: to.Ptr("Write deployments resource"), // Operation: to.Ptr("write"), // Provider: to.Ptr("Nginx.NginxPlus"), // Resource: to.Ptr("deployments"), // }, // }}, // } } ``` ``` Output: ``` #### type [OperationsClientListOptions](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L318) [¶](#OperationsClientListOptions) ``` type OperationsClientListOptions struct { } ``` OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. #### type [OperationsClientListResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/response_types.go#L83) [¶](#OperationsClientListResponse) ``` type OperationsClientListResponse struct { [OperationListResult](#OperationListResult) } ``` OperationsClientListResponse contains the response from method OperationsClient.NewListPager. #### type [PrivateIPAddress](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L322) [¶](#PrivateIPAddress) ``` type PrivateIPAddress struct { PrivateIPAddress *[string](/builtin#string) `json:"privateIPAddress,omitempty"` PrivateIPAllocationMethod *[NginxPrivateIPAllocationMethod](#NginxPrivateIPAllocationMethod) `json:"privateIPAllocationMethod,omitempty"` SubnetID *[string](/builtin#string) `json:"subnetId,omitempty"` } ``` #### func (PrivateIPAddress) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L838) [¶](#PrivateIPAddress.MarshalJSON) ``` func (p [PrivateIPAddress](#PrivateIPAddress)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type PrivateIPAddress. #### func (*PrivateIPAddress) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L847) [¶](#PrivateIPAddress.UnmarshalJSON) ``` func (p *[PrivateIPAddress](#PrivateIPAddress)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type PrivateIPAddress. #### type [ProvisioningState](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L71) [¶](#ProvisioningState) ``` type ProvisioningState [string](/builtin#string) ``` ``` const ( ProvisioningStateAccepted [ProvisioningState](#ProvisioningState) = "Accepted" ProvisioningStateCanceled [ProvisioningState](#ProvisioningState) = "Canceled" ProvisioningStateCreating [ProvisioningState](#ProvisioningState) = "Creating" ProvisioningStateDeleted [ProvisioningState](#ProvisioningState) = "Deleted" ProvisioningStateDeleting [ProvisioningState](#ProvisioningState) = "Deleting" ProvisioningStateFailed [ProvisioningState](#ProvisioningState) = "Failed" ProvisioningStateNotSpecified [ProvisioningState](#ProvisioningState) = "NotSpecified" ProvisioningStateSucceeded [ProvisioningState](#ProvisioningState) = "Succeeded" ProvisioningStateUpdating [ProvisioningState](#ProvisioningState) = "Updating" ) ``` #### func [PossibleProvisioningStateValues](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/constants.go#L86) [¶](#PossibleProvisioningStateValues) ``` func PossibleProvisioningStateValues() [][ProvisioningState](#ProvisioningState) ``` PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. #### type [PublicIPAddress](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L328) [¶](#PublicIPAddress) ``` type PublicIPAddress struct { ID *[string](/builtin#string) `json:"id,omitempty"` } ``` #### func (PublicIPAddress) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L873) [¶](#PublicIPAddress.MarshalJSON) ``` func (p [PublicIPAddress](#PublicIPAddress)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type PublicIPAddress. #### func (*PublicIPAddress) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L880) [¶](#PublicIPAddress.UnmarshalJSON) ``` func (p *[PublicIPAddress](#PublicIPAddress)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddress. #### type [ResourceProviderDefaultErrorResponse](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L332) [¶](#ResourceProviderDefaultErrorResponse) ``` type ResourceProviderDefaultErrorResponse struct { Error *[ErrorResponseBody](#ErrorResponseBody) `json:"error,omitempty"` } ``` #### func (ResourceProviderDefaultErrorResponse) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L900) [¶](#ResourceProviderDefaultErrorResponse.MarshalJSON) ``` func (r [ResourceProviderDefaultErrorResponse](#ResourceProviderDefaultErrorResponse)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type ResourceProviderDefaultErrorResponse. #### func (*ResourceProviderDefaultErrorResponse) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L907) [¶](#ResourceProviderDefaultErrorResponse.UnmarshalJSON) ``` func (r *[ResourceProviderDefaultErrorResponse](#ResourceProviderDefaultErrorResponse)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type ResourceProviderDefaultErrorResponse. #### type [ResourceSKU](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L336) [¶](#ResourceSKU) ``` type ResourceSKU struct { // REQUIRED; Name of the SKU. Name *[string](/builtin#string) `json:"name,omitempty"` } ``` #### func (ResourceSKU) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L927) [¶](#ResourceSKU.MarshalJSON) ``` func (r [ResourceSKU](#ResourceSKU)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type ResourceSKU. #### func (*ResourceSKU) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L934) [¶](#ResourceSKU.UnmarshalJSON) ``` func (r *[ResourceSKU](#ResourceSKU)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKU. #### type [StorageAccount](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L341) [¶](#StorageAccount) ``` type StorageAccount struct { AccountName *[string](/builtin#string) `json:"accountName,omitempty"` ContainerName *[string](/builtin#string) `json:"containerName,omitempty"` } ``` #### func (StorageAccount) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L954) [¶](#StorageAccount.MarshalJSON) ``` func (s [StorageAccount](#StorageAccount)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type StorageAccount. #### func (*StorageAccount) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L962) [¶](#StorageAccount.UnmarshalJSON) ``` func (s *[StorageAccount](#StorageAccount)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type StorageAccount. #### type [SystemData](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L347) [¶](#SystemData) ``` type SystemData struct { // The timestamp of resource creation (UTC). CreatedAt *[time](/time).[Time](/time#Time) `json:"createdAt,omitempty"` // The identity that created the resource. CreatedBy *[string](/builtin#string) `json:"createdBy,omitempty"` // The type of identity that created the resource. CreatedByType *[CreatedByType](#CreatedByType) `json:"createdByType,omitempty"` // The timestamp of resource last modification (UTC) LastModifiedAt *[time](/time).[Time](/time#Time) `json:"lastModifiedAt,omitempty"` // The identity that last modified the resource. LastModifiedBy *[string](/builtin#string) `json:"lastModifiedBy,omitempty"` // The type of identity that last modified the resource. LastModifiedByType *[CreatedByType](#CreatedByType) `json:"lastModifiedByType,omitempty"` } ``` SystemData - Metadata pertaining to creation and last modification of the resource. #### func (SystemData) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L985) [¶](#SystemData.MarshalJSON) ``` func (s [SystemData](#SystemData)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type SystemData. #### func (*SystemData) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L997) [¶](#SystemData.UnmarshalJSON) ``` func (s *[SystemData](#SystemData)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. #### type [UserIdentityProperties](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models.go#L367) [¶](#UserIdentityProperties) ``` type UserIdentityProperties struct { // READ-ONLY ClientID *[string](/builtin#string) `json:"clientId,omitempty" azure:"ro"` // READ-ONLY PrincipalID *[string](/builtin#string) `json:"principalId,omitempty" azure:"ro"` } ``` #### func (UserIdentityProperties) [MarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L1032) [¶](#UserIdentityProperties.MarshalJSON) ``` func (u [UserIdentityProperties](#UserIdentityProperties)) MarshalJSON() ([][byte](/builtin#byte), [error](/builtin#error)) ``` MarshalJSON implements the json.Marshaller interface for type UserIdentityProperties. #### func (*UserIdentityProperties) [UnmarshalJSON](https://github.com/Azure/azure-sdk-for-go/blob/sdk/resourcemanager/nginx/armnginx/v2.1.0/sdk/resourcemanager/nginx/armnginx/models_serde.go#L1040) [¶](#UserIdentityProperties.UnmarshalJSON) ``` func (u *[UserIdentityProperties](#UserIdentityProperties)) UnmarshalJSON(data [][byte](/builtin#byte)) [error](/builtin#error) ``` UnmarshalJSON implements the json.Unmarshaller interface for type UserIdentityProperties.
lzf
hex
Erlang
Toggle Theme lzf v0.1.3 API Reference === Modules --- [Lzf](Lzf.html) Decompresses a binary that was compressed in LZF format Toggle Theme lzf v0.1.3 Lzf === Decompresses a binary that was compressed in LZF format. [Link to this section](#summary) Summary === [Functions](#functions) --- [decompress(compressed)](#decompress/1) Returns a decompressed binary [decompress_chunk(chunk)](#decompress_chunk/1) [decompress_chunk(arg1, position, decompressed)](#decompress_chunk/3) [parse_chunks(arg1, chunks)](#parse_chunks/2) [Link to this section](#functions) Functions === [Link to this function](#decompress/1 "Link to this function") decompress(compressed) ``` decompress([binary](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: [binary](https://hexdocs.pm/elixir/typespecs.html#built-in-types)() ``` Returns a decompressed binary [Link to this function](#decompress_chunk/1 "Link to this function") decompress_chunk(chunk) [Link to this function](#decompress_chunk/3 "Link to this function") decompress_chunk(arg1, position, decompressed) [Link to this function](#parse_chunks/2 "Link to this function") parse_chunks(arg1, chunks) ``` parse_chunks([binary](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()) :: [binary](https://hexdocs.pm/elixir/typespecs.html#built-in-types)() ```
jinja.js
npm
JavaScript
Jinja.js === Client-side rendering of Twig/Jinja/Jinjs templates. --- Demos --- You can find demos under the `/tests` folder: * [Basic Javascript](https://github.com/visionmedia/express/blob/HEAD/tests/01-vanilla.html) * [The `include` function](https://github.com/visionmedia/express/blob/HEAD/tests/02-include.html) * [The `extends` function](https://github.com/visionmedia/express/blob/HEAD/tests/03-extends.html) * [The `macro` function](https://github.com/visionmedia/express/blob/HEAD/tests/04-macro.html) --- Get Started --- ### 1. Include Script ``` <script src="lib/jinja.min.js"></script> ``` ### 2. Add HTML Markup ``` <script type="text/jinja" id="standalone"> <h1>Welcome to {{ title|capitalize}}!</h1> </script> ``` ### 3. Render #### a. jQuery ``` <script src="lib/jinja.jquery.js"></script> ... <script> // Replace #content with rendered template $('#content').jinja({ title: 'jinja.js' }); </script> ``` #### b. Vanilla Javascript ``` <script> var script = document.getElementById('standalone'); var template = script.innerHTML; var context = { title: 'jinja.js' }; var content = Jinja.render(template, context); document.write(content); // or var container = document.createElement('div'); container.innerHTML = content; script.parentNode.replaceChild(container, script); </script> ``` --- Building --- A quick build script is included at `bin/build` that will install dependencies, compile & compress: ``` $ ./bin/build npm info it worked if it ends with ok npm info using [email protected] … Finished! ``` This will create: * `build/build.js` -> `lib/jinja.js` * `build/build.min.js` -> `lib/jinja.min.js` ### Requirements * [NodeJS](http://nodejs.org/) * [npm](http://npmjs.org/) * [Browserify](https://github.com/substack/node-browserify) * Java (for YUI Compressor) --- Author --- * <NAME> [<EMAIL>](mailto:<EMAIL>) --- #### See Also * [node-jinjs](https://github.com/ravelsoft/node-jinjs/wiki) * [node-browserify](https://github.com/substack/node-browserify) Readme --- ### Keywords none
sentry-backtrace
rust
Rust
Crate sentry_backtrace === Backtrace Integration and utilities for sentry. Exposes functions to capture, process and convert/parse stacktraces, as well as integrations to process event stacktraces. Structs --- * AttachStacktraceIntegrationIntegration to attach stacktraces to Events. * FrameRepresents a frame. * ProcessStacktraceIntegrationIntegration to process Event stacktraces. * StacktraceRepresents a stacktrace. Functions --- * backtrace_to_stacktraceConvert a `backtrace::Backtrace` into a Rust `Stacktrace` * current_stacktraceReturns the current backtrace as sentry stacktrace. * current_threadCaptures information about the current thread. * parse_stacktraceParses a backtrace string into a Sentry `Stacktrace`. * process_event_stacktraceProcesses a `Stacktrace`. * trim_stacktraceA helper function to trim a stacktrace. Struct sentry_backtrace::AttachStacktraceIntegration === ``` pub struct AttachStacktraceIntegration; ``` Integration to attach stacktraces to Events. This integration will add an additional thread backtrace to captured messages, respecting the `attach_stacktrace` option. Implementations --- ### impl AttachStacktraceIntegration #### pub fn new() -> Self Creates a new Integration to attach stacktraces to Events. Trait Implementations --- ### impl Debug for AttachStacktraceIntegration #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> AttachStacktraceIntegration Returns the “default value” for a type. #### fn name(&self) -> &'static str Name of this integration. &self, event: Event<'static>, options: &ClientOptions ) -> Option<Event<'static>The Integrations Event Processor Hook. Called whenever the integration is attached to a Client.Auto Trait Implementations --- ### impl RefUnwindSafe for AttachStacktraceIntegration ### impl Send for AttachStacktraceIntegration ### impl Sync for AttachStacktraceIntegration ### impl Unpin for AttachStacktraceIntegration ### impl UnwindSafe for AttachStacktraceIntegration Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V Struct sentry_backtrace::Frame === [] ``` pub struct Frame { pub function: Option<String>, pub symbol: Option<String>, pub module: Option<String>, pub package: Option<String>, pub filename: Option<String>, pub abs_path: Option<String>, pub lineno: Option<u64>, pub colno: Option<u64>, pub pre_context: Vec<String, Global>, pub context_line: Option<String>, pub post_context: Vec<String, Global>, pub in_app: Option<bool>, pub vars: BTreeMap<String, Value, Global>, pub image_addr: Option<Addr>, pub instruction_addr: Option<Addr>, pub symbol_addr: Option<Addr>, pub addr_mode: Option<String>, } ``` Represents a frame. Fields --- `function: Option<String>`The name of the function is known. Note that this might include the name of a class as well if that makes sense for the language. `symbol: Option<String>`The potentially mangled name of the symbol as it appears in an executable. This is different from a function name by generally being the mangled name that appears natively in the binary. This is relevant for languages like Swift, C++ or Rust. `module: Option<String>`The name of the module the frame is contained in. Note that this might also include a class name if that is something the language natively considers to be part of the stack (for instance in Java). `package: Option<String>`The name of the package that contains the frame. For instance this can be a dylib for native languages, the name of the jar or .NET assembly. `filename: Option<String>`The filename (basename only). `abs_path: Option<String>`If known the absolute path. `lineno: Option<u64>`The line number if known. `colno: Option<u64>`The column number if known. `pre_context: Vec<String, Global>`The sources of the lines leading up to the current line. `context_line: Option<String>`The current line as source. `post_context: Vec<String, Global>`The sources of the lines after the current line. `in_app: Option<bool>`In-app indicator. `vars: BTreeMap<String, Value, Global>`Optional local variables. `image_addr: Option<Addr>`If known the location of the image. `instruction_addr: Option<Addr>`If known the location of the instruction. `symbol_addr: Option<Addr>`If known the location of symbol. `addr_mode: Option<String>`Optionally changes the addressing mode. The default value is the same as `"abs"` which means absolute referencing. This can also be set to `"rel:DEBUG_ID"` or `"rel:IMAGE_INDEX"` to make addresses relative to an object referenced by debug id or index. This for instance is necessary for WASM processing as WASM does not use a unified address space. Trait Implementations --- ### impl Clone for Frame #### fn clone(&self) -> Frame Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn default() -> Frame Returns the “default value” for a type. #### fn deserialize<__D>( __deserializer: __D ) -> Result<Frame, <__D as Deserializer<'de>>::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn eq(&self, other: &Frame) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Serialize for Frame #### fn serialize<__S>( &self, __serializer: __S ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Auto Trait Implementations --- ### impl RefUnwindSafe for Frame ### impl Send for Frame ### impl Sync for Frame ### impl Unpin for Frame ### impl UnwindSafe for Frame Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Struct sentry_backtrace::ProcessStacktraceIntegration === ``` pub struct ProcessStacktraceIntegration; ``` Integration to process Event stacktraces. This integration will trim backtraces, depending on the `trim_backtraces` and `extra_border_frames` options. It will then classify each frame according to the `in_app_include` and `in_app_exclude` options. Implementations --- ### impl ProcessStacktraceIntegration #### pub fn new() -> Self Creates a new Integration to process stacktraces. Trait Implementations --- ### impl Debug for ProcessStacktraceIntegration #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> ProcessStacktraceIntegration Returns the “default value” for a type. #### fn name(&self) -> &'static str Name of this integration. &self, event: Event<'static>, options: &ClientOptions ) -> Option<Event<'static>The Integrations Event Processor Hook. Called whenever the integration is attached to a Client.Auto Trait Implementations --- ### impl RefUnwindSafe for ProcessStacktraceIntegration ### impl Send for ProcessStacktraceIntegration ### impl Sync for ProcessStacktraceIntegration ### impl Unpin for ProcessStacktraceIntegration ### impl UnwindSafe for ProcessStacktraceIntegration Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T, U> TryFrom<U> for Twhere U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V Struct sentry_backtrace::Stacktrace === [] ``` pub struct Stacktrace { pub frames: Vec<Frame, Global>, pub frames_omitted: Option<(u64, u64)>, pub registers: BTreeMap<String, RegVal, Global>, } ``` Represents a stacktrace. Fields --- `frames: Vec<Frame, Global>`The list of frames in the stacktrace. `frames_omitted: Option<(u64, u64)>`Optionally a segment of frames removed (`start`, `end`). `registers: BTreeMap<String, RegVal, Global>`Optional register values of the thread. Implementations --- ### impl Stacktrace #### pub fn from_frames_reversed(frames: Vec<Frame, Global>) -> Option<StacktraceOptionally creates a stacktrace from a list of stack frames. Trait Implementations --- ### impl Clone for Stacktrace #### fn clone(&self) -> Stacktrace Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### fn default() -> Stacktrace Returns the “default value” for a type. #### fn deserialize<__D>( __deserializer: __D ) -> Result<Stacktrace, <__D as Deserializer<'de>>::Error>where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. #### fn eq(&self, other: &Stacktrace) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`.1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.### impl Serialize for Stacktrace #### fn serialize<__S>( &self, __serializer: __S ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where __S: Serializer, Serialize this value into the given Serde serializer. Auto Trait Implementations --- ### impl RefUnwindSafe for Stacktrace ### impl Send for Stacktrace ### impl Sync for Stacktrace ### impl Unpin for Stacktrace ### impl UnwindSafe for Stacktrace Blanket Implementations --- ### impl<T> Any for Twhere T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere U: From<T>, #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error.#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.### impl<V, T> VZip<V> for Twhere V: MultiLane<T>, #### fn vzip(self) -> V ### impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>, Function sentry_backtrace::backtrace_to_stacktrace === ``` pub fn backtrace_to_stacktrace(bt: &Backtrace) -> Option<Stacktrace> ``` Convert a `backtrace::Backtrace` into a Rust `Stacktrace` Function sentry_backtrace::current_stacktrace === ``` pub fn current_stacktrace() -> Option<Stacktrace> ``` Returns the current backtrace as sentry stacktrace. Function sentry_backtrace::current_thread === ``` pub fn current_thread(with_stack: bool) -> Thread ``` Captures information about the current thread. If `with_stack` is set to `true` the current stacktrace is attached. Function sentry_backtrace::process_event_stacktrace === ``` pub fn process_event_stacktrace( stacktrace: &mut Stacktrace, options: &ClientOptions ) ``` Processes a `Stacktrace`. Trims a `Stacktrace` and marks frames as in-app based on the provided `ClientOptions`. Function sentry_backtrace::trim_stacktrace === ``` pub fn trim_stacktrace<F>(stacktrace: &mut Stacktrace, f: F)where F: Fn(&Frame, &Stacktrace) -> bool, ``` A helper function to trim a stacktrace.
GWASbyCluster
cran
R
Package ‘GWASbyCluster’ October 12, 2022 Type Package Title Identifying Significant SNPs in Genome Wide Association Studies (GWAS) via Clustering Version 0.1.7 Date 2019-10-09 Author <NAME>, <NAME>, <NAME>, <NAME><<EMAIL>>, <NAME> <<EMAIL>> Maintainer <NAME> <<EMAIL>> Depends R (>= 3.5.0), Biobase Imports stats, snpStats, methods, rootSolve, limma Description Identifying disease-associated significant SNPs using clustering approach. This package is im- plementation of method proposed in Xu et al (2019) <DOI:10.1038/s41598-019-50229-6>. License GPL (>= 2) NeedsCompilation no Repository CRAN Date/Publication 2019-10-11 09:30:06 UTC R topics documented: esSi... 2 esSimDiffPrior... 3 estMemSNP... 5 estMemSNPs.oneSetHyperPar... 8 simGenoFun... 11 simGenoFuncDiffPrior... 13 esSim An ExpressionSet Object Storing Simulated Genotype Data Description An ExpressionSet object storing simulated genotype data. The minor allele frequency (MAF) of cases has the same prior as that of controls. Usage data("esSim") Details In this simulation, we generate additive-coded genotypes for 3 clusters of SNPs based on a mixture of 3 Bayesian hierarchical models. In cluster +, the minor allele frequency (MAF) θx+ of cases is greater than the MAF θy+ of controls. In cluster 0, the MAF θ0 of cases is equal to the MAF of controls. In cluster −, the MAF θx− of cases is smaller than the MAF θy− of controls. The proportions of the 3 clusters of SNPs are π+ , π0 , and π− , respectively. We assume a “half-flat shape” bivariate prior for the MAF in cluster + 2h+ (θx+ ) h+ (θy+ ) I (θx+ > θy+ ) , where I(a) is hte indicator function taking value 1 if the event a is true, and value 0 otherwise. The function h+ is the probability density function of the beta distribution Beta (α+ , β+ ). We assume θ0 has the beta prior Beta(α0 , β0 ). We also assume a “half-flat shape” bivariate prior for the MAF in cluster − 2h− (θx− ) h− (θy− ) I (θx− > θy− ) . The function h− is the probability density function of the beta distribution Beta (α− , β− ). Given a SNP, we assume Hardy-Weinberg equilibrium holds for its genotypes. That is, given MAF θ, the probabilities of genotypes are P r(geno = 2) = θ2 P r(geno = 1) = 2θ (1 − θ) P r(geno = 0) = (1 − θ) We also assume the genotypes 0n(wild-type), h 1 (heterozygote),ioand 2 (mutation) follows a multino- mial distribution M ultinomial 1, θ2 , 2θ (1 − θ) , (1 − θ) We set the number of cases as 100, the number of controls as 100, and the number of SNPs as 1000. The hyperparameters are α+ = 2, β+ = 5, π+ = 0.1, α0 = 2, β0 = 5, π0 = 0.8, α− = 2, β− = 5, π− = 0.1. Note that when we generate MAFs from the half-flat shape bivariate priors, we might get very small MAFs or get MAFs > 0.5. In these cased, we then delete this SNP. So the final number of SNPs generated might be less than the initially-set number 1000 of SNPs. For the dataset stored in esSim, there are 872 SNPs. 83 SNPs are in cluster -, 714 SNPs are in cluster 0, and 75 SNPs are in cluster +. References <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Model-based clustering for identifying disease-associated SNPs in case-control genome-wide association studies. Scientific Reports 9, Article number: 13686 (2019) https://www.nature.com/articles/s41598-019-50229-6. Examples data(esSim) print(esSim) pDat=pData(esSim) print(pDat[1:2,]) print(table(pDat$memSubjs)) fDat=fData(esSim) print(fDat[1:2,]) print(table(fDat$memGenes)) print(table(fDat$memGenes2)) esSimDiffPriors An ExpressionSet Object Storing Simulated Genotype Data Description An ExpressionSet object storing simulated genotype data. The minor allele frequency (MAF) of cases has different prior than that of controls. Usage data("esSimDiffPriors") Details In this simulation, we generate additive-coded genotypes for 3 clusters of SNPs based on a mixture of 3 Bayesian hierarchical models. In cluster +, the minor allele frequency (MAF) θx+ of cases is greater than the MAF θy+ of controls. In cluster 0, the MAF θ0 of cases is equal to the MAF of controls. In cluster −, the MAF θx− of cases is smaller than the MAF θy− of controls. The proportions of the 3 clusters of SNPs are π+ , π0 , and π− , respectively. We assume a “half-flat shape” bivariate prior for the MAF in cluster + 2hx+ (θx+ ) hy+ (θy+ ) I (θx+ > θy+ ) , where I(a) is hte indicator function taking value 1 if the event a is true, and value 0 otherwise. The function hx+ is the probability density function of the beta distribution Beta (αx+ , βx+ ). The function hy+ is the probability density function of the beta distribution Beta (αy+ , βy+ ). We assume θ0 has the beta prior Beta(α0 , β0 ). We also assume a “half-flat shape” bivariate prior for the MAF in cluster − 2hx− (θx− ) hy− (θy− ) I (θx− > θy− ) . The function hx− is the probability density function of the beta distribution Beta (αx− , βx− ). The function hy− is the probability density function of the beta distribution Beta (αy− , βy− ). Given a SNP, we assume Hardy-Weinberg equilibrium holds for its genotypes. That is, given MAF θ, the probabilities of genotypes are P r(geno = 2) = θ2 P r(geno = 1) = 2θ (1 − θ) P r(geno = 0) = (1 − θ) We also assume the genotypes 0n(wild-type), h 1 (heterozygote),ioand 2 (mutation) follows a multino- 2 2 mial distribution M ultinomial 1, θ , 2θ (1 − θ) , (1 − θ) We set the number of cases as 100, the number of controls as 100, and the number of SNPs as 1000. The hyperparameters are αx+ = 2, βx+ = 3, αy+ = 2, βy+ = 8, π+ = 0.1, α0 = 2, β0 = 5, π0 = 0.8, αx− = 2, βx− = 8, αy− = 2, βy− = 3, π− = 0.1. Note that when we generate MAFs from the half-flat shape bivariate priors, we might get very small MAFs or get MAFs > 0.5. In these cased, we then delete this SNP. So the final number of SNPs generated might be less than the initially-set number 1000 of SNPs. For the dataset stored in esSim, there are 838 SNPs. 64 SNPs are in cluster -, 708 SNPs are in cluster 0, and 66 SNPs are in cluster +. References <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Model-based clustering for identifying disease-associated SNPs in case-control genome-wide association studies. Scientific Reports 9, Article number: 13686 (2019) https://www.nature.com/articles/s41598-019-50229-6. Examples data(esSimDiffPriors) print(esSimDiffPriors) pDat=pData(esSimDiffPriors) print(pDat[1:2,]) print(table(pDat$memSubjs)) fDat=fData(esSimDiffPriors) print(fDat[1:2,]) print(table(fDat$memGenes)) print(table(fDat$memGenes2)) estMemSNPs Estimate SNP cluster membership Description Estimate SNP cluster membership. Only update cluster mixture proportions. Assume the 3 clusters have different sets of hyperparameters. Usage estMemSNPs(es, var.memSubjs = "memSubjs", eps = 0.001, MaxIter = 50, bVec = rep(3, 3), pvalAdjMethod = "fdr", method = "FDR", fdr = 0.05, verbose = FALSE) Arguments es An ExpressionSet object storing SNP genotype data. It contains 3 matrices. The first matrix, which can be extracted by exprs method (e.g., exprs(es)), stores genotype data, with rows are SNPs and columns are subjects. The second matrix, which can be extracted by pData method (e.g., pData(es)), stores phenotype data describing subjects. Rows are subjects, and columns are phenotype variables. The third matrix, which can be extracted by fData method (e.g., fData(es)), stores feature data describing SNPs. Rows are SNPs and columns are feature variables. var.memSubjs character. The name of the phenotype variable indicating subject’s case-control status. It must take only two values: 1 indicating case and 0 indicating control. eps numeric. A small positive number as threshold for convergence of EM algo- rithm. MaxIter integer. A positive integer indicating maximum iteration in EM algorithm. bVec numeric. A vector of 2 elements. Indicates the parameters of the symmetric Dirichlet prior for proportion mixtures. pvalAdjMethod character. Indicating p-value adjustment method. c.f. p.adjust. method method to obtain SNP cluster membership based on the responsibility matrix. The default value is “FDR”. The other possible value is “max”. see details. fdr numeric. A small positive FDR threshold used to call SNP cluster membership verbose logical. Indicating if intermediate and final results should be output. Details In this simulation, we generate additive-coded genotypes for 3 clusters of SNPs based on a mixture of 3 Bayesian hierarchical models. In cluster +, the minor allele frequency (MAF) θx+ of cases is greater than the MAF θy+ of controls. In cluster 0, the MAF θ0 of cases is equal to the MAF of controls. In cluster −, the MAF θx− of cases is smaller than the MAF θy− of controls. The proportions of the 3 clusters of SNPs are π+ , π0 , and π− , respectively. We assume a “half-flat shape” bivariate prior for the MAF in cluster + 2h+ (θx+ ) h+ (θy+ ) I (θx+ > θy+ ) , where I(a) is hte indicator function taking value 1 if the event a is true, and value 0 otherwise. The function h+ is the probability density function of the beta distribution Beta (α+ , β+ ). We assume θ0 has the beta prior Beta(α0 , β0 ). We also assume a “half-flat shape” bivariate prior for the MAF in cluster − 2h− (θx− ) h− (θy− ) I (θx− > θy− ) . The function h− is the probability density function of the beta distribution Beta (α− , β− ). Given a SNP, we assume Hardy-Weinberg equilibrium holds for its genotypes. That is, given MAF θ, the probabilities of genotypes are P r(geno = 2) = θ2 P r(geno = 1) = 2θ (1 − θ) P r(geno = 0) = (1 − θ) We also assume the genotypes 0n(wild-type), h 1 (heterozygote),ioand 2 (mutation) follows a multino- 2 2 mial distribution M ultinomial 1, θ , 2θ (1 − θ) , (1 − θ) For each SNP, we calculat its posterior probabilities that it belongs to cluster k. This forms a matrix with 3 columns. Rows are SNPs. The 1st column is the posterior probability that the SNP belongs to cluster −. The 2nd column is the posterior probability that the SNP belongs to cluster 0. The 3rd column is the posterior probability that the SNP belongs to cluster +. We call this posterior probability matrix as responsibility matrix. To determine which cluster a SNP eventually belongs to, we can use 2 methods. The first method (the default method) is “FDR” method, which will use FDR criterion to determine SNP cluster membership. The 2nd method is use the maximum posterior probability to decide which cluster a SNP belongs to. Value A list of 12 elements wMat matrix of posterior probabilities. The rows are SNPs. There are 3 columns. The first column is the posterior probability that a SNP belongs to cluster - given genotypes of subjects. The second column is the posterior probability that a SNP belongs to cluster 0 given genotypes of subjects. The third column is the posterior probability that a SNP belongs to cluster + given genotypes of subjects. memSNPs a vector of SNP cluster membership for the 3-cluster partitionfrom the mixture of 3 Bayesian hierarchical models. memSNPs2 a vector of binary SNP cluster membership. 1 indicates the SNP has different MAFs between cases and controls. 0 indicates the SNP has the same MAF in cases as that in controls. piVec a vector of cluster mixture proportions. alpha.p the first shape parameter of the beta prior for MAF obtaind from initial 3-cluster partitions based on GWAS for cluster +. beta.p the second shape parameter of the beta prior for MAF obtaind from initial 3- cluster partitions based on GWAS for cluster +. alpha0 the first shape parameter of the beta prior for MAF obtaind from initial 3-cluster partitions based on GWAS for cluster 0. beta0 the second shape parameter of the beta prior for MAF obtaind from initial 3- cluster partitions based on GWAS for cluster 0. alpha.n the first shape parameter of the beta prior for MAF obtaind from initial 3-cluster partitions based on GWAS for cluster -. beta.n the second shape parameter of the beta prior for MAF obtaind from initial 3- cluster partitions based on GWAS for cluster -. loop number of iteration in EM algorithm diff sum of the squared difference of cluster mixture proportions between current iteration and previous iteration in EM algorithm. if eps < eps, we claim the EM algorithm converges. res.limma object returned by limma Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>> References <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Model-based clustering for identifying disease-associated SNPs in case-control genome-wide association studies. Scientific Reports 9, Article number: 13686 (2019) https://www.nature.com/articles/s41598-019-50229-6. Examples data(esSimDiffPriors) print(esSimDiffPriors) es=esSimDiffPriors[1:500,] fDat = fData(es) print(fDat[1:2,]) print(table(fDat$memGenes)) res = estMemSNPs( es = es, var.memSubjs = "memSubjs") print(table(fDat$memGenes, res$memSNPs)) estMemSNPs.oneSetHyperPara Estimate SNP cluster membership Description Estimate SNP cluster membership. Only update cluster mixture proportions. Assume all 3 clusters have the same set of hyperparameters. Usage estMemSNPs.oneSetHyperPara(es, var.memSubjs = "memSubjs", eps = 1.0e-3, MaxIter = 50, bVec = rep(3, 3), pvalAdjMethod = "none", method = "FDR", fdr = 0.05, verbose = FALSE) Arguments es An ExpressionSet object storing SNP genotype data. It contains 3 matrices. The first matrix, which can be extracted by exprs method (e.g., exprs(es)), stores genotype data, with rows are SNPs and columns are subjects. The second matrix, which can be extracted by pData method (e.g., pData(es)), stores phenotype data describing subjects. Rows are subjects, and columns are phenotype variables. The third matrix, which can be extracted by fData method (e.g., fData(es)), stores feature data describing SNPs. Rows are SNPs and columns are feature variables. var.memSubjs character. The name of the phenotype variable indicating subject’s case-control status. It must take only two values: 1 indicating case and 0 indicating control. eps numeric. A small positive number as threshold for convergence of EM algo- rithm. MaxIter integer. A positive integer indicating maximum iteration in EM algorithm. bVec numeric. A vector of 2 elements. Indicates the parameters of the symmetric Dirichlet prior for proportion mixtures. pvalAdjMethod character. Indicating p-value adjustment method. c.f. p.adjust. method method to obtain SNP cluster membership based on the responsibility matrix. The default value is “FDR”. The other possible value is “max”. see details. fdr numeric. A small positive FDR threshold used to call SNP cluster membership verbose logical. Indicating if intermediate and final results should be output. Details We characterize the distribution of genotypes of SNPs by a mixture of 3 Bayesian hierarchical models. The 3 Bayeisan hierarchical models correspond to 3 clusters of SNPs. In cluster +, the minor allele frequency (MAF) θx+ of cases is greater than the MAF θy+ of controls. In cluster 0, the MAF θ0 of cases is equal to the MAF of controls. In cluster −, the MAF θx− of cases is smaller than the MAF θy− of controls. The proportions of the 3 clusters of SNPs are π+ , π0 , and π− , respectively. We assume a “half-flat shape” bivariate prior for the MAF in cluster + 2h (θx+ ) h (θy+ ) I (θx+ > θy+ ) , where I(a) is hte indicator function taking value 1 if the event a is true, and value 0 otherwise. The function h is the probability density function of the beta distribution Beta (α, β). We assume θ0 has the beta prior Beta(α, β). We also assume a “half-flat shape” bivariate prior for the MAF in cluster − 2h (θx− ) h (θy− ) I (θx− > θy− ) . Given a SNP, we assume Hardy-Weinberg equilibrium holds for its genotypes. That is, given MAF θ, the probabilities of genotypes are P r(geno = 2) = θ2 P r(geno = 1) = 2θ (1 − θ) P r(geno = 0) = (1 − θ) We also assume the genotypes 0n(wild-type), h 1 (heterozygote),ioand 2 (mutation) follows a multino- 2 2 mial distribution M ultinomial 1, θ , 2θ (1 − θ) , (1 − θ) For each SNP, we calculat its posterior probabilities that it belongs to cluster k. This forms a matrix with 3 columns. Rows are SNPs. The 1st column is the posterior probability that the SNP belongs to cluster −. The 2nd column is the posterior probability that the SNP belongs to cluster 0. The 3rd column is the posterior probability that the SNP belongs to cluster +. We call this posterior probability matrix as responsibility matrix. To determine which cluster a SNP eventually belongs to, we can use 2 methods. The first method (the default method) is “FDR” method, which will use FDR criterion to determine SNP cluster membership. The 2nd method is use the maximum posterior probability to decide which cluster a SNP belongs to. Value A list of 10 elements wMat matrix of posterior probabilities. The rows are SNPs. There are 3 columns. The first column is the posterior probability that a SNP belongs to cluster - given genotypes of subjects. The second column is the posterior probability that a SNP belongs to cluster 0 given genotypes of subjects. The third column is the posterior probability that a SNP belongs to cluster + given genotypes of subjects. memSNPs a vector of SNP cluster membership for the 3-cluster partitionfrom the mixture of 3 Bayesian hierarchical models. memSNPs2 a vector of binary SNP cluster membership. 1 indicates the SNP has different MAFs between cases and controls. 0 indicates the SNP has the same MAF in cases as that in controls. piVec a vector of cluster mixture proportions. alpha the first shape parameter of the beta prior for MAF obtaind from initial 3-cluster partitions based on GWAS. beta the second shape parameter of the beta prior for MAF obtaind from initial 3- cluster partitions based on GWAS. loop number of iteration in EM algorithm diff sum of the squared difference of cluster mixture proportions between current iteration and previous iteration in EM algorithm. if eps < eps, we claim the EM algorithm converges. res.limma object returned by limma Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>> References <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Model-based clustering for identifying disease-associated SNPs in case-control genome-wide association studies. Scientific Reports 9, Article number: 13686 (2019) https://www.nature.com/articles/s41598-019-50229-6. Examples data(esSimDiffPriors) print(esSimDiffPriors) fDat = fData(esSimDiffPriors) print(fDat[1:2,]) print(table(fDat$memGenes)) res = estMemSNPs.oneSetHyperPara( es = esSimDiffPriors, var.memSubjs = "memSubjs") print(table(fDat$memGenes, res$memSNPs)) simGenoFunc Simulate Genotype Data from a Mixture of 3 Bayesian Hierarchical Models Description Simulate Genotype Data from a Mixture of 3 Bayesian Hierarchical Models. The minor allele frequency (MAF) of cases has the same prior as that of controls. Usage simGenoFunc(nCases = 100, nControls = 100, nSNPs = 1000, alpha.p = 2, beta.p = 5, pi.p = 0.1, alpha0 = 2, beta0 = 5, pi0 = 0.8, alpha.n = 2, beta.n = 5, pi.n = 0.1, low = 0.02, upp = 0.5, verbose = FALSE) Arguments nCases integer. Number of cases. nControls integer. Number of controls. nSNPs integer. Number of SNPs. alpha.p numeric. The first shape parameter of Beta prior in cluster +. beta.p numeric. The second shape parameter of Beta prior in cluster +. pi.p numeric. Mixture proportion for cluster +. alpha0 numeric. The first shape parameter of Beta prior in cluster 0. beta0 numeric. The second shape parameter of Beta prior in cluster 0. pi0 numeric. Mixture proportion for cluster 0. alpha.n numeric. The first shape parameter of Beta prior in cluster −. beta.n numeric. The second shape parameter of Beta prior in cluster −. pi.n numeric. Mixture proportion for cluster −. low numeric. A small positive value. If a MAF generated from half-flat shape bi- variate prior is smaller than low, we will delete the SNP to be generated. upp numeric. A positive value. If a MAF generated from half-flat shape bivariate prior is greater than upp, we will delete the SNP to be generated. verbose logical. Indicating if intermediate results or final results should be output to output screen. Details In this simulation, we generate additive-coded genotypes for 3 clusters of SNPs based on a mixture of 3 Bayesian hierarchical models. In cluster +, the minor allele frequency (MAF) θx+ of cases is greater than the MAF θy+ of controls. In cluster 0, the MAF θ0 of cases is equal to the MAF of controls. In cluster −, the MAF θx− of cases is smaller than the MAF θy− of controls. The proportions of the 3 clusters of SNPs are π+ , π0 , and π− , respectively. We assume a “half-flat shape” bivariate prior for the MAF in cluster + 2h+ (θx+ ) h+ (θy+ ) I (θx+ > θy+ ) , where I(a) is hte indicator function taking value 1 if the event a is true, and value 0 otherwise. The function h+ is the probability density function of the beta distribution Beta (α+ , β+ ). We assume θ0 has the beta prior Beta(α0 , β0 ). We also assume a “half-flat shape” bivariate prior for the MAF in cluster − 2h− (θx− ) h− (θy− ) I (θx− > θy− ) . The function h− is the probability density function of the beta distribution Beta (α− , β− ). Given a SNP, we assume Hardy-Weinberg equilibrium holds for its genotypes. That is, given MAF θ, the probabilities of genotypes are P r(geno = 2) = θ2 P r(geno = 1) = 2θ (1 − θ) P r(geno = 0) = (1 − θ) We also assume the genotypes 0n(wild-type), h 1 (heterozygote),ioand 2 (mutation) follows a multino- mial distribution M ultinomial 1, θ2 , 2θ (1 − θ) , (1 − θ) Note that when we generate MAFs from the half-flat shape bivariate priors, we might get very small MAFs or get MAFs > 0.5. In these cased, we then delete this SNP. So the final number of SNPs generated might be less than the initially-set number of SNPs. Value An ExpressionSet object stores genotype data. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>> References <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Model-based clustering for identifying disease-associated SNPs in case-control genome-wide association studies. Scientific Reports 9, Article number: 13686 (2019) https://www.nature.com/articles/s41598-019-50229-6. Examples set.seed(2) esSim = simGenoFunc( nCases = 100, nControls = 100, nSNPs = 500, alpha.p = 2, beta.p = 5, pi.p = 0.1, alpha0 = 2, beta0 = 5, pi0 = 0.8, alpha.n = 2, beta.n = 5, pi.n = 0.1, low = 0.02, upp = 0.5, verbose = FALSE ) print(esSim) pDat = pData(esSim) print(pDat[1:2,]) print(table(pDat$memSubjs)) fDat = fData(esSim) print(fDat[1:2,]) print(table(fDat$memGenes)) print(table(fDat$memGenes2)) simGenoFuncDiffPriors Simulate Genotype Data from a Mixture of 3 Bayesian Hierarchical Models Description Simulate Genotype Data from a Mixture of 3 Bayesian Hierarchical Models. The minor allele frequency (MAF) of cases has different priors than that of controls. Usage simGenoFuncDiffPriors( nCases = 100, nControls = 100, nSNPs = 1000, alpha.p.ca = 2, beta.p.ca = 3, alpha.p.co = 2, beta.p.co = 8, pi.p = 0.1, alpha0 = 2, beta0 = 5, pi0 = 0.8, alpha.n.ca = 2, beta.n.ca = 8, alpha.n.co = 2, beta.n.co = 3, pi.n = 0.1, low = 0.02, upp = 0.5, verbose = FALSE) Arguments nCases integer. Number of cases. nControls integer. Number of controls. nSNPs integer. Number of SNPs. alpha.p.ca numeric. The first shape parameter of Beta prior in cluster + for cases. beta.p.ca numeric. The second shape parameter of Beta prior in cluster + for cases. alpha.p.co numeric. The first shape parameter of Beta prior in cluster + for controls. beta.p.co numeric. The second shape parameter of Beta prior in cluster + for controls. pi.p numeric. Mixture proportion for cluster +. alpha0 numeric. The first shape parameter of Beta prior in cluster 0. beta0 numeric. The second shape parameter of Beta prior in cluster 0. pi0 numeric. Mixture proportion for cluster 0. alpha.n.ca numeric. The first shape parameter of Beta prior in cluster − for cases. beta.n.ca numeric. The second shape parameter of Beta prior in cluster − for cases. alpha.n.co numeric. The first shape parameter of Beta prior in cluster − for controls. beta.n.co numeric. The second shape parameter of Beta prior in cluster − for controls. pi.n numeric. Mixture proportion for cluster −. low numeric. A small positive value. If a MAF generated from half-flat shape bi- variate prior is smaller than low, we will delete the SNP to be generated. upp numeric. A positive value. If a MAF generated from half-flat shape bivariate prior is greater than upp, we will delete the SNP to be generated. verbose logical. Indicating if intermediate results or final results should be output to output screen. Details In this simulation, we generate additive-coded genotypes for 3 clusters of SNPs based on a mixture of 3 Bayesian hierarchical models. In cluster +, the minor allele frequency (MAF) θx+ of cases is greater than the MAF θy+ of controls. In cluster 0, the MAF θ0 of cases is equal to the MAF of controls. In cluster −, the MAF θx− of cases is smaller than the MAF θy− of controls. The proportions of the 3 clusters of SNPs are π+ , π0 , and π− , respectively. We assume a “half-flat shape” bivariate prior for the MAF in cluster + 2h+ (θx+ ) h+ (θy+ ) I (θx+ > θy+ ) , where I(a) is hte indicator function taking value 1 if the event a is true, and value 0 otherwise. The function h+ is the probability density function of the beta distribution Beta (α+ , β+ ). We assume θ0 has the beta prior Beta(α0 , β0 ). We also assume a “half-flat shape” bivariate prior for the MAF in cluster − 2h− (θx− ) h− (θy− ) I (θx− > θy− ) . The function h− is the probability density function of the beta distribution Beta (α− , β− ). Given a SNP, we assume Hardy-Weinberg equilibrium holds for its genotypes. That is, given MAF θ, the probabilities of genotypes are P r(geno = 2) = θ2 P r(geno = 1) = 2θ (1 − θ) P r(geno = 0) = (1 − θ) We also assume the genotypes 0n(wild-type), h 1 (heterozygote),ioand 2 (mutation) follows a multino- 2 2 mial distribution M ultinomial 1, θ , 2θ (1 − θ) , (1 − θ) Note that when we generate MAFs from the half-flat shape bivariate priors, we might get very small MAFs or get MAFs > 0.5. In these cased, we then delete this SNP. So the final number of SNPs generated might be less than the initially-set number of SNPs. Value An ExpressionSet object stores genotype data. Author(s) <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>> References <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Model-based clustering for identifying disease-associated SNPs in case-control genome-wide association studies. Scientific Reports 9, Article number: 13686 (2019) https://www.nature.com/articles/s41598-019-50229-6. Examples set.seed(2) esSimDiffPriors = simGenoFuncDiffPriors( nCases = 100, nControls = 100, nSNPs = 500, alpha.p.ca = 2, beta.p.ca = 3, alpha.p.co = 2, beta.p.co = 8, pi.p = 0.1, alpha0 = 2, beta0 = 5, pi0 = 0.8, alpha.n.ca = 2, beta.n.ca = 8, alpha.n.co = 2, beta.n.co = 3, pi.n = 0.1, low = 0.02, upp = 0.5, verbose = FALSE ) print(esSimDiffPriors) pDat = pData(esSimDiffPriors) print(pDat[1:2,]) print(table(pDat$memSubjs)) fDat = fData(esSimDiffPriors) print(fDat[1:2,]) print(table(fDat$memGenes)) print(table(fDat$memGenes2))
highcharts-vue
npm
JavaScript
Highcharts-Vue === *The official Highcharts wrapper for Vue framework.* **This package now also supports Vue 3 and Composition API** 🎉 Table of Contents --- 1. [Getting started](#getting-started) 1. [Requirements](#requirements) 2. [Installation](#installation) 2. [Using](#using) 1. [Registering globally as a plugin](#registering-globally-as-a-plugin) 2. [Registering locally in your component](#registering-locally-in-your-component) 3. [Implementing stockChart, mapChart and ganttChart](#implementing-stockchart-mapchart-and-ganttchart) 4. [Loading maps](#loading-maps) 5. [Changing global component tag name](#changing-global-component-tag-name) 6. [Chart callback parameter](#chart-callback-parameter) 7. [Chart object reference](#chart-object-reference) 8. [Using a specific Highcharts instance](#using-a-specific-highcharts-instance) 3. [Demo apps](#demo-apps) 4. [Online demos](#online-demos) 5. [Component Properties](#component-properties) 6. [Useful links](#useful-links) Getting started --- ### Requirements In order to use `highcharts-vue` you need to have the following installed: * `npm` (installed globally in the OS) * `vue` (version >= 2.0.0) * `highcharts` (*Highcharts package version should be at least `v5.0.11`, but it is always better to keep it up to date.*) ### Installation Install `highcharts-vue` package by: ``` npm install highcharts-vue ``` ### Using There are two ways of adding Highcharts-Vue wrapper to your project: #### Registering globally as a plugin The way described below is recommended when wanted to make a wrapper component available from everywhere in your app. In your main app file should have Vue and Highcharts-Vue packages imported: ``` import Vue from 'vue' import HighchartsVue from 'highcharts-vue' ``` Next, you can register it as a plugin in your Vue object: ``` Vue.use(HighchartsVue) ``` #### Registering locally in your component This option is recommended for direct use in specific components of your app. First, you should import the Chart component object from Highcharts-Vue package in your component file: ``` import { Chart } from 'highcharts-vue' ``` Then, you've to register it in your Vue instance configuration, namely in `components` section: ``` { components: { highcharts: Chart } } ``` *NOTE:* *If you would like to use Highcharts-Vue wrapper by attaching it using `<script>` tag in your `<head>` section of HTML document, of course it is possible and you should use one of .js files from `dist` of this package directory. After that, the `HighchartsVue` object should be available from `window` scope. Here is the example with this way of implementation: [JSFiddle example](https://jsfiddle.net/BlackLabel/ukc2kqnb/)* ### Configure #### Options parameter If you've done one of the above (importing and registering the wrapper), it allows you to use the Highcharts-Vue component in your app, just by adding `<highcharts>` html element, and passing chart configuration object by its `:options` parameter, which is **required**: ``` <highcharts :options="chartOptions"></highcharts> ``` for example: ``` new Vue({ data() { return { chartOptions: { series: [{ data: [1, 2, 3] // sample data }] } } } }) ``` #### Importing Highcharts modules To use any of Highcharts modules, you're obligated to import that module to your file, as well as Highcharts package itself and add that module by passing Highcharts to it, for example: ``` import Highcharts from 'highcharts' import exportingInit from 'highcharts/modules/exporting' exportingInit(Highcharts) ``` Demo: <https://codesandbox.io/s/highcharts-vue-demo-forked-ws2qlc#### Implementing stockChart, mapChart and ganttChart Highcharts-Vue wrapper uses `chart` constructor by default, so if you need to implement `stockChart`, `mapChart` or `ganttChart`, just add `stock`, `map` or `gantt` module as described above and use `:constructor-type` parameter in your html component element: ``` import Highcharts from 'highcharts' import stockInit from 'highcharts/modules/stock' stockInit(Highcharts) ``` ``` <highcharts :constructor-type="'stockChart'" :options="chartOptions"></highcharts> ``` Stock demo: <https://codesandbox.io/s/unruffled-tree-n3qrt8Map demo: <https://codesandbox.io/s/wonderful-northcutt-72jq96Gantt demo: <https://codesandbox.io/s/magical-feather-56lkmv#### Loading maps There are two ways of loading maps and using them with wrapper. You can install the [@highcharts/map-collection](https://www.npmjs.com/package/@highcharts/map-collection) npm package with all maps included, and then import that maps which you would like to use in your project: ``` import Highcharts from 'highcharts' import HighchartsMapModule from 'highcharts/modules/map' import mapData from '@highcharts/map-collection/custom/world.geo.json' HighchartsMapModule(Highcharts) Highcharts.maps['myMapName'] = mapData ``` If you won't install a package with all maps, there is an option to choose necessary map from [Highmaps collection](https://code.highcharts.com/mapdata/) collection and copy a map data into a new file in your project. Then just import it wherever you want, and use it in the same way like above. *The [Demo apps](#demo-apps) included in this repostory show the second approach.* Map demo: <https://codesandbox.io/s/wonderful-northcutt-72jq96#### Changing global component tag name If you would like to use global component tag name other than `<highcharts>`, you could achieve that by passing object with `tagName: [TAG_NAME]` pair as an option argument when registering the plugin, for example: ``` import Vue from 'vue' import HighchartsVue from 'highcharts-vue' Vue.use(HighchartsVue, {tagName: 'charts'}) ``` It allows you to use: ``` <charts :options="chartOptions"></charts> ``` #### Chart callback parameter If you need to use callback from `Highcharts.chart(renderTo, options [, callback])` function, you could pass it by `:callback` parameter through HTML component element: ``` <highcharts :options="chartOptions" :callback="someFunction"> ``` Then, `someFunction` will be called when chart is loaded. #### Chart object reference You can access the Chart object instance if necessary (e.g when need to get some data or use any of `Chart.prototype` functions), by calling specific Vue component instance `chart` field, but it is *not supported* to update the chart using its built-in functions, because that could cause a problems with data synchronization between your app and the chart itself (it disturbs conception of using wrappers). The most recommended way of implementing it, is to use it in the way presented in demo apps. #### Using Highcharts `setOptions()` method If you would like to use `Highcharts.setOptions()` method to define some parameters which would be set globally on all of charts, we recommend you to use it in the main file of your app, although there should be Highcharts package imported before. ``` import Highcharts from 'highcharts'; Highcharts.setOptions({ // options here }) ``` #### Using a specific Highcharts instance Occasionally you'll want to create your charts basing on specific Highcharts version for some reason. Then you can set it up in two different ways, depending on your individual needs. The **first one** is by setting a Highcharts instance while registering a wrapper component as a global plugin, by passing it through the `options` of Vue's install function, as below: ``` import Vue from 'vue' import Highcharts from 'highcharts' import HighchartsVue from 'highcharts-vue' Vue.use(HighchartsVue, { highcharts: Highcharts }) ``` After doing it, all charts will be generated basing on passed instance. A **second way** is to pass the Highcharts instance through the props of `highcharts` component. Then, as a result, only that chart will be generated basing on passed instance: ``` <highcharts :options="chartOptions" :highcharts="hcInstance"></highcharts> ``` ``` import Highcharts from 'highcharts' export default { name: 'app', data() { return { hcInstance: Highcharts, chartOptions: { series: [{ data: [1, 2, 3] }] } } } } ``` *Note that both ways of usage are **optional**, because wrapper automatically uses available Highcharts instance by default from peer dependency.* Demo apps --- If you would like to play with live app created with Highcharts Vue wrapper, or just want to see how it everything should looks like, this repository include the demo examples, which you can simply run locally on your machine. To achieve that, clone this repository, open terminal/console and enter below commands from the repository root level: To run the demo based on Vue v2: ``` npm run build:app-v2 npm run app-v2 ``` or Vue 3: ``` npm run build:app-v3 npm run app-v3 ``` Server always runs at `http://localhost:8080`, unless it's taken by another process. Then you need to manually copy & visit the address displayed in terminal. Online demos --- ### Vue 3 * Basic line: <https://codesandbox.io/s/clever-newton-6c6m3s> * Stock: <https://codesandbox.io/s/unruffled-tree-n3qrt8> * Maps: <https://codesandbox.io/s/wonderful-northcutt-72jq96> * Gantt: <https://codesandbox.io/s/magical-feather-56lkmv### Vue 2 * Basic line: <https://codesandbox.io/s/xenodochial-williamson-w7yvk4> * Stock: <https://codesandbox.io/s/angry-snyder-2k5wff> * Map: <https://codesandbox.io/s/jolly-pare-h7j43z> * Gantt: <https://codesandbox.io/s/youthful-khayyam-c4tylq### Other demos * Using the `chart` object: <https://codesandbox.io/s/hidden-silence-ykkhvk> * Store: <https://codesandbox.io/s/highcharts-vue-demo-zrok6> * NuxtJS (with SSR): <https://codesandbox.io/s/z8jovxx04> * Portals: <https://codesandbox.io/s/highcharts-vue-demo-voo9m> * Synchronized charts: <https://codesandbox.io/s/vue-template-jyp7oComponent Properties --- Here is the list of all available props allowed to pass directly to your `<highcharts>` component instance, which wrapper is able to handle. | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `:options` | Object | yes | Highcharts chart configuration object | | `:constructor-type` | String | no | Chart constructor type using to init specific chart. Allowed options: `'chart'`, `'stockChart'`, `'mapChart'`. First one is set for default. | | `:callback` | Function | no | Function passed as a callback during chart init, and triggered when chart is loaded. | | `:updateArgs` | Array | no | Array of `update()`'s function optional arguments. Parameters should be defined in the same order like in native Highcharts function: `[redraw, oneToOne, animation]`. [Here](https://api.highcharts.com/class-reference/Highcharts.Chart#update) is a more specific description of the parameters. | | `:highcharts` | Object | no | A specific Highcharts instance. It's useful when required to build charts using different Highcharts versions. | | `:deepCopyOnUpdate` | Boolean | no | Whether to make a deep copy of object passed to `Chart.update()` function. In order to avoid passing references of arrays, it's set to **true** by default. ***NOTE:** That can cause a decrease of performance while processing a big amount of data, because copying source data is much expensive, and then it's recommended to disable that option by setting it to `false`.* | Useful links --- * [Highcharts General Documentation](https://www.highcharts.com/docs) * [Highcharts API](https://api.highcharts.com/highcharts/) Readme --- ### Keywords * highcharts * wrapper * vue * component
dvdcoll
ctan
TeX
###### Contents * 1 Simple Example * 2 Class options * 2.1 dvdlabel * 2.2 dvdskip * 2.3 language * 2.4 pagenumbers * 2.5 heading * 2.6 pdfencoding * 3 Environments * 3.1 Dvd * 4 Commands * 4.1 Sectioning commands * 4.1.1 \DvdPart * 4.1.2 \DvdSeries * 4.2 DVD title commands * 4.2.1 \DvdTitle * 4.2.2 \DvdTitleWithDescription * 4.2.3 \Description * 4.2.4 \AutoTitle * 4.2.5 \DvdCounter * 4.2.6 \DvdSpace * 4.3 Spaces, lengths, widths, * 4.3.1 \SetCounterSpace * 4.3.2 \SetTOCSecIndent * 4.3.3 \SetTOCNumwidth * 4.3.4 \SetLRSecNumwidth * 4.4 Misc. commands * 4.4.1 \SetSeason * 4.4.2 \SetThirdColumnAddition * 4.4.3 \listofdvds * 4.4.4 \listofemptydescriptions * 4.4.5 \listoffaultyrecordings * 4.4.6 \SetLFRName * 4.4.7 \pdfmarginnote Simple Example Take a first look to the structure of a file using dvdcoll.cls ``` <documentclass[pagenumbers=yes]{dvdcoll} ``` <usepackage[german]{babel} <usepackage[latin]{inputenc} <usepackage[Tl]{fontenc} <usepackage{textcomp} <usepackage{bera} <begin{document} <tableofcontents ``` <DvdPart{Fernsehserien} <DvdSeries{Jake2.0} <begin{Dvd}{} <DvdTitle{GeburteinesHelden}{40:16} <DvdTitle{ErsteSchritte}{39:45} <DvdTitle{DieChina-Connection}{40:14} <DvdTitle{DieWaffenunddasMadechen}{38:29} <end{Dvd} <begin{Dvd}{} <DwdTitle{DieAkteDumont}{38:50} <DvdTitle{DerFeindinmeinKorper}{39:52} <DvdTitle{Jerry2.0}{39:53} <DvdTitle{DerMittelsmann}{39:21} <end{Dvd} <end{Dcount} ``` You will find a larger example (more details, commands, options,...) in dccexample.<tex/pdf>. As you can see, dvdcoll.cls is quite easy to use! ## 2 Class options The class options will be described will all possible values. The respective default value will be typeset bold. ### dvdlabel \dvdlabel = \(\langle\)**wide**\(\rangle\), \(\langle\)narrow\(\rangle\) By using the option \(\langle\)**wide**\(\rangle\), the given \(\langle\)**label**\(\rangle\) in the environment Dvd will be set on the right side of the table. \(\langle\)**narrow\(\rangle\) will typeset \(\langle\)**label**\(\rangle\) in short distance after the title. ### dvdskip \[\mbox{dvdskip = \langle\mbox{small}\rangle,\langle\mbox{medium}\rangle,\langle\mbox{ big}\rangle}\] The option dvdskip will influence the vertical spacing after each table (environment Dvd). Just play around with the possible values. ### Language \[\mbox{language = \langle\mbox{label}\rangle,anylanguage}\] dvdcoll.cls is designed to deal with several languages. The following table will give an overview over the supported languages at the moment. Feel free to provide others. \begin{tabular}{l l l} languages2 & possible options3 \\ \hline english & \(\langle\mbox{english}\rangle\), \(\langle\mbox{canadian}\rangle\rangle\), \(\langle\mbox{UKenglish}\rangle\), \(\langle\langle\mbox{british}\rangle\rangle\), \(\langle\langle\mbox{Usenglish}\rangle\), \\ & (\(\langle\mbox{american}\rangle\), \(\langle\mbox{australian}\rangle\), \(\langle\mbox{(newzealand}\rangle\))) \\ french & \(\langle\mbox{french}\rangle\), (\(\langle\mbox{french}\rangle\)), (\(\langle\mbox{francais}\rangle\)), (\(\langle\mbox{acadian}\rangle\)), (\(\langle\mbox{canadien}\rangle\)) \\ german & \(\langle\mbox{german}\rangle\), (\(\langle\mbox{german}\rangle\)), \(\langle\mbox{ngerman}\rangle\), \(\langle\mbox{austrian}\rangle\), \(\langle\mbox{naustrian}\rangle\) \\ italian & \(\langle\mbox{italian}\rangle\) \\ polish4 & \(\langle\mbox{polish}\rangle\) \\ portuguese & \(\langle\mbox{portuguese}\rangle\), (\(\langle\mbox{portuguese}\rangle\)), \(\langle\mbox{brazilian}\rangle\), (\(\langle\mbox{brazil}\rangle\)) \\ spanish & \(\langle\mbox{spanish}\rangle\) \\ \hline \end{tabular} Footnote 2: files contributed by <NAME> (french), <NAME> (italian), <NAME> (polish), <NAME> (portuguese), <NAME> (spanish) Footnote 3: At the moment there are no differences between these options. They are provided for compatibility with babel Footnote 4: needs pdfencoding = \(\langle\mbox{unicode}\rangle\) (see: 2.6) The evaluation of the option language will follow these priorities: 1. explicit given value 2. evaluation of the option given to the package babel 3. using option \(\langle\mbox{english}\rangle\) by default So, if you don't specify any language, dvdcoll.cls will try to evaluate the option given to babel. If all that fails, the option \(\langle\mbox{english}\rangle\) will be used! ### 2.4 pagenumbers \[\mbox{pagenumbers = \langle\mbox{yes}\rangle,\langle\mbox{no}\rangle}\] Of course, \(\langle\mbox{yes}\rangle\) will lead to pages with numbers, where as \(\langle\mbox{no}\rangle\) will give no pagenumbers. ### 2.5 heading \[\text{heading = }\langle\text{\bf nonumber}\rangle,\langle\text{\bf number}\rangle\] \[\langle\text{\bf nonumber}\rangle\text{ will give unnumbered headings, while }\langle\text{\bf number}\rangle\text{ will give numbered headings.}\] Tip! If you want to produce a printversion, you should consider the combination of \(\text{\bf pagenumbers = }\langle\text{\bf no}\rangle\) and \(\text{\bf heading = }\langle\text{\bf nonumber}\rangle\). You just have to print the new pages and insert them into your paper mountain. ### 2.6 pdfencoding pdfencoding = \(\langle\text{\bf pdf}\text{\bf docencoding}\rangle\), \(\langle\text{\bf unicode}\rangle\) To secure the correct output in the bookmarks and pdf annotations, a new class option pdfencoding was introduced in dvdcoll.cls v1.1. You can choose between PDFDocEncoding (which is similar to latin1) and Unicode. For the conversion to the respective encoding, dvdcoll.cls is using the command \pdfstringdef from the package hyperref. Unfortunately, this encoding is not trivial and the algorithm that \pdfstringdef is using has a nonlinear complexity. The longer the text input - especially in descriptions - the longer takes the run time of the algorithm in overproportional manner. Therefore dvdcoll.cls has a simplified - but run time optimized - version of this command, which unfortunately only works with PDFDocEncoding. Whenever possible, dvdcoll.cls should be used with PDFDocEncoding. Unfortunately, this is just possible for languages, which use only characters contained in PDFDocEncoding. On the whole, these are the languages of western Europe. That's why the support of polish is just possible with the option \(\langle\text{\bf unicode}\rangle\). Because of the problems described above with Unicode, it's recommended to keep the description texts as short as possible, which leads of course to a conflict between text length and usability. Finally, i would like to point to the fact, that there is no relation between input encoding (like utf8) and the option \(\langle\text{\bf unicode}\rangle\), i.e. it's possible to compile unicode-encoded files with the option \(\langle\text{\bf pdf}\text{\bf docencoding}\rangle\). But one is confined to the characters contained in PDFDocEncoding. ## 3 Environments ### 3.1 Dvd Now we arrived at the central part of dvdcoll.cls. The environment Dvd is used to define the DVDs. With the argument \(\{\langle\text{\bf title}\rangle\}\) you can specify a title, but you don't have to do. If \(\{\langle\text{\bf title}\rangle\}\) is left empty, dvdcoll.cls will create titles automatically by the series - specified in \(\backslash\)DvdSeries (see: 4.1.2) - followed by a counter, which is reset by every new dvd series. There are some other commands you can use in\(\{\langle\mathit{title}\rangle\}\), if you wish to have more influence in the process of setting the title automatically. (see: 4.2.4, 4.2.5 and 4.2.6) \(\{\langle\mathit{label}\rangle\}\) can be used to set the label you are using in your archives, e.g. DVD12. By default the label will be typeset bold enclosed by brackets5. You can change that by redefining \dc@print@dvdlabel. Keep in mind that you can influence the typesetting with the class option dvdlabel. (see: 2.1) There is also the possibility of automatic creation of labels with the command options of \DvdSeries. (see: 4.1.2) Footnote 5: Of course, the brackets are not typeset, if no label is specified. ## 4 Commands ### Sectioning commands The following commands can be used for structuring your archives. #### 4.1.1 \DvdPart You can split up your archives into different parts like tv series, documentaries and so on. You just have to use \DvdPart. #### 4.1.2 \DvdSeries Additionally, you can specify a dvd series, e.g. Star Trek - The Next Generation. Keep in mind that \(\{\langle\mathit{series}\rangle\}\) can be used in automatic titling! (see: 3.1) The optional arguments \(\{\langle\mathit{dvdnumbering}\rangle\}\) and \(\{\langle\mathit{title}\rangle\underline{\langle\mathit{title}\rangle\underline{ \langle\mathit{height}\rangle}}\}\) can both influence the style of numbering in Dvd and the \DvdTitle commands with the values \(\langle\mathit{normal}\rangle\) and \(\langle\mathit{season}\rangle\). In the case of \(\langle\mathit{season}\rangle\), the Dvd counter will be typeset e.g. 'J.A.G. 2.1', where as the titles will be typeset '01x15 Hemlock'. You can change the output format of the counters by redefining \dc@print@counter. Setting \(\{\langle\mathit{dvdnumering}\rangle\}\) with the value \(\langle\mathit{season}\rangle\) will insert a new level 'Season' into the bookmarks and group the DVDs into the season. The \(\{\langle\mathit{labelbase}\rangle\}\)* command options can be used for automatic label creation. These labels will have the following format: \[\{\langle\mathit{labelbaseprefix}\rangle\}\,\{\langle\mathit{labelbase} \rangle\}\,\{\langle\mathit{labelbasesuffix}\rangle\}\] where \(\{\langle\mathit{labelbase}\rangle\}\) will have the length of \(\{\langle\mathit{labelbaselength}\rangle\}\) digits, e.g. RW01, RW02,... (labelbase=1, labelbaselength=2 (default: 4), labelbaseprefix=RW). If you want to produce a DVD list with \listofdvds (see: 4.4.3) it is advisable to create labels with the same length all over your document to avoid a ugly looking list. ### DVD title commands #### 4.2.1\DvdTitle \DvdTitle is used to specify the respective titles ({(title)}) on your dvd (within environment Dvd). {\length} is used to typeset the length (e.g. 43:12) and in general followed by the addition **min**. You can change that by using \SetThirdColumnAddition. (see: 4.4.2) You can use the argument {\length} to mark the title as faulty or missing. Additionally, the title will be included in the LFR (List of faulty recordings). (see: 4.4.5) All supported languages (see: 2.3) at the moment use the letter **F** as marker. #### 4.2.2\DvdTitleWithDescription \DvdTitleWithDescription is equivalent to \DvdTitle apart from the fact, that {(title)} will have a link to a pdf annotation with a description of the recording. (see: 4.2.3) #### 4.2.3\Description \Description(\description) You have to use \Description before \DvdTitleWithDescription (see: 4.2.2) to specify the {\description}, which will be typeset into a pdf annotation. #### 4.2.4\Autofitte \Autofitte If you want to add an extra title to the automatically generated dvd titles in Dvd, you can use \Autofitte in the argument {(title)} and simply add your extra title. #### 4.2.5\DvdCounter \DvdCounter will provide the dvd counter with correct spacing, if you want to leave the process of automatic titles. #### 4.2.6\DvdSpace \DvdSpace can be used to get the same space, that is used within the process of automatic titling. By default, it is set to **0.7em**. You can change that by using \SetCounterSpace. (see: 4.3.1) ### Spaces, lengths, widths,... #### 4.3.1\SetCounterSpace \SetCounterSpace can be used to change the standard space used within the {(width)} process of automatic titling, which is by default set to **0.7em**. ## References * URL: [http://partners.adobe.com/public/developer/en/pdf/PDFReference16.pdf](http://partners.adobe.com/public/developer/en/pdf/PDFReference16.pdf) * URL: [http://partners.adobe.com/public/developer/en/acrobat/sdk/pdf/javascript/AcroJ5.pdf](http://partners.adobe.com/public/developer/en/acrobat/sdk/pdf/javascript/AcroJ5.pdf) * ISBN 3-8266-0785-6 * ISBN 3-936427-45-3 * ISBN 3-8273-7166-X * ISBN 3-7723-6109-9 **Y** yes, class option value 4
github.com/pilagod/gorm-cursor-paginator
go
Go
README [¶](#section-readme) --- ### gorm-cursor-paginator [Build Status](https://travis-ci.org/pilagod/gorm-cursor-paginator) [Coverage Status](https://coveralls.io/github/pilagod/gorm-cursor-paginator?branch=master) [Go Report Card](https://goreportcard.com/report/github.com/pilagod/gorm-cursor-paginator) [Codacy Badge](https://app.codacy.com/app/pilagod/gorm-cursor-paginator?utm_source=github.com&utm_medium=referral&utm_content=pilagod/gorm-cursor-paginator&utm_campaign=Badge_Grade_Dashboard) A paginator doing cursor-based pagination based on [GORM](https://github.com/jinzhu/gorm) #### Installation ``` go get -u github.com/pilagod/gorm-cursor-paginator ``` #### Usage by Example > For more comprehensive examples, you can check [example/main.go](https://github.com/pilagod/gorm-cursor-paginator/raw/master/example/main.go) and [paginator_test.go](https://github.com/pilagod/gorm-cursor-paginator/raw/master/paginator_test.go) Assume there is an query struct for paging: ``` type PagingQuery struct { After *string Before *string Limit *int Order *string } ``` and a GORM model: ``` type Model struct { ID int CreatedAt time.Time } ``` You can simply build up a new cursor paginator from the PagingQuery like: ``` import ( paginator "github.com/pilagod/gorm-cursor-paginator" ) func GetModelPaginator(q PagingQuery) *paginator.Paginator { p := paginator.New() p.SetKeys("CreatedAt", "ID") // [default: "ID"] (supporting multiple keys, order of keys matters) if q.After != nil { p.SetAfterCursor(*q.After) // [default: nil] } if q.Before != nil { p.SetBeforeCursor(*q.Before) // [default: nil] } if q.Limit != nil { p.SetLimit(*q.Limit) // [default: 10] } if q.Order != nil && *q.Order == "asc" { p.SetOrder(paginator.ASC) // [default: paginator.DESC] } return p } ``` Then you can start to do pagination easily with GORM: ``` func Find(db *gorm.DB, q PagingQuery) ([]Model, paginator.Cursor, error) { var models []Model stmt := db.Where(/* ... other filters ... */) stmt = db.Or(/* ... more other filters ... */) // get paginator for Model p := GetModelPaginator(q) // use GORM-like syntax to do pagination result := p.Paginate(stmt, &models) if result.Error != nil { // ... } // get cursor for next iteration cursor := p.GetNextCursor() return models, cursor, nil } ``` After paginating, you can call `GetNextCursor()`, which returns a `Cursor` struct containing cursor for next iteration: ``` type Cursor struct { After *string `json:"after"` Before *string `json:"before"` } ``` That's all ! Enjoy your paging in the GORM world 🎉 #### License © <NAME> (pilagod), 2018-NOW Released under the [MIT License](https://github.com/pilagod/gorm-cursor-paginator/raw/master/LICENSE) Documentation [¶](#section-documentation) --- ### Index [¶](#pkg-index) * [Variables](#pkg-variables) * [func Decode(cursor string) []interface{}](#Decode) * [func Encode(v reflect.Value, keys []string) string](#Encode) * [type Cursor](#Cursor) * [type CursorDecoder](#CursorDecoder) * + [func NewCursorDecoder(ref interface{}, keys ...string) (CursorDecoder, error)](#NewCursorDecoder) * [type CursorEncoder](#CursorEncoder) * + [func NewCursorEncoder(keys ...string) CursorEncoder](#NewCursorEncoder) * [type Order](#Order) * [type Paginator](#Paginator) * + [func New() *Paginator](#New) * + [func (p *Paginator) GetNextCursor() Cursor](#Paginator.GetNextCursor) + [func (p *Paginator) Paginate(stmt *gorm.DB, out interface{}) *gorm.DB](#Paginator.Paginate) + [func (p *Paginator) SetAfterCursor(afterCursor string)](#Paginator.SetAfterCursor) + [func (p *Paginator) SetBeforeCursor(beforeCursor string)](#Paginator.SetBeforeCursor) + [func (p *Paginator) SetKeys(keys ...string)](#Paginator.SetKeys) + [func (p *Paginator) SetLimit(limit int)](#Paginator.SetLimit) + [func (p *Paginator) SetOrder(order Order)](#Paginator.SetOrder) ### Constants [¶](#pkg-constants) This section is empty. ### Variables [¶](#pkg-variables) ``` var ( ErrInvalidDecodeReference = [errors](/errors).[New](/errors#New)("decode reference should be struct") ErrInvalidField = [errors](/errors).[New](/errors#New)("invalid field") ErrInvalidOldField = [errors](/errors).[New](/errors#New)("invalid old field") ) ``` Errors for decoders ### Functions [¶](#pkg-functions) #### func [Decode](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/util.go#L24) [¶](#Decode) added in v1.1.1 ``` func Decode(cursor [string](/builtin#string)) []interface{} ``` Decode decodes cursor into values in the same order as encoding Deprecated: Decode will remove in v2, use CursorDecoder instead #### func [Encode](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/util.go#L18) [¶](#Encode) added in v1.1.1 ``` func Encode(v [reflect](/reflect).[Value](/reflect#Value), keys [][string](/builtin#string)) [string](/builtin#string) ``` Encode encodes properties in order defined by keys on the struct of v Deprecated: Encode will remove in v2, use CursorEncoder instead ### Types [¶](#pkg-types) #### type [Cursor](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/cursor.go#L4) [¶](#Cursor) added in v1.0.0 ``` type Cursor struct { After *[string](/builtin#string) `json:"after" query:"after"` Before *[string](/builtin#string) `json:"before" query:"before"` } ``` Cursor cursor data #### type [CursorDecoder](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/cursor_decoder.go#L14) [¶](#CursorDecoder) added in v1.2.0 ``` type CursorDecoder interface { Decode(cursor [string](/builtin#string)) []interface{} } ``` CursorDecoder decoder for cursor #### func [NewCursorDecoder](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/cursor_decoder.go#L19) [¶](#NewCursorDecoder) added in v1.2.0 ``` func NewCursorDecoder(ref interface{}, keys ...[string](/builtin#string)) ([CursorDecoder](#CursorDecoder), [error](/builtin#error)) ``` NewCursorDecoder creates cursor decoder #### type [CursorEncoder](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/cursor_encoder.go#L13) [¶](#CursorEncoder) added in v1.2.0 ``` type CursorEncoder interface { Encode(v interface{}) [string](/builtin#string) } ``` CursorEncoder encoder for cursor #### func [NewCursorEncoder](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/cursor_encoder.go#L18) [¶](#NewCursorEncoder) added in v1.2.0 ``` func NewCursorEncoder(keys ...[string](/builtin#string)) [CursorEncoder](#CursorEncoder) ``` NewCursorEncoder creates cursor encoder #### type [Order](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/order.go#L4) [¶](#Order) added in v1.0.1 ``` type Order [string](/builtin#string) ``` Order type for order ``` const ( ASC [Order](#Order) = "ASC" DESC [Order](#Order) = "DESC" ) ``` Orders #### type [Paginator](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L23) [¶](#Paginator) ``` type Paginator struct { // contains filtered or unexported fields } ``` Paginator a builder doing pagination #### func [New](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L18) [¶](#New) ``` func New() *[Paginator](#Paginator) ``` New inits paginator #### func (*Paginator) [GetNextCursor](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L58) [¶](#Paginator.GetNextCursor) added in v1.0.0 ``` func (p *[Paginator](#Paginator)) GetNextCursor() [Cursor](#Cursor) ``` GetNextCursor returns cursor for next pagination #### func (*Paginator) [Paginate](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L63) [¶](#Paginator.Paginate) ``` func (p *[Paginator](#Paginator)) Paginate(stmt *[gorm](/github.com/jinzhu/gorm).[DB](/github.com/jinzhu/gorm#DB), out interface{}) *[gorm](/github.com/jinzhu/gorm).[DB](/github.com/jinzhu/gorm#DB) ``` Paginate paginates data #### func (*Paginator) [SetAfterCursor](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L33) [¶](#Paginator.SetAfterCursor) ``` func (p *[Paginator](#Paginator)) SetAfterCursor(afterCursor [string](/builtin#string)) ``` SetAfterCursor sets paging after cursor #### func (*Paginator) [SetBeforeCursor](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L38) [¶](#Paginator.SetBeforeCursor) ``` func (p *[Paginator](#Paginator)) SetBeforeCursor(beforeCursor [string](/builtin#string)) ``` SetBeforeCursor sets paging before cursor #### func (*Paginator) [SetKeys](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L43) [¶](#Paginator.SetKeys) ``` func (p *[Paginator](#Paginator)) SetKeys(keys ...[string](/builtin#string)) ``` SetKeys sets paging keys #### func (*Paginator) [SetLimit](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L48) [¶](#Paginator.SetLimit) ``` func (p *[Paginator](#Paginator)) SetLimit(limit [int](/builtin#int)) ``` SetLimit sets paging limit #### func (*Paginator) [SetOrder](https://github.com/pilagod/gorm-cursor-paginator/blob/v1.3.0/paginator.go#L53) [¶](#Paginator.SetOrder) ``` func (p *[Paginator](#Paginator)) SetOrder(order [Order](#Order)) ``` SetOrder sets paging order
PolarCAP
cran
R
Package ‘PolarCAP’ July 10, 2023 Title Access the Polarization in Comparative Attitudes Project Version 1.0.1 Description Distributes data from the Polarization in Comparative Attitudes Project. Helper functions enable data retrieval in wide and tidy formats for user-defined countries and years. Provides support for case-insensitive country names in many languages. Mehlhaff (2022) <https: //imehlhaff.net/files/Polarization%20and%20Democracy.pdf>. License CC0 Encoding UTF-8 RoxygenNote 7.2.0 URL https://github.com/imehlhaff/PolarCAP BugReports https://github.com/imehlhaff/PolarCAP/issues Depends R (>= 2.10) Imports tidyr, countrycode NeedsCompilation no Author <NAME> [aut, cre, cph] (<https://orcid.org/0000-0001-5776-005X>) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-07-10 16:10:12 UTC R topics documented: get.PolarCA... 2 melt.PolarCA... 3 to.ISO... 4 get.PolarCAP Retrieve PolarCAP Data Description Retrieves PolarCAP data for defined countries and years. Returns data in wide format. For tidy format, use melt.PolarCAP(). Usage get.PolarCAP( countries = NA, years = NA, type = c("ideology", "affect"), value.only = FALSE, include.se = FALSE ) Arguments countries a character vector of countries to be retrieved. See Details. years a numeric vector of years to be retrieved. type a character vector indicating which polarization estimates should be returned. Must be "ideology", "affect", or both. value.only a logical indicating whether get.PolarCAP() should return a data frame of re- sults (FALSE, the default) or a single estimate as a scalar (TRUE). include.se a logical indicating whether standard errors should be returned. Defaults to FALSE. Details Ideally, country names passed to countries would be ISO 3166-1 alpha-3 country codes (case- insensitive). However, get.PolarCAP() will accept country names in almost any language or for- mat and attempt to convert them to ISO3 codes by calling to.ISO3(). get.PolarCAP() will alert the user to any country names still unrecognized after this conversion and return results only for those which are recognized. Value If value.only = FALSE, get.PolarCAP() returns a data frame with columns corresponding to country names, country ISO3 codes, years, polarization estimates for the polarization type(s) given in type, and associated standard errors (if include.se = TRUE). If value.only = TRUE, get.PolarCAP() returns a scalar polarization estimate for the polarization type given in type. Examples get.PolarCAP("USA", c(2018, 2019), "ideology", include.se = TRUE) get.PolarCAP("USA", c(2018, 2019), c("ideology", "affect"), include.se = TRUE) countries <- rep(c("MEX", "USA"), each = 2) years <- rep(c(2018, 2019), 2) data <- as.data.frame(cbind(countries, years)) data$ideology1 <- apply(data, 1, function(x) get.PolarCAP(x[1], x[2], type = "ideology", value.only = TRUE)) data melt.PolarCAP Retrieve Tidy PolarCAP Data Description Retrieves PolarCAP data for defined countries and years. Returns data in tidy format. For wide format, or to return a polarization estimate as a scalar, use get.PolarCAP(). Usage melt.PolarCAP( countries = NA, years = NA, type = c("ideology", "affect"), include.se = FALSE ) Arguments countries a character vector of countries to be retrieved. See Details. years a numeric vector of years to be retrieved. type a character vector indicating which polarization estimates should be returned. Must be "ideology", "affect", or both. include.se a logical indicating whether standard errors should be returned. Defaults to FALSE. Details Ideally, country names passed to countries would be ISO 3166-1 alpha-3 country codes (case- insensitive). However, melt.PolarCAP() will accept country names in almost any language or format and attempt to convert them to ISO3 codes by calling to.ISO3(). melt.PolarCAP() will alert the user to any country names still unrecognized after this conversion and return results only for those which are recognized. Value a data frame with columns corresponding to country names, country ISO3 codes, years, polarization types given in type, polarization estimates, and associated standard errors (if include.se = TRUE). Examples melt.PolarCAP("USA", c(2018, 2019), "ideology", include.se = TRUE) melt.PolarCAP("USA", c(2018, 2019), c("ideology", "affect"), include.se = TRUE) to.ISO3 Convert Country Names for PolarCAP Retrieval Description Checks if requested countries are formatted correctly for PolarCAP and attempts to convert them to ISO 3166-1 alpha-3 country codes if not. Usage to.ISO3(countries) Arguments countries a character vector of countries to be checked (case-insensitive). Value a character vector of length equal to that of countries. Examples to.ISO3(c("ALB", "aus", "united states"))
MPV
cran
R
Package ‘MPV’ September 5, 2023 Title Data Sets from Montgomery, Peck and Vining Version 1.63 Author <NAME> and <NAME> Description Most of this package consists of data sets from the textbook Introduction to Linear Regression Analysis, by Montgomery, Peck and Vining. All data sets from the 3rd edition are included and many from the 6th edition are also included. The package also contains some additional data sets and functions. Maintainer <NAME> <<EMAIL>> LazyLoad true LazyData true Depends R (>= 3.5.0), lattice, KernSmooth, randomForest ZipData no License Unlimited NeedsCompilation no Repository CRAN Date/Publication 2023-09-05 11:10:05 UTC R topics documented: BCCIPlo... 4 BCLPBia... 5 BiasVarPlo... 6 BioOxyDeman... 7 b... 7 cemen... 8 cigbutt... 9 earthquak... 9 fire... 10 GANOV... 11 gasdat... 11 GFplo... 12 GRegplo... 13 Julie... 15 lengthguesse... 16 lesion... 17 LPBia... 18 moto... 18 noisyimag... 19 oldwas... 20 p11.1... 21 p11.1... 22 p12.1... 22 p12.1... 23 p12.1... 24 p12.... 25 p13.... 25 p13.1... 26 p13.... 27 p13.2... 27 p13.... 28 p13.... 29 p13.... 29 p13.... 30 p13.... 31 p14.... 32 p14.... 32 p15.... 33 p2.1... 34 p2.1... 34 p2.1... 35 p2.1... 36 p2.1... 37 p2.1... 38 p2.1... 39 p2.1... 39 p2.... 40 p2.... 41 p4.1... 42 p4.1... 43 p4.2... 44 p5.... 45 p5.1... 45 p5.1... 46 p5.1... 47 p5.1... 48 p5.... 49 p5.2... 49 p5.2... 50 p5.2... 51 p5.2... 51 p5.... 52 p5.... 53 p5.... 54 p7.... 54 p7.1... 55 p7.1... 56 p7.1... 56 p7.1... 57 p7.1... 58 p7.1... 58 p7.1... 59 p7.... 60 p7.2... 61 p7.... 61 p7.... 62 p8.1... 63 p8.1... 63 p8.... 64 p9.1... 65 pathoe... 66 PRES... 66 qqANOV... 67 quadlin... 68 Qyplo... 69 rado... 70 rectangle... 71 rftes... 72 seismictiming... 72 softdrin... 73 sola... 74 stai... 74 table.b... 75 table.b1... 76 table.b1... 77 table.b1... 78 table.b1... 78 table.b1... 79 table.b1... 80 table.b1... 81 table.b1... 81 table.b1... 82 table.b1... 83 table.b... 84 table.b2... 84 table.b2... 85 table.b2... 86 table.b2... 87 table.b2... 87 table.b... 88 table.b... 89 table.b... 90 table.b... 91 table.b... 92 table.b... 93 table.b... 94 tarimag... 95 tplo... 95 tree.sampl... 96 Uplo... 97 width... 98 windWin8... 98 Wpgtem... 99 wxNW... 99 BCCIPlot Confidence Intervals for Bias Corrected Local Regression Description Graphs of confidence interval estimates for bias and standard deviation of in bias-corrected local polynomial regression curve estimates. Usage BCCIPlot(data, k1=1, k2=2, h, h2, output, g, layout, incl.biasplot, plotdata) Arguments data A data frame, whose first column must be the explanatory variable and whose second column must be the response variable. k1 degree of local polynomial used in curve estimator. k2 degree of local polynomial used in bias estimator. h bandwidth for regression estimator. h2 bandwidth for bias estimator. output if TRUE, numeric output is printed to the console window. g the target function, if known (for use in simulations). layout if TRUE, a 2x1 layout of plots is sent to the graphics device. incl.biasplot if TRUE, the confidence intervals for the bias of the uncorrected estimate are plotted. plotdata if TRUE, the data points are plotted as a scatter plot. Value A list containing the confidence interval limits, pointwise estimates of bias, standard deviation of bias, curve estimate, standard deviation of curve estimate, and approximate confidence limits for curve estimates. Graphs of the curve estimate confidence limits and the bias confidence limits. Author(s) W. <NAME> and <NAME> BCLPBias Bias for Bias-Corrected Local Polynomial Regression Description Confidence interval estimates for bias in local polynomial regression. Usage BCLPBias(xy,k1,k2,h,h2,numgrid=401,alpha=.95) Arguments xy A data frame, whose first column must be the explanatory variable and whose second column must be the response variable. k1 degree of local polynomial used in curve estimator. k2 degree of local polynomial used in bias estimator. h bandwidth for regression estimator. h2 bandwidth for bias estimator. numgrid number of gridpoints used in the curve estimator. alpha nominal confidence level. Value A list containing the confidence interval limits, pointwise estimates of bias, standard deviation of bias, curve estimate, standard deviation of curve estimate, and approximate confidence limits for curve estimates and corresponding bias-corrected estimates. Author(s) <NAME> and <NAME> BiasVarPlot Local Polynomial Bias and Variability Description Graphs of confidence interval estimates for bias and standard deviation of in local polynomial re- gression curve estimates. Usage BiasVarPlot(data, k1=1, k2=2, h, h2, output=FALSE, g, layout=TRUE) Arguments data A data frame, whose first column must be the explanatory variable and whose second column must be the response variable. k1 degree of local polynomial used in curve estimator. k2 degree of local polynomial used in bias estimator. h bandwidth for regression estimator. h2 bandwidth for bias estimator. output if true, numeric output is printed to the console window. g the target function, if known (for use in simulations). layout if true, a 2x1 layout of plots is sent to the graphics device. Value A list containing the confidence interval limits, pointwise estimates of bias, standard deviation of bias, curve estimate, standard deviation of curve estimate, and approximate confidence limits for curve estimates. Graphs of the curve estimate confidence limits and the bias confidence limits. Author(s) <NAME> and <NAME> BioOxyDemand Biochemical Oxygen Demand Description The BioOxyDemand data frame has 14 rows and 2 columns. Usage data(BioOxyDemand) Format This data frame contains the following columns: x a numeric vector y a numeric vector Source <NAME>. (2000) Probability and Statistics for Engineering and the Sciences (5th ed), Duxbury Examples plot(BioOxyDemand) summary(lm(y ~ x, data = BioOxyDemand)) bp Blood Pressure Measurements on a Single Adult Male Description Systolic and diastolic blood pressure measurement readings were taken on a 56-year-old male over a 39 day period, sometimes in the mornings (AM) and sometimes in the evening (PM). Varying number of replicate measurements were taken at each time point. Usage bp Format A data frame with 121 observations on the following 4 variables. TimeofDay factor with levels AM and PM Date numeric Systolic numeric Diastolic numeric Examples require(lattice) xyplot(Date ~ Diastolic|TimeofDay, groups=cut(Systolic, c(0, 130, 140, 200)), data = bp, col=c(3, 1, 2), pch=16) matplot(bp[, c(3, 4)], type="l", lwd=2, ylab="Pressure") n <- nrow(bp) abline(v=(1:n)[bp[,1]=="PM"]-.5, col="grey") abline(v=(1:n)[bp[,1]=="PM"], col="grey") abline(v=(1:n)[bp[,1]=="PM"]+.5, col="grey") bp.stk <- stack(bp, c("Systolic", "Diastolic")) bp.tmp <- rbind(bp[,1:2], bp[,1:2]) bp.stk <- cbind(bp.tmp, bp.stk) names(bp.stk) <- c("TimeofDay", "Date", "Pressure", "Type") reps <- NULL for (j in rle(paste(bp.stk$Date, bp.stk$TimeofDay))$lengths) reps <- c(reps, (1:j)) bp.stk$Rep <- reps xyplot(Pressure ~ I(Date+Rep/24)|TimeofDay, groups=Type, data = bp.stk, xlab="Date", pch=16) cement Table B21 - Cement Data Description The cement data frame has 13 rows and 5 columns. Usage data(cement) Format This data frame contains the following columns: y a numeric vector x1 a numeric vector x2 a numeric vector x3 a numeric vector x4 a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(cement) pairs(cement) cigbutts Cigarette Butts Description On a university campus there are a number of areas designated for smoking. Outside of those areas, smoking is not permitted. One of the smoking areas is towards the north end of the campus near some parking lots and a large walkway towards one of the residences. Along the walkway, cigarette butts are visible in the nearby grass. Numbers of cigarette butts were counted at various distances from the smoking area in 200x80 square-cm quadrats located just west of the walkway. Usage data("cigbutts") Format A data frame with 15 observations on the following 2 variables. distance distance from gazebo count observed number of butts earthquake Earthquakes Data Description The earthquake data frame contains measurements of latitude, longitude, focal depth and magnitude for all earthquakes having magnitude greater than 5.8 between 1964 and 1985. Usage earthquake Format This data frame contains 2178 observations on the following columns: depth numeric vector of focal depths. latitude latitudinal coordinate. longitude longitudinal coordinate. magnitude numeric vector of magnitudes. Source <NAME> (1996), Smoothing Methods in Statistics, Springer-Verlag, New York. Examples summary(earthquake) fires Micro-fires recorded in a lab setting Description Rate of spread measurements (inches/s) in each direction: East, West, North and South for each of 31 experimental runs at given slopes, measured over the given time period of each (measured in seconds). Usage fires Format A data frame with 31 observations on the following 7 variables. Run numeric Slope numeric: vertical rise divided by horizontal run, inclined from East to West ROS_E numeric: rate of spread measured in easterly direction ROS_W numeric: rate of spread measured in westerly direction ROS_S numeric: rate of spread measured in southerly direction ROS_N numeric: rate of spread measured in northerly direction Time numeric Source <NAME>. and <NAME>. (2013) Assessing a stochastic fire spread simulator. Journal of Environmental Informatics. 22:1-12. GANOVA Graphical ANOVA Plot Description Graphical analysis of one-way ANOVA data. It allows visualization of the usual F-test. Usage GANOVA(dataset, var.equal=TRUE, type="QQ", center=TRUE, shift=0) Arguments dataset A data frame, whose first column must be the factor variable and whose second column must be the response variable. var.equal Logical: if TRUE, within-sample variances are assumed to be equal type "QQ" or "hist" center if TRUE, center and scale the means to match the scale of the errors shift on the histogram, lift the points representing the means above the horizontal axis by this amount. Value A QQ-plot or a histogram and rugplot Author(s) <NAME> and <NAME> Source Braun, W.J. 2013. Naive Analysis of Variance. Journal of Statistics Education. gasdata Natural Gas Consumption in a Single-Family Residence Description This data frame contains the average monthly volume of natural gas used in the furnace of a 1600 square foot house located in London, Ontario, for each month from 2006 until 2011. It also contains the average temperature for each month, and a measure of degree days. Insulation was added to the roof on one occasions, the walls were insulated on a second occasion, and the mid-efficiency furnace was replaced with a high-efficiency furnace on a third occasion. Usage data("gasdata") Format A data frame with 70 observations on the following 9 variables. month numeric 1=January, 12=December degreedays numeric, Celsius cubicmetres total volume of gas used in a month dailyusage average amount of gas used per day temp average temperature in Celsius year numeric I1 indicator that roof insulation is present I2 indicator that wasll insulation is present I3 indicator that high efficiency furnace is present GFplot Graphical F Plot for Significance in Regression Description This function analyzes regression data graphically. It allows visualization of the usual F-test for significance of regression. Usage GFplot(X, y, plotIt=TRUE, sortTrt=FALSE, type="hist", includeIntercept=TRUE, labels=FALSE) Arguments X The design matrix. y A numeric vector containing the response. plotIt Logical: if TRUE, a graph is drawn. sortTrt Logical: if TRUE, an attempt is made at sorting the predictor effects in descend- ing order. type "QQ" or "hist" includeIntercept Logical: if TRUE, the intercept effect is plotted; otherwise, it is omitted from the plot. labels logical: if TRUE, names of predictor variables are used as labels; otherwise, the design matrix column numbers are used as labels Value A QQ-plot or a histogram and rugplot, or a list if plotIt=FALSE Author(s) <NAME> Source Braun, W.J. 2013. Regression Analysis and the QR Decomposition. Preprint. Examples # Example 1 X <- p4.18[,-4] y <- p4.18[,4] GFplot(X, y, type="hist", includeIntercept=FALSE) title("Evidence of Regression in the Jojoba Oil Data") # Example 2 set.seed(4571) Z <- matrix(rnorm(400), ncol=10) A <- matrix(rnorm(81), ncol=9) simdata <- data.frame(Z[,1], crossprod(t(Z[,-1]),A)) names(simdata) <- c("y", paste("x", 1:9, sep="")) GFplot(simdata[,-1], simdata[,1], type="hist", includeIntercept=FALSE) title("Evidence of Regression in Simulated Data Set") # Example 3 GFplot(table.b1[,-1], table.b1[,1], type="hist", includeIntercept=FALSE) title("Evidence of Regression in NFL Data Set") # An example where stepwise AIC selects the complement # of the set of variables that are actually in the true model: X <- pathoeg[,-10] y <- pathoeg[,10] par(mfrow=c(2,2)) GFplot(X, y) GFplot(X, y, sortTrt=TRUE) GFplot(X, y, type="QQ") GFplot(X, y, sortTrt=TRUE, type="QQ") X <- table.b1[,-1] # NFL data y <- table.b1[,1] GFplot(X, y) GRegplot Graphical Regression Plot Description This function analyzes regression data graphically. It allows visualization of the usual F-test for significance of regression. Usage GRegplot(X, y, sortTrt=FALSE, includeIntercept=TRUE, type="hist") Arguments X The design matrix. y A numeric vector containing the response. sortTrt Logical: if TRUE, an attempt is made at sorting the predictor effects in descend- ing order. includeIntercept Logical: if TRUE, the intercept effect is plotted; otherwise, it is omitted from the plot. type Character: hist, for histogram; dot, for stripchart Value A histogram or dotplot and rugplot Author(s) <NAME> Source Braun, W.J. 2014. Visualization of Evidence in Regression Analysis with the QR Decomposition. Preprint. Examples # Example 1 X <- p4.18[,-4] y <- p4.18[,4] GRegplot(X, y, includeIntercept=FALSE) title("Evidence of Regression in the Jojoba Oil Data") # Example 2 set.seed(4571) Z <- matrix(rnorm(400), ncol=10) A <- matrix(rnorm(81), ncol=9) simdata <- data.frame(Z[,1], crossprod(t(Z[,-1]),A)) names(simdata) <- c("y", paste("x", 1:9, sep="")) GRegplot(simdata[,-1], simdata[,1], includeIntercept=FALSE) title("Evidence of Regression in Simulated Data Set") # Example 3 GRegplot(table.b1[,-1], table.b1[,1], includeIntercept=FALSE) title("Evidence of Regression in NFL Data Set") # An example where stepwise AIC selects the complement # of the set of variables that are actually in the true model: X <- pathoeg[,-10] y <- pathoeg[,10] par(mfrow=c(2,1)) GRegplot(X, y) GRegplot(X, y, sortTrt=TRUE) X <- table.b1[,-1] # NFL data y <- table.b1[,1] GRegplot(X, y) Juliet Juliet Description Juliet has 28 rows and 9 columns. The data is of the input and output of the Spirit Still "Juliet" from Endless Summer Distillery. It is suggested to split the data by the Batch factor for ease of use. Usage Juliet Format The data frame contains the following 9 columns. Batch a Factor determing how many times the volume has been through the still. Vol1 Volume in litres, initial P1 Percent alcohol present, initial LAA1 Litres Absolute Alcohol initial, Vol1*P1 Vol2 Volume in litres, final P2 Percent alcohol present, final LAA2 Litres Absolute Alcohol final, Vol2*P2 Yield Percent yield obtained, LAA2/LAA1 Date Character, Date of run Details The purpose of this information is to determine the optimal initial volume and percentage. The information is broken down by Batch. A batch factor 1 means that it is the first time the liquid has gone through the spirit still. The first run through the still should have the most loss due to the "heads" and "tails". Literature states that the first run through a spirit still should yield 70 percent. A batch factor 2 means that it is the second time the liquid has gone through the spirit still. A batch factor 3 means that it is the third time or more that the liquid has gone through the spirit still. Each subsequent distillation should result in a higher yield, never to exceed 95 percent. Source <NAME>, Endless Summer Distillery, (2015). Examples summary(Juliet) #Split apart the Batch factor for easier use. juliet<-split(Juliet,Juliet$Batch) juliet1<-juliet$'1' juliet2<-juliet$'2' juliet3<-juliet$'3' plot(LAA1~LAA2,data=Juliet) plot(LAA1~LAA2,data=juliet1) lengthguesses Length Guesses Data Description The lengthguesses list consists of 2 numeric vectors, one giving the metric-converted length guesses (in feet) of an auditorium whose actual length (in meters) was 13.1m, and the other con- taining the length guesses of 69 others (in meters). Usage data(lengthguesses) Format This list contains the following columns: imperial a numeric vector of 69 student guesses as to the length of an auditorium using the imperial system, converted to meters. metric a numeric vector of 44 student guesses as to the length of an auditorium using the metric system. Source <NAME>. and the M345 Course Team (1986) M345 Statistical Methods, Unit 1: Data, distributions and uncertainty, Milton Keynes: The Open University. Tables 2.1 and 2.4. References <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (1994) A Handbook of Small Data Sets. Boca Raton: Chapman & Hall/CRC. Examples with(lengthguesses, t.test(imperial, metric)) lesions Lesions in Rat Colons Description Numbers of aberrant crypt foci (ACF) in each of six cross-sectional regions of the colons of 66 rats subjected to varying doses of the carcinogen azoxymethane (AOM), sacrificed at 3 different times. Usage lesions Format This data frame contains the following columns: T Incubation time factor, levels: 6, 12 and 18 weeks INJ Number of injections SECT Section of colon, a factor with levels 1 through 6, where 1 denotes the proximal end of the colon and 6 denotes the distal end RAT Label for animal within a particular T-INJ factor level combination ACF.Total Total number of ACF lesions in a section of a rat’s colon ACF.total.mult Sum of ACF multiplicities for a section of a rat’s colon id Identifier for each of the 66 rats. Source <NAME>, University of Northern British Columbia, Prince George, Canada. References <NAME>, <NAME> and <NAME>. Dose response and proliferative characteristics of aber- rant crypt foci: putative preneoplastic lesions in rat colon. Carcinogenesis, 12(11): 2093-2098, 1991. Examples summary(lesions) ACF.All <- aggregate(ACF.Total ~ id + INJ + T, FUN=sum, data = lesions) lesions.glm <- glm(ACF.Total ~ INJ * T, data = ACF.All, family=poisson) summary(lesions.glm) lesions.qp <- glm(ACF.Total ~ INJ * T, data = ACF.All, family=quasipoisson) summary(lesions.qp) lesions.noInt <- glm(ACF.Total ~ INJ + T, data = ACF.All, family=quasipoisson) summary(lesions.noInt) LPBias Local Polynomial Bias Description Confidence interval estimates for bias in local polynomial regression. Usage LPBias(xy,k1,k2,h,h2,numgrid=401,alpha=.95) Arguments xy A data frame, whose first column must be the explanatory variable and whose second column must be the response variable. k1 degree of local polynomial used in curve estimator. k2 degree of local polynomial used in bias estimator. h bandwidth for regression estimator. h2 bandwidth for bias estimator. numgrid number of gridpoints used in the curve estimator. alpha nominal confidence level. Value A list containing the confidence interval limits, pointwise estimates of bias, standard deviation of bias, curve estimate, standard deviation of curve estimate, and approximate confidence limits for curve estimates. Author(s) <NAME> and <NAME> motor Motor Vibration Data Description Noise measurements for 5 samples of motors, each sample based on a different brand of bearing. Usage data("motor") Format A data frame with 5 columns. Brand 1 A numeric vector length 6 Brand 2 A numeric vector length 6 Brand 3 A numeric vector length 6 Brand 4 A numeric vector length 6 Brand 5 A numeric vector length 6 Source Devore, J. and <NAME> (2005) Applied Statistics for Engineers and Scientists. Thomson. noisyimage noisy image Description The noisyimage is a list. The third component is noisy version of the third component of tarimage. Usage data(noisyimage) Format This list contains the following elements: x a numeric vector having 101 elements. y a numeric vector having 101 elements. xy a numeric matrix having 101 rows and columns Examples with(noisyimage, image(x, y, xy)) oldwash oldwash Description The oldwash dataframe has 49 rows and 8 columns. The data are from the start up of a wash still considering the amount of time it takes to heat up to a specified temperature and possible influencing factors. Usage data("oldwash") Format A data frame with 49 observations on the following 8 variables. Date character, the date of the run startT degrees Celsius, numeric, initial temperature endT degrees Celsius, numeric, final temperature time in minutes, numeric, amount of time to reach final temperature Vol in litres, numeric, amount of liqiud in the tank (max 2000L) alc numeric, the percentage of alcohol present in the liquid who character, relates to the person who ran the still batch factor with levels 1 = first time through, 2 = second time through Details The purpose of the wash still is to increase the percentage of alcohol and strip out unwanted partic- ulate. It can take a long time to heat up and this can lead to problems in meeting production time limits. Source <NAME>, Endless Summer Distillery (2014) Examples oldwash.lm<-lm(log(time)~startT+endT+Vol+alc+who+batch,data=oldwash) summary(oldwash.lm) par(mfrow=c(2,2)) plot(oldwash.lm) data2<-subset(oldwash,batch==2) hist(data2$time) data1<-subset(oldwash,batch==1) hist(data1$time) oldwash.lmc<-lm(time~startT+endT+Vol+alc+who+batch,data=data1) summary(oldwash.lmc) plot(oldwash.lmc) oldwash.lmd<-lm(time~startT+endT+Vol+alc+who+batch,data=data2) summary(oldwash.lmd) plot(oldwash.lmd) p11.12 Data For Problem 11-12 Description The p11.12 data frame has 19 observations on satellite cost. Usage data(p11.12) Format This data frame contains the following columns: cost first-unit satellite cost x weight of the electronics suite Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References Simpson and Montgomery (1998) Examples data(p11.12) attach(p11.12) plot(cost~x) detach(p11.12) p11.15 Data set for Problem 11-15 Description The p11.15 data frame has 9 rows and 2 columns. Usage data(p11.15) Format This data frame contains the following columns: x a numeric vector y a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References Ryan (1997), Stefanski (1991) Examples data(p11.15) plot(p11.15) attach(p11.15) lines(lowess(x,y)) detach(p11.15) p12.11 Data Set for Problem 12-11 Description The p12.11 data frame has 44 observations on the fraction of active chlorine in a chemical product as a function of time after manufacturing. Usage data(p12.11) Format This data frame contains the following columns: xi time yi available chlorine Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p12.11) plot(p12.11) lines(lowess(p12.11)) p12.12 Data Set for Problem 12-12 Description The p12.12 data frame has 18 observations on an chemical experiment. A nonlinear model relating concentration to reaction time and temperature with an additive error is proposed to fit these data. Usage data(p12.12) Format This data frame contains the following columns: x1 reaction time (in minutes) x2 temperature (in degrees Celsius) y concentration (in grams/liter) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p12.12) attach(p12.12) # fitting the linearized model logy.lm <- lm(I(log(y))~I(log(x1))+I(log(x2))) summary(logy.lm) plot(logy.lm, which=1) # checking the residuals # fitting the nonlinear model y.nls <- nls(y ~ theta1*I(x1^theta2)*I(x2^theta3), start=list(theta1=.95, theta2=.76, theta3=.21)) summary(y.nls) plot(resid(y.nls)~fitted(y.nls)) # checking the residuals p12.16 Data Set for Problem 12-16 Description The p12.16 data frame has 26 observations on 5 variables. Usage data(p12.16) Format This data frame contains the following columns: Mixture numeric x1 numeric x2 numeric x3 numeric y numeric Source Montgomery, D.C., <NAME>., and Vining, C.G. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. References Myers, R. Technometrics, vol. 6, no. 4, 343-356, 1964. p12.8 Data Set for Problem 12-8 Description The p12.8 data frame has 14 rows and 2 columns. Usage data(p12.8) Format This data frame contains the following columns: x a numeric vector y a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p12.8) p13.1 Data Set for Problem 13-1 Description The p13.1 data frame has 25 observation on the test-firing results for surface-to-air missiles. Usage data(p13.1) Format This data frame contains the following columns: x target speed (in Knots) y hit (=1) or miss (=0) Source <NAME>., <NAME>., and Vining, C.G. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.1) p13.16 Data Set for Problem 13-16 Description The p13.16 data frame has 16 rows and 5 columns. Usage data(p13.16) Format This data frame contains the following columns: X1 a numeric vector X2 a numeric vector X3 a numeric vector X4 a numeric vector Y a numeric vector Source Montgomery, D.C., <NAME>., and Vining, C.G. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.16) p13.2 Data Set for Problem 13-2 Description The p13.2 data frame has 20 observations on home ownership. Usage data(p13.2) Format This data frame contains the following columns: x family income y home ownership (1 = yes, 0 = no) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.2) p13.20 Data Set for Problem 13-20 Description The p13.20 data frame has 30 rows and 2 columns. Usage data(p13.20) Format This data frame contains the following columns: yhat a numeric vector resdev a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.20) p13.3 Data Set for Problem 13-3 Description The p13.3 data frame has 10 observations on the compressive strength of an alloy fastener used in aircraft construction. Usage data(p13.3) Format This data frame contains the following columns: x load (in psi) n sample size r number failing Source Montgomery, D.C., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.3) p13.4 Data Set for Problem 13-4 Description The p13.4 data frame has 11 observations on the effectiveness of a price discount coupon on the purchase of a two-litre beverage. Usage data(p13.4) Format This data frame contains the following columns: x discount n sample size r number redeemed Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.4) p13.5 Data Set for Problem 13-5 Description The p13.5 data frame has 20 observations on new automobile purchases. Usage data(p13.5) Format This data frame contains the following columns: x1 income x2 age of oldest vehicle y new purchase less than 6 months later (1=yes, 0=no) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.5) p13.6 Data Set for Problem 13-6 Description The p13.6 data frame has 15 observations on the number of failures of a particular type of valve in a processing unit. Usage data(p13.6) Format This data frame contains the following columns: valve type of valve numfail number of failures months months Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p13.6) p13.7 Data Set for Problem 13-7 Description The p13.7 data frame has 44 observations on the coal mines of the Appalachian region of western Virginia. Usage data(p13.7) Format This data frame contains the following columns: y number of fractures in upper seams of coal mines x1 inner burden thickness (in feet), shortest distance between seam floor and the lower seam x2 percent extraction of the lower previously mined seam x3 lower seam height (in feet) x4 time that the mine has been in operation (in years) Source Montgomery, D.C., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References Myers (1990) Examples data(p13.7) p14.1 Data Set for Problem 14-1 Description The p14.1 data frame has 15 rows and 3 columns. Usage data(p14.1) Format This data frame contains the following columns: x a numeric vector y a numeric vector time a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p14.1) p14.2 Data Set for Problem 14-2 Description The p14.2 data frame has 18 rows and 3 columns. Usage data(p14.2) Format This data frame contains the following columns: t a numeric vector xt a numeric vector yt a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p14.2) p15.4 Data Set for Problem 15-4 Description The p15.4 data frame has 40 rows and 4 columns. Usage data(p15.4) Format This data frame contains the following columns: x1 a numeric vector x2 a numeric vector y a numeric vector set a factor with levels e and p Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p15.4) p2.10 Data Set for Problem 2-10 Description The p2.10 data frame has 26 observations on weight and systolic blood pressure for randomly selected males in the 25-30 age group. Usage data(p2.10) Format This data frame contains the following columns: weight in pounds sysbp systolic blood pressure Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p2.10) attach(p2.10) cor.test(weight, sysbp, method="pearson") # tests rho=0 # using Fisher's Z-transform p2.12 Data Set for Problem 2-12 Description The p2.12 data frame has 12 observations on the number of pounds of steam used per month at a plant and the average monthly ambient temperature. Usage data(p2.12) Format This data frame contains the following columns: temp ambient temperature (in degrees F) usage usage (in thousands of pounds) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p2.12) attach(p2.12) usage.lm <- lm(usage ~ temp) summary(usage.lm) predict(usage.lm, newdata=data.frame(temp=58), interval="prediction") detach(p2.12) p2.13 Data Set for Problem 2-13 Description The p2.13 data frame has 16 observations on the number of days the ozone levels exceeded 0.2 ppm in the South Coast Air Basin of California for the years 1976 through 1991. It is believed that these levels are related to temperature. Usage data(p2.13) Format This data frame contains the following columns: days number of days ozone levels exceeded 0.2 ppm index a seasonal meteorological index giving the seasonal average 850 millibar temperature. Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References <NAME>. (1993) Update on Ozone Trends in California’s South Coast Air Basin. Air Waste, 43, 226-227. Examples data(p2.13) attach(p2.13) plot(days~index, ylim=c(-20,130)) ozone.lm <- lm(days ~ index) summary(ozone.lm) # plots of confidence and prediction intervals: ozone.conf <- predict(ozone.lm, interval="confidence") lines(sort(index), ozone.conf[order(index),2], col="red") lines(sort(index), ozone.conf[order(index),3], col="red") ozone.pred <- predict(ozone.lm, interval="prediction") lines(sort(index), ozone.pred[order(index),2], col="blue") lines(sort(index), ozone.pred[order(index),3], col="blue") detach(p2.13) p2.14 Data Set for Problem 2-14 Description The p2.14 data frame has 8 observations on the molar ratio of sebacic acid and the intrinsic viscosity of copolyesters. One is interested in predicting viscosity from the sebacic acid ratio. Usage data(p2.14) Format This data frame contains the following columns: ratio molar ratio visc viscosity Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References <NAME>, and Tsai (1995) Separation and Characterizations of Thermotropic Copolyesters of p- Hydroxybenzoic Acid, Sebacic Acid and Hydroquinone. Journal of Applied Polymer Science, 56, 471-476. Examples data(p2.14) attach(p2.14) plot(p2.14, pch=16, ylim=c(0,1)) visc.lm <- lm(visc ~ ratio) summary(visc.lm) visc.conf <- predict(visc.lm, interval="confidence") lines(ratio, visc.conf[,2], col="red") lines(ratio, visc.conf[,3], col="red") visc.pred <- predict(visc.lm, interval="prediction") lines(ratio, visc.pred[,2], col="blue") lines(ratio, visc.pred[,3], col="blue") detach(p2.14) p2.15 Data Set for Problem 2-15 Description The p2.15 data frame has 8 observations on the impact of temperature on the viscosity of toluene- tetralin blends. This particular data set deals with blends with a 0.4 molar fraction of toluene. Usage data(p2.15) Format This data frame contains the following columns: temp temperature (in degrees Celsius) visc viscosity (mPa s) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References Byers and Williams (1987) Viscosities of Binary and Ternary Mixtures of Polynomatic Hydrocar- bons. Journal of Chemical and Engineering Data, 32, 349-354. Examples data(p2.15) attach(p2.15) plot(visc ~ temp, pch=16) visc.lm <- lm(visc ~ temp) plot(visc.lm, which=1) detach(p2.15) p2.16 Data Set for Problem 2-16 Description The p2.16 data frame has 33 observations on the pressure in a tank the volume of liquid. Usage data(p2.16) Format This data frame contains the following columns: volume volume of liquid pressure pressure in the tank Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References Carroll and Spiegelman (1986) The Effects of Ignoring Small Measurement Errors in Precision Instrument Calibration. Journal of Quality Technology, 18, 170-173. Examples data(p2.16) attach(p2.16) plot(pressure ~ volume, pch=16) pressure.lm <- lm(pressure ~ volume) plot(pressure.lm, which=1) summary(pressure.lm) detach(p2.16) p2.17 Data Set for Problem 2-17 Description The p2.17 data frame has 17 observations on the boiling point of water (in Fahrenheit degrees) for various barometric pressures (in inches of mercury). Usage data(p2.17) Format This data frame contains the following columns: BoilingPoint numeric vector BarometricPressure numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. References Atkinson, A.C. (1985) Plots, Transformations and Regression, Clarendon Press, Oxford. Examples data(p2.17) attach(p2.17) plot(BoilingPoint ~ BarometricPressure, pch=16) detach(p2.17) p2.18 Data Set for Problem 2-18 Description The p2.18 data frame has 21 observations on the advertising expenses (in millions of US dollars) and retain impressions (in millions per week) for various companies. Usage data(p2.18) Format This data frame contains the following columns: Firm character vector Amount.Spent numeric vector Returned.Impressions numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples data(p2.18) attach(p2.18) plot(Returned.Impressions ~ Amount.Spent, pch=16) detach(p2.18) p2.7 Data Set for Problem 2-7 Description The p2.7 data frame has 20 observations on the purity of oxygen produced by a fractionation process. It is thought that oxygen purity is related to the percentage of hydrocarbons in the main condensor of the processing unit. Usage data(p2.7) Format This data frame contains the following columns: purity oxygen purity (percentage) hydro hydrocarbon (percentage) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p2.7) attach(p2.7) purity.lm <- lm(purity ~ hydro) summary(purity.lm) # confidence interval for mean purity at 1% hydrocarbon: predict(purity.lm,newdata=data.frame(hydro = 1.00),interval="confidence") detach(p2.7) p2.9 Data Set for Problem 2-9 Description The p2.9 data frame has 25 rows and 2 columns. See help on softdrink for details. Usage data(p2.9) Format This data frame contains the following columns: y a numeric vector: time x a numeric vector: cases stocked Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p2.9) p4.18 Data Set for Problem 4-18 Description The p4.18 data frame has 13 observations on an experiment to produce a synthetic analogue to jojoba oil. Usage data(p4.18) Format This data frame contains the following columns: x1 reaction temperature x2 initial amount of catalyst x3 pressure y yield Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References Coteron, Sanchez, Matinez, and Aracil (1993) Optimization of the Synthesis of an Analogue of Jojoba Oil Using a Fully Central Composite Design. Canadian Journal of Chemical Engineering. Examples data(p4.18) y.lm <- lm(y ~ x1 + x2 + x3, data=p4.18) summary(y.lm) y.lm <- lm(y ~ x1, data=p4.18) p4.19 Data Set for Problem 4-19 Description The p4.19 data frame has 14 observations on a designed experiment studying the relationship be- tween abrasion index for a tire tread compound and three factors. Usage data(p4.19) Format This data frame contains the following columns: x1 hydrated silica level x2 silane coupling agent level x3 sulfur level y abrasion index for a tire tread compound Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References Derringer and Suich (1980) Simultaneous Optimization of Several Response Variables. Journal of Quality Technology. Examples data(p4.19) attach(p4.19) y.lm <- lm(y ~ x1 + x2 + x3) summary(y.lm) plot(y.lm, which=1) y.lm <- lm(y ~ x1) detach(p4.19) p4.20 Data Set for Problem 4-20 Description The p4.20 data frame has 26 observations on a designed experiment to determine the influence of five factors on the whiteness of rayon. Usage data(p4.20) Format This data frame contains the following columns: acidtemp acid bath temperature acidconc cascade acid concentration watertemp water temperature sulfconc sulfide concentration amtbl amount of chlorine bleach y a measure of the whiteness of rayon Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References Myers and Montgomery (1995) Response Surface Methodology, pp. 267-268. Examples data(p4.20) y.lm <- lm(y ~ acidtemp, data=p4.20) summary(y.lm) p5.1 Data Set for Problem 5-1 Description The p5.1 data frame has 8 observations on the impact of temperature on the viscosity of toluene- tetralin blends. Usage data(p5.1) Format This data frame contains the following columns: temp temperature visc viscosity Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References <NAME> Williams (1987) Viscosities of Binary and Ternary Mixtures of Polyaromatic Hydrocar- bons. Journal of Chemical and Engineering Data, 32, 349-354. Examples data(p5.1) plot(p5.1) p5.10 Data Set for Problem 5-10 Description The p5.10 data frame has 27 observations on the effect of three factors on a printing machine’s ability to apply coloring inks on package labels. Usage data(p5.10) Format This data frame contains the following columns: x1 speed x2 pressure x3 distance yi1 response 1 yi2 response 2 yi3 response 3 ybar.i average response si standard deviation of the 3 responses Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(p5.10) attach(p5.10) y.lm <- lm(ybar.i ~ x1 + x2 + x3) plot(y.lm, which=1) detach(p5.10) p5.11 Data Set for Problem 5-11 of the Third Edition of MPV Description The p5.11 data frame has 8 observations on an experiment with a catapult. This data set is used in Exercise 5.13 of the 6th edition of MPV. Usage data(p5.11) Format This data frame contains the following columns: x1 hook x2 arm length x3 start angle x4 stop angle yi1 response 1 yi2 response 2 yi3 response 3 Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. See Also p5.13 Examples attach(p5.11) ybar.i <- apply(p5.11[,5:7], 1, mean) sd.i <- apply(p5.11[,5:7], 1, sd) y.lm <- lm(ybar.i ~ x1 + x2 + x3 + x4) plot(y.lm, which=1) detach(p5.11) p5.12 Data Set for Problem 5-12 Description The p5.12 data frame has 27 observations on 3 variables, with responses replicated 3 times. Aver- ages and standard deviations are calculated for each level of the experimental design. Usage data(p5.12) Format This data frame contains the following columns: i numeric, experimental run number xi numeric x2 numeric x3 numeric yi1 response 1 yi2 response 2 yi3 response 3 ybari average of 3 responses at ith level si standard deviation of 3 responses at ith level Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. References <NAME>. and <NAME>. (1990) "Combining Taguchi and Response Surface Philosophies: A Dual Response Approach," Journal of Quality Technology, 22, 15-22. Examples y.lm <- lm(ybari ~ xi + x2 + x3, data = p5.12) plot(y.lm, which=1) p5.13 Data Set for Problem 5-13 Description The p5.13 data frame has 8 observations on 4 variables, with responses replicated 3 times. Usage data(p5.13) Format This data frame contains the following columns: x1 numeric x2 numeric x3 numeric x4 numeric y.1 response 1 y.2 response 2 y.3 response 3 Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME> and Sons. References <NAME>., <NAME>., <NAME>., Schmidt, and <NAME>. (1992) "The catapult problem; en- hanced engineering modeling using experimental design," Quality Engineering, 4, 463-473. Examples y.lm <- lm(I((y.1+y.2+y.3)/3) ~ x1 + x2 + x3 + x4, data = p5.13) plot(y.lm, which=1) p5.2 Data Set for Problem 5-2 Description The p5.2 data frame has 11 observations on the vapor pressure of water for various temperatures. Usage data(p5.2) Format This data frame contains the following columns: temp temperature (K) vapor vapor pressure (mm Hg) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p5.2) plot(p5.2) p5.21 Data Set for Problem 5-21 Description The p5.21 data frame has 4 observations on 2 variables (replicated 4 times). Usage data(p5.21) Format This data frame contains the following columns: Mix.Rate a numeric vector y1 a numeric vector y2 a numeric vector y3 a numeric vector y4 a numeric vector Source Montgomery, D.C., <NAME>., and Vining, C.G. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples cementStrength <- reshape(p5.21, idvar = "Mix.Rate", varying=list(2:5), direction="long", v.names=c("TensileStrength")) rownames(cementStrength) <- NULL anova(lm(TensileStrength ~ Mix.Rate*time, data = cementStrength)) p5.22 Data Set for Problem 5-22 Description The p5.22 data frame has 18 observations on 2 variables. Usage data(p5.22) Format This data frame contains the following columns: Temp a numeric vector Density a numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples anova(lm(Density ~ Temp, data = p5.22)) p5.23 Data Set for Problem 5-23 Description The p5.23 data frame has 18 observations on 3 variables. Usage data(p5.23) Format This data frame contains the following columns: Batch a character vector Pressure a numeric vector Strength a numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples anova(lm(Strength ~ Pressure*Batch, data = p5.23)) p5.24 Data Set for Problem 5-24 Description The p5.24 data frame has 13 observations on 7 variables. Usage data(p5.24) Format This data frame contains the following columns: Location a character vector x1 a numeric vector x2 a numeric vector x3 a numeric vector x4 a numeric vector x5 a numeric vector y a numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. References <NAME>. and <NAME>. "Water Use Efficiency of Wheat in a Mediterranean-type Environ- ment, I The Relation between Yield, Water Use, and Climate," Australian Journal of Agricultural Research, 35, 743-764, 1984. Examples lm(y ~ x1 + x2 + x3 + x4 + x5, data = p5.24) p5.3 Data Set for Problem 5-3 Description The p5.3 data frame has 12 observations on the number of bacteria surviving in a canned food product and the number of minutes of exposure to 300 degree Fahrenheit heat. Usage data(p5.3) Format This data frame contains the following columns: bact number of surviving bacteria min number of minutes of exposure Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p5.3) plot(bact~min, data=p5.3) p5.4 Data Set for Problem 5-4 Description The p5.4 data frame has 8 observations on 2 variables. Usage data(p5.4) Format This data frame contains the following columns: x a numeric vector y a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p5.4) plot(y ~ x, data=p5.4) p5.5 Data Set for Problem 5-5 Description The p5.5 data frame has 14 observations on the average number of defects per 10000 bottles due to stones in the bottle wall and the number of weeks since the last furnace overhaul. Usage data(p5.5) Format This data frame contains the following columns: defects a numeric vector weeks a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p5.5) defects.lm <- lm(defects~weeks, data=p5.5) plot(defects.lm, which=1) p7.1 Data Set for Problem 7-1 Description The p7.1 data frame has 10 observations on a predictor variable. Usage data(p7.1) Format This data frame contains the following columns: x a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(p7.1) attach(p7.1) x2 <- x^2 detach(p7.1) p7.11 Data Set for Problem 7-11 Description The p7.11 data frame has 11 observations on production cost versus production lot size. Usage data(p7.11) Format This data frame contains the following columns: x production lot size y average production cost per unit Source Montgomery, D.C., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(p7.11) plot(y ~ x, data=p7.11) p7.13 Data Set for Problem 7-13 Description The p7.13 data frame has 11 observations on production cost versus production lot size. (This data set was for problem 7-11 in the third edition of MPV). Usage data(p7.13) Format This data frame contains the following columns: x production lot size y average production cost per unit Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME> and Sons. Examples plot(y ~ x, data=p7.13) p7.15 Data Set for Problem 7-15 Description The p7.15 data frame has 6 observations on vapor pressure of water at various temperatures. Usage data(p7.15) Format This data frame contains the following columns: y vapor pressure (mm Hg) x temperature (degrees Celsius) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(p7.15) y.lm <- lm(y ~ x, data=p7.15) plot(y ~ x, data=p7.15) abline(coef(y.lm)) plot(y.lm, which=1) p7.16 Data Set for Problem 7-16 Description The p7.16 data frame has 26 observations on the observed mole fraction solubility of a solute at a constant temperature. Usage data(p7.16) Format This data frame contains the following columns: y negative logarithm of the mole fraction solubility x1 dispersion partial solubility x2 dipolar partial solubility x3 hydrogen bonding Hansen partial solubility Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References (1991) Journal of Pharmaceutical Sciences 80, 971-977. Examples data(p7.16) pairs(p7.16) p7.17 Data Set for Problem 7-17 Description The p7.17 data frame has 6 observations on vapor pressure of water at various temperatures. This data set is the same as p7.15 which was used for exercise 7-15 in the third edition of MPV. Usage data(p7.17) Format This data frame contains the following columns: y vapor pressure (mm Hg) x temperature (degrees Celsius) Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME> and Sons. Examples y.lm <- lm(y ~ x, data=p7.17) plot(y ~ x, data=p7.17) abline(coef(y.lm)) plot(y.lm, which=1) p7.18 Data Set for Problem 7-18 Description The p7.18 data frame has 26 observations on the observed mole fraction solubility of a solute at a constant temperature. This data set is the same as p7.16 which was for problem 7-16 in the third edition of MPV. Usage data(p7.18) Format This data frame contains the following columns: y negative logarithm of the mole fraction solubility x1 dispersion partial solubility x2 dipolar partial solubility x3 hydrogen bonding Hansen partial solubility Source <NAME>., <NAME>., and Vining, C.G. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References (1991) Journal of Pharmaceutical Sciences 80, 971-977. Examples pairs(p7.18) p7.19 Data Set for Problem 7-19 Description The p7.19 data frame has 10 observations on the concentration of green liquor and paper machine speed from a kraft paper machine. Usage data(p7.19) Format This data frame contains the following columns: y green liquor (g/l) x paper machine speed (ft/min) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References (1986) Tappi Journal. Examples data(p7.19) y.lm <- lm(y ~ x + I(x^2), data=p7.19) summary(y.lm) p7.2 Data Set for Problem 7-2 Description The p7.2 data frame has 10 observations on solid-fuel rocket propellant weight loss. Usage data(p7.2) Format This data frame contains the following columns: x months since production y weight loss (kg) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p7.2) y.lm <- lm(y ~ x + I(x^2), data=p7.2) summary(y.lm) plot(y ~ x, data=p7.2) p7.20 Data Set for Problem 7-20 Description The p7.20 data frame has 10 observations on the concentration of green liquor and paper machine speed from a kraft paper machine.This data set is the same as p7.19 which was used in problem 7.19 of the third edition of MPV. Usage data(p7.20) Format This data frame contains the following columns: y green liquor (g/l) x paper machine speed (ft/min) Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. References (1986) Tappi Journal. Examples data(p7.20) y.lm <- lm(y ~ x + I(x^2), data=p7.20) summary(y.lm) p7.4 Data Set for Problem 7-4 Description The p7.4 data frame has 12 observations on two variables. Usage data(p7.4) Format This data frame contains the following columns: x a numeric vector y a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p7.4) y.lm <- lm(y ~ x + I(x^2), data = p7.4) summary(y.lm) p7.6 Data Set for Problem 7-6 Description The p7.6 data frame has 12 observations on softdrink carbonation. Usage data(p7.6) Format This data frame contains the following columns: y carbonation x1 temperature x2 pressure Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p7.6) y.lm <- lm(y ~ x1 + I(x1^2) + x2 + I(x2^2) + I(x1*x2), data=p7.6) summary(y.lm) p8.11 Data Set for Problem 8-11 Description The p8.11 data frame has 25 observations on the tensile strength of synthetic fibre used for men’s shirts. Usage data(p8.11) Format This data frame contains the following columns: y tensile strength percent percentage of cotton Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References Montgomery (2001) Examples data(p8.11) y.lm <- lm(y ~ percent, data=p8.11) model.matrix(y.lm) p8.16 Data Set for Problem 8-16 Description The p8.16 data frame has 17 observations on 4 variables. Usage data(p8.16) Format This data frame contains the following columns: Location numeric INHIBIT numeric UVB numeric SURFACE character Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. References <NAME>. et al., "Ozone depletion: Ultraviolet radiation and phytoplankton biology in Antartic waters," Science, 255, 952-957, 1992. p8.3 Data Set for Problem 8-3 Description The p8.3 data frame has 25 observations on delivery times taken by a vending machine route driver. Usage data(p8.3) Format This data frame contains the following columns: y delivery time (in minutes) x1 number of cases of product stocked x2 distance walked by route driver Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(p8.3) pairs(p8.3) p9.10 Data Set for Problem 9-10 Description The p9.10 data frame has 31 observations on the rut depth of asphalt pavements prepared under different conditions. Usage data(p9.10) Format This data frame contains the following columns: y change in rut depth/million wheel passes (log scale) x1 viscosity (log scale) x2 percentage of asphalt in surface course x3 percentage of asphalt in base course x4 indicator x5 percentage of fines in surface course x6 percentage of voids in surface course Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References Gorman and Toman (1966) Examples data(p9.10) pairs(p9.10) pathoeg Pathological Example Description Artificial regression data which causes stepwise regression with AIC to produce a highly non- parsimonious model. The true model used to simulate the data has only one real predictor (x8). Usage pathoeg Format This data frame contains the following columns: x1 a numeric vector x2 a numeric vector x3 a numeric vector x4 a numeric vector x5 a numeric vector x6 a numeric vector x7 a numeric vector x8 a numeric vector x9 a numeric vector y a numeric vector PRESS PRESS statistic Description Computation of Allen’s PRESS statistic for an lm object. Usage PRESS(x) Arguments x An lm object Value Allen’s PRESS statistic. Author(s) <NAME> See Also lm Examples data(p4.18) attach(p4.18) y.lm <- lm(y ~ x1 + I(x1^2)) PRESS(y.lm) detach(p4.18) qqANOVA QQ Plot for Analysis of Variance Description This function is used to display the weight of the evidence against null main effects in data coming from a 1 factor design, using a QQ plot. In practice this method is often called via the function GANOVA. Usage qqANOVA(x, y, plot.it = TRUE, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)), ...) Arguments x numeric vector of errors y numeric vector of scaled responses plot.it logical vector indicating whether to plot or not xlab character, x-axis label ylab character, y-axis label ... any other arguments for the plot function Value A QQ plot is drawn. Author(s) <NAME> quadline Quadratic Overlay Description Overlays a quadratic curve to a fitted quadratic model. Usage quadline(lm.obj, ...) Arguments lm.obj A lm object (a quadratic fit) ... Other arguments to the lines function; e.g. col Value The function superimposes a quadratic curve onto an existing scatterplot. Author(s) <NAME> See Also lm Examples data(p4.18) attach(p4.18) y.lm <- lm(y ~ x1 + I(x1^2)) plot(x1, y) quadline(y.lm) detach(p4.18) Qyplot Analysis of Variance Plot for Regression Description This function analyzes regression data graphically. It allows visualization of the usual F-test for significance of regression. Usage Qyplot(X, y, plotIt=TRUE, sortTrt=FALSE, type="hist", includeIntercept=TRUE, labels=FALSE) Arguments X The design matrix. y A numeric vector containing the response. plotIt Logical: if TRUE, a graph is drawn. sortTrt Logical: if TRUE, an attempt is made at sorting the predictor effects in descend- ing order. type "QQ" or "hist" includeIntercept Logical: if TRUE, the intercept effect is plotted; otherwise, it is omitted from the plot. labels logical: if TRUE, names of predictor variables are used as labels; otherwise, the design matrix column numbers are used as labels Value A QQ-plot or a histogram and rugplot, or a list if plotIt=FALSE Author(s) <NAME> Source Braun, W.J. 2013. Regression Analysis and the QR Decomposition. Preprint. Examples # Example 1 X <- p4.18[,-4] y <- p4.18[,4] Qyplot(X, y, type="hist", includeIntercept=FALSE) title("Evidence of Regression in the Jojoba Oil Data") # Example 2 set.seed(4571) Z <- matrix(rnorm(400), ncol=10) A <- matrix(rnorm(81), ncol=9) simdata <- data.frame(Z[,1], crossprod(t(Z[,-1]),A)) names(simdata) <- c("y", paste("x", 1:9, sep="")) Qyplot(simdata[,-1], simdata[,1], type="hist", includeIntercept=FALSE) title("Evidence of Regression in Simulated Data Set") # Example 3 Qyplot(table.b1[,-1], table.b1[,1], type="hist", includeIntercept=FALSE) title("Evidence of Regression in NFL Data Set") # An example where stepwise AIC selects the complement # of the set of variables that are actually in the true model: X <- pathoeg[,-10] y <- pathoeg[,10] par(mfrow=c(2,2)) Qyplot(X, y) Qyplot(X, y, sortTrt=TRUE) Qyplot(X, y, type="QQ") Qyplot(X, y, sortTrt=TRUE, type="QQ") X <- table.b1[,-1] # NFL data y <- table.b1[,1] Qyplot(X, y) radon Radon Release Description Percentage of radon from water released in showers with orifices of various diameters. Four repli- cates were obtained, but it should be noted that the temperatures for the replicates (in degrees Celsius) are 21, 30, 38, and 46, respectively. This information should really be accounted for in any serious analysis of the data. Usage data("radon") Format A data frame with 15 observations on the following 2 variables. diameter shower orifice diameter in mm rep 1 percentage radon released in first run rep 2 percentage radon released in second run rep 3 percentage radon released in third run rep 4 percentage radon released in fourth run Source <NAME>. and <NAME>. (1992) Influence of Water Temperature and Shower Head Orifice Size on the Release of Radon During Showering, Environment International, 18, 363-369. rectangles Length Measurements on Rectangular Objects Description Observations of heights, widths and diagonal lengths of several rectangular objects, such as books, photographs, and so on were measured. Only the data in MPV versions 1.62 and later can be trusted; there were errors in the third column in previous versions. Usage rectangles Format A data frame with 51 observations on the following 4 variables. h numeric, heights in centimeters w numeric, widths in centimeters d numeric, diagonal lengths in centimeters index numeric, sum of squares of heights and widths Examples x <- sqrt(rectangles$index) y <- rectangles$d y.lp <- locpoly(x, y, bandwidth=dpill(x,y), degree=1) plot(y ~ x) lines(y.lp, col=2, lty=2) abline(0,1) # y = x + measurement error plot(y.lp$y - y.lp$x, type="l", col=2) rftest Pseudorandom Number Testing via Random Forest Description Given a sequence of pseudorandom numbers, this function constructs a random forest prediction model for successive values, based on previous values up to a given lag. The ability of the ran- dom forest model to predict future values is inversely related to the quality of the sequence as an approximation to locally random numbers. Usage rftest(u, m=5) Arguments u numeric, a vector of pseudorandom numbers to test m numeric, number of lags to test Value Side effect is a two way layout of graphs showing effectiveness of prediction on a training and a testing subset of data. Good predictions indicate a poor quality sequence. Author(s) <NAME> Examples x <- runif(200) rftest(x, m = 4) seismictimings Seismic Timing Data Description The seismictimings data frame has 504 rows and 3 columns. Thickness of a layer of Alberta substratum as measured by several transects of geophones. Usage seismictimings Format This data frame contains the following columns: x longitudinal coordinate of geophone. y latitudinal coordinate of geophone. z time for signal to pass through substratum. Examples plot(y ~ x, data = seismictimings) softdrink Softdrink Data Description The softdrink data frame has 25 rows and 3 columns. Usage data(softdrink) Format This data frame contains the following columns: y a numeric vector x1 a numeric vector x2 a numeric vector Source Montgomery, D.C., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(softdrink) solar Solar Data Description The solar data frame has 29 rows and 6 columns. Usage data(solar) Format This data frame contains the following columns: total.heat.flux a numeric vector insolation a numeric vector focal.pt.east a numeric vector focal.pt.south a numeric vector focal.pt.north a numeric vector time.of.day a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(solar) stain Stain Removal Data Description Data on an experiment to remove ketchup stains from white cotton fabric by soaking the stained fabric in one of five substrates for one hour. Remaining stains were scored visually and subjectively according to a 6-point scale (0 = completely clean, 5 = no change) The stain data frame has 15 rows and 2 columns. Usage data(stain) Format This data frame contains the following columns: treatment a factor response a numeric vector Examples data(stain) table.b1 Table B1 Description The table.b1 data frame has 28 observations on National Football League 1976 Team Perfor- mance. Usage data(table.b1) Format This data frame contains the following columns: y Games won in a 14 game season x1 Rushing yards x2 Passing yards x3 Punting average (yards/punt) x4 Field Goal Percentage (FGs made/FGs attempted) x5 Turnover differential (turnovers acquired - turnovers lost) x6 Penalty yards x7 Percent rushing (rushing plays/total plays) x8 Opponents’ rushing yards x9 Opponents’ passing yards Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(table.b1) attach(table.b1) y.lm <- lm(y ~ x2 + x7 + x8) summary(y.lm) # over-all F-test: y.null <- lm(y ~ 1) anova(y.null, y.lm) # partial F-test for x7: y7.lm <- lm(y ~ x2 + x8) anova(y7.lm, y.lm) detach(table.b1) table.b10 Table B10 Description The table.b10 data frame has 40 observations on kinematic viscosity of a certain solvent system. Usage data(table.b10) Format This data frame contains the following columns: x1 Ratio of 2-methoxyethanol to 1,2-dimethoxyethane x2 Temperature (in degrees Celsius) y Kinematic viscosity (.000001 m2/s Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References Viscosimetric Studies on 2-Methoxyethanol + 1, 2-Dimethoxyethane Binary Mixtures from -10 to 80C. Canadian Journal of Chemical Engineering, 75, 494-501. Examples data(table.b10) attach(table.b10) y.lm <- lm(y ~ x1 + x2) summary(y.lm) detach(table.b10) table.b11 Table B11 Description The table.b11 data frame has 38 observations on the quality of Pinot Noir wine. Usage data(table.b11) Format This data frame contains the following columns: Clarity a numeric vector Aroma a numeric vector Body a numeric vector Flavor a numeric vector Oakiness a numeric vector Quality a numeric vector Region a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(table.b11) attach(table.b11) Quality.lm <- lm(Quality ~ Clarity + Aroma + Body + Flavor + Oakiness + factor(Region)) summary(Quality.lm) detach(table.b11) table.b12 Table B12 Description The table.b12 data frame has 32 rows and 6 columns. Usage data(table.b12) Format This data frame contains the following columns: temp a numeric vector soaktime a numeric vector soakpct a numeric vector difftime a numeric vector diffpct a numeric vector pitch a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(table.b12) table.b13 Table B13 Description The table.b13 data frame has 40 rows and 7 columns. Usage data(table.b13) Format This data frame contains the following columns: y a numeric vector x1 a numeric vector x2 a numeric vector x3 a numeric vector x4 a numeric vector x5 a numeric vector x6 a numeric vector Source Montgomery, D.C., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(table.b13) table.b14 Table B14 Description The table.b14 data frame has 25 observations on the transient points of an electronic inverter. Usage data(table.b14) Format This data frame contains the following columns: x1 width of the NMOS Device x2 length of the NMOS Device x3 width of the PMOS Device x4 length of the PMOS Device x5 a numeric vector y transient point of PMOS-NMOS Inverters Source Montgomery, D.C., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. Examples data(table.b14) y.lm <- lm(y ~ x1 + x2 + x3 + x4, data=table.b14) plot(y.lm, which=1) table.b15 Table B15 - Air Pollution and Mortality Data Description The table.b15 data frame has 60 observations on the mortality, environment, and demographic variables for a sample of American cities. Usage data(table.b15) Format This data frame contains the following columns: City character vector Mort numeric vector, age-adjusted mortality from all causes per 100000 Precip numeric vector, precipitation in inches Educ numeric vector, median number of school years completed Nonwhite numeric vector, percentage of 1960 population that is nonwhite Nox numeric vector, relative pollution potential of nitrous oxides SO2 numeric vector, relative pollution potential of sulfur dioxide Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. References <NAME>. and <NAME>. [1978], "Some applications of Chernuff faces: A technique for graphically representing multivariate data", in Graphical Representation of Multivariate Data, Aca- demic Press, New York. Examples data(table.b15) pairs(table.b15[,-1]) table.b16 Table B16 Data Set Description The table.b16 data frame has 38 observations on 6 variables. Usage data(table.b16) Format This data frame contains the following columns: Country character LifeExp numeric People.per.TV numeric People.per.Dr numeric LifeExpMale numeric LifeExpFemale numeric Source Montgomery, D.C., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME> and Sons. table.b17 Table B17 Description The table.b17 data frame has 25 observations on 5 variables. Usage data(table.b17) Format This data frame contains the following columns: Satisfaction numeric vector Age numeric vector Severity numeric vector Surgical.Medical numeric vector Anxiety numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME> and Sons. Examples pairs(table.b17) table.b18 Table B18 Description The table.b18 data frame has 16 observations on 9 variables. Usage data(table.b18) Format This data frame contains the following columns: y numeric vector x1 numeric vector x2 numeric vector x3 numeric vector x4 numeric vector x5 numeric vector x6 numeric vector x7 numeric vector x8 numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME> and Sons. Examples pairs(table.b18) table.b19 Table B19 Description The table.b19 data frame has 32 observations on 11 variables. Usage data(table.b19) Format This data frame contains the following columns: y numeric vector x1 numeric vector x2 numeric vector x3 numeric vector x4 numeric vector x5 numeric vector x6 numeric vector x7 numeric vector x8 numeric vector x9 numeric vector x10 numeric vector Source Montgomery, D.C., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME>iley and Sons. Examples pairs(table.b19) table.b2 Table B2 Description The table.b2 data frame has 29 rows and 6 columns. Usage data(table.b2) Format This data frame contains the following columns: y a numeric vector x1 a numeric vector x2 a numeric vector x3 a numeric vector x4 a numeric vector x5 a numeric vector Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. Examples data(table.b2) table.b20 Table B20 Description The table.b20 data frame has 18 observations on 6 variables. Usage data(table.b20) Format This data frame contains the following columns: x1 numeric vector x2 numeric vector x3 numeric vector x4 numeric vector x5 numeric vector y numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples pairs(table.b20) table.b22 Table B22 - Baseball Data Description The table.b22 data frame has 30 observations on 12 variables. Usage data(table.b22) Format This data frame contains the following columns: Team character vector Wins numeric vector Batter.Age numeric vector Runs numeric vector HRs numeric vector SLG numeric vector Pitcher.Age numeric vector ERA numeric vector SO numeric vector HRA numeric vector RA.G numeric vector Errors numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples pairs(table.b22[,-1]) table.b23 Table B23 Description The table.b23 data frame has 59 observations on 8 variables. Usage data(table.b23) Format This data frame contains the following columns: Player character vector Per numeric vector Lane.Agility.Time..Seconds. numeric vector Shuttle.Run..Seconds. numeric vector Three.Quarter.Sprint..Seconds. numeric vector Standing.Vertical.Leap..Inches. numeric vector Max.Vertical.Leap..Inches. numeric vector Position character vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples pairs(table.b23[,-c(1, 8)]) table.b24 Table B24 - Rental Data Description The table.b24 data frame has 51 observations on 6 variables. Usage data(table.b24) Format This data frame contains the following columns: City character vector Population numeric vector X95th.Percentile.Income numeric vector Median.Sale.Price numeric vector Median.Price.sqft numeric vector Rental.Price numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, John Wiley and Sons. Examples pairs(table.b24[,-1]) table.b25 Table B25 Golf Data Description The table.b25 data frame has 50 observations on 6 variables. Usage data(table.b25) Format This data frame contains the following columns: Player character vector Average.Score numeric vector SG..Off.the.Tee numeric vector SG..Approach.to.Green numeric vector SG..Around.the.Green numeric vector SG..Putting numeric vector Source <NAME>., <NAME>., and <NAME>. (2021) Introduction to Linear Regression Analy- sis. 6th Edition, <NAME> and Sons. Examples pairs(table.b25[,-1]) table.b3 Table B3 Description The table.b3 data frame has observations on gasoline mileage performance for 32 different auto- mobiles. Usage data(table.b3) Format This data frame contains the following columns: y Miles/gallon x1 Displacement (cubic in) x2 Horsepower (ft-lb) x3 Torque (ft-lb) x4 Compression ratio x5 Rear axle ratio x6 Carburetor (barrels) x7 No. of transmission speeds x8 Overall length (in) x9 Width (in) x10 Weight (lb) x11 Type of transmission (1=automatic, 0=manual) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References Motor Trend, 1975 Examples data(table.b3) attach(table.b3) y.lm <- lm(y ~ x1 + x6) summary(y.lm) # testing for the significance of the regression: y.null <- lm(y ~ 1) anova(y.null, y.lm) # 95% CI for mean gas mileage: predict(y.lm, newdata=data.frame(x1=275, x6=2), interval="confidence") # 95% PI for gas mileage: predict(y.lm, newdata=data.frame(x1=275, x6=2), interval="prediction") detach(table.b3) table.b4 Table B4 Description The table.b4 data frame has 24 observations on property valuation. Usage data(table.b4) Format This data frame contains the following columns: y sale price of the house (in thousands of dollars) x1 taxes (in thousands of dollars) x2 number of baths x3 lot size (in thousands of square feet) x4 living space (in thousands of square feet) x5 number of garage stalls x6 number of rooms x7 number of bedrooms x8 age of the home (in years) x9 number of fireplaces Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References <NAME>. and Wellington (1980) Prediction, Linear Regression and Minimum Sum of Relative Errors. Technometrics, 19, 1977. Examples data(table.b4) attach(table.b4) y.lm <- lm(y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9) summary(y.lm) detach(table.b4) table.b5 Data Set for Table B5 Description The table.b5 data frame has 27 observations on liquefaction. Usage data(table.b5) Format This data frame contains the following columns: y CO2 x1 Space time (in min) x2 Temperature (in degrees Celsius) x3 Percent solvation x4 Oil yield (g/100g MAF) x5 Coal total x6 Solvent total x7 Hydrogen consumption Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References (1978) Belle Ayr Liquefaction Runs with Solvent. Industrial Chemical Process Design Develop- ment, 17, 3. Examples data(table.b5) attach(table.b5) y.lm <- lm(y ~ x6 + x7) summary(y.lm) detach(table.b5) table.b6 Data Set for Table B6 Description The table.b6 data frame has 28 observations on a tube-flow reactor. Usage data(table.b6) Format This data frame contains the following columns: y Nb0Cl3 concentration (g-mol/l) x1 COCl2 concentration (g-mol/l) x2 Space time (s) x3 Molar density (g-mol/l) x4 Mole fraction CO2 Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References (1972) Kinetics of Chlorination of Niobium oxychloride by Phosgene in a Tube-Flow Reactor. Industrial and Engineering Chemistry, Process Design Development, 11(2). Examples data(table.b6) # Partial Solution to Problem 3.9 attach(table.b6) y.lm <- lm(y ~ x1 + x4) summary(y.lm) detach(table.b6) table.b7 Data Set for Table B7 Description The table.b7 data frame has 16 observations on oil extraction from peanuts. Usage data(table.b7) Format This data frame contains the following columns: x1 CO2 pressure (bar) x2 CO2 temperature (in degrees Celsius) x3 peanut moisture (percent by weight) x4 CO2 flow rate (L/min) x5 peanut particle size (mm) y total oil yield Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, <NAME> and Sons. References <NAME>. An Application of Fractional Experimental Designs. Quality Engineering, 1, 19-23. Examples data(table.b7) attach(table.b7) # partial solution to Problem 3.11: peanuts.lm <- lm(y ~ x1 + x2 + x3 + x4 + x5) summary(peanuts.lm) detach(table.b7) table.b8 Table B8 Description The table.b8 data frame has 36 observations on Clathrate formation. Usage data(table.b8) Format This data frame contains the following columns: x1 Amount of surfactant (mass percentage) x2 Time (min) y Clathrate formation (mass percentage) Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References <NAME>., <NAME>., <NAME>., and <NAME>. Study on a Cool Storage System Using HCFC-14 lb Clathrate. Canadian Journal of Chemical Engineering, 75, 353-360. Examples data(table.b8) attach(table.b8) clathrate.lm <- lm(y ~ x1 + x2) summary(clathrate.lm) detach(table.b8) table.b9 Data Set for Table B9 Description The table.b9 data frame has 62 observations on an experimental pressure drop. Usage data(table.b9) Format This data frame contains the following columns: x1 Superficial fluid velocity of the gas (cm/s) x2 Kinematic viscosity x3 Mesh opening (cm) x4 Dimensionless number relating superficial fluid velocity of the gas to the superficial fluid veloc- ity of the liquid y Dimensionless factor for the pressure drop through a bubble cap Source <NAME>., <NAME>., and <NAME>. (2001) Introduction to Linear Regression Analy- sis. 3rd Edition, John Wiley and Sons. References <NAME>., <NAME>., and <NAME>. A Correlation of Two-Phase Pressure Drops in Screen-Plate Bubble Column. Canadian Journal of Chemical Engineering, 71, 460-463. Examples data(table.b9) attach(table.b9) # Partial Solution to Problem 3.13: y.lm <- lm(y ~ x1 + x2 + x3 + x4) summary(y.lm) detach(table.b9) tarimage target image Description The tarimage is a list. Most of the values are 0, but there are small regions of 1’s. Usage data(tarimage) Format This list contains the following elements: x a numeric vector having 101 elements. y a numeric vector having 101 elements. xy a numeric matrix having 101 rows and columns Examples with(tarimage, image(x, y, xy)) tplot Graphical t Test for Regression Description This function analyzes regression data graphically. It allows visualization of the usual t-tests for individual regression coefficients. Usage tplot(X, y, plotIt=TRUE, type="hist", includeIntercept=TRUE) Arguments X The design matrix. y A numeric vector containing the response. plotIt Logical: if TRUE, a graph is drawn. type "QQ" or "hist" includeIntercept Logical: if TRUE, the intercept effect is plotted; otherwise, it is omitted from the plot. Value A QQ-plot or a histogram and rugplot, or a list if plotIt=FALSE Author(s) W. <NAME> Examples # Jojoba oil data set X <- p4.18[,-4] y <- p4.18[,4] tplot(X, y, type="hist", includeIntercept=FALSE) title("Tests for Individual Coefficients in the Jojoba Oil Regression") # Simulated data set where none of the predictors are in the true model: set.seed(4571) Z <- matrix(rnorm(400), ncol=10) A <- matrix(rnorm(81), ncol=9) simdata <- data.frame(Z[,1], crossprod(t(Z[,-1]),A)) names(simdata) <- c("y", paste("x", 1:9, sep="")) X <- simdata[,-1] y <- simdata[,1] tplot(X, y, type="hist", includeIntercept=FALSE) title("Tests for Individual Coefficients for the Simulated Data Set") # NFL Data set: X <- table.b1[,-1] y <- table.b1[,1] tplot(X, y, type="hist", includeIntercept=FALSE) title("Tests for Individual Coefficients for the NFL Data Set") # Simulated Data set where x8 is the only predictor in the true model: X <- pathoeg[,-10] y <- pathoeg[,10] par(mfrow=c(2,2)) tplot(X, y) tplot(X, y, type="QQ") tree.sample Sample of Loblolly Pine Data Description A random sample of observations taken from the ’Loblolly’ data frame, one per Seed. Usage data("tree.sample") Format A data frame with 12 observations on the following 2 variables. height tree heights (ft) age tree ages (yr) Uplot Plot of Multipliers in Regression ANOVA Plot Description This function graphically displays the coefficient multipliers used in the Regression Plot for the given predictor. Usage Uplot(X.qr, Xcolumn = 1, ...) Arguments X.qr The design matrix or the QR decomposition of the design matrix. Xcolumn The column(s) of the design matrix under study; this can be either integer valued or a character string. ... Additional arguments to barchart. Value A bar plot is displayed. Author(s) <NAME> Examples # Jojoba oil data set X <- p4.18[,-4] Uplot(X, 1:4) # NFL data set; see GFplot result first X <- table.b1[,-1] Uplot(X, c(2,3,9)) # In this example, x8 is the only predictor in # the true model: X <- pathoeg[,-10] y <- pathoeg[,10] pathoeg.F <- GFplot(X, y, plotIt=FALSE) Uplot(X, "x8") Uplot(X, 9) # same as above Uplot(pathoeg.F$QR, 9) # same as above X <- table.b1[,-1] Uplot(X, c("x2", "x3", "x9")) widths Measurements of the Widths of Book Covers Description Measurements in centimeters of the widths of a random collection of books. Usage widths Format A numeric vector of length 24. windWin80 Winnipeg Wind Speed Description The windWin80 data frame has 366 observations on midnight and noon windspeed at the Winnipeg International Airport for the year 1980. Usage data(windWin80) Format This data frame contains the following columns: h0 a numeric vector containing the wind speeds at midnight. h12 a numeric vector containing the wind spees at the following noon. Examples data(windWin80) ts.plot(windWin80$h12^2) Wpgtemp Winnipeg Maximum Temperatures Description The Wpgtemp data frame has 7671 observations on daily maximum temperatures at the Winnipeg International Airport for the years 1960 through 1980. Usage data(Wpgtemp) Format This data frame contains the following columns: temperature A numeric vector containing the temperatures in degrees Celsius day A numeric vector denoting the observation date in numbers of days after December 31, 1959 Source Environment Canada Examples summary(Wpgtemp) wxNWO Weather Observations for Three Stations in Northwestern Ontario Description Daily observations taken from 2012 through 2021 on temperature, rain, snow and wind for Fort Frances, Kenora and Dryden, Ontario. Usage wxNWO Format A data frame with 10959 observations on the following 31 variables. Longitude numeric Latitude numeric Station.Name character Climate.ID numeric Date.Time numeric Year numeric Month numeric Day numeric Data.Quality numeric Max.Temp numeric Max.Temp.Flag numeric Min.Temp numeric Min.Temp.Flag numeric Mean.Temp numeric Mean.Temp.Flag numeric Heat.Deg.Days numeric Heat.Deg.Days.Flag numeric Cool.Deg.Days numeric Cool.Deg.Days.Flag numeric Total.Rain numeric Total.Rain.Flag numeric Total.Snow numeric Total.Snow.Flag numeric Total.Precip numeric Total.Precip.Flag numeric Snow.on.Ground numeric Snow.on.Ground.Flag numeric Dir.of.Max.Gust numeric Dir.of.Max.Gust.Flag numeric Speed.of.Max.Gust numeric Speed.of.Max.Gust.Flag numeric Source Environment Canada
cmmr
cran
R
Package ‘cmmr’ October 12, 2022 Type Package Title CEU Mass Mediator RESTful API Version 0.1.2 Date 2019-03-26 Depends R (>= 3.1.0) Imports httr (>= 1.3.1), progress (>= 1.2.0), RJSONIO (>= 1.3-0) Author <NAME> <<EMAIL>>, <NAME> <<EMAIL>>, <NAME> <<EMAIL>> Maintainer <NAME> <<EMAIL>> Description CEU (CEU San Pablo University) Mass Mediator is an on-line tool for aiding researchers in performing metabolite annotation. 'cmmr' (CEU Mass Mediator RESTful API) allows for programmatic access in R: batch search, batch advanced search, MS/MS (tandem mass spec- trometry) search, etc. For more information about the API Endpoint please go to <https: //github.com/lzyacht/cmmr>. License GPL-3 Encoding UTF-8 LazyData true URL https://github.com/lzyacht/cmmr RoxygenNote 6.1.1 Suggests testthat NeedsCompilation no Repository CRAN Date/Publication 2019-04-16 09:42:44 UTC R topics documented: advanced_batch_searc... 2 batch_searc... 4 create_advanced_batch_bod... 5 create_batch_bod... 6 create_msms_bod... 7 msms_searc... 8 advanced_batch_search Encapsulation of CEU Mass Mediator advanced batch search API. Description advanced_batch_search returns the body string of a POST request. using the following code to install the dependencies: install.packages(c("httr", "progress", "RJSONIO")) Usage advanced_batch_search(cmm_url = paste0("http://ceumass.eps.uspceu.es/mediator/api/v3/", "advancedbatch"), chemical_alphabet = "all", modifiers_type = "none", metabolites_type = "all-except-peptides", databases = "[\"hmdb\"]", masses_mode = "mz", ion_mode = "positive", adducts = "[\"all\"]", deuterium = "false", tolerance = "7.5", tolerance_mode = "ppm", masses = "[400.3432, 288.2174]", all_masses = "[]", retention_times = "[18.842525, 4.021555]", all_retention_times = "[]", composite_spectra = paste0("[[{ \"mz\": 400.3432, \"intensity\": 307034.88 }, ", "{ \"mz\": 311.20145, \"intensity\": 400.03336 }]]")) Arguments cmm_url ’http://ceumass.eps.uspceu.es/mediator/api/v3/advancedbatch’ or your local one chemical_alphabet "CHNOPS", "CHNOPSCL", "ALL" modifiers_type "none", "NH3", "HCOO", "CH3COO", "HCOONH3", "CH3COONH3" metabolites_type "all-except-peptides", "only-lipids", "all-including-peptides" databases "all", "all-except-mine", "HMDB", "LipidMaps", "Metlin", "Kegg", "in-house", "mine" masses_mode "neutral", "mz" ion_mode "positive", "negative" adducts for positive mode ["M+H", "M+2H", "M+Na", "M+K", "M+NH4", "M+H- H2O"] for negative mode ["M-H", "M+Cl", "M+FA-H", "M-H-H2O"], for neu- tral ["M"] deuterium boolean ’true’ ’false’ tolerance double (Range: [0..100]) tolerance_mode "ppm", "mDa" masses double all_masses array of doubles retention_times double all_retention_times array of doubles composite_spectra array of arrays of spectra_object Value If all inputs are all correctly formatted, a dataframe will be returned for the result. Author(s) <NAME> <<EMAIL>> Georgetown University, USA License: GPL (>= 3) Examples df <- advanced_batch_search( cmm_url = paste0( 'http://ceumass.eps.uspceu.es/mediator/api/v3/', 'advancedbatch'), chemical_alphabet = 'all', modifiers_type = 'none', metabolites_type = 'all-except-peptides', databases = '["hmdb"]', masses_mode = 'mz', ion_mode = 'positive', adducts = '["all"]', deuterium = 'false', tolerance = '7.5', tolerance_mode = 'ppm', masses = '[400.3432, 288.2174]', all_masses = '[]', retention_times = '[18.842525, 4.021555]', all_retention_times = '[]', composite_spectra = paste0( '[[{ "mz": 400.3432, "intensity": 307034.88 }, ', '{ "mz": 311.20145, "intensity": 400.03336 }]]' )) batch_search Encapsulation of CEU Mass Mediator batch search API Description batch_search returns the dataframe of all the database search results. using the following code to install the dependencies: install.packages(c("httr", "progress", "RJSONIO")) Usage batch_search(cmm_url = "http://ceumass.eps.uspceu.es/mediator/api/v3/batch", metabolites_type = "all-except-peptides", databases = "[\"all-except-mine\"]", masses_mode = "mz", ion_mode = "positive", adducts = "[\"M+H\",\"M+Na\"]", tolerance = 10, tolerance_mode = "ppm", unique_mz) Arguments cmm_url ’http://ceumass.eps.uspceu.es/mediator/api/v3/batch’ or your local API Endpoint metabolites_type "all-except-peptides", "only-lipids", "all-including-peptides" databases "all", "all-except-mine", "HMDB", "LipidMaps", "Metlin", "Kegg", "in-house", "mine" masses_mode "neutral", "mz" ion_mode "positive", "negative" adducts for positive mode [M+H, M+2H, M+Na, M+K,M+NH4, M+H-H2O] tolerance double (Range: [0..100]) tolerance_mode "ppm", "mDa" unique_mz An array of unique m/zs Value dataframe for search results Author(s) <NAME> <<EMAIL>> Georgetown University, USA License: GPL (>= 3) Examples ## Not run: batch_search(c(670.4623, 1125.2555, 602.6180)) ## End(Not run) create_advanced_batch_body Create POST request Body for batch search Description create_advanced_batch_body returns a string of advanced search POST request body. Usage create_advanced_batch_body(chemical_alphabet = "all", modifiers_type = "none", metabolites_type = "all-except-peptides", databases = "[\"hmdb\"]", masses_mode = "mz", ion_mode = "positive", adducts = "[\"all\"]", deuterium = "false", tolerance = "7.5", tolerance_mode = "ppm", masses = "[400.3432, 288.2174]", all_masses = "[]", retention_times = "[18.842525, 4.021555]", all_retention_times = "[]", composite_spectra = paste0("[[{ \"mz\": 400.3432, \"intensity\": 307034.88 }, ", "{ \"mz\": 311.20145, \"intensity\": 400.03336 }]]")) Arguments chemical_alphabet "CHNOPS", "CHNOPSCL", "ALL" modifiers_type "none", "NH3", "HCOO", "CH3COO", "HCOONH3", "CH3COONH3" metabolites_type "all-except-peptides", "only-lipids", "all-including-peptides" databases "all", "all-except-mine", "HMDB", "LipidMaps", "Metlin", "Kegg", "in-house", "mine" masses_mode "neutral", "mz" ion_mode "positive", "negative" adducts for positive mode ["M+H", "M+2H", "M+Na", "M+K", "M+NH4", "M+H- H2O"] for negative mode ["M-H", "M+Cl", "M+FA-H", "M-H-H2O"], for neu- tral ["M"] deuterium boolean ’true’ ’false’ tolerance double (Range: [0..100]) tolerance_mode "ppm", "mDa" masses double all_masses array of doubles retention_times double all_retention_times array of doubles composite_spectra array of arrays of spectra_object Value If all inputs are all correctly formatted, a dataframe will be returned for the result. Author(s) <NAME> <<EMAIL>> Georgetown University, USA License: GPL (>= 3) create_batch_body Create POST request Body for batch search Description create_batch_body returns a string of a POST request body. Usage create_batch_body(metabolites_type = "all-except-peptides", databases = "[\"all-except-mine\"]", masses_mode = "mz", ion_mode = "positive", adducts = "[\"M+H\",\"M+Na\"]", tolerance = 10, tolerance_mode = "ppm", unique_mz) Arguments metabolites_type "all-except-peptides", "only-lipids", "all-including-peptides" databases "all", "all-except-mine", "HMDB", "LipidMaps", "Metlin", "Kegg", "in-house", "mine" masses_mode "neutral", "mz" ion_mode "positive", "negative" adducts for positive mode [M+H, M+2H, M+Na, M+K,M+NH4, M+H-H2O] tolerance double (Range: [0..100]) tolerance_mode "ppm", "mDa" unique_mz An array of unique m/zs Value If all inputs are all correctly formatted, a string of a POST request will be returned for the result. Author(s) <NAME> <<EMAIL>> Georgetown University, USA License: GPL (>= 3) Examples batch_body <- create_batch_body('all-except-peptides', '["all-except-mine"]', 'mz', 'positive', '["M+H","M+Na"]', 10, 'ppm', c(670.4623, 1125.2555, 602.6180)) batch_body <- create_batch_body('all-except-peptides', '["all-except-mine"]', 'mz', 'negative', '["M-H","M+Cl"]', 10, 'ppm', c(670.4623, 1125.2555, 602.6180)) ## Not run: create_batch_body(c(670.4623, 1125.2555, 602.6180)) ## End(Not run) create_msms_body Create MS/MS search POST request body Description create_msms_body returns a string of a POST request body. Usage create_msms_body(ion_mass, ms_ms_peaks, precursor_ion_tolerance = 500, precursor_ion_tolerance_mode = "mDa", precursor_mz_tolerance = 1000, precursor_mz_tolerance_mode = "mDa", ion_mode = "positive", ionizationVoltage = "all", spectra_types = "experimental") Arguments ion_mass ion_mass ms_ms_peaks ms_ms_peaks precursor_ion_tolerance precursor_ion_tolerance precursor_ion_tolerance_mode precursor_ion_tolerance_mode precursor_mz_tolerance precursor_mz_tolerance precursor_mz_tolerance_mode precursor_mz_tolerance_mode ion_mode ion_mode ionizationVoltage ionizationVoltage spectra_types spectra_types Value If all inputs are all correctly formatted, a string of a POST request will be returned for the result. Author(s) <NAME> <<EMAIL>> Georgetown University, USA License: GPL (>= 3) msms_search Encapsulation of CEU Mass Mediator batch search API. Description batch_search returns the dataframe of all the database search results. using the following code to install the dependencies: install.packages(c("httr", "progress", "RJSONIO")) Usage msms_search(ion_mass, ms_ms_peaks, precursor_ion_tolerance = 100, precursor_ion_tolerance_mode = "mDa", precursor_mz_tolerance = 500, precursor_mz_tolerance_mode = "mDa", ion_mode, ionizationVoltage = "all", spectra_types = "experimental", cmm_url = "http://ceumass.eps.uspceu.es/mediator/api/msmssearch") Arguments ion_mass ion_mass ms_ms_peaks ms_ms_peaks precursor_ion_tolerance precursor_ion_tolerance precursor_ion_tolerance_mode precursor_ion_tolerance_mode precursor_mz_tolerance precursor_mz_tolerance precursor_mz_tolerance_mode precursor_mz_tolerance_mode ion_mode ion_mode ionizationVoltage ionizationVoltage spectra_types spectra_types cmm_url "http://ceumass.eps.uspceu.es/mediator/api/msmssearch" or your local one Value If all inputs are all correctly formatted, a dataframe will be returned for the result. Author(s) <NAME> <<EMAIL>> Georgetown University, USA License: GPL (>= 3) Examples ms_ms_peaks = matrix( c(40.948, 0.174, 56.022, 0.424, 84.37, 53.488, 101.50, 8.285, 102.401, 0.775, 129.670, 100.000, 146.966, 20.070), ncol = 2, byrow = TRUE) msms_search(ion_mass = 147, ms_ms_peaks = ms_ms_peaks, ion_mode = 'positive')
multipart
hex
Erlang
API Reference === [modules](#modules) Modules --- [Multipart](Multipart.html) [`Multipart`](Multipart.html#content) constructs multipart messages. [Multipart.Part](Multipart.Part.html) Represents an individual part of a [`Multipart`](Multipart.html) message. Multipart === [`Multipart`](Multipart.html#content) constructs multipart messages. It aims to produce multipart messages that are compatible with [RFC 2046](https://tools.ietf.org/html/rfc2046#section-5.1) for general use, and [RFC 7578](https://tools.ietf.org/html/rfc7578) for constructing `multipart/form-data` requests. [Link to this section](#summary) Summary === [Types](#types) --- [t()](#t:t/0) [Functions](#functions) --- [add\_part(multipart, part)](#add_part/2) Adds a part to the [`Multipart`](Multipart.html#content) message. [body\_binary(multipart)](#body_binary/1) Returns a binary of the [`Multipart`](Multipart.html#content) message body. [body\_stream(multipart)](#body_stream/1) Returns a [`Stream`](https://hexdocs.pm/elixir/Stream.html) of the [`Multipart`](Multipart.html#content) message body. [content\_length(multipart)](#content_length/1) Returns the length of the [`Multipart`](Multipart.html#content) message in bytes. [content\_type(multipart, mime\_type)](#content_type/2) Returns the Content-Type header for the [`Multipart`](Multipart.html#content) message. [new(boundary \\ generate\_boundary())](#new/1) Create a new [`Multipart`](Multipart.html#content) request. [Link to this section](#types) Types === [Link to this section](#functions) Functions === Multipart.Part === Represents an individual part of a [`Multipart`](Multipart.html) message. [Link to this section](#summary) Summary === [Types](#types) --- [body()](#t:body/0) [headers()](#t:headers/0) [name()](#t:name/0) [t()](#t:t/0) [Functions](#functions) --- [binary\_body(body, headers \\ [])](#binary_body/2) Builds a `Part` with a binary body. [file\_body(path, headers \\ [])](#file_body/2) Builds a `Part` with a streaming file body. [file\_content\_field(path, content, name, headers \\ [], opts \\ [])](#file_content_field/5) Builds a form-data `Part` with an in-memory file body. [file\_field(path, name, headers \\ [], opts \\ [])](#file_field/4) Builds a form-data `Part` with a streaming file body. [stream\_body(stream, headers \\ [])](#stream_body/2) Builds a `Part` with a [`Stream`](https://hexdocs.pm/elixir/Stream.html) body. [stream\_field(stream, name, headers \\ [])](#stream_field/3) Builds a form-data `Part` with a streaming body. [text\_field(body, name, headers \\ [])](#text_field/3) Builds a form-data `Part` with a text body. [Link to this section](#types) Types === [Link to this section](#functions) Functions ===
rand_core
rust
Rust
Crate rand_core === Random number generation traits This crate is mainly of interest to crates publishing implementations of `RngCore`. Other users are encouraged to use the `rand` crate instead which re-exports the main traits and error types. `RngCore` is the core trait implemented by algorithmic pseudo-random number generators and external random-number sources. `SeedableRng` is an extension trait for construction from fixed seeds and other random number generators. `Error` is provided for error-handling. It is safe to use in `no_std` environments. The `impls` and `le` sub-modules include a few small functions to assist implementation of `RngCore`. Modules --- blockThe `BlockRngCore` trait and implementation helpers implsHelper functions for implementing `RngCore` functions. leLittle-Endian utilities Structs --- ErrorError type of random number generators OsRng`getrandom`A random number generator that retrieves randomness from the operating system. Traits --- CryptoRngA marker trait used to indicate that an `RngCore` or `BlockRngCore` implementation is supposed to be cryptographically secure. CryptoRngCoreAn extension trait that is automatically implemented for any type implementing `RngCore` and `CryptoRng`. RngCoreThe core of a random number generator. SeedableRngA random number generator that can be explicitly seeded. Struct rand_core::OsRng === ``` pub struct OsRng; ``` Available on **crate feature `getrandom`** only.A random number generator that retrieves randomness from the operating system. This is a zero-sized struct. It can be freely constructed with `OsRng`. The implementation is provided by the getrandom crate. Refer to getrandom documentation for details. This struct is only available when specifying the crate feature `getrandom` or `std`. When using the `rand` lib, it is also available as `rand::rngs::OsRng`. Blocking and error handling --- It is possible that when used during early boot the first call to `OsRng` will block until the system’s RNG is initialised. It is also possible (though highly unlikely) for `OsRng` to fail on some platforms, most likely due to system mis-configuration. After the first successful call, it is highly unlikely that failures or significant delays will occur (although performance should be expected to be much slower than a user-space PRNG). Usage example --- ``` use rand_core::{RngCore, OsRng}; let mut key = [0u8; 16]; OsRng.fill_bytes(&mut key); let random_u64 = OsRng.next_u64(); ``` Trait Implementations --- ### impl Clone for OsRng #### fn clone(&self) -> OsRng Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more ### impl Debug for OsRng #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more ### impl Default for OsRng #### fn default() -> OsRng Returns the “default value” for a type. Read more ### impl RngCore for OsRng #### fn next_u32(&mut self) -> u32 Return the next random `u32`. Read more #### fn next_u64(&mut self) -> u64 Return the next random `u64`. Read more #### fn fill_bytes(&mut self, dest: &mut [u8]) Fill `dest` with random data. Read more #### fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), ErrorFill `dest` entirely with random data. Read more ### impl Copy for OsRng ### impl CryptoRng for OsRng Auto Trait Implementations --- ### impl RefUnwindSafe for OsRng ### impl Send for OsRng ### impl Sync for OsRng ### impl Unpin for OsRng ### impl UnwindSafe for OsRng Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ### impl<T> Borrow<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more ### impl<T> BorrowMut<T> for Twhere    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> CryptoRngCore for Twhere    T: CryptoRng + RngCore, #### fn as_rngcore(&mut self) -> &mut dyn RngCoreNotable traits for dyn RngCore`impl Read for dyn RngCore` Upcast to an `RngCore` trait object. ### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership. #### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more #### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T, U> TryFrom<U> for Twhere    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. ### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion.
sim2Dpredictr
cran
R
Package ‘sim2Dpredictr’ April 3, 2023 Title Simulate Outcomes Using Spatially Dependent Design Matrices Version 0.1.1 Description Provides tools for simulating spatially dependent predictors (continuous or binary), which are used to generate scalar outcomes in a (generalized) linear model framework. Continuous predictors are generated using traditional multivariate normal distributions or Gauss Markov ran- dom fields with several correlation function approaches (e.g., see Rue (2001) <doi:10.1111/1467- 9868.00288> and Furrer and Sain (2010) <doi:10.18637/jss.v036.i10>), while binary predictors are gener- ated using a Boolean model (see Cressie and Wikle (2011, ISBN: 978-0-471-69274-4)). Parameter vectors exhibiting spatial clustering can also be easily specified by the user. Depends R (>= 3.5.0) License GPL-3 Encoding UTF-8 Imports MASS, Rdpack, spam (>= 2.2-0), tibble, dplyr, matrixcalc RdMacros Rdpack RoxygenNote 7.2.3 Suggests knitr, rmarkdown, testthat, V8 URL https://github.com/jmleach-bst/sim2Dpredictr BugReports https://github.com/jmleach-bst/sim2Dpredictr NeedsCompilation no Author <NAME> [aut, cre, cph] Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-04-03 13:00:02 UTC R topics documented: beta_builde... 2 chol_s2D... 5 classify_multiclas... 9 correlation_builde... 10 corr_fu... 12 generate_gri... 14 generate_multinom_prob... 15 inf_2D_imag... 16 make_rejectio... 19 neighbors_by_dis... 20 precision_builde... 21 proximity_builde... 23 sample_FP_Powe... 25 sim2D_binaryma... 27 sim2D_RandSet_HPP... 29 sim_MVN_... 31 sim_Y_Binary_... 34 sim_Y_MVN_... 38 within_are... 42 beta_builder Create a Parameter Vector from Lattice Locations Description Specify the locations in the lattice/image that have non-zero parameters as well as the values for those parameters, and the function creates the parameter vector that matches the correct locations in the design matrix. Usage beta_builder( row.index, col.index, im.res, B0 = 0, B.values, index.type = "manual", decay.fn = "gaussian", phi = 0.5, max.d = Inf, h, w, bayesian = FALSE, bayesian.dist = NULL, bayesian.scale = NULL, output.indices = TRUE ) Arguments row.index, col.index Vectors of row/columns indices for non-zero parameters. If index.type = "manual", each vector should contain specific coordinates. If index.type = "rectangle", each vector should specify rectangle length; e.g. row.index = 1:3 means the rectangle’s ’length’ is from rows 1 to 3. If index.type = "ellipse", the ar- guments should be scalar values specifying the row/column coordinates for the center of the ellipse. If index.type = "decay", the arguments should specify the row/column coordinates, respectively, of the peak parameter value. im.res A vector specifying the dimension/resolution of the image. The first entry is the number of ’rows’ in the lattice/image, and the second entry is the number of ’columns’ in the lattice/image. B0 is the "true" intercept value; default is 0. B.values is a vector "true" parameter values for non-zero parameters. The order of as- signment is by row. If B.values argument is a single value, then all non-zero parameters are assigned to that value, unless decay.fn has been specified, in which case B.values is the "peak", and non-zero parameters decay smoothly by distance. index.type is one of index.type = c("manual", "rectangle", "ellipse", "decay") • index.type = "manual" uses row.index and col.index arguments to specify manually selected non-zero locations. This setting is good for irregular shaped regions. • index.type = "rectangle" uses row.index and col.index arguments to spec- ify a rectangular region of non-zero parameters. • index.type = "ellipse" uses w and h arguments to specify elliptical re- gion of non-zero parameters. • index.type = "decay" allows the user to specify a peak location with row.index and col.index, as with index.type = "ellipse". However, the non-zero parameter values decay as a function of distance from the peak. decay.fn An argument to specify the decay function of non-zero parameters decay from the peak when index.type = "decay". Options are "exponential" or "gaus- sian". The rate of decay is given by B.values ∗ exp(−phi ∗ d) and B.values ∗ exp(−phi ∗ d2 ) for "exponential" and "gaussian", respectively. The default is decay.fn = "gaussian". Note that d is the Euclidean distance between the peak and a specified location, while phi is the rate of decay and is set by the user with phi. phi A scalar value greater than 0 that determines the decay rate of non-zero param- eters when index.type = "decay". The default is phi = 0.5. max.d When index.type = "decay", max.d determines the maximum Euclidean dis- tance from the peak that is allowed to be non-zero; parameters for locations further than max.d from the peak are set to zero. If this argument is not set by the user then all parameter values are determined by the decay function. w, h If index.type = "ellipse" then the width and height of the ellipse, respectively. bayesian If TRUE, then parameters are drawn from distributions based on initial B.values vector. Default is FALSE. bayesian.dist When bayesian = TRUE, specifies the distribution of the parameters. Options are "gaussian" and uniform. bayesian.scale A list. When bayesian = TRUE and bayesian.dist = "gaussian", specifies the sd for the distributions of parameters. When bayesian = TRUE and bayesian.dist = "uniform", specifies the width for the uniform distributions for the parame- ters. The first entry should be one of "unique", "binary". If "unique", then the second entry in the list should be a vector with length equal to B.values + 1 with unique values for the sd’s/widths, including B0. B0 can be set to a constant value by setting the first position of bayesian.scale[[2]] to 0. If "binary", then the second entry in the list should be a 3-element vector whose first entry is the sd/width of B0, second entry the sd/width of "non-zero" or "important" parameters, and the third entry is the sd/width of the "zero" or "irrelevant" pa- rameters. output.indices If output.indices = TRUE, then the first element of the returned list contains the indices for the non-zero parameter locations (Default). If output.indices = FALSE, then only the parameter vector is returned. Value A 2-element list containing (1) indices for the locations of "true" non-zero parameters, and (2) a parameter vector. Note The order of the parameters is by row. That is, if the lattice/image is 4x4, then parameters 1-4 make up the first row, 5-8 then second, and so forth. Examples ## example Bex1 <- beta_builder(row.index = c(5, 5, 6, 6), col.index = c(5, 6, 5, 6), im.res = c(10, 10), B0 = 0, B.values = rep(1, 4)) ## True non-zero parameters are locations 45, 46, 55, 56 in B ## i.e. locations (5, 5), (5, 6), (6, 5), (6, 6) ## Suppose that we index rows by i = 1, ... , I ## cols by j = 1, ... , J ## The index for a parameter is given by J * (i - 1) + j ## In this example, I = 10, J = 10; Thus: ## (5, 5) -> 10 * (5 - 1) + 5 = 45 ## (5, 6) -> 10 * (5 - 1) + 6 = 46 ## (6, 5) -> 10 * (6 - 1) + 5 = 55 ## (6, 6) -> 10 * (6 - 1) + 6 = 45 Bex1 ## length 101 (includes B0 w/ 100 variable parameter values) length(Bex1$B) ## example: index.type = "rectangle" Bex2 <- beta_builder(row.index = 12:15, col.index = 6:19, im.res = c(20, 20), B0 = 16, B.values = 1:(length(12:15) * length(6:19)), index.type = "rectangle") Bex2 matrix(Bex2$B[-1], nrow = 20, byrow = TRUE) ## example: index.type = "ellipse" Bex3 <- beta_builder(row.index = 4, col.index = 5, im.res = c(10, 10), B0 = 16, B.values = 3, index.type = "ellipse", h = 5, w = 4) Bex3 matrix(Bex3$B[-1], nrow = 10, byrow = TRUE) ## decaying parameter values Bex4 <- beta_builder(row.index = 10, col.index = 20, im.res = c(30, 30), B0 = 0, B.values = 10, index.type = "decay", max.d = 7, output.indices = FALSE) inf_2D_image(B = Bex4, im.res = c(30, 30), binarize.B = FALSE) Bex5 <- beta_builder(row.index = 4, col.index = 5, im.res = c(10, 10), B0 = 16, B.values = 5, index.type = "ellipse", h = 5, w = 4, bayesian = TRUE, bayesian.dist = "gaussian", bayesian.scale = list("binary", c(0, 1, 0.25))) inf_2D_image(B = Bex5$B, im.res = c(10, 10), binarize.B = FALSE) chol_s2Dp Build and Take the Cholesky Decomposition of a Covariance Matrix Description The function first builds a correlation matrix with correlation.builder, converts that matrix to a covariance matrix if necessary, and then takes the Cholesky decomposition of the matrix using either base R or the R package spam. Note that spam is particularly effective when the matrix is sparse. Usage chol_s2Dp( matrix.type = "cov", im.res, use.spam = FALSE, corr.structure = "ar1", rho = NULL, phi = NULL, tau = 1, alpha = 0.75, corr.min = NULL, neighborhood = "none", w = NULL, h = NULL, r = NULL, print.R = FALSE, print.S = FALSE, print.Q = FALSE, sigma = 1, triangle = "upper", print.all = FALSE, round.d = FALSE, return.cov = TRUE, return.prec = TRUE ) Arguments matrix.type Determines whether to build a covariance matrix, "cov", or a precision matrix, "prec". See correlation_builder{sim2Dpredictr} and precision_builder{sim2Dpredictr} for more details. im.res A vector defining the dimension of spatial data. The first entry is the number of rows and the second entry is the number of columns. use.spam If use.spam = TRUE then use tools from the R package spam; otherwise, base R functions are employed. For large dimension MVN with sparse correlation structure, spam is recommended; otherwise, base R may be faster. Defaults to FALSE. corr.structure One of "ar1", exponential, gaussian, or "CS". Correlations between loca- tions i and j are rhod for corr.structure = "ar1", exp(−phi∗d) for corr.structure = "exponential", exp(−phi ∗ d2 ) for corr.structure = "gaussian", and rho when corr.structure = "CS". Note that d is the Euclidean distance be- tween locations i and j. rho This is the maximum possible correlation between locations i and j. For all i,j rho MUST be between -1 and 1. phi A scalar value greater than 0 that determines the decay rate of correlation. This argument is only utilized when corr.structure %in% c("exponential", "gaussian"). tau A vector containing precision parameters. If of length 1, then all precisions are assumed equal. Otherwise the length of tau should equal the number of variables. alpha A scalar value between 0 and 1 that defines the strength of correlations. Note that when alpha = 0 the data are independent and when alpha = 1, the joint distribution is the improper Intrinsic Autoregression (IAR), which cannot be used to generate data. Note also that while alpha does control dependence it is not interpretable as a correlation. corr.min Scalar value to specify the minimum non-zero correlation. Any correlations below corr.min are set to 0. Especially for high image resolution using this option can result in a sparser covariance matrix, which may significantly speed up draws when using spam. This option is preferred to using neighborhood and associated arguments when the primary concern is to avoid very small corre- lations and improve computation efficiency. Default is NULL, which places no restrictions on the correlations. neighborhood Defines the neighborhood within which marginal correlations are non-zero. The default is "none", which allows marginal correlations to extend indefinitely. neighborhood = "round" defines a circular neighborhood about locations and neighborhood = "rectangle" defines a rectangular neighborhood about loca- tions. Note that this argument differs from that in precision_builder, in which neighborhood defines conditional non-zero correlations. w, h If neighborhood = "rectangle" then w and h are the number of locations to the left/right and above/below a location i that define its neighborhood. Any locations outside this neighborhood have have zero correlation with location i. r If neighborhood = "round", then if locations i,j are separated by distance d ≥ r, the correlation between them is zero. print.R, print.S, print.Q Logical. When TRUE, then print the correlation, covariance, or precision matrix before taking the Cholesky decomposition. If sigma = 1, then S = R. sigma Specify the desired standard deviations; the default is 1, in which case the Cholesky decomposition is of a correlation matrix. If sigma != 1, then the Cholesky decomposition is of a covariance Matrix. • If sigma is a vector then length(sigma) must be equal to the total number of locations, i.e. (n.row ∗ n.col)by(n.row ∗ n.col). • sigma can take any scalar value when specifying common standard devia- tion. triangle Determine whether to output an upper (triangle = "upper") or lower (triangle = "lower") triangular matrix. print.all If print.all = TRUE, then prints each correlation and allows you to check whether the correlations are as you intended. This option is NOT recommended for large point lattices/images. round.d If round.d = TRUE, then d is rounded to the nearest whole number. return.cov, return.prec Logical. When TRUE, also return the covariance or precision matrix, respec- tively. This is recommended when using spam to generate draws from the MVN. Value Matrix of dimension (n.row x n.col) x (n.row x n.col). If either return.cov or return.prec is TRUE, then returns a list where the first element is the covariance or precision matrix, and the second element is the Cholesky factor. References <NAME>, <NAME>, Gelfand AE (2015). Hierarchical Modeling and Analysis for Spatial Data, Second edition. Chapman & Hall/CRC, Boca Raton, Florida. Ripley BD (1987). Stochastic Simulation. John Wiley & Sons. doi:10.1002/9780470316726. <NAME> (2001). “Fast Sampling of Gaussian Markov Random Fields.” Journal of the Royal Statisti- cal Society B, 63, 325-338. doi:10.1111/14679868.00288. <NAME>, <NAME> (2010). “spam: A Sparse Matrix R Package with Emphasis on MCMC Methods for Gaussian Markov Random Fields.” Journal of Statistical Software, 36(10), 1-25. https:// www.jstatsoft.org/v36/i10/. Examples ## Use R package spam for Cholesky decomposition R_spam <- chol_s2Dp(im.res = c(3, 3), matrix.type = "prec", use.spam = TRUE, neighborhood = "ar1", triangle = "upper") ## Use base R for Cholesky decomposition R_base <- chol_s2Dp(corr.structure = "ar1", im.res = c(3, 3), rho = 0.15, neighborhood = "round", r = 3, use.spam = FALSE) ## Specify standard deviations instead of default of sigma = 1. R_sd <- chol_s2Dp(corr.structure = "ar1", im.res = c(3, 3), rho = 0.15, neighborhood = "round", r = 3, sigma = runif(9, 1.1, 4)) ## Not run: ## Print options ON R_pr_on <- chol_s2Dp(corr.structure = "ar1", im.res = c(3, 3), rho = 0.15, sigma = 1:9, neighborhood = "round", r = 3, print.R = TRUE, print.S = TRUE) ## End(Not run) classify_multiclass Classify subjects based on predicted probabilities for each class Description Classify subjects based on predicted probabilities for each class. The predicted probabilities can be input by the user or calculated within function using parameter estimates and design matrix for a multinomial regression model. Usage classify_multiclass( predicted.probs = NULL, category.names, keep.probs = TRUE, B = NULL, X = NULL, X.incl.X0 = FALSE ) Arguments predicted.probs A matrix where the number of rows is equal to the number of subjects and the number of columns equals the number of categories. predicted.probs[i, j] contains the probability that subject i belongs to category j. category.names A vector containing the names of each category. The order of names should match the order of columns in predicted.probs; correspondingly, the length of the vector should equal the number of columns in predicted.probs. keep.probs Logical. When TRUE, the output is data frame consisting of the information in predicted.probs with an additional column predicted.class that contains the predicted class for each subject. When FALSE, a vector of the predicted classes is returned. B A list, each element of which contains a parameter vector. The list should have length V - 1, i.e., should contain parameter values associated with all categories except the reference category, following Agresti (2007). Alternatively, B may be a list of length V if one desires to specify parameters for every category, i.e., the over-parameterized model used in Friedman (2010). X A matrix, each row of which contains subject covariate/predictor values. X.incl.X0 Logical. When TRUE, X should contain column of 1’s for the intercept. Other- wise, a column of 1’s is generated internally. Default is FALSE. Details Classification for each subject is determined based on the category with highest predicted probabil- ity. Value Depending on the option selected for keep.probs, returns a data frame or vector. Examples ## number of categories vt <- 3 ## covariate values xt <- matrix(rnorm(10 * 2), ncol = 2, nrow = 10) ## list of parameter vectors (over-parameterized model) bu <- list(b1 = c(0, 0.25, 0.25), b2 = c(0, -0.25, -0.25), b3 = c(0, 0.25, -0.25)) ## subject specific probabilities for each category ## (over-parameterized model) prp <- generate_multinom_probs(V = vt, X = xt, B = bu) classify_multiclass(predicted.probs = prp, category.names = c("A", "B", "C")) ## generate predicted probabilities within function classify_multiclass(predicted.probs = NULL, category.names = c("A", "B", "C"), X = xt, B = bu) correlation_builder Build a Correlation Matrix for 2D Spatial Data Description This function "builds" a correlation matrix based on user specifications. Usage correlation_builder( corr.structure = "ar1", im.res, corr.min = NULL, neighborhood = "none", rho = NULL, phi = NULL, w = NULL, h = NULL, r = NULL, print.all = FALSE, round.d = FALSE ) Arguments corr.structure One of "ar1", exponential, gaussian, or "CS". Correlations between loca- tions i and j are rhod for corr.structure = "ar1", exp(−phi∗d) for corr.structure = "exponential", exp(−phi ∗ d2 ) for corr.structure = "gaussian", and rho when corr.structure = "CS". Note that d is the Euclidean distance be- tween locations i and j. im.res A vector defining the dimension of spatial data. The first entry is the number of rows and the second entry is the number of columns. corr.min Scalar value to specify the minimum non-zero correlation. Any correlations below corr.min are set to 0. Especially for high image resolution using this option can result in a sparser covariance matrix, which may significantly speed up draws when using spam. This option is preferred to using neighborhood and associated arguments when the primary concern is to avoid very small corre- lations and improve computation efficiency. Default is NULL, which places no restrictions on the correlations. neighborhood Defines the neighborhood within which marginal correlations are non-zero. The default is "none", which allows marginal correlations to extend indefinitely. neighborhood = "round" defines a circular neighborhood about locations and neighborhood = "rectangle" defines a rectangular neighborhood about loca- tions. Note that this argument differs from that in precision_builder, in which neighborhood defines conditional non-zero correlations. rho This is the maximum possible correlation between locations i and j. For all i,j rho MUST be between -1 and 1. phi A scalar value greater than 0 that determines the decay rate of correlation. This argument is only utilized when corr.structure %in% c("exponential", "gaussian"). w, h If neighborhood = "rectangle" then w and h are the number of locations to the left/right and above/below a location i that define its neighborhood. Any locations outside this neighborhood have have zero correlation with location i. r If neighborhood = "round", then if locations i,j are separated by distance d ≥ r, the correlation between them is zero. print.all If print.all = TRUE, then prints each correlation and allows you to check whether the correlations are as you intended. This option is NOT recommended for large point lattices/images. round.d If round.d = TRUE, then d is rounded to the nearest whole number. Value Returns (nr ∗ nc)by(nr ∗ nc) correlation matrix. Note Caution is recommended when using corr.min or neighborhood to set many correlations to 0, as not all specifications will result in a positive definite matrix. In particular, sharp drop-offs tend to result in non-positive definite matrices. Examples ## examples correlation_builder(corr.structure = "ar1", im.res = c(3, 3), rho = 0.5, neighborhood = "round", r = 6, print.all = TRUE) correlation_builder(corr.structure = "exponential", im.res = c(3, 3), phi = 0.5, neighborhood = "round", r = 3, print.all = TRUE) correlation_builder(corr.structure = "CS", im.res = c(3, 3), rho = 0.5, print.all = TRUE) ## no "true" zeros, but gets close c.nr <- correlation_builder(corr.structure = "ar1", neighborhood = "none", corr.min = NULL, im.res = c(15, 15), rho = 0.5) length(c.nr[c.nr > 0]) min(c.nr) ## set corr.min gives many zero entries; sparser structure c.r <- correlation_builder(corr.structure = "ar1", neighborhood = "none", corr.min = 0.01, im.res = c(15, 15), rho = 0.5) ## raw number > 0 length(c.r[c.r > 0]) ## proportion > 0 length(c.r[c.r > 0]) / length(c.nr) corr_fun Specify the Correlation Function between Two Locations Description This is primarily for use within correlation builder, and may be altered/expanded to handle more complicated correlation functions if desired. Usage corr_fun( corr.structure, im.res, corr.min = NULL, rho = NULL, phi = NULL, neighborhood = "none", round.d = FALSE, w = NULL, h = NULL, r = NULL, i, j, k, v ) Arguments corr.structure One of "ar1", "exponential", "gaussian", or "CS". Correlations between locations i and j are rhod for corr.structure = "ar1", exp(−phi ∗ d) for corr.structure = "exponential", exp(−phi∗d2 ) for corr.structure = "gaussian", and rho when corr.structure = "CS". Note that d is the Euclidean distance between locations i and j. im.res A vector defining the dimension of spatial data. The first entry is the number of rows and the second entry is the number of columns. corr.min Scalar value to specify the minimum non-zero correlation. Any correlations below corr.min are set to 0. Especially for high image resolution using this option can result in a sparser covariance matrix, which may significantly speed up draws when using spam. This option is preferred to using neighborhood and associated arguments when the primary concern is to avoid very small corre- lations and improve computation efficiency. Default is NULL, which places no restrictions on the correlations. rho This is the maximum possible correlation between locations i and j. For all i,j rho MUST be between -1 and 1. phi A scalar value greater than 0 that determines the decay of correlation. This argu- ment is only utilized when corr.structure %in% c("exponential", "gaussian"). neighborhood Defines the neighborhood within which marginal correlations are non-zero. The default is "none", which allows marginal correlations to extend indefinitely. neighborhood = "round" defines a circular neighborhood about locations and neighborhood = "rectangle" defines a rectangular neighborhood about loca- tions. round.d If round.d = TRUE, then d is rounded to the nearest whole number. w, h If neighborhood = "rectangle" then w and h are the number of locations to the left/right and above/below a location i that define its neighborhood. Any locations outside this neighborhood have have zero correlation with location i. r If neighborhood = "round", then if locations i,j are separated by distance d ≥ r, the correlation between them is zero. i, j, k, v These are the coordinates for the two locations. Location 1 has coordinates (i, j) and location 2 has coordinates (k, v). Value A single element vector containing the correlation between spatial locations with indices (i, j) and (k, v). Examples ## examples corr_fun(corr.structure = "ar1", im.res = c(3, 3), rho = 0.5, neighborhood = "round", r = 6, i = 1, j = 2, k = 2, v = 3) corr_fun(corr.structure = "ar1", im.res = c(3, 3), rho = 0.5, neighborhood = "rectangle", w = 1, h = 1, i = 1, j = 2, k = 2, v = 3) generate_grid Convert a 2D Space to Grid Coordinates Description Input the limits of a 2D space and the desired image resolution, then the function outputs the appro- priate grid/lattice coordinates. Usage generate_grid(im.res, xlim = c(0, 1), ylim = c(0, 1)) Arguments im.res A vector specifying the dimension/resolution of the image. The first entry is the number of ’rows’ in the lattice/image, and the second entry is the number of columns’ in the lattice/image. xlim, ylim These are the 2D image limits. Defaults for both are c(0, 1). It is not rec- ommended to alter these arguments unless changing the limits has a specific practical utility. Value A data frame whose first column is x-coordinates and whose second column is y-coordinates. generate_multinom_probs Generate Probabilities for Multinomial Draws Description Obtain probabilities for each category of a multinomial distribution based on covariate and param- eter values based on the logit models for the multinomial distribution. Usage generate_multinom_probs(V = NULL, B = NULL, X = NULL, X.incl.X0 = FALSE) Arguments V A numeric value stating the number of categories desired. B A list, each element of which contains a parameter vector. The list should have length V - 1, i.e., should contain parameter values associated with all categories except the reference category, following Agresti (2007). Alternatively, B may be a list of length V if one desires to specify parameters for every category, i.e., the over-parameterized model used in Friedman (2010). X A matrix, each row of which contains subject covariate/predictor values. X.incl.X0 Logical. When TRUE, X should contain column of 1’s for the intercept. Other- wise, a column of 1’s is generated internally. Default is FALSE. Value A matrix containing subject-specific probabilities for each category of the multinomial distribution. The number of rows equals nrow(X) and the number of columns equals V. References <NAME> (2007). An Introduction to Categorical Analysis, 2nd edition. <NAME>, Hoboken, New Jersey. <NAME>, <NAME>, <NAME> (2010). “Regularization paths for generalized linear models via coordinate descent.” Journal of Statistical Software, 33, 1-22. doi:10.18637/jss.v033.i01. Examples ## number of categories vt <- 3 ## covariate values xt <- matrix(rnorm(10 * 2), ncol = 2, nrow = 10) ## list of parameter vectors bt <- list(b1 = c(1, 0.25, -0.25), b2 = c(-0.5, 0.15, 0.15)) ## list of parameter vectors (over-parameterized model) bu <- list(b1 = c(1, 0.25, -0.25), b2 = c(-0.5, 0.15, 0.15), b3 = c(-1, 0.1, -0.20)) ## subject specific probabilities for each category generate_multinom_probs(V = vt, X = xt, B = bt) ## subject specific probabilities for each category ## (over-parameterized model) generate_multinom_probs(V = vt, X = xt, B = bu) inf_2D_image Display Inference Results for 2D Predictors Description Provide graphics for spatial extent of predictor parameters, rejections and/or the truth/falsity of the rejections. Usage inf_2D_image( rejections = NULL, B = NULL, im.res, test.statistic = NULL, reject.threshold = NULL, binarize.B = TRUE, grid.color = "grey", n.colors = length(unique(B)), B.incl.B0 = TRUE, plot.title = TRUE, manual.title = NULL, title.size = 1 ) Arguments rejections A binary vector; rejection[i] = 1 means the null hypothesis is rejected for parameter B[i], whereas rejection[i] = 0 means that the null hypothesis was not rejected for parameter B[i]. B A vector of "true" parameter values. For inference purposes, this can be a vector of actual parameter values, or a binary vector indicating non-zero status. im.res A vector defining the dimension of spatial data. The first entry is the number of rows and the second entry is the number of columns. test.statistic A vector of test statistics; e.g., t-statistics or p-values that are used to determine whether or not to reject the null hypothesis. reject.threshold A list whose first element is the rejection criteria, e.g., the minimum t-statistic or maximum p-value for which to reject the null hypothesis. The second element is one of c("greater", "less", "2-tailed"), which tell the function to reject when the values in test.statistic are greater than or less than the thresh- old, the test is a 2-tailed, respectively. In the latter case the function internally calculates the upper or lower threshold needed for the 2-tailed test. binarize.B Either TRUE (default) or FALSE. When binarize.B = TRUE the parameter vec- tor is converted to a binary vector where 1 indicates non-zero parameter and 0 indicates zero-valued parameter. grid.color Specify the color for the grid lines. n.colors Determines the number of colors in the printed image. Default is length(unique(B)), but it is recommended to use trial and error to determine the ideal setting for spe- cific situations. B.incl.B0 If B.incl.B0 = TRUE then the first entry should be the intercept, B0. B.incl.B0 = FALSE indicates that the first entry of B is not an intercept. plot.title When plot.title = TRUE a title accompanies the output graph, and plot.title = FALSE suppresses the title. manual.title When plot.title = TRUE, use manual.title to specify a title manually. title.size Specifies the size of the title text. This is based on cex.main within the image() function. Default is 1. Value An image depicting the spatial extent of some image characteristic. Note If both rejections and B are specified then the function provides an image with separate color each for: • No rejection and B[i] = 0 (i.e. True Negative). • No rejection and B[i] != 0 (i.e. False Negative). • Rejection and B[i] = 0 (i.e. False Positive). • Rejection and B[i] != 0 (i.e. True Positive). Examples ## parameter vector Bex <- beta_builder(row.index = c(rep(5, 3), rep(6, 3), rep(7, 3)), col.index = rep(c(5, 6, 7), 3), im.res = c(10, 10), index.type = "manual", B0 = 0, B.values = 1:9, output.indices = FALSE) ## co-opt beta builder to get rejections rejex <- beta_builder(row.index = c(rep(4, 3), rep(5, 3), rep(6, 3)), col.index = rep(c(4, 5, 6), 3), im.res = c(10, 10), index.type = "manual", B0 = 0, B.values = rep(1, 9), output.indices = FALSE)[-1] rejex.sm2 <- beta_builder(row.index = 5:6, col.index = 5:6, im.res = c(10, 10), B0 = 0, B.values = 1, output.indices = FALSE)[-1] ## just B inf_2D_image(B = Bex, im.res = c(10, 10)) ## just rejections inf_2D_image(rejections = rejex, im.res = c(10, 10)) ## both B and rejections inf_2D_image(rejections = rejex, B = Bex, im.res = c(10, 10)) inf_2D_image(rejections = rejex.sm2, B = Bex, im.res = c(10, 10)) ## larger dimension example Bex2 <- beta_builder(row.index = 5:15, col.index = 16:20, im.res = c(50, 50), B0 = 0, B.values = 1:(length(5:15) * length(16:20)), index.type = "rectangle", output.indices = FALSE) rejex2 <- beta_builder(row.index = 13:21, col.index = 30:41, im.res = c(50, 50), B0 = 0, B.values = rep(1, (length(13:21) * length(30:41))), index.type = "rectangle", output.indices = FALSE)[-1] rejex3 <- beta_builder(row.index = 5:20, col.index = 16:30, im.res = c(50, 50), B0 = 0, B.values = rep(1, (length(5:20) * length(16:30))), index.type = "rectangle", output.indices = FALSE)[-1] rejex4 <- beta_builder(row.index = 5:10, col.index = 16:17, im.res = c(50, 50), B0 = 0, B.values = rep(1, (length(5:10) * length(16:17))), index.type = "rectangle", output.indices = FALSE)[-1] ## images inf_2D_image(B = Bex2, im.res = c(50, 50)) inf_2D_image(B = Bex2, im.res = c(50, 50), binarize.B = FALSE) inf_2D_image(rejections = rejex2, im.res = c(50, 50)) ## No TP inf_2D_image(rejections = rejex2, B = Bex2, im.res = c(50, 50)) ## ALL TP inf_2D_image(rejections = Bex2[-1], B = Bex2, im.res = c(50, 50)) ## No FN inf_2D_image(rejections = rejex3, B = Bex2, im.res = c(50, 50)) ## No FP, but FN inf_2D_image(rejections = rejex4, im.res = c(50, 50)) inf_2D_image(B = Bex2, im.res = c(50, 50)) inf_2D_image(rejections = rejex4, B = Bex2, im.res = c(50, 50)) make_rejection Determine rejections Description Determine rejections Usage make_rejection(B, reject.threshold, test.statistic) Arguments B A vector of "true" parameter values. For inference purposes, this can be a vector of actual parameter values, or a binary vector indicating non-zero status. reject.threshold A list whose first element is the rejection criteria, e.g., the minimum t-statistic or maximum p-value for which to reject the null hypothesis. The second element is one of c("greater", "less", "2-tailed"), which tell the function to reject when the values in test.statistic are greater than or less than the thresh- old, the test is a 2-tailed, respectively. In the latter case the function internally calculates the upper or lower threshold needed for the 2-tailed test. test.statistic A vector of test statistics; e.g., t-statistics or p-values that are used to determine whether or not to reject the null hypothesis. Value A vector of hypothesis testing rejection indicators, where 1 indicates a rejection and 0 otherwise. neighbors_by_dist Determine and store neighbors by Euclidean Distance Constraints Description Determine and store neighbors by Euclidean Distance Constraints Usage neighbors_by_dist(x, y, coords, im.res, r, print.ring = FALSE) Arguments x, y are the row and column coordinates, respectively. coords A dataframe containing indices and coordinates for the image. im.res A vector containing the number of rows and columns, respectively. r A scalar value determining the radius within which other locations are neighbors to the current location (x, y). print.ring When print.ring = TRUE, each iteration is shown, with corresponding infor- mation regarding the number of neighbors present in each ring. This argument primarily exists to allow the user to test whether the neighborhood structure specified is as desired. Value A tibble whose first column contains x indices, second column contains y indices, and third column denotes the current ring about a location. Note This function avoids testing all points for being with a certain distance in order to determine neigh- bor status of a given point by progressively widening a box around the point. Each iteration widens the box by an extra ring, and we only test points in the new ring. If at the end of testing a ring there are no new neighbors then we stop expanding the box and return the neighbors’ coordinates. For computational efficiency, this function assumes that all arguments except the current point’s coordinates have been specified. Examples ## Necessary pre-specified arguments required for the function to work. ## image resoluation + number of spatial predictors im.res <- c(5, 5) J <- prod(im.res) ## create predictor indices w/ coordinates row.id <-rep(1, im.res[2]) for (i in 2:im.res[1]) { row.id <- c(row.id, rep(i, im.res[2])) } coords <- data.frame(index = 1:J, row.id = row.id, col.id = rep(c(1:im.res[2]), im.res[1]) ) neighbors_by_dist(x = 2, y = 2, im.res = im.res, coords = coords, r = 2) precision_builder Construct a Precision Matrix Description This function constructs the precision matrix for a Conditional Autoregression (CAR). Usage precision_builder( im.res, tau = 1, alpha = 0.75, neighborhood = "ar1", weight = "binary", phi = 1, r = NULL, w = NULL, h = NULL, digits.Q = 10 ) Arguments im.res A vector defining the dimension of spatial data. The first entry is the number of rows and the second entry is the number of columns. tau A vector containing precision parameters. If of length 1, then all precisions are assumed equal. Otherwise the length of tau should equal the number of variables. alpha A scalar value between 0 and 1 that defines the strength of correlations. Note that when alpha = 0 the data are independent and when alpha = 1, the joint distribution is the improper Intrinsic Autoregression (IAR), which cannot be used to generate data. Note also that while alpha does control dependence it is not interpretable as a correlation. neighborhood Defines the neighborhood within which conditional correlations are non-zero. This differs from use in correlation_builder, where the neighborhood de- fines non-zero marginal correlations. The default is "ar1", which creates a neighborhood where the spatial locations directly above, below, left, and right of a location are included in the neighborhood. More complicated neighborhoods can be specified by neighborhood = "round", which defines a circular neigh- borhood about each location, and neighborhood = "rectangle", which defines a rectangular neighborhood about each location. weight Determines how weights are assigned. "distance" assigns weights as the in- verse of Euclidean distance times a constant, phi. "binary" assigns weights to 1 for neighbors and 0 otherwise. phi When weight = "distance" a constant by which to multiply the inverse of Eu- clidean distance. Defaults to 1, and must exceed 0. r If neighborhood = "round", then locations i,j are separated by distance d ≥ r are conditionally independent. w, h If neighborhood = "rectangle" then w and h are the number of locations to the left/right and above/below a location i that define its neighborhood. Any lo- cations outside this neighborhood are conditionally independent of the specified location. digits.Q Determines the number of digits to round entries in the precision matrix. Default is 10. Details This formulation of the CAR model is based on a formulation found in (Banerjee et al. 2015) where the joint distribution of the of the conditionally specified random variables are assumed to be N (0, [diag(tau2 )(D − alphaW )]−1 ) and all neighbors are weighted 1. When weights other than 1 are desired, the joint distribution is N (0, [diag(tau2 )D(I − alphaD−1 W )]−1 ), e.g. as in (Jin et al. 2005). Value A (precision) matrix. References <NAME>, <NAME>, Gelfand AE (2015). Hierarchical Modeling and Analysis for Spatial Data, Second edition. Chapman & Hall/CRC, Boca Raton, Florida. <NAME>, <NAME>, <NAME> (2005). “Generalized Hierarchical Multivariate CAR Models for Areal Data.” Biometrics, 61(4), 950-961. doi:10.1111/j.15410420.2005.00359.x. Examples ## Not run: precision_builder(im.res = c(3, 3), tau = 1, alpha = 0.75, neighborhood = "ar1") ## binary weights precision_builder(im.res = c(3, 3), tau = 1, alpha = 0.75, neighborhood = "round", r = 3) ## weights based on distance precision_builder(im.res = c(3, 3), tau = 1, alpha = 0.75, weight = "distance", phi = 1, neighborhood = "round", r = 3) precision_builder(im.res = c(3, 3), tau = 1, alpha = 0.75, neighborhood = "rectangle", w = 2, h = 2) ## End(Not run) proximity_builder Generate a Proximity Matrix Description Generates a proximity matrix where non-zero entries are the weights associated with neighbors, and zero entries are not neighbors. Usage proximity_builder( im.res, neighborhood = "ar1", type = c("sparse", "full"), weight = "binary", phi = 1, r = NULL, h = NULL, w = NULL, include.coords = FALSE, print.im = FALSE ) Arguments im.res A vector defining the dimension of spatial data. The first entry is the number of rows and the second entry is the number of columns. neighborhood Determines how to assign neighbor status to locations; i.e. 1 for neighbors, 0 otherwise. type = "round" assigns neighbor status to locations within ra- dius r. type = "ar1" assigns 1 to locations directly above or beside. type = "rectangle" assigns neighbor status to locations within w units to the left or right and h units up or down. type Specifies either sparse (type = "sparse") or full (type = "full") proximity matrix. weight Determines how weights are assigned. "distance" assigns weights as the in- verse of Euclidean distance times a constant, phi. "binary" assigns weights to 1 for neighbors and 0 otherwise. phi When weight = "distance" a constant by which to multiply the inverse of Eu- clidean distance. Defaults to 1. r, h, w When neighborhood = "round", r specifies the radius within which other loca- tions are neighbors. When neighborhood = "rectangle", w and h specify the number of units to the left/right and above/below the location are to be counted as neighbors. include.coords If type = "sparse" and include.coords = TRUE, then the coordinates of neigh- bors are returned along with their indices. print.im Allows user to print the 2D "image" matrix with index labels to visually verify that the proximity matrix is as expected. Value A (proximity) matrix. Examples ## Not run: ## adjacency matrix with sparse structure (i.e., 2 columns) ## and ar1 neighborhood sp.ar1 <- proximity_builder(im.res = c(3, 3), weight = "binary", neighborhood = "ar1", type = "sparse") ## adjacency matrix with full structure ## (i.e., prod(im.dim) rows & columns) and ar1 neighborhood full.ar1 <- proximity_builder(im.res = c(3, 3), weight = "binary", neighborhood = "ar1", type = "full") ## proximity matrix weighted by distance (sparse) sp.rnd <- proximity_builder(im.res = c(3, 3), weight = "distance", neighborhood = "round", r = 2, type = "sparse", include.coords = TRUE) ## proximity matrix weighted by distance (full) full.rnd <- proximity_builder(im.res = c(3, 3), weight = "distance", neighborhood = "round", r = 2, type = "full") ## End(Not run) sample_FP_Power Obtain Sample False Positive Rates and Power Description This function calculates sample FDR, FWER, and Power for large numbers of predictors, given a vector of "true" parameter values and a vector of associated rejections. In the case that more than 1 predictor has a "true" non-zero parameter, then Power is defined as the proportion/percentage of those "true" parameters identified. Usage sample_FP_Power( rejections = NULL, FP = NULL, TP = NULL, test.statistic = NULL, reject.threshold = NULL, B = NULL, B.incl.B0 = TRUE, full.summary = FALSE ) Arguments rejections A binary vector; rejection[i] = 1 means the null hypothesis is rejected for parameter B[i], whereas rejection[i] = 0 means that the null hypothesis was not rejected for parameter B[i]. FP, TP Binary vectors of false positive and true positive indicators, respectively. FP[i] = 1 means the null hypothesis was incorrectly rejected, and TP[i] = 1 means the null hypothesis was correctly rejected. If either argument is NULL, then these vectors are computed; this is the default setting. test.statistic A vector of test statistics; e.g., t-statistics or p-values that are used to determine whether or not to reject the null hypothesis. reject.threshold A list whose first element is the rejection criteria, e.g., the minimum t-statistic or maximum p-value for which to reject the null hypothesis. The second element is one of c("greater", "less", "2-tailed"), which tell the function to reject when the values in test.statistic are greater than or less than the thresh- old, the test is a 2-tailed, respectively. In the latter case the function internally calculates the upper or lower threshold needed for the 2-tailed test. B A vector of "true" parameter values. For inference purposes, this can be a vector of actual parameter values, or a binary vector indicating non-zero status. B.incl.B0 If B.incl.B0 = TRUE then the first entry should be the intercept, B0. B.incl.B0 = FALSE indicates that the first entry of B is not an intercept. full.summary If full.summary = TRUE then the total numbers of rejections, false positives, true positives, and non-zero parameters are output along with FDR, FWER, and Power; otherwise, only FDR, FWER, and Power are output. Value A data frame with columns for sample FDR, FWER, and Power. Note The default operating approach is that the null hypothesis is B[i] = 0 for each parameter. If other hypotheses are being tested then B should be converted to a binary vector indicating whether the null hypothesis should have been rejected. Examples ## example 1 ## rejection vector rej.ex <- c(0, 1, 1, 0, 0, 1, 0) ## false positive vector fp.ex <- c(0, 0, 1, 0, 0, 0, 0) ## true positive vector tp.ex <- c(0, 1, 0, 0, 0, 1, 0) ## parameter vector par.ex <- c(0, 4, 0, 0, 3, 9, 0) sample_FP_Power(rej.ex, fp.ex, tp.ex, par.ex, B.incl.B0 = FALSE) ## Function can calculate TP and FP vectors sample_FP_Power(rejections = rej.ex, FP = NULL, TP = NULL, B = par.ex, B.incl.B0 = FALSE) ## example 2: sum(FP, TP) must equal sum(rejections) or ## function stops execution rej.ex2 <- c(0, 1, 0, 0, 0, 1, 0) fp.ex2 <- c(0, 0, 1, 0, 0, 0, 0) tp.ex2 <- c(0, 1, 0, 0, 0, 1, 0) par.ex2 <- c(0, 4, 0, 0, 3, 9, 0) ## Not run: sample_FP_Power(rej.ex2, fp.ex2, tp.ex2, par.ex2, B.incl.B0 = FALSE) ## End(Not run) ## example 3: calculate rejections from vector of test statistics zstat <- c(-0.5, 1.98, 2.01, 1.45, -1.99) # 2-tailed sample_FP_Power(test.statistic = zstat, reject.threshold = list(1.96, "2-tailed"), B = c(0, 0, 4, 1, -2), B.incl.B0 = FALSE) # 1-tailed (upper) sample_FP_Power(test.statistic = zstat, reject.threshold = list(1.96, "greater"), B = c(0, 0, 4, 1, -2), B.incl.B0 = FALSE) ## p-value sample_FP_Power(test.statistic = c(0.44, 0.04, 0.01, 0.06, 0.02 ), reject.threshold = list(0.05, "less"), B = c(0, 0, 4, 1, -2), B.incl.B0 = FALSE) sim2D_binarymap Generate a Binary Map via the Boolean Method Description Use a Homogenous Poisson Process to generate random "events", a uniform distribution to generate circles of random radii about the events, and take the union to obtain a random set. This is mapped onto a lattice to obtain a binary map. Usage sim2D_binarymap( N, xlim = c(0, 1), ylim = c(0, 1), im.res, radius.bounds = c(0.02, 0.1), lambda = 50, random.lambda = FALSE, lambda.sd = 10, lambda.bound = NULL, prior = "gamma", sub.area = FALSE, min.sa = c(0.1, 0.1), max.sa = c(0.3, 0.3), radius.bounds.min.sa = c(0.02, 0.05), radius.bounds.max.sa = c(0.08, 0.15), print.subj.sa = FALSE, print.lambda = FALSE, print.iter = FALSE, store.type = "list", output.randset = FALSE ) Arguments N A scalar value determining the number of images to create. xlim, ylim These are the 2D image limits. Defaults for both are c(0, 1). It is not rec- ommended to alter these arguments unless changing the limits has a specific practical utility. im.res A vector specifying the dimension/resolution of the image. The first entry is the number of ’rows’ in the lattice/image, and the second entry is the number of columns’ in the lattice/image. radius.bounds A 2-element vector whose first and second entries determine the minimum and maximum radius sizes, respectively; these will be the bounds of the uniform dis- tribution used to draw the radii. If sub.area = TRUE, then use radius.bounds.min.sa and radius.bounds.max.sa. lambda A scalar value specifying the mean/intensity value of the Poisson process. If random.lambda = FALSE then this is the parameter used to generate the binary image for each subject. If random.lambda = TRUE, then this is the mean param- eter in the distribution used to draw subject-specific lambda. random.lambda random.lambda = TRUE allows the lambda (mean/intensity) parameter in the Poisson process to vary randomly by subject. lambda.sd Only utilized when random.lambda = TRUE, and specifies the standard deviation in the distribution used to draw subject-specific lambda. lambda.bound Only utilized when random.lambda = TRUE, and allows the user to specify a lower and upper bound for the subject-specific lambda; if the randomly selected value is outside of this range, then another draw is taken. This continues until a value is selected within the specified bounds. If no bounds are desired then specify lambda.bound = NULL. prior Only utilized when random.lambda = TRUE, and specifies the distribution from which to draw the subject-specific lambda. Options are c("gaussian", "gamma"). sub.area When sub.area = TRUE, a random sub-section of the image is chosen, within which the Poisson process is used to generate the binary image. min.sa, max.sa Only utilized when sub.area = TRUE, and determines the width and height of the minimum and maximum sub-areas; e.g., if min.sa = c(0.1, 0.1), then the smallest possible random sub-area is a 0.1 x 0.1 square. radius.bounds.min.sa, radius.bounds.max.sa Only utilized when sub.area = TRUE, and specifies radius.bounds for the min- imum and maximum sub-areas, respectively. This information is used to adap- tively alter the bounds in between the minimum and maximum sub-areas. print.subj.sa, print.lambda, print.iter These arguments are either TRUE or FALSE, and define print options for check- ing that the function is working as the user intends. print.subj.sa = TRUE prints the x-and y-limits for each subject’s sub-area. print.lambda = TRUE prints each subject’s mean and realized events; the means will be the same un- less random.lambda = TRUE, but the number of realized events will always vary. print.iter = TRUE is only used when random.lambda = TRUE and is.null(lambda.bound) = FALSE, and shows iterations for re-drawing when the randomly selected inten- sity is outside the specified bounds. store.type One of c("list", "matrix", "all"). When store.type = "list", the out- put is a list where each element is a matrix defining a subject image. If store.type = "matrix", then the images are vectorized by row and each row of the output matrix contains an image vector for a single subject. output.randset Logical. When TRUE, stores the data frame of original draws from the HPPP and and random radii from sim2D_RandSet_HPPP(). This data frame is stored in the first element of the output list named randset. The second element of the output list is a list/matrix of the final subject images depending on store.type and named images. Value A list; each element is a matrix of zeroes and ones. References <NAME>, <NAME> (2011). Statistics for Spatio-Temporal Data, Wiley Series in Probability and Statistics. John Wiley & Sons, Hoboken, NJ. Examples bin_ims <- sim2D_binarymap(N = 5, im.res = c(10, 10), store.type = "list", lambda = 50, sub.area = TRUE, min.sa = c(0.10, 0.10), max.sa = c(0.5, 0.5), radius.bounds.min.sa = c(0.015, 0.04), radius.bounds.max.sa = c(0.041, 0.06)) rotate = function(x){ t(apply(x, 2, rev)) } for (i in 1:length(bin_ims)) { image(rotate(bin_ims[[i]]), col = c("white", "darkgreen"), axes = FALSE) box() grid(nx = 10, ny = 10, col = "black", lty = 1) } sim2D_RandSet_HPPP Generate a Random Set Using a Poisson Process and Random Radii About Events Description A random set is generated by using a Poisson process in 2D space to choose ’event’ locations, about which a circle of random radius is ’drawn’. The union of the circles defines ultimately defines the set. Usage sim2D_RandSet_HPPP( N, xlim = c(0, 1), ylim = c(0, 1), radius.bounds = c(0.02, 0.1), lambda = 50, lambda.sd = 10, lambda.bound = NULL, prior = "gamma", random.lambda = FALSE, sub.area = FALSE, min.sa = c(0.1, 0.1), max.sa = c(0.3, 0.3), radius.bounds.min.sa = c(0.02, 0.05), radius.bounds.max.sa = c(0.08, 0.15), print.subj.sa = FALSE, print.lambda = FALSE, print.iter = FALSE ) Arguments N A scalar value determining the number of images to create. xlim, ylim These are the 2D image limits. Defaults for both are c(0, 1). It is not rec- ommended to alter these arguments unless changing the limits has a specific practical utility. radius.bounds A 2-element vector whose first and second entries determine the minimum and maximum radius sizes, respectively; these will be the bounds of the uniform dis- tribution used to draw the radii. If sub.area = TRUE, then use radius.bounds.min.sa and radius.bounds.max.sa. lambda A scalar value specifying the mean/intensity value of the Poisson process. If random.lambda = FALSE then this is the parameter used to generate the binary image for each subject. If random.lambda = TRUE, then this is the mean param- eter in the distribution used to draw subject-specific lambda. lambda.sd Only utilized when random.lambda = TRUE, and specifies the standard deviation in the distribution used to draw subject-specific lambda. lambda.bound Only utilized when random.lambda = TRUE, and allows the user to specify a lower and upper bound for the subject-specific lambda; if the randomly selected value is outside of this range, then another draw is taken. This continues until a value is selected within the specified bounds. If no bounds are desired then specify lambda.bound = NULL. prior Only utilized when random.lambda = TRUE, and specifies the distribution from which to draw the subject-specific lambda. Options are c("gaussian", "gamma"). random.lambda random.lambda = TRUE allows the lambda (mean/intensity) parameter in the Poisson process to vary randomly by subject. sub.area When sub.area = TRUE, a random sub-section of the image is chosen, within which the Poisson process is used to generate the binary image. min.sa, max.sa Only utilized when sub.area = TRUE, and determines the width and height of the minimum and maximum sub-areas; e.g., if min.sa = c(0.1, 0.1), then the smallest possible random sub-area is a 0.1 x 0.1 square. radius.bounds.min.sa, radius.bounds.max.sa Only utilized when sub.area = TRUE, and specifies radius.bounds for the min- imum and maximum sub-areas, respectively. This information is used to adap- tively alter the bounds in between the minimum and maximum sub-areas. print.subj.sa, print.lambda, print.iter These arguments are either TRUE or FALSE, and define print options for check- ing that the function is working as the user intends. print.subj.sa = TRUE prints the x-and y-limits for each subject’s sub-area. print.lambda = TRUE prints each subject’s mean and realized events; the means will be the same un- less random.lambda = TRUE, but the number of realized events will always vary. print.iter = TRUE is only used when random.lambda = TRUE and is.null(lambda.bound) = FALSE, and shows iterations for re-drawing when the randomly selected inten- sity is outside the specified bounds. Value A dataframe with columns for subject ID, x-coordinates, y-coordinates, and associated radii. References <NAME>, <NAME> (2011). Statistics for Spatio-Temporal Data, Wiley Series in Probability and Statistics. <NAME> & <NAME>, NJ. sim_MVN_X Simulate Spatially Correlated MVN Data Description Takes N draws from a Multivariate Normal (MVN) distribution using either base R or the R package spam. This function requires the Cholesky decomposition of the desired covariance matrix. Usage sim_MVN_X( N, mu = 0, L = NULL, R = NULL, S = NULL, Q = NULL, use.spam = FALSE, use.MASS = FALSE, X.categorical = FALSE, X.num.categories = 2, X.category.type = "percentile", X.percentiles = NULL, X.manual.thresh = NULL, X.cat.names = NULL ) Arguments N The number of draws to take from MVN; i.e., the number of subjects. mu One of the following: • A single scalar value for common mean. • A vector of length nrow(R) (equivalently nrow(R)) containing means for the MVN. L, R L and R are lower and upper triangular matrices, respectively, and are the Cholesky factor(s) of the desired covariance matrix for the MVN. Obtain L or R via chol_s2Dp() with settings triangle = "lower" or triangle = "upper", respectively. Spec- ify either L or R, but NOT both. S, Q A covariance or precision matrix respectively. These are for use with spam, and can be extracted from output of chol_s2Dp after choosing return.cov = TRUE or return.prec = TRUE, respectively. use.spam Logical. If use.spam = TRUE then use tools from the R package spam; other- wise, base R functions are employed. For large dimension MVN with sparse correlation structure, spam is recommended; otherwise, base R may be faster. Defaults to FALSE. Requires either the covariance matrix S or precision matrix, Q, that corresponds to the Cholesky factor. use.MASS Logical. When TRUE draws X from MVN using mvrnorm from MASS. Note that this requires specification of the covariance matrix, S. Specifying the precision matrix instead may slow down the process for large dimensions. Recommended to use spam to generate draws when specifying a precision matrix, Q. X.categorical Default is X.categorical = FALSE. If X.categorical = TRUE then thresholds are applied to categorize each predictor/image value. X.num.categories A scalar value denoting the number of categories in which to divide the data. X.category.type Tells R how to categorize the data. Options are X.category.type = c("percentile", "manual"). If X.category.type = "percentile" then the data are divided into percentiles based on X.num.categories; e.g. if X.num.categories = 4 then the values are divided into quartiles, and values in Q1 equal 0, be- tween Q1 and Q2 equal 1, between Q2 and Q3 equal 2, and greater than Q3 equal 3. If X.category.type = "manual" then specify the cutoff points with X.manual.thresh. X.percentiles A vector of percentiles to be used in thresholding when X.categorical = TRUE and X.category.type = "percentile". The length of this vector should equal the number of categories minus one, and all values should be between zero and one. X.manual.thresh A vector containing the thresholds for categorizing the values; e.g. if X.num.categories = 4 and X.manual.thresh = c(-3, 1, 17), then values less than -3 are set to 0, equal or greater than -3 and less than 1 are set to 1, equal or greater than 1 but less than 17 are set to 2, and equal or greater than 17 are set to 3. Note that length(X.manual.thresh) must always equal X.num.categories - 1. X.cat.names A vector of category names. If X.cat.names = NULL then the initial integers assigned are left as the values; the names in X.cat.names are assigned in as- cending order. Value Matrix of dimension N x (nrow(L)) (or equivalently N x (nrow(R))) where each row is draw from MVN, and each column represents a different "variable"; e.g. location in an image. Note This function requires the Cholesky decomposition of the desired covariance matrix for the MVN; this allows for using this function in simulating multiple datasets of N MVN draws while only taking the Cholesky decomposition of the covariance matrix once. References <NAME>, <NAME> (2010). “spam: A Sparse Matrix R Package with Emphasis on MCMC Methods for Gaussian Markov Random Fields.” Journal of Statistical Software, 36(10), 1-25. https:// www.jstatsoft.org/v36/i10/. <NAME> (1987). Stochastic Simulation. John Wiley & Sons. doi:10.1002/9780470316726. <NAME> (2001). “Fast Sampling of Gaussian Markov Random Fields.” Journal of the Royal Statisti- cal Society B, 63, 325-338. doi:10.1111/14679868.00288. Examples ## verify MVN with base R set.seed(732) Lex <- chol_s2Dp(corr.structure = "ar1", im.res = c(3, 3), rho = 0.25, sigma = 1, use.spam = FALSE, corr.min = 0.02, triangle = "lower", return.cov = TRUE) XbR = sim_MVN_X(N = 1000, mu = 0, L = Lex$L) apply(XbR, 2, mean) cov(XbR) Lex$S ## verify MVN with \code{spam} set.seed(472) Rex <- chol_s2Dp(im.res = c(3, 3), matrix.type = "prec", use.spam = TRUE, neighborhood = "ar1", triangle = "upper", return.prec = TRUE) Xspam = sim_MVN_X(N = 1000, mu = 0, R = Rex$R, Q = Rex$Q) apply(Xspam, 2, mean) solve(cov(Xspam)) as.matrix(Rex$Q) ## Categories set.seed(832) Xtest <- sim_MVN_X(N = 30, mu = 0, L = Lex$L, X.categorical = TRUE, X.num.categories = 3, X.category.type = "percentile", X.cat.names = c("A", "B", "C")) Xtest sim_Y_Binary_X Simulate Scalar Outcomes from Simulated Spatially Dependent Binary Predictors Description N spatially dependent binary design vectors are simulated using sim2D_binarymap. These design vectors are used to then simulate scalar outcomes that have one of Gaussian, Binomial, or Poisson distributions. Usage sim_Y_Binary_X( N, B, rand.err = 1, dist, incl.subjectID = TRUE, binomial.method = "traditional", count.method = "traditional", Y.thresh = NULL, print.out = FALSE, xlim = c(0, 1), ylim = c(0, 1), im.res, radius.bounds = c(0.02, 0.1), lambda = 50, random.lambda = FALSE, lambda.sd = 10, lambda.bound = NULL, prior = "gamma", sub.area = FALSE, min.sa = c(0.1, 0.1), max.sa = c(0.3, 0.3), radius.bounds.min.sa = c(0.02, 0.05), radius.bounds.max.sa = c(0.08, 0.15), print.subj.sa = FALSE, print.lambda = FALSE, print.iter = FALSE ) Arguments N A scalar value determining the number of images to create. B A vector parameter values; i.e. "betas". Note that length(B) must equal p + 1 = n.row * n.col + 1; e.g. for normal outcomes Y = XB + e with Y a scalar outcome and e the random error. rand.err A scalar for the random error variance when dist = "gaussian". dist The distribution of the scalar outcome. • dist = "gaussian" has Y = XB + e, where e N (0, rand.err). • dist = "binomial" is drawn from eqnBin(XB, XB(1-XB)) using rbinom() when binary.method = "Traditional". If binary.method = "Gaussian", then simulation is based on a cutoff using binary.cutoff. • dist = "poisson" is drawn from P oisson(XB) using rpois(). incl.subjectID When incl.subjectID = TRUE a column of subject indices is generated. Y.thresh = NULL (default). If binomial.method = "gaussian manual", then Y.thresh should be any scalar real number; values equal or above this cutoff are as- signed 1 and values below are assigned 0. If binomial.method = "gaussian percentile", then values equal or above this percentile are assigned 1, and other wise 0; in this case values should be between 0 and 1. For example, if Y.thresh = 0.9, then the cutoff is the 90th percentile. binomial.method One of c("traditional", "gaussian manual","gaussian percentile"). Only specified when dist = "binomial", and determines whether draws are directly taken from a binomial distribution or if draws are taken from a Multivariate Nor- mal Distribution (in the manner of dist = "gaussian") and thresholds imposed to binarize the outcomes. binomial.method = "gaussian manual" allows the user to specify specific values for categorizing outcomes. binomial.method = "gaussian percentile" allows the user to specify percentiles for binariz- ing the data. Both approaches use Y.thresh to specify the cutoff value(s). If binomial.method = "gaussian percentile" and Y.thresh = NULL then the median is used as the threshold. If binomial.method = "gaussian manual" and Y.thresh = NULL, then 0 is used as the threshold. Default is binomial.method = "traditional". count.method One of c("traditional", "rounding"). When count.method = "traditional", the outcomes are drawn sequentially using rpois(). When count.method = "traditional", the outcomes are drawn from an MVN, then values less than or equal to 0 are set to 0, and all other values are rounded to the nearest whole number. Y.thresh When binomial.method = "traditional" print.out If print.out = TRUE then print the following for each subject, indexed y: • X[y] %*% B • p[y], lambda[y] for Binomial, Poisson, respectively. This is useful to see the effect of image parameter selection and beta parameter selection on distributional parameters for the outcome of interest. xlim, ylim These are the 2D image limits. Defaults for both are c(0, 1). It is not rec- ommended to alter these arguments unless changing the limits has a specific practical utility. im.res A vector specifying the dimension/resolution of the image. The first entry is the number of ’rows’ in the lattice/image, and the second entry is the number of columns’ in the lattice/image. radius.bounds A 2-element vector whose first and second entries determine the minimum and maximum radius sizes, respectively; these will be the bounds of the uniform dis- tribution used to draw the radii. If sub.area = TRUE, then use radius.bounds.min.sa and radius.bounds.max.sa. lambda A scalar value specifying the mean/intensity value of the Poisson process. If random.lambda = FALSE then this is the parameter used to generate the binary image for each subject. If random.lambda = TRUE, then this is the mean param- eter in the distribution used to draw subject-specific lambda. random.lambda random.lambda = TRUE allows the lambda (mean/intensity) parameter in the Poisson process to vary randomly by subject. lambda.sd Only utilized when random.lambda = TRUE, and specifies the standard deviation in the distribution used to draw subject-specific lambda. lambda.bound Only utilized when random.lambda = TRUE, and allows the user to specify a lower and upper bound for the subject-specific lambda; if the randomly selected value is outside of this range, then another draw is taken. This continues until a value is selected within the specified bounds. If no bounds are desired then specify lambda.bound = NULL. prior Only utilized when random.lambda = TRUE, and specifies the distribution from which to draw the subject-specific lambda. Options are c("gaussian", "gamma"). sub.area When sub.area = TRUE, a random sub-section of the image is chosen, within which the Poisson process is used to generate the binary image. min.sa, max.sa Only utilized when sub.area = TRUE, and determines the width and height of the minimum and maximum sub-areas; e.g., if min.sa = c(0.1, 0.1), then the smallest possible random sub-area is a 0.1 x 0.1 square. radius.bounds.min.sa, radius.bounds.max.sa Only utilized when sub.area = TRUE, and specifies radius.bounds for the min- imum and maximum sub-areas, respectively. This information is used to adap- tively alter the bounds in between the minimum and maximum sub-areas. print.subj.sa, print.lambda, print.iter These arguments are either TRUE or FALSE, and define print options for check- ing that the function is working as the user intends. print.subj.sa = TRUE prints the x-and y-limits for each subject’s sub-area. print.lambda = TRUE prints each subject’s mean and realized events; the means will be the same un- less random.lambda = TRUE, but the number of realized events will always vary. print.iter = TRUE is only used when random.lambda = TRUE and is.null(lambda.bound) = FALSE, and shows iterations for re-drawing when the randomly selected inten- sity is outside the specified bounds. Value A data frame where each row consists of a single subject’s data. Col 1 is the outcome, Y, and each successive column contains the subject predictor values. Note Careful parameter selection, i.e. B, is necessary to ensure that simulated outcomes are reasonable; in particular, counts arising from the Poisson distribution can be unnaturally large. References <NAME>, <NAME> (2011). Statistics for Spatio-Temporal Data, Wiley Series in Probability and Statistics. John Wiley & Sons, Hoboken, NJ. <NAME> (1987). Stochastic Simulation. John Wiley & Sons. doi:10.1002/9780470316726. Examples ## Define non-zero beta values Bex <- beta_builder(row.index = c(3, 3, 4), col.index = c(3, 4, 3), im.res = c(5, 5), B0 = 0, B.values = rep(1/3, 3), output.indices = FALSE) ## Simulate Datasets ## parameter values Nex = 10 set.seed(28743) Gauss.ex <- sim_Y_Binary_X(N = Nex, B = Bex, dist = "gaussian", im.res = c(5, 5)) hist(Gauss.ex$Y) ## direct draws from binomial Bin.ex <- sim_Y_Binary_X(N = Nex, B = Bex, im.res = c(5, 5), dist = "binomial", print.out = TRUE) table(Bin.ex$Y) sim_Y_MVN_X Simulate Scalar Outcomes from Simulated Spatially Correlated Pre- dictors Description N spatially correlated design vectors are simulated from an MVN. These design vectors are used to then simulate scalar outcomes that have one of Gaussian, Binomial, Multinomial or Poisson distributions. Usage sim_Y_MVN_X( N, B, L = NULL, R = NULL, S = NULL, Q = NULL, use.spam = TRUE, mu = 0, rand.err = 1, dist = "gaussian", V = NULL, incl.subjectID = TRUE, threshold.method = "none", Y.thresh = NULL, X.categorical = FALSE, X.num.categories = 2, X.category.type = "percentile", X.manual.thresh = NULL, X.cat.names = NULL, print.out = FALSE ) Arguments N The number of draws to take from MVN; i.e., the number of subjects. B A vector parameter values; i.e. "betas". Note that length(B) must equal p + 1 = n.row * n.col + 1; e.g. for normal outcomes Y = XB + e with Y a scalar outcome and e the random error. Note that when dist = "multinomial" then B should be a list with length equal to V - 1, i.e., should contain parameter values associated with all categories except the reference category. Alternatively, when dist = "multinomial" B may be a list of length V if one desires to specify pa- rameters for every category, i.e., the over-parameterized model used in Friedman (2010). L, R L and R are lower and upper triangular matrices, respectively, and are the Cholesky factor(s) of the desired covariance matrix for the MVN. Obtain L or R via chol_s2Dp() with settings triangle = "lower" or triangle = "upper", respectively. Spec- ify either L or R, but NOT both. S, Q A covariance or precision matrix respectively. These are for use with spam, and can be extracted from output of chol_s2Dp after choosing return.cov = TRUE or return.prec = TRUE, respectively. use.spam Logical. If use.spam = TRUE then use tools from the R package spam; other- wise, base R functions are employed. For large dimension MVN with sparse correlation structure, spam is recommended; otherwise, base R may be faster. Defaults to FALSE. Requires either the covariance matrix S or precision matrix, Q, that corresponds to the Cholesky factor. mu One of the following: • A single scalar value for common mean. • A vector of length nrow(R) (equivalently nrow(R)) containing means for the MVN. rand.err A vector for the random error standard deviation when dist = "gaussian", or thresholding is used to obtain non-Normal draws. Must have length 1 or length N. dist The distribution of the scalar outcome. • dist = "gaussian" has Y = XB + e, where e N (0, rand.err). • dist = "binomial": Y is drawn from a binomial distribution with prob- ability of "success" equal to 1/(1 + 1/exp(XB)) using rbinom() when binary.method = "traditional". If binary.method = "gaussian", then simulation is based on a cutoff using binary.cutoff. • dist = "multinomial": Y is drawn from sample() using probabilities generated based on Chapter 6.1.3 of Agresti (2007) when length(B) = V - 1 or Friedman (2010) when the length(B) = V. Threshold-based ap- proaches are not currently supported. • dist = "poisson": Y is drawn from P oisson(exp(XB)) using rpois(). V A numeric value stating the number of categories desired when dist = "multinomial". incl.subjectID When incl.subjectID = TRUE a column of subject indices is generated. threshold.method One of "none", "manual", "percentile", "round". When "none" draws from Binomial or Poisson distributions are taken subject-wise using base R func- tions. For the remaining options, draws are first taken from a Normal distribu- tion and then thresholded. "manual" uses Y.thresh to manually select a cutoff, "percentile" uses Y.thresh to select percentiles used to bin outcomes, and "round" sets values equal or less than 0 to 0, and rounds all positive values to the nearest whole number. Y.thresh A manual value used to threshold when threshold.method = "manual"; val- ues equal or greater than the cutoff are assigned 1 and all others 0. When threshold.method = "percentile", a percentile to use to bin outcomes. X.categorical Default is X.categorical = FALSE. If X.categorical = TRUE then thresholds are applied to categorize each predictor/image value. X.num.categories A scalar value denoting the number of categories in which to divide the data. X.category.type Tells R how to categorize the data. Options are X.category.type = c("percentile", "manual"). If X.category.type = "percentile" then the data are divided into percentiles based on X.num.categories; e.g. if X.num.categories = 4 then the values are divided into quartiles, and values in Q1 equal 0, be- tween Q1 and Q2 equal 1, between Q2 and Q3 equal 2, and greater than Q3 equal 3. If X.category.type = "manual" then specify the cutoff points with X.manual.thresh. X.manual.thresh A vector containing the thresholds for categorizing the values; e.g. if X.num.categories = 4 and X.manual.thresh = c(-3, 1, 17), then values less than -3 are set to 0, equal or greater than -3 and less than 1 are set to 1, equal or greater than 1 but less than 17 are set to 2, and equal or greater than 17 are set to 3. Note that length(X.manual.thresh) must always equal X.num.categories - 1. X.cat.names A vector of category names. If X.cat.names = NULL then the initial integers assigned are left as the values; the names in X.cat.names are assigned in as- cending order. print.out If print.out = TRUE then print the following for each subject, indexed y: • X[y] %*% B • p[y], lambda[y] for Binomial, Poisson, respectively. This is useful to see the effect of image parameter selection and beta parameter selection on distributional parameters for the outcome of interest. Value A data frame where each row consists of a single subject’s data. Col 1 is the outcome, Y, and each successive column contains the subject predictor values. Note Careful parameter selection, i.e. B, is necessary to ensure that simulated outcomes are reasonable; in particular, counts arising from the Poisson distribution can be unnaturally large. References <NAME>, <NAME> (2010). “spam: A Sparse Matrix R Package with Emphasis on MCMC Methods for Gaussian Markov Random Fields.” Journal of Statistical Software, 36(10), 1-25. https:// www.jstatsoft.org/v36/i10/. R<NAME> (1987). Stochastic Simulation. John Wiley & Sons. doi:10.1002/9780470316726. <NAME> (2001). “Fast Sampling of Gaussian Markov Random Fields.” Journal of the Royal Statisti- cal Society B, 63, 325-338. doi:10.1111/14679868.00288. <NAME> (2007). An Introduction to Categorical Analysis, 2nd edition. John Wiley & Sons, Hoboken, New Jersey. <NAME>, <NAME>, <NAME> (2010). “Regularization paths for generalized linear models via coordinate descent.” Journal of Statistical Software, 33, 1-22. doi:10.18637/jss.v033.i01. Examples ## generate precision matrix and take Cholesky decomposition Rpre <- chol_s2Dp(im.res = c(3, 3), matrix.type = "prec", use.spam = TRUE, neighborhood = "ar1", triangle = "upper", return.prec = TRUE) ## Generate correlation matrix & take Cholesky decomposition Rcov <- chol_s2Dp(corr.structure = "ar1", im.res = c(3, 3), rho = 0.5, triangle = "upper", use.spam = FALSE, neighborhood = "none") ## Define non-zero beta values Bex <- beta_builder(row.index = c(2, 3), col.index = c(3, 3), im.res = c(3, 3), B0 = 0, B.values = rep(1, 2), output.indices = FALSE) ## Simulate Datasets ## parameter values Nex = 100 set.seed(28743) ## with precision matrix Gauss.exp <- sim_Y_MVN_X(N = Nex, B = Bex, R = Rpre$R, Q = Rpre$Q, dist = "gaussian") hist(Gauss.exp$Y) ## with covariance matrix Gauss.exc <- sim_Y_MVN_X(N = Nex, B = Bex, R = Rcov$R, S = Rcov$S, dist = "gaussian") hist(Gauss.exc$Y) ## direct draws from binomial Bin.ex <- sim_Y_MVN_X(N = Nex, B = Bex, R = Rcov$R, S = Rcov$S, dist = "binomial", print.out = TRUE) table(Bin.ex$Y) ## manual cutoff Bin.ex2 <- sim_Y_MVN_X(N = Nex, B = Bex, R = Rcov$R, S = Rcov$S, dist = "binomial", threshold.method = "manual", Y.thresh = 1.25) table(Bin.ex2$Y) ## percentile cutoff Bin.ex3 <- sim_Y_MVN_X(N = Nex, B = Bex, R = Rcov$R, S = Rcov$S, dist = "binomial", threshold.method = "percentile", Y.thresh = 0.75) table(Bin.ex3$Y) ## Poisson Example - note the large counts Pois.ex <- sim_Y_MVN_X(N = Nex, B = Bex, R = Rcov$R, S = Rcov$S, dist = "poisson", print.out = TRUE) mean(Pois.ex$Y) quantile(Pois.ex$Y, probs = c(0, 0.1, 0.25, 0.45, 0.5, 0.75, 0.9, 0.95, 0.99, 1)) hist(Pois.ex$Y) within_area Determine Whether Lattice Points are Within or Without a Random Set Description Determine whether locations in the image/lattice (from generate.grid) are within or without the union of a random set generated by sim2D_HPPP_coords(). If the Euclidean distance between a lattice location and any ’event’ is less than the radius about the ’event’, then the location is said to be within the random set. Otherwise, it is without the random set. Usage within_area(grid.centers, radii, event.xcoord, event.ycoord) Arguments grid.centers Output from generate.grid() that specifies the coordinates of the lattice loca- tions in native space. radii A vector of radii values. event.xcoord, event.ycoord Paired vectors specifying the x- and y- coordinates, respectively, of each ’event’ from the Poisson process. Value A data frame with lattice x- and y- coordinates, and a binary vector where 1 indicates the location is within the random set, and 0 indicates the location is without the random set.
@types/redux-promise
npm
JavaScript
[Installation](#installation) === > `npm install --save @types/redux-promise` [Summary](#summary) === This package contains type definitions for redux-promise (<https://github.com/acdlite/redux-promise>). [Details](#details) === Files were exported from <https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/redux-promise>. [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/redux-promise/index.d.ts) --- ``` import * as Redux from "redux"; declare const promise: ReduxPromise.Promise; export = promise; declare namespace ReduxPromise { export interface Promise extends Redux.Middleware {} } declare module "redux" { type PromiseAction<S> = (dispatch: Redux.Dispatch<S>, getState?: () => S) => any; interface Dispatch<S> { <R>(asyncAction: PromiseAction<S>): R; } } ``` ### [Additional Details](#additional-details) * Last updated: Wed, 18 Oct 2023 11:45:06 GMT * Dependencies: [redux](https://npmjs.com/package/redux) [Credits](#credits) === These definitions were written by [<NAME>](https://github.com/molekilla), and [Kaur Kuut](https://github.com/xStrom). Readme --- ### Keywords none
tsdb
cran
R
Package ‘tsdb’ February 20, 2023 Type Package Title Terribly-Simple Data Base for Time Series Version 1.1-0 Date 2023-02-20 Maintainer <NAME> <<EMAIL>> Description A terribly-simple data base for numeric time series, written purely in R, so no external database-software is needed. Series are stored in plain-text files (the most-portable and enduring file type) in CSV format. Timestamps are encoded using R's native numeric representation for 'Date'/'POSIXct', which makes them fast to parse, but keeps them accessible with other software. The package provides tools for saving and updating series in this standardised format, for retrieving and joining data, for summarising files and directories, and for coercing series from and to other data types (such as 'zoo' series). License GPL-3 Imports datetimeutils, fastmatch, utils, zoo Suggests data.table, tinytest URL http://enricoschumann.net/R/packages/tsdb/, https://github.com/enricoschumann/tsdb, https://gitlab.com/enricoschumann/tsdb NeedsCompilation no Author <NAME> [aut, cre] (<https://orcid.org/0000-0001-7601-6576>) Repository CRAN Date/Publication 2023-02-20 16:00:02 UTC R topics documented: tsdb-packag... 2 as.ts_tabl... 3 file_inf... 4 read_ts_table... 5 ts_tabl... 7 ttim... 8 write_ts_tabl... 9 tsdb-package Terribly-Simple Database for Time Series Description A terribly-simple data base for numeric time series, written purely in R, so no external database- software is needed. Series are stored in plain-text files (the most-portable and enduring file type) in CSV format; timestamps are encoded using R’s native numeric representation for Date/POSIXct, which makes them fast to parse, but keeps them accessible with other software. The package pro- vides tools for saving and updating series in this standardised format, for retrieving and joining data, for summarising files and directories, and for coercing series from and to other data types (such as ’zoo’ series). Details See the functions ts_table and as.ts_table for creating a ts_table. See write_ts_table and read_ts_tables for storing and loading a ts_table (or several). For getting started, see the tutorial at https://gitlab.com/enricoschumann/tsdb/blob/master/ README.org or https://github.com/enricoschumann/tsdb/blob/master/README.org . Author(s) <NAME> See Also ts_table and as.ts_table for creating a ts_table write_ts_table and read_ts_tables for storing and loading a ts_table as.ts_table Coerce to ts_table Description Coerce objects to ts_table Usage as.ts_table(x, ...) ## S3 method for class 'zoo' as.ts_table(x, columns, ...) Arguments x object to be coerced to ts_table columns character ... arguments to be passed to other methods Details A generic function for coercing objects to class ts_table. Value a ts_table Author(s) <NAME> See Also read_ts_tables Examples library("zoo") as.ts_table(zoo(1:5, Sys.Date()-5:1), ## note that the "columns" columns = "value") ## must be specified file_info Information about Data File Description Provides information about data stored in file: columns, number of observations, range of times- tamps. Usage file_info(dir, file) Arguments dir character file character Details Provide information, such as number of entries, of specified files. It is recommended that code that uses the returned information to alter or write tables, should explicitly check whether a table exists (column exists in the returned data.frame). For instance, a value of NA for min.timestamp would occur for a non-existing file, but also if the file could not be read for some reason. Value An object of type file_info, which is a data.frame with information such as whether a file exists, minimum and maximum timestamp, and more. Author(s) <NAME> See Also ts_table Examples ts <- ts_table(1:3, as.Date("2018-12-3") + 1:3, columns = "A") d <- tempdir() write_ts_table(ts, file = "temp", dir = d) file_info(d, "temp") read_ts_tables Read Time-Series Data from Files Description Read time-series data from files and merge them. Usage read_ts_tables(file, dir, t.type = "guess", start, end, columns, return.class = NULL, drop.weekends = FALSE, column.names = "%dir%/%file%::%column%", backend = "csv", read.fn = NULL, frequency = "1 sec", timestamp) Arguments file character dir character t.type character: guess, Date or POSIXct start a timestamp: either of classes Date or POSIXct (possibly including timezone information), or a character string. Strings are passed to as.Date/as.POSIXct. Note in particular that a string of the form "YYYY-MM-DD HH:MM:SS", when passed to as.POSIXct, will be interpreted as a datetime in the current timezone. It is best to always specify start: if start is missing, the function will use the first timestamp of the first time-series it reads. end a timestamp: either of classes Date or POSIXct (possibly including timezone information), or a character string. Strings are passed to as.Date/as.POSIXct. Note in particular that a string of the form "YYYY-MM-DD HH:MM:SS", when passed to as.POSIXct, will be interpreted as a datetime in the current timezone. It is best to always specify end: if end is missing, the function will use the current time (which may not be appropriate: for instance, when forecasts are stored). columns character. return.class NULL (default) or character: if NULL, a list is returned. Also supported are zoo, data.frame and ts_table. drop.weekends logical column.names character: a format string for column names; may contain %dir%, %file%, and %column%. It is only used when return.class is data.frame or zoo. backend character: currently, only ‘csv’ is fully supported read.fn NULL or character: use ‘fread’ to use fread from package data.table frequency character; used compute a regular grid between start and end. The argu- ment is only used when t.type is POSIXct (or guessed to be POSIXct) and no timestamp is specified. If set to NA, the function will first read all files and compute timestamp as the union of all files’ timestamps. timestamp a vector of timestamps: if specified, only data at the times in timestamp are selected Details Read time-series data from CSV files. Value When return.class is NULL, a list: data a numeric matrix timestamp Date or POSIXct columns character file.path character Otherwise an object of class as specified by argument return.class. Author(s) <NAME> See Also write_ts_table Examples t1 <- ts_table(1:3, as.Date("2018-12-3") + 1:3, columns = "A") t2 <- ts_table(4:5, as.Date("2018-12-3") + 1:2, columns = "A") d <- tempdir() ## this is just an example. ## Actual (valuable) data should never ## be stored in a tempdir! write_ts_table(t1, dir = d, file = "t1") write_ts_table(t2, dir = d, file = "t2") read_ts_tables(c("t1", "t2"), dir = d, columns = "A", return.class = "zoo", column.names = "%file%.%column%") ts_table Create ts_table Description Create a ts_table. Usage ts_table(data, timestamp, columns) Arguments data numeric timestamp Date or POSIXct columns column names Details Create a time-series table (ts_table). A ts_table is a numeric matrix, so there is always a dim attribute. For a ts_table x, you get the number of observations with dim(x)[1L]. Attached to this matrix are several attributes: timestamp a vector: the numeric representation of the timestamp t.type character: the class of the original timestamp, either Date or POSIXct columns a character vector that provides the columns names There may be other attributes as well, but these three are always present. Timestamps must be of class Date or POSIXct (POSIXlt is converted). A tzone attribute is dropped. A ts_table is not meant as a time-series class. For most computations (plotting, calculation of statistics, etc.), the ts_table must first be coerced to zoo, xts, a data.frame or a similar data structure. Methods that perform such coercions are responsible for converting the numeric times- tamp vector to an actual timestamp. For this, they may use the function ttime (‘translate time’). Value a ts_table Author(s) <NAME> See Also as.ts_table Examples ts_table(1:5, Sys.Date() - 5:1, columns = "value") ttime Translate Timestamps Description Translate a vector of timestamps. Usage ttime(x, from = "datetime", to = "numeric", tz = "", strip.attr = TRUE, format = "%Y-%m-%d") Arguments x numeric from character: datetime, numeric or character to character: numeric, Date or POSIXct tz character strip.attr logical: strip attributes; in particular, timezone information format character Details ttime (‘translate time’) converts timestamps between formats. Author(s) <NAME> See Also ts_table Examples ttime(Sys.Date()) ttime(17397, from = "numeric", to = "Date") write_ts_table Write Time-Series Data to File Description Write time-series data to files. Usage write_ts_table(ts, dir, file, add = FALSE, overwrite = FALSE, replace.file = FALSE, backend = "csv") Arguments ts a ts_table dir character file character add logical: if TRUE, add data with timestamps that are not in a file. overwrite logical: overwrite existing file when data differs. overwrite implies add. replace.file logical: if TRUE, an existing file is deleted and replaced by a new file (i.e. con- taining ts) backend a string; currently, only csv is supported Details The function takes a ts_table and writes it to a file. If the file already exists and both add and overwrite are FALSE (the default), nothing is written. When add is TRUE, the function checks if ts contains timestamps not yet in the file and, if there are any, writes only those data. When overwrite is TRUE, the function merges all observations in the file with those in ts and writes the result back to the file. If ts contains timestamps that were already in the file, the data in the file are overwritten. Note that no data will be removed from the file: timestamps not in ts remain unchanged in the file. Value Invisibly, the number of data rows written to a file. Author(s) <NAME> See Also read_ts_tables Examples t1 <- ts_table(1:3, as.Date("2018-12-3") + 1:3, columns = "A") t2 <- ts_table(4:5, as.Date("2018-12-3") + 1:2, columns = "A") d <- tempdir() ## this is just an example. ## Actual (valuable) data should never ## be stored in a tempdir! write_ts_table(t1, dir = d, file = "t1") write_ts_table(t2, dir = d, file = "t2") read_ts_tables(c("t1", "t2"), dir = d, columns = "A", return.class = "zoo", column.names = "%file%.%column%")
biblatex
ctan
TeX
# biblatex-juradiss Ver. 0.23 <NAME> 1. Oktober 2020 ## Inhaltsverzeichnis 1 Einleitung 2 Kurzanleitung 3 Installation 4 Dokumentenklasse 5 Verhaltnis zu biblatex-jura 6 Einzelne Eintragstypen 6.1 Eintragstyp article 6.1 Eintragssubtyp newsletter 6.1 Eintragstyp book 6.1 Eintragstyp commentary 6.1 Eintragstyp recollection 6.1 Eintragstyp periodical 6.1 Eintragstyp online 6.1 Eintragstyp jurisdiction 6.1 Eintragstyp legal 7 Anleitung zur Anpassung der Stilvorgaben 8 Weitere Anpassungen 8.1 Darstellung mehrerer Personen mit gleichem Nachnamen 8.2 Querverweis 9 Quellen - Beispielverzeichnisse 10 Kategorie 1 11 Artikel 12 Kommentare 13 Allgemeine Quellen ## 1 Einleitung Diese Dokumentation erklart in kurzen Worten die Anpassungen des Stils biblatex-juradiss und wie man sie nutzen kann. Indirekt werden dabei auch einige Funktionen von biblatex erlautert, auf das aufsetzt. Grundsatzlich sollte man bei Fragen zu den Funktionen von biblatex die sehr gute und ausfuhrliche Dokumentation von biblatex konsultieren. Ohne zumindest das Uberfliegen des User-Guide in der Dokumentation zu biblatex lasst sich biblatex und biblatex-juradiss nicht sinnvoll verwenden. Inzwischen gibt es auch eine deutsche Fassung. Zum Schnelleinstieg werden im folgenden Abschnitt <<Kurzanleitung<< die Voraussetzungen zur Verwendung von biblatex-juradiss kurz erlautert. Danach erfolgt die Darstellung der Zitierstile der unterschiedlichen Dokumentenarten mit Beispielen. ## 2 Kurzanleitung Anleitung zur Installation von biblatex-juradiss (unter Windows), falls man keine offizielle Installation von MiKTeXoder TeXlive hat; dann ware ohnehin alles vorhanden: 1. Installation von MiKTeX/TeXlive 2. Installation von packages uber den PackageManager: * biblatex * biblatex-dw * etoolbox * logreq * csquotes * juramisc (wenn man die Dokumentenklasse hiervon benutzen mochte) ## 3 Installation biblatex-juradiss setzt auf den Paketen biblatex und biblatex-dw auf. Grund hierfur ist, dass biblatex alle Funktionen erst bereitstellt, die es ermoglichen individuelle Zitierstile zu entwickeln. Die Zitierweise deutscher Juristen ist allerdings so speziell im Vergleich zu dem sonst ublichen, dass es noch zusatzlich weiterer Funktionen bedarf, diese vollstandig abzubilden. Diese finden sich in biblatex-dw. Zwar hatte man diese auch aus dem Paket herausnehmen und in biblatex-juradiss integrieren konnen, aber der Aufwand hierfur erschien mir zu gross. Zudem ist mit dem gut gepflegten Paket biblatex-dw sichergestellt, dass die von diesem bereitgestellten Funktionen auch trotz der sehr schnellen Entwicklung von biblatex zuverlassig erhalten und kompatibel bleiben. Dies fuhrt dazu, dass zur Verwendung von biblatex-juradiss auch das Paket biblatex-dw vorhanden sein muss. Dessen Funktionen werden uber biblatex-juradiss direkt eingebunden, es muss nicht erst per Paketoption uber biblatex geladen werden. Um biblatex-juradiss zu verwenden muss dieses als Paketoption von biblatex eingebunden werden. Dies geschieht durch die Anweisung \usepackage[style=biblatex-juradiss]{biblatex} Sofern man die Dateien nicht uber eine TeX-Distribution, wie TeXLive oder MiTeX installiert, kopiert man die Dateien biblatex-juradiss.cbx und biblatex-juradiss.bbx in das Verzeichnis <TEXMFLOCAL>/tex/latex/biblatex-juradiss wobei <TEXMFLOCAL> der Wurzelpfad der TeX-Installation ist. Danach muss man die Dateiliste bei MiKTZucher das Menu oder allgemein durch Ausfuhren von texhash aktualisieren. ## 4 Dokumentenklasse Fur die Erstellung einer Doktorarbeit wurde die Dokumentenklasse jurabook aus dem Paket juramisc verwendet. Das Paket bietetet viele nutzliche Optionen und integriert bereits die von Juristen verwendete Bezeichnung der Gliederungsebenen (A., I., 1., a), aa), (1), (a)). Leider wird das Paket seit einiger Zeit nicht mehr gepflagt, weshalb es inzwischen vielleicht nicht mehr uneingeschrankt zu empfehlen ist. Eine Alternative ist die Verwendung der Dokumentenklasse book und die individuelle Anpassung des Inhaltsverzeichnisses. Gerade mit dem Paket titletoc ist das keine grosse Kunst. Will man seine Doktorarbeit spater in einem Verlag veroffentlichen empfeilt sich das ohnehin. Denn dieser hat oftmals seine eigene TeX-Vorlage, die Fragen wie Fussnotenumbruch und Formatierung der Kopfzeilen selbst regelt. Hier kann die Umstellung von jurabook auf die verlagsspezifische Vorlage umstandlicher sein, als wenn man das zuvor selbst angepass hat (so war es jedenfalls bei mir), denn dann kann man die eigenen Anpassungen durch die des Verlags ersetzen. ## 5 Verhaltnis zu biblatex-jura biblatex-jura hat ebenso wie dieses Paket das Ziel das Schreiben juristischer Texte mit TeX zu ermoglichen. ## 6 Einzelne Eintragstypen ### Eintragstyp article Zeitschriftenartikel werden als Fu\(\ssnote\)1, im laufenden Text als _Mustermann_, NZG 1999, 797 (800) oder am Ende so ausgegeben. (_ders._, NZG 1999, 797 [800]) Footnote 1: _Mustermann_, NZG 1999, 797 (800). Zeitschriftenartikel werden als Fu\(\ssnote\)\(\{\)footnote\([800]\)\(\{\)Mustermann1999\(\}\), im laufenden Text als \(\{\)\(\)\(\}\)cite\([800]\)\(\{\)Mustermann1999\(\}\) oder am Ende so ausgegeben.\(\sim\)\(\{\)parencite\([800]\)\(\{\)Mustermann1999\(\}\)Es gibt zwar auch die Moglichkeit die konkrete Fundstelle (hier in runden Klammern) einfach nur durch ein Komma zu trennen, aber gerade wenn man mehrere Zitate hintereinander setzt, helfen die runden Klammern m.E. beim Trennen der einzelnen Zitate. Die kursive Schrift von Personen fordert bei Funstone mit vielen Belegen zudem die Lesbarkeit. Der Literaturverzeichniseintrag sieht so aus: **Literatur** Mustermann, _Michael_, Gestaltungsmoglichkeiten bei Anreizsystemen, NZG 1999, S. 797-900. Teilweise wird inzwischen empfohlen im Literaturverzeichnis nicht nur die Anfangs-, sondern auch die Endseite eines Beitrags anzugeben, um zeigen, dass man nicht lediglich blind zitiert hat, sondern den Beitrag zumindest mal selbst in der Hand hatte. Im naturwissenschaftlichen Bereich ist das wohl ublicher. Ich finde die Idee nicht schlecht, jedenfalls unterstutzt biblatex-juradiss das auch seit Version 0.1f. ### Eintragssubtyp newsletter Nicht oft, aber manchmal kommt es durchaus vor, dass man in juristischen Texten auch Tageszeitungen zitiert (zB die SZ oder die FAZ, in Dissertationen kommt auch schon mal die TAZ vor..) Fur Tageszeitungen sieht biblatex keinen eigenen Stil vor. Es besteht aber die Moglichkeit eigene Stile fur Unterarten von Eintragstypen zu definieren. Ein Eintrag wird einem bestimmten entsvubtitle zugeordnet, indem man dem jeweiligen Eintrag in der Literaturdatenbank das Feld entsvubtype hinzufugt und in diesem den entsprechenden Subtyp angibt. Fur Tageszeitungen habe ich das uber den Typ newsletter gemacht. In diesem gibt man bei Tageszeitungen neben dem Autor und dem Namen der Zeitschrift das Datum der Ausgabe (Feld date, Format: JJJJJ-MM-TT), sowie deren Nummer (Feld volume) an. Beispielsleintrag: @ARTICLE[oldag2011, author = {<NAME>}, gender = {sm}, title = {Wenn Teenies Banker spielen}, journal = {SZ}, pages = {30}, entrysubtype = {newspaper}, volume = {208}, date = {2011-09-09}, } Ausgabe als FunBnote2, im laufenden Text als _Oldag_, SZ v. 9. 9. 2011, 30 oder am Ende so ausgegeben. (_ders._, SZ v. 9. 9. 2011, 30) Literaturverzeichniseintrag: Beispiel fur eine Fussnote von zwei Monografien eines Autors5, im laufenden Text als _Birk_, Steuerrecht, S. 231; _ders_, Allg. Steuerrecht, S. 34 und am Ende. (_ders._, Steuerrecht, S. 231; _ders._, Allg. Steuerrecht, S. 34) Footnote 5: _Birk_, Steuerrecht, S. 231; _ders._, Allg. Steuerrecht, S. 34. Beispiel fur eine Fussnote von zwei Monografien eines Autors\foottimes[231]{Birk2008}[34]{Birk1994}, im laufenden Text als \cites[231]{Birk2008}[34]{Birk1994} und am Ende.\parencies[231]{Birk2008}[34]{Birk1994} Im Literaturverzeichnis wird entsprechend angegeben, wie das jeweilige Werk zitiert wird, der Zusatz >>zitiert als<< erscheint bei Zeitschriften nie, bei Festschriften immer: **Literatur** Birk, _Dieter_, Allgemeines Steuerrecht, 2. Aufl., Munchen 1994, _zitiert als_: _Birk_, Allg. Steuerrecht. _Ders._, Steuerrecht, 12. Aufl., Heidelberg 2009, _zitiert als_: _Birk_, Steuerrecht. ### Eintragstyp commentary Die Zitation von juristischen Kommentaren ist die grosste Herausforderung fur meinen Stil gewesen. Zitiert wird ein Kommentar, indem das prenote-Feld genutzt wird. Der \cite-Befehl von biblatex kennt ein prenote und ein postnote-Feld. Bei dem Befehl \cite[50]{bibtexkey} wird das postnote-Feld mit dem Inhalt der eckigen Klammer gefullt (hier die 50). Dessen Inhalt kommt an das Ende des jeweiligen Zitats (deshalb POSTnote-Feld). Das prenote-Feld wird mit dem Inhalt der ersten eckigen Klammer gefullt, wenn man dem bibtex-Schlussel im \cite-Befehl zwei eckige Klammern voranstellt: \cite[\(\verb"Bearbeiter"][50]{bibtexkey}.\)6 Footnote 6: Mehr zu der Funktionsweise von prenote und postnote-Feldern ist in der Dokumentation von biblatex zu finden. Wird bei Kommentaren die Auflagenzahl angegeben, so wird diese als kleine hochgestellte Zahl hinter den Herausgeber, oder den Kommentaramen geschrieben. So lassen sich Zitate von Kommentar-Bearbeitern aus unterschiedlichen Auflagen recht einfach voneinander unterscheiden. Das Zitat eines juristischen Kommentars als Fussnote7, im laufenden Text als _Donald_, in: Duck, _Dietmar_, SS 4 Rn. 443 oder am Ende. (_Donald_, in: Duck, _Dietmar_, SS 4 Rn. 443) Footnote 7: _Donald_, in: _Duck_2, § 4 Rn. 443. Im Literaturverzeichnis sieht dieser wie folgt aus: **Literatur** Duck, _Dietmar_ (Hrsg.), Spannendesgesetz, Kommentar, 2. Aufl., Munchen 2009, _zitiert als_: _Bearbeiter_, in: _Duck_2. Footnote 2: _Donald_, in: _Duck_2, § 4 Rn. 443. Kommentare werden ublicherweise mit den Namen der Herausgeber zitiert, genauso ublich ist es aber auch, den Namen eines alten Herausgebers als Zitat zu verwenden, oder einen Eigennamen. Hierfur ist das Feld shorthand da. Ist es nicht leer, so wird dessen Inhalt statt die Namen der Herausgeber fur das Fussnotenzitat verwendet. Will man einem oder mehreren Herausgebern oder Autoren eine bestimmte Eigenschaft zuordnen z. B. Begrunder oder Fortfuhrer, so kann man dies, indem man dem Eintrag in der Hat eine Festschrift viele Herausgeber, kann man einstellen, dass im Literaturverzeichnis nur der ert emit dem Zusatz u.a. genannt wird. Die Anzahl, bis zu der alle Herausgeber genannt werden sollen definiert man uber die Paketoption von biblatex maxnames (ich verwende maxnames=3). So sieht es als Fussnote10, so im laufenden Text _Schwaiger_, in: FS Hauptmann, 337 und so am Ende eines Satzes. (_ders._, in: FS Hauptmann, 337) Footnote 10: _Schwaiger_, in: FS Hauptmann, 337. Im Literaturverzeichnis sieht der Eintrag einer Festschrift mit funf Herausgebern wie folgt aus: **Literatur** Schwaiger, _Gregor_, Aufischtsrat und Autonomie, in: Grundmann, _Stefanie u. a._ (Hrsg.), Unternehmen und Verantwortung, Festschrift fur <NAME>, Berlin 2004, S. 337, _zitiert als_: _Schwaiger_, FS Hauptmann. ### Eintragstyp periodical Der Eintragstyp periodical ist an sich eine Abwandlung des Eintragstyps article. Er ist gedacht fur Archivzeitschriften, die neben dem Jahrgang auch zusatzlich eine laufende Nummer fur das jeweilige Jahr verwenden (zB AGR, AcP, ZHR, und fur den Steuerrechtler: DStJG). Die Jahrgangsnummer wird in das Feld volume eingetragen. Als Fussnote11, im laufenden Text als _Lutz_, ZHR 159 (1995), 287 und am Ende eines Satzes. (_ders._, ZHR 159 [1995], 287) Footnote 11: _Lutz_, ZHR 159 (1995), 287. Literaturverzeichniseintrag: **Literatur** Lutz, _Martin_, Moglichkeiten der Verbesserung, ZHR 159 (1995), S. 287. ### Eintragstyp online Dieser Eintragstyp ist fur Dokumente, die nur online zuganglich sind, z. B. Pressemitteilungen oder Stellungnahmen von Verbanden oder Professoren zu Gesetzesvorhaben etc. Derzeit sieht dieser Eintragstyp lediglich die Felder author, title, shorttitle, sowie url und urldate vor. Die URL wird nur im LitVerz angezeigt, zusammen mit dem Datum des letzten Abrufs (urldate, Format: JJJJ-MM-TT). Wenn ein shorttitle eingetragen wird, so wird dieser auch in der Fussnote aufgefuhrrt. Ausgabe als Fussnote12, im laufenden Text als _Hirte_, S. 3 oder am Ende eines Satzes. (_ders._, S. 3) Der Eintrag im Literaturverzeichnis sieht so aus: ## Literatur * Hirte, _Heribert_, Stellungnahme zum Fraktionsentwurf eines Gesetzes zur Angemessenheit der Vorstandsvergutung (VorstAG) fur den Deutschen Bundestag, _abrufbar unter_: [http://www.uni-augsburg.de/de/jura/fakultaet/lehrende/moellers/materialien/materialdateien/040_deutsch](http://www.uni-augsburg.de/de/jura/fakultaet/lehrende/moellers/materialien/materialdateien/040_deutsch) e_gesetzgebungsgeschichte/gesetz_angemessenheit_vorstandsverguetung/pdf/stellungnahm e_3.pdf (abgerufen am 3. 4. 2011). ### Eintragstyp jurisdiction Ein kleines Alleinstellungsmerkmal dieses Stils ist die Unterstutzung eines Verweisstills fur juristische Literatur UND fur Gerichtsurteile, sowie offizielle Dokumente. Hierfur gibt es zwar auch das Paket jurarsp. Es wurde aber in den letzten Jahren nicht mehr weiterentwickelt. In seiner Funktionsvielfalt ist es meinem Stil zwar in vielen Bereichen uberlegen und auch den ein oder anderen Darstellungsfehler wegen inzwischen eingetretener Inkompatibilitat konnte ich durch Anderung der Paketdateien erreichen. Aber biblatex und jurarsp arbeiten nicht zusammen. So sieht biblatex nicht, dass zwischen zwei Literaturzitaten ein Rechtsprechungszitat ist und wendet die idem-Funktion an. Auch in die <<iteBefehle kann man die Rechtsprechungszitate nicht integrieren. Ausserdem musste man bibtex immer einmal separat uber die Rechtsprechungs-Bibdatei laufen lassen. Diese Nachteile haben mich veranlasst einen eigenen Stil fur Rechtsprechungszitate zu schreiben. Dafur dient der Eintragstyp jurisdiction. Genauso wie der Eintragstyp legal ist er von biblatex zwar vorgesehen, enthalt aber keine Zitiervorgaben. Der Eintragstyp jurisdiction hat folgende Felder: * author = Name des Gerichts (zB BFH, BVerfG, BGH etc.) * gender = Fur die idem-Funktion (zB dass. bei Eintrag: "sn", zB fur das BVerfG, oder ders., dann Eintrag: "sm", zB fur den BGH)13 Footnote 13: Ausführliche Erklärung zu gender in der biblatex -Dokumentation. * date = Urteilsdatum in der Form JJJ-MM-TT * decision = fur Art der Entscheidung, zB Urteil oder Beschluss * sign = Aktenzeichen * officialvolume = Name der Entscheidungssammlung oder der Zeitschrift der primaren Fundstelle inkl. Band oder Jahrgang (zB BGHZ 31 oder BVerfGE 13, aber auch NJW 2011 oder juris (nv)) Die primare Fundstelle ist oftmals eine Entscheidungssammlung. Hier ist es dann manchmal ublich, eine weitere Fundstelle in einer juristischen Zeitschrift anzugeben. Zu diesem Zweck gibt es die Moglichkeit die zweite Fundstelle als sekundare Fundstelle anzugeben. Das ist aber optional. * officialpages = Erste Seite der Entscheidung in der primaren Fundstelle * pages = Erste Seite des Urteils in der sekundaren Fundstelle * journaltitle = Zeitschriftenname in der sekundaren Fundstelle * journalyear = Zeitschriftenjahrgang in der sekundaren Fundstelle * decisionname = Entscheidungssname (zB. Centros oder Herrenreiter) Will man die obigen Feldnamen (also decision und sign usw.) in seiner Literaturdatenbank verwenden, so muss man biblatex zwingend mit biber benutzen und nicht mit bibtex. Denn biblatex bringt zwar von Hause aus den Eintragstyp jurisdiction mit, aber keine Felder die speziell fur diesen Eintragstypbenotigt werden, also Felder fur das Aktenzeichen, die primare und sekundare Fundstelle usw. Diese Felder werden alle durch biblatex-juradiss definiert. Ausgabe als Fussnote14, im laufenden Text als _BVerfG_, Beschluss v. 12. 5. 2009 (2 BvL 1/00) BVerfGE 123, 111 (3) (= FR 2009, 873) - Jubilaumsruckstellung - oder am Ende eines Satzes. (_dass._, Beschluss v. 12. 5. 2009 [2 BvL 1/00] BVerfGE 123, 111 [3] [= FR 2009, 873] - Jubilaumsruckstellung -) Einen Eintrag fur das Literaturverzeichnis kann ich derzeit noch nicht prasentieren. Bisher habe ich nicht vor, ein eigenes Rechtsprechungsverzeichnis in meiner Promotion anzugeben. Daher habe ich bisher auch noch keine Energie in die Erstellung eines solchen Verzeichnisses investiert. Damit die Rechtsprechungszitate nicht doch in komischer Form im Literaturverzeichnis auftauchen sollte man diese beim Aufruf des Literaturverzeichnisses durch die Option nottype=jurisdiction aussen vor lassen. Das gleiche gilt fur den Eintragstyp legal: Beispiel: \printlnbigraphy[nottype=jurisdiction,nottype=legal] Footnote 14: _BVerfG_, Beschluss v. 12. 5. 2009 (2 BvL 1/00) BVerfGE 123, 111 (3) (= FR 2009, 873) – Jubilaumsrückstellung –. **Literatur** Birk, _Dieter_, Allgemeines Steuerrecht, 2. Aufl., Munchen 1994, _zitiert als_: Birk, Allg. Steuerrecht. _Ders._, Steuerrecht, 12. Aufl., Heidelberg 2009, _zitiert als_: Birk, Steuerrecht. Brummerhoff, _Dieter_, Finanzwissenschaft, 9. Aufl., Munchen u.a. 2007. Duck, _Dietmar_ (Hrsg.), Spannendesgesetz, Kommentar, 2. Aufl., Munchen 2009, _zitiert als_: Bearbeiter, in: _Duck\({}^{2}\)_. Gans, _Dietmar_ (Hrsg.) / Pantoffel, _Frank_ (Begr.), Handbuch des Rechts, des sonstigen Rechts und ubriger Gesetze, Kommentar, 2. Aufl., Munchen 2002, _zitiert als_: Bearbeiter, in: _Handbuch des Rechts\({}^{2}\)_. Hausmann, _Benedikt_, Notwendige Erwerbsaufwendungen, Berlin 1998, zugl.: Diss. jur. Univ. Munster 1997. Hirte, _Heribert_, Stellungnahme zum Fraktionsentwurf eines Gesetzes zur Angemessenheit der Vorstandsvergutung (VorstAG) fur den Deutschen Bundestag, _abrufbar unter_: [http://www.uni-augsburg.de/de/jura/fakultaet/lehrende/moellers/materialien/materialdateien/040_deutsch](http://www.uni-augsburg.de/de/jura/fakultaet/lehrende/moellers/materialien/materialdateien/040_deutsch) e_gesetzgebungsgeschichte/gesetz_angemessenheit_vorstandsverguetung/pdf/stellungnahme_a_3.pdf (abgerufen am 3. 4. 2011). Kirchhof, _Ferdinand_, Die Tauglichkeit von Abgaben zur Lenkung des Verhaltens, DVBI 2000, S. 1166. Kirchhof, _Paul_, Die freiheitsrechtliche Struktur der Steuerrechtsordnung, StuW 2006, S. 3. Lutz, _Martin_, Moglichkeiten der Verbesserung, ZHR 159 (1995), S. 287. Mustermann, _Michael_, Gestaltungsmoglichkeiten bei Anreizsystemen, NZG 1999, S. 797-900. Oldag, _Andreas_, Wenn Teenies Banker spielen, SZ v. 9. 9. 2011, Nr. 208, S. 30. Schwaiger, _Gregor_, Aufsichtsrat und Autonomie, in: Grundmann, _Stefanie u. a._ (Hrsg.), Unternehmen und Verantwortung, Festschrift fur <NAME>, Berlin 2004, S. 337, _zitiert als_: _Schwaiger_, FS Hauptmann. ### Eintragstyp legal Zuletzt soll noch der Eintragstyp legal vorgestellt werden. Fur diesen gilt das gleiche, wie zum Eintragstyp jurisdiction. Nur eigene Feldnamen mussen hier nicht konvertiert werden, da ich hier in - wie ich finde gerade noch vertretbarer Weise - bestehende Felder verwende. Das Feld journaltitle enthalt dabei die Bezeichnung der jeweiligen Veroffentlichung, zB BT-Drs., oder BMF-Schreiben. Das Feld journalsubtitle enthalt dann die Bezeichnung des konkreten Dokuments, zB 16/12278 oder v. 5. 5. 2011. Ein Eintrag in der Literaturdatenbank sieht dann beispielsweise so aus: @LEGAL{bt16-12278, journalsubtitle = {16/12278}, journaltitle = {BT-Drs.}, title = {BT-Drucksache 16/12278} } Da es das besondere von offiziellen Dokumenten ist, dass man keinen Autor angibt (denn dieser ergibt sich aus dem Namen des Dokuments) ist dieser auch nicht vorgesehen. Ausgabe als Fu\(\ssnote\)15, im laufenden Text als BT-Drs. 16/12278, 3 oder am Ende eines Satzes. (BT-Drs. 16/12278, 3) Ein Verzeichnis der offiziellen Dokumente habe ich derzeit ebenfalls nicht fur meine Promotion geplant, dementsprechend gibt es hierfur auch noch keinen Stil. Auch hier ist zu beachten, dass der Eintragstyp beim Darstellen des Literaturverzeichnisses aussen vor gelassen werden sollte.16 Footnote 15: BT-Drs. 16/12278, 3. Footnote 16: Vgl. oben 6.1, S. 11. ## 7 Anleitung zur Anpassung der Stilvorgaben Nun ist der Stil der Zitate sehr an meinen Vorstellungen orientiert. Hier spielt der individuelle Geschmack auch immer eine Rolle. Dieser Stil soll damit zunachst alles mithringen, um LaTeX fur juristicsche Texte verwenden zu konnen und der konkrete Stil soll hierfur als Beispiel dienen, was man damit machen kann. Gerade die Optik der Zitate und der Darstellung des Literaturverzeichnisses lasst sich aber mit sehr einfachen Mitteln anpassen. Hier ein kleines Beispiel: Mochte man beispielsweise, dass auch bei Zeitschriften stets ein in: zwischen Autor und Zeitschriftenname steht, so kopiert man den bisherigen Code fur die Darstellung von Zeitschriftenartikeln in die Praambel des eigenen Dokuments und passt diesen den eigenen Vorstellungen an: Schritt 1: Kopieren des entsprechenden Codes aus der biblatex-juradis.cbx (die cbx-Dateien enthalten Code fur Zitate, die bbx-Dateien enthalten Code fur das Literaturverzeichnis) Schritt 2: Einfugen des Codes zwischen \documentclass und } Wenn man <NAME> und <NAME> zitiert, geht das als Fu8note\footcites[1167]{Kirchhof2000}[5]{Kirchhof2006}, im laufenden Text als \cites[1167]{Kirchhof2000}[5]{Kirchhof2006}oder am Endee eines Satzes.\parencies[1167]{Kirchhof2000}[5]{Kirchhof2006} ``` Die Darstellung im Literaturverzeichnis andert sich nicht. ### Querverweis Zudem habe ich einen Kurzbefehl eingefuhrt, den ich recht nutzlich finde. Mit \qverweis{} kann man auf eine andere Stelle im Dokument verweisen. Die Stelle wird mit \label{Name} markiert. Der Befehl \qverweis{Name} fugt an der Stelle dann stets den jeweiligen Gliederungspunkt und die Seite ein, auf der sich die Markierung befindet.18 Footnote 18: Z.B. vgl. hierzu die das derzeitige Kapitel Qerverweis, unter 8.2, S. 14. ## Quellen - Beispielverzeichnisse Die folgenden Quellenverzeichnisse sind Beispiele, die uber die Definition \defbibheading{subbib}{\addsubsec{m1}} als nichtnummerierte \subsection ausgegeben, aber ins TOC eingefugt werden. Fur die Dokumentenklasse scrartcl wurde dazu \addsubsec definiert \makeatletter \newcommand\addsubsec{\SecDef}@addsubsec\@saddsubsec} \newcommand*{\@addsubsec}{} \def\@addsubsec[m1]n2{\ \edef\reserved@a{\ \unexpanded{\ \subsection[m1]}{m2}\ \c@secnumdepth= \}{\the\c@secnumdepth\relax }\% \c@secnumdepth=\numerpr \sectionnumdepth-1\relax \reserved@a \} \newcommand*{\@saddsubsec}[1]{\subsection*{m1}\addsubsecmark{}} \makeatother Die Ausgabe der Teilquellenverzeichnisse fur die benutzte Literaturdatenbank erfolgte mit: \printlnbibliography[heading=subbib,category=1,title=Kategorie 1] \printlnbibliography[heading=subbib,type=article,title=Artikel]printbibliography[heading=subbib,type=commentary,title=Kommentare] printbibliography[heading=subbib,nottype=article,nottype=commentary,title=Allgemeine Quellen] ### Categorie 1 Mustermann, _Michael_, Gestaltungsmoglichkeiten bei Anreizsystemen, NZG 1999, S. 797-900. ### Artikel Kirchhof, _Ferdinand_, Die Tauglichkeit von Abgaben zur Lenkung des Verhaltens, DVBl 2000, S. 1166. Kirchhoff, _Paul_, Die freiheitsrechtliche Struktur der Steuerrechtsordnung, StuW 2006, S. 3. Mustermann, _Michael_, Gestaltungsmoglichkeiten bei Anreizsystemen, NZG 1999, S. 797-900. Oldag, _Andreas_, Wenn Teenies Banker spielen, SZ v. 9. 2011, Nr. 208, S. 30. ### Kommentare Duck, _Dietmar_ (Hrsg.), Spannendesgesetz, Kommentar, 2. Aufl., Munchen 2009, _zitiert als_: _Bearbeiter_, in: _Duck_2. Gans, _Dietmar_ (Hrsg.) / Pantoffel, _Frank_ (Begr.), Handbuch des Rechts, des sonstigen Rechts und ubriger Gesetze, Kommentar, 2. Aufl., Munchen 2002, _zitiert als_: _Bearbeiter_, in: _Handbuch des Rechts_2. ### Allgemeine Quellen Birk, _Dieter_, Allgemeines Steuerrecht, 2. Aufl., Munchen 1994, _zitiert als_: _Birk_, Allg. Steuerrecht. _Ders._, Steuerrecht, 12. Aufl., Heidelberg 2009, _zitiert als_: _Birk_, Steuerrecht. Brummerhoff, _Dieter_, Finanzwissenschaft, 9. Aufl., Munchen u.a. 2007. BT-Drucksache 16/12278, _zitiert als_: _Bearbeiter_, in. BVerfG, Jubilaumsruckstellung, 12. 5. 2009, 873, _zitiert als_: _Bearbeiter_, in: _BVerfG_. Hausmann, _Benedikt_, Notwendige Erwerbsaufwendungen, Berlin 1998, zugl.: Diss. jur. Univ. Munster 1997. Hirte, _Heribert_, Stellungnahme zum Fraktionsentwurf eines Gesetzes zur Angemessenheit der Vorstandsvergutung (VorstAG) fur den Deutschen Bundestag, _abrufbar unter_: [http://www.uni-augsburg.de/de/jura/fakultaet/lehrende/moellers/materialien/materialdateien/040_deutsche_gesetzgebungsgeschichte/gesetz_angemessenheit_vorstandsverguetung/pdf/stellungnahme_3.pdf](http://www.uni-augsburg.de/de/jura/fakultaet/lehrende/moellers/materialien/materialdateien/040_deutsche_gesetzgebungsgeschichte/gesetz_angemessenheit_vorstandsverguetung/pdf/stellungnahme_3.pdf) (abgerufen am 3. 4. 2011). Lutz, _Martin_, Moglichkeiten der Verbesserung, ZHR 159 (1995), S. 287. Schwaiger, _Gregor_, Aufsichtsrat und Autonomie, in: Grundmann, _Stefanie u. a._ (Hrsg.), Unternehmen und Verantwortung, Festschrift fur <NAME>, Berlin 2004, S. 337, _zitiert als_: _Schwaiger_, FS Hauptmann.
rolog
cran
R
Package ‘rolog’ June 29, 2023 Type Package Title Query 'SWI'-'Prolog' from R Version 0.9.14 Date 2023-06-27 Maintainer <NAME> <<EMAIL>> Description This R package connects to 'SWI'- 'Prolog', <https://www.swi-prolog.org/>, so that R can send deterministic and non- deterministic queries to 'prolog' ('consult', 'query'/'submit', 'once', 'findall'). License FreeBSD Imports Rcpp (>= 1.0.7), methods, utils Depends R (>= 4.2) URL https://github.com/mgondan/rolog BugReports https://github.com/mgondan/rolog/issues LinkingTo Rcpp, rswipl (>= 9.1.9) RoxygenNote 7.2.3 Encoding UTF-8 SystemRequirements GNU Make, swi-prolog Suggests rmarkdown, knitr, rswipl, DiagrammeR, DiagrammeRsvg, rsvg, htmltools, testthat (>= 3.0.0) Config/testthat/edition 3 VignetteBuilder knitr, rmarkdown NeedsCompilation yes Author <NAME> [aut, com, cre] (Universität Innsbruck), European Commission [fnd] (Erasmus+ Programme, 2019-1-EE01-KA203-051708) Repository CRAN Date/Publication 2023-06-29 11:40:02 UTC R topics documented: as.rolo... 2 clea... 3 consul... 3 findal... 4 onc... 5 portra... 7 postpro... 8 prepro... 8 quer... 9 rolog_don... 10 rolog_ini... 11 rolog_o... 11 rolog_option... 12 submi... 12 as.rolog Translate simplified to canonical representation Description Translate simplified to canonical representation Usage as.rolog(query = quote(member(.X, ""[a, "b", 3L, 4, (pi), TRUE, .Y]))) Arguments query an R call representing a Prolog query with prolog-like syntax, e.g., ‘member(.X, ""[a, b, .Y])‘ for use in [query()], [once()], and [findall()]. The argument is translated to Rolog’s representation, with R calls corresponding to Prolog terms and R expressions corresponding to Prolog variables. Variables and expressions in parentheses are evaluated. See Also [query()], [once()], [findall()] Examples q <- quote(member(.X, ""[a, "b", 3L, 4, pi, (pi), TRUE, .Y])) as.rolog(q) q <- quote(member(.X, ""[a, "b", 3L, 4, pi, (pi), TRUE, .Y])) findall(as.rolog(q)) clear Clear current query Description Clear current query Usage clear() Value TRUE (invisible) See Also query() for a opening a query. submit() for a submitting a query. once() for a opening a query, submitting it, and clearing it again. findall() for a opening a query, collecting all solutions, and clearing it again. Examples query(call("member", expression(X), list(quote(a), "b", 3L, 4))) submit() # X = a submit() # X = "b" clear() consult Consult a prolog database Description Consult a prolog database Usage consult(fname = system.file(file.path("pl", "family.pl"), package = "rolog")) Arguments fname file name of database Value TRUE on success See Also once(), findall(), and query()/submit()/clear() for executing queries Examples consult(fname=system.file(file.path("pl", "family.pl"), package="rolog")) findall(call("ancestor", quote(pam), expression(X))) findall Invoke a query several times Description Invoke a query several times Usage findall( query = call("member", expression(X), list(quote(a), "b", 3L, 4, TRUE, expression(Y))), options = list(portray = FALSE), env = globalenv() ) Arguments query an R call. The R call consists of symbols, integers and real numbers, character strings, boolean values, expressions, lists, and other calls. Vectors of booleans, integers, floating point numbers, and strings with length N > 1 are translated to prolog compounds !/N, %/N, #/N and $$/N, respectively. The names can be modified with the options below. options This is a list of options controlling translation from and to prolog. • boolvec (see option rolog.boolvec, default is !) is the name of the prolog compound for vectors of booleans. • intvec, realvec, charvec define the compound names for vectors of integers, doubles and strings, respectively (defaults are %, # and $$). • If scalar is TRUE (default), vectors of length 1 are translated to scalar pro- log elements. If scalar is FALSE, vectors of length 1 are also translated to compounds. env The R environment in which the query is run (default: globalenv()). This is mostly relevant for r_eval/2. Value If the query fails, an empty list is returned. If the query succeeds N >= 1 times, a list of length N is returned, each element being a list of conditions for each solution, see once(). See Also once() for a single query query(), submit(), and clear() for fine-grained control over non-deterministic queries rolog_options() Examples # This query returns a list stating that it works if X = a, "b", ... findall(call("member", expression(X), list(quote(a), "b", 3L, 4, TRUE, NULL, NA))) # Continued findall(call("member", expression(X), list(call("sin", call("/", quote(pi), 2)), expression(Y)))) # The same using simplified syntax q <- quote(member(.X, ""[a, "b", 3L, 4, TRUE, NULL, NA, sin(pi/2), .Y])) findall(as.rolog(q)) once Invoke a query once Description Invoke a query once Usage once( query = call("member", expression(X), list(quote(a), "b", 3L, 4, TRUE, expression(Y))), options = list(portray = FALSE), env = globalenv() ) Arguments query an R call. The R call consists of symbols, integers and real numbers, character strings, boolean values, expressions, lists, and other calls. Vectors of booleans, integers, floating point numbers, and strings with length N > 1 are translated to prolog compounds !/N, %/N, #/N and $$/N, respectively. The names can be modified with the options below. options This is a list of options controlling translation from and to prolog. • boolvec (see option rolog.boolvec, default is !) is the name of the prolog compound for vectors of booleans. • intvec, realvec, charvec define the compound names for vectors of integers, doubles and strings, respectively (defaults are %, # and $$). • If scalar is TRUE (default), vectors of length 1 are translated to scalar pro- log elements. If scalar is FALSE, vectors of length 1 are also translated to compounds. env The R environment in which the query is run (default: globalenv()). This is mostly relevant for r_eval/2. Value If the query fails, FALSE is returned. If the query succeeds, a (possibly empty) list is returned that includes the bindings required to satisfy the query. See Also findall() for querying all solutions query(), submit(), and clear() for fine-grained control over non-deterministic queries rolog_options() for options controlling R to prolog translation Examples # This query returns FALSE once(call("member", 1, list(quote(a), quote(b), quote(c)))) # This query returns an empty list meaning yes, it works once(call("member", 3, list(1, 2, 3))) # This query returns a list stating that it works if X = 1 once(call("member", 1, list(quote(a), expression(X)))) # The same query using simplified syntax q = quote(member(1, ""[a, .X])) once(as.rolog(q)) # This query returns a list stating that X = 1 and Z = expression(Y) once(call("=", list(expression(X), expression(Y)), list(1, expression(Z)))) # This works for X = [1 | _]; i.e. something like [|](1, expression(_6330)) once(call("member", 1, expression(X))) # This returns S = '1.0' (scalar) once(call("format", call("string", expression(S)), "~w", list(1)), options=list(scalar=TRUE)) # This returns S = '#(1.0)' (vector), because the 1 is translated to #(1.0). # To prevent "~w" from being translated to $$("~w"), it is given as an atom. once(call("format", call("string", expression(S)), as.symbol("~w"), list(1)), options=list(scalar=FALSE)) portray Translate an R call to a prolog compound and pretty print it Description Translate an R call to a prolog compound and pretty print it Usage portray( query = call("member", expression(X), list(quote(a), "b", 3L, 4, TRUE, expression(Y))), options = NULL ) Arguments query an R call. The R call consists of symbols, integers and real numbers, char- acter strings, boolean values, expressions and lists, and other calls. Vectors of booleans, integers, floating point numbers, and strings with length N > 1 are translated to prolog compounds !/N, %/N, #/N and $$/N, respectively. The names can be modified with the options below. options This is a list of options controlling translation from and to prolog. • boolvec (see option rolog.boolvec, default is !) is the name of the prolog compound for vectors of booleans. • intvec, realvec, charvec define the compound names for vectors of integers, doubles and strings, respectively (defaults are %, # and $$). • If scalar is TRUE (default), vectors of length 1 are translated to scalar pro- log elements. If scalar is FALSE, vectors of length 1 are also translated to compounds. Details The R elements are translated to the following prolog citizens: • numeric -> real (vectors of size N -> #/N) • integer -> integer (vectors -> %/N) • character -> string (vectors -> $$/N) • symbol/name -> atom • expression -> variable • call/language -> compound • boolean -> true, false (atoms) • list -> list Value character string with the prolog syntax of the call See Also rolog_options() for fine-grained control over the translation postproc Default hook for postprocessing Description Default hook for postprocessing Usage postproc(constraint = call("=<", 1, 2)) Arguments constraint the R call representing constraints of the Prolog query. Value The default hook translates the inequality and smaller-than-or-equal-to back from Prolog (\=, =<) to R (!=, <=). See Also [rolog_options()] for fine-grained control over the translation preproc Default hook for preprocessing Description Default hook for preprocessing Usage preproc(query = quote(1 <= sin)) Arguments query the R call representing the Prolog query. Value The default hook translates the inequality and smaller-than-or-equal-to from R (!=, <=) to Prolog (\=, =<). Moreover, primitive functions are converted to regular functions. See Also [rolog_options()] for fine-grained control over the translation query Create a query Description Create a query Usage query( query = call("member", expression(X), list(quote(a), "b", 3L, 4, TRUE, expression(Y))), options = NULL, env = globalenv() ) Arguments query an R call. The R call consists of symbols, integers and real numbers, character strings, boolean values, expressions, lists, and other calls. Vectors of booleans, integers, floating point numbers, and strings with length N > 1 are translated to prolog compounds !/N, %/N, #/N and $$/N, respectively. The names can be modified with the options below. options This is a list of options controlling translation from and to prolog. • boolvec (see option rolog.boolvec, default is !) is the name of the prolog compound for vectors of booleans. • intvec, realvec, charvec define the compound names for vectors of integers, doubles and strings, respectively (defaults are %, # and $$). • If scalar is TRUE (default), vectors of length 1 are translated to scalar pro- log elements. If scalar is FALSE, vectors of length 1 are also translated to compounds. env The R environment in which the query is run (default: globalenv()). This is mostly relevant for r_eval/2. Details SWI-Prolog does not allow multiple open queries. If another query is open, it it is closed and a warning is shown. Value If the creation of the query succeeds, TRUE. See Also once() for a query that is submitted only a single time. findall() for a query that is submitted until it fails. Examples query(call("member", expression(X), list(quote(a), "b", 3L, 4, TRUE, expression(Y)))) submit() # X = a submit() # X = "b" clear() query(call("member", expression(X), list(quote(a), "b", 3L, 4, TRUE, expression(Y), NA, NaN, Inf, NULL, function(x) {y <- sin(x); y^2}))) submit() # X = a submit() # X = "b" submit() # X = 3L submit() # X = 4.0 submit() # X = TRUE submit() # X = expression(Y) or Y = expression(X) submit() # X = NA submit() # X = NaN submit() # X = Inf submit() # X = NULL submit() # X = function(x) {y <- sin(x); y^2})) submit() # FALSE (no more results) submit() # warning that no query is open query(call("member", expression(X), list(quote(a), "b", 3L, 4))) query(call("member", expression(X), list(TRUE, expression(Y)))) # warning that another query is open clear() rolog_done Clean up when detaching the library Description Clean up when detaching the library Usage rolog_done() Value ‘TRUE‘ on success rolog_init Start prolog Description Start prolog Usage rolog_init(argv1 = commandArgs()[1]) Arguments argv1 file name of the R executable Details SWI-prolog is automatically initialized when the rolog library is loaded, so this function is normally not directly invoked. Value ‘TRUE‘ on success rolog_ok Check if rolog is properly loaded Description Check if rolog is properly loaded Usage rolog_ok(warn = FALSE, stop = FALSE) Arguments warn raise a warning if problems occurred stop raise an error if problems occurred Value TRUE if rolog is properly loaded rolog_options Quick access the package options Description Quick access the package options Usage rolog_options() Details Translation from R to Prolog • numeric vector of size N -> realvec/N (default is ##) • integer vector of size N -> intvec/N (default is %%) • boolean vector of size N -> boolvec/N (default is !!) • character vector of size N -> charvec/N (default is $$) • scalar: if TRUE (default), translate R vectors of length 1 to scalars • portray: if TRUE (default) whether to return the prolog translation as an attribute to the return value of once(), query() and findall() Value list with some options for translating R expressions to prolog submit Submit a query that has been opened with query() before. Description Submit a query that has been opened with query() before. Usage submit(options = NULL) Arguments options This is a list of options controlling translation from and to Prolog. Here, only postproc is relevant. Value If the query fails, FALSE is returned. If the query succeeds, a (possibly empty) list is returned that includes the bindings required to satisfy the query. See Also query() for a opening a query. rolog_options() for fine-grained control on the translation from R to Prolog and back. clear() for a clearing a query. once() for a opening a query, submitting it, and clearing it again. findall() for a opening a query, collecting all solutions, and clearing it again. Examples query(call("member", expression(X), list(quote(a), "b", 3L, 4, expression(Y)))) submit() # X = 3L submit() # X = 4.0 submit() # X = TRUE submit() # X = expression(Y) or Y = expression(X) submit() # FALSE submit() # warning that no query is open query(call("member", expression(X), list(quote(a), "b", 3L, 4))) submit() # X = a submit() # X = "b" clear()
fifinddo
ctan
TeX
# Filtration TeX(t) Files by TeX+ Footnote †: This file describes version v0.61 of ffitinddo.sty as of 2012/11/17. <NAME> [http://contact-ednotes.sty.de.vu](http://contact-ednotes.sty.de.vu) ###### Abstract **f**find**do** starts implementing parsing of plain text or TeX files using TeX, generalizing the philosophy behind docstrip, based on how TeX reads macro arguments. Rather than typesetting the edited input stream immediately, results are written to another file, in the first instance as input for TeX. Rather than presenting a "complete study" of a computer-scientific idea, it aims at practical applications. The main one at present is makedoc which removes certain comment marks from package files and inserts listing commands. Parsing macros are not defined anew at every input chunk, but once before a file is processed. This also allows for _expandable_ sequences of replacements, e.g., with txt\(\,\rightarrow\,\)TeX functionality. The method of testing for substrings is carefully discussed, revealing an earlier mistake (then) shared with substr.sty and LaTeX's internal \in@. **Keywords:** text filtering, macro programming,.txt to.tex enhancement _FIDO, FIND!_ _or:_ _FIND FIDO!_ _oder:_ _FIFI, SUCH!_ ###### Contents * 1 Introduction: The Gnome of the Aim * 1.1 Parsing by TeX--are you mad? * 1.2 Useful for... * 1.2.1 Comparisons * 1.3 For insiders Preliminaries * 2.1 Head of file (Legalese) * 2.2 Format and package version * 2.3 Category codes * 3 File handling * 3.1 Opening, Writing to, Closing Output * 3.2 Processing Input * 3.3 A Combining Shorthand * 4 Basic handling of substring conditionals * 4.1 "Substring Theory" * 4.2 Plan for proceeding * 4.3 Meta-Setup * 4.4 Setup for conditionals * 4.5 Setup for sandboxes * 4.6 Getting rid of the tildes * 4.7 Alternative Setup * 4.8 Calling conditionals * 4.9 Copy jobs * 5 Programming tools * 5.1 Tails of conditionals * 5.2 Line counter * 5.3 "Identity job" LEAVE and "default job" * 5.2 Setup for expandable chains of replacements * 5.1 The backbone macro * 5.2 The basic setup interface macro * 5.3 Automatic chaining * 5.4 CorrectHook launching the replacement chain * 6 Leave package mode * 7 Ponded * 8 PERSION HISTORY * 9 ## 1 Introduction: The Gnome of the Aim ### Parsing by TeX--are you mad? The package name ffinddo is a \listfiles-compatible abbreviation of 'file-finddo'1 (or think of 'if found do'). ffinddo implements (or aims at) general parsing (extracting, replacing [converting], expanding,...) using TeX where texhax posters strongly urge to use sed, awk, or Perl. ffinddo's opposed rationales are: Footnote 1: ‘file’ possibly for “searching TeX(t) files” (I don’t remember my thoughts!), while there were requests for doing replacements on LaTeX_environments_ on texhax. However, the package might be enhanced in this direction... so the name may be wrong... but now I like it so much... Or the reason was that results are written to a _separate file_, not typeset immediately.—Let me also mention that _‘Fifi’_ (as the package name starts) is a kind of German equivalent to the “English” _‘Fido’_, or may have been. * It works instantly on any TeX installation. (_Restrictions:_ Some TeX versions \write certain hex codes for certain characters, cf. TeXbook p. 45, I have seen this with PCTEX. However, some applications of ffinddo are nothing but technical steps where you will read the result files rarely anyway. * You can apply and customize it like any TeX macros, knowing just TeX (or even only the documentation of some user-friendly extension of ffinddo), without the need of learning any additional script language. * The syntax of usual utilities (e.g., "wildcards") is sometimes difficult with _TeX_ files with all their backslashes, square brackets, stars, question marks... At least the first item is just the philosophy of the docstrip program, standard for installing TeX packages; and while I am typing this, I find at least 14 other similar packages in Jurgen Fenn's _Topic Index_ of the _TeX Catalogue:_ [http://mirror.ctan.org/help/Catalogue/bytopic.html#parsingfiles](http://mirror.ctan.org/help/Catalogue/bytopic.html#parsingfiles) (Some of them may have been _reactance_ to texhax and other postings urging not to try something like this; some seem just to be celebrations of the power of TeX--yes, celebrate!) Actually, TeX's mechanism of collecting macro arguments is hard-wired parsing at quite a high level. LaTeX hides this from "simple-minded" users by a convention _not_ to use that full power of TeX for _end-user macros_. _Internally_, LaTeX_does_ use it in reading lists of options and file dates as well as to implement certain FOR- and WHILE-like loop programming structures. LaTeX's \in@/\ifin@ construction is an implementation of a "_\(\langle\)string1\(\rangle\)_ occurs in \(\langle\)string2\(\rangle\)" test. More packages seem to use this idea for extracting file informations, like texshade.2 Footnote 2: [http://ctan.org/pkg/texshade](http://ctan.org/pkg/texshade) However, such packages don't make much ado about parsing, there seems to be no general setup mechanism as are presented by ffinddo. Indeed, tayloring parsing macros to specific applications may often be more efficient than a general approach. ### Useful for... My main application of ffinddo at present is typesetting documentations of packages using makedoc which removes certain percent marks and inserts listing commands, so you edit a package file with as little documentation markup as possible. This may be extended to other kinds of documents as an alternative to easylatex or wiki (the approach of which is dangerous and incompatible with certain other things). I have used a similar own package ktproc successfully, where more features were implemented for practical purposes than are here so far, yet I don't like its implementation, want to improve it here. This package also _created batch files_, e.g., to remove temporary files. This could be used for package handling: typset the documentation at the desired place in the tree, write the packages to another, write a batch file to remove files that are not needed any more after installation (cf. make). I used ktproc also for _large-scale substitutions_ (it had been decided to change the orthography in a part of a book). Other large-scale substitutions may be: * inserting \index commands; * inserting (soft) hyphenation commands near accents; * manual umlaut-conversion.3 Footnote 3: If you know the “names” of the encodings, <NAME>’s stringenc may be preferable. * typographical (or even orthographical) corrections (same mistake many times on each of hundreds of pages). You may turn... into $\dots$ and etc. into etc.\ etc.4 This could replace packages like easylatex,5 txt2latex,6 txt2tex7 in a customizable way, using, e.g., the "correct" hook from makedoc.sty as exemplified in mdoccorr.cfg (see examples section of makedoc.pdf). You should find fdtxttex.tpl, a ffinddo script to try or apply \MakeDocCorrectHook from mdoccorr.cfg, as well as fdtxttex.tex that runs a dialogue for the same purpose if you can manage to run it (WinShell?). You can then try to create your own \MakeDocCorrectHook. Section 6 provides setup for macros of this kind. Footnote 4: But what when a new sentence is starting indeed? Well, cf. is an easier example.—etc. even showed a problem in niceverb. mdoccorr.cfg replaces etc. only, so you can keep the extra space by a code line break. * as to easylatex again, _lists_ could be detected and transformed into LaTeX list commands. This could re-implement the lists functionality of wiki.sty that is somewhat dangerous. * introduce your own _shortands_ to be expanded not as LaTeX macros, but by text substitution;In certain cases, insertions deteriorate readability, hyphenation corrections even make text search difficult. It is therefore suggested to 1. keep editing the file without the insertions, 2. run the script (commands based on ffinddo) for insertions in the preamble of the main file ("\jobname.tex", maybe \input the script file) and 3. \input the result file within the document environment. In general, differences to "manual" replacing by the substitution function of your _text editor_ is that * you first keep the original version, * you can check the resulting file before you replace the original file by it, * you can store the replacement script in order to check for mistakes at a later stage of your work, * you can do _all_ the replacements in _one run_ (by _one_ script to check for mistakes), * you can store replacement scripts for future applications, so you needn't type the patterns and replacement strings anew. #### 1.2.1 Comparisons It should be noted (perhaps here) that the present approach to parsing is a quite _simple_ one and in this respect much different to the string handling mechanisms of stringstrings,8 ted,9 xstrings10 (as I understand them, perhaps also coolstr11) which are _much more powerful_ than what is offered here--but perhaps slow and for practical applications possibly replaceable by the present approach. _Expandable replacement_ seems not to exist outside ffinddo (2009/04/13). Footnote 8: [http://ctan.org/pkg/stringstrings](http://ctan.org/pkg/stringstrings) Footnote 9: [http://ctan.org/pkg/ted](http://ctan.org/pkg/ted) Footnote 10: [http://ctan.org/pkg/xstrings](http://ctan.org/pkg/xstrings) Much is missing, I know.12 I am just implementing what I actually need and what could show that this approach is worth being pursued. Footnote 12: There is more in my badly implemented btproc_sty. ### For insiders _Warning:_ You may (at least at the present state of the work) have little success with this package, if you don't know about TeX's category codes and how TeX macros are defined. The package rather provides tools for package writers. You may, however, be able to run other packages which just load ffinddo as required background. That ffinddo acts on "TeX(t)" files or so means that (at present) I think of applications on "plain text" files which will usually be TeX input files. "At present" they are read without "special characters," so essentially category codes of input characters are either 11 ("letter") or 12 ("other"). This way some things are easier than with usual TeX applications: 1. You can "look into" curly braces and "behind" comment characters. 2. There are exact or safe tests especially of _empty macro arguments_ that are "expandable," i.e., they are "robust," don't need assignments, can be executed in \writeing and in \edef definitions. "Usually," the safe way to test emptiness is storing a macro argument as a macro, say \tempo, in order to test \ifx\tempo\empty where \empty has been defined by \def\empty{} in the format. But this requires some \def\tempo{\#\(n)} which breaks in "mere expanding" (TeX _evaluates_\tempo instead of defining it). An _expandable_ test on emptiness is, e.g. \ifx$#\(n)$, where we hope that it becomes \iftrue just if macro argument \(n) is empty indeed. However, "usually" it may _also_ become \iftrue when \(n) starts with $--if the latter has category code 3 ("math shift"). But ffinddo does not assign category code 3 to any character from the input file! Therefore \ifx$#\(n)$ is \iftrue _exactly_ if \(n) is empty. 3. You can avoid interference with packages that are needed for typesetting. You can do the "preprocessing" in one run with typesetting, but you should do the preprocessing before you load packages needed for typesetting. One may even try to keep the macros and settings for preprocessing local to a group. The essential approach of ffinddo to looking for single strings is described in some detail in section 4. The implementation of ffinddo is as follows. User commands are specially highlighted (boxed/coloured), together with their syntax description. ## 2 Preliminaries ### Head of file (Legalese) 1 %% Macro package 'fifinddo.sty' for LaTeX2e, %% FIDO, FIND! 2 %% copyright (C) 2009-2012 <NAME>, 3 %% [http://www.contact-ednotes.sty.de.vu](http://www.contact-ednotes.sty.de.vu) 4 %% -- author-maintained in the sense of LPPL below -- 5 %% for processing tex(t) files 6 %% (checking, filtering, converting, substituting, expanding,...) 7 8 \def\fileversion{0.61} \def\filedate{2012/11/17} 9 10 %% This file can be redistributed and/or modified under 11 %% the terms of the LaTeX Project Public License; either 12 %% version 1.3c of the License, or any later version. 13 %% The latest version of this license is in 14 %% 15 %% [http://www.later-project.org/lppl.txt](http://www.later-project.org/lppl.txt) 16 %% 17 %% We did our best to help you, but there is NO WARRANTY. 18 %% Please report bugs, problems, and suggestions via 19 %% 20 %% [http://www.contact-ednotes.sty.de.vu](http://www.contact-ednotes.sty.de.vu) 21 %% 22 %% For the full documentation, look for 'fifinddo.pdf'. 23 %% Its source starts in 'fifinddo.tex'. ### Format and package version ``` 1NeedsTeXFormat{LaTeX2e}[1994/12/01] 25 % 1994/12/01: \newcommand* etc. 36 \ProvidesPackage{fifinddo}[\filedate\space v\fileversion\space filtering TeX(t) files by TeX (UL)] ``` ### Category codes We use the "underscore" as "compound identifier:" ``` 1\RequirePackage{stacklet}\PushCatMakeLetter_ %% 2012/08/27v0.6moves definition of \MakeActiveDef to actcodes in the catcodes bundle: 29 \RequirePackage{actcodes} ``` fifinddo uses TeX's feature of delimited macro parameters for matching _strings_ of characters. In order to get expected results, _category codes_ must match as well. ``` 1PatternCodes is used in setup macros for reading patterns for this purpose. It defaults to \fdPatternCodes. We offer \SetPatternCodes{_commands} for redefining \PatternCodes and \ResetPatternCodes for returning to \fdPatternCodes, so setup scripts such as mdoccorr.cfg have shorter lines. 30 \newcommand*{\fdPatternCodes}{\MakeOther\&MakeOther}$ 31 \newcommand*{\SetPatternCodes}{def\PatternCodes} 32 \newcommand*{\ResetPatternCodes}{let\PatternCodes} 33 \newcommand*{\PatternCodes}{\}{\ResetPatternCodes} 34 %% TODO adding/removing; '*' may be wrong 2010/03/29 It would be bad to have \MakeOther\% and \MakeOther\\\\\ here in that this may have unexpected, weird effects with arguments of setup macros. (With \MakeOther\\\\ you must not indent within a setup command, and if you add \MakeOther\% the setup command must stay in one line.) Therefore neither \dospecials nor \@sanitize are used. Curly braces remain untouched as default delimiters in setup macros. For matching them, you must use \MakeOther\{ and \MakeOther\} in your \PatternCodes, or \Delimiters to introduce new ones at the same time, e.g., \Delimiters\[]: ... moves into conditional with v0.5. Resetting line counter: ``` \global\c@fdInputLine=\z@ \begingroup \MakeOther\{\MakeOther\}\@sanitize...switching into "plain text mode"; from docstrip.tex: ``` %MakeOther\^^A\MakeOther\^^K%%irrelevant,notLaTeX \-cf.TeXbookpp.43ff.,368ff., "extended keyboards", up-/downarrow; \-"math specials",cf. "space specials" ``` \endlinechar\m@ne \MakeOther\^^I%ASCIIhorizontaltab--guessed!?~~L!? ``` With v0.31, we support non-ASCII: ``` \count@=128 \loop \ifnum\count@<\@cclvi \catcode\count@=12 \advance\count@\@ne \repeat \1% \loop\ifeof\@inputcheck\else \read\@inputcheckto\}fdfInputLine \ignorespaces#3% v0.42 supports \IfFDpreviousInputEmpty,cf.section5.1: ``` \expandafter\left\IfFDpreviousInputEmpty \ifx\fdInputLine\@empty\@firstoftwo \else\@secondoftwo\fi \repeat \endgroup \fi \closein\@inputcheck ``` Added for v0.5, cf. Sec.3.3 ``` \ifFinalInputFile \CloseResultFile\FinalInputFilefalse \fi ``` ``` \CopyFile[\(changes)]{\(file)}] is an application of \ProcessFileWith that "copies" the content of file \(file) into the file specified by \ResultFile. However, optional \(changes) allows some "modifications" while "copying"--especially, conversion of text encodings by active characters and expanding macros for generating HTML or other code. The "starred" variant \CopyFile*] copies one empty line only when one empty line in the input file is followed by more of them. It may be more efficient _not_ to use the following setup macros but to type the macros yourself, just using the following as templates. The setup macros are especially useful with patterns that contain "special characters," as when you are looking for lines that might be package comments. ### Meta-Setup A setup command \(\(\mathit{setup\mbox{-}cmd}\)) will have the following syntax: \(\langle\)_changes_\(\rangle\) will, in the first instance, be category code changes for reading \(\langle\)_pattern_\(\rangle\) overriding the settings in \(\backslash\)PatternCodes. They are executed after the latter in a local group. It may be safer to redefine \(\backslash\)PatternCodes instead of using the optional \(\langle\)_changes_\(\rangle\) argument. A macro \(\langle\)StartFDsetup{\(\langle\)_do-setup\(\rangle\)}{\(\{\langle\)job-id\(\rangle\}\)}{\(\{\langle\)_changes\(\rangle\}\)} shared by setup commands may read \(\langle\)_job-id\(\rangle\)_ and \(\langle\)_changes_\(\rangle\) for \(\langle\)_setup-cmd\(\rangle\)_. \(\langle\)_do-setup\(\rangle\)_ will be the macro that reads \(\langle\)_pattern_\(\rangle\) (and more) and processes it. It must contain \(\backslash\)endgroup to match \(\backslash\)begingroup from \(\backslash\)FD_prepare_pattern. \(\langle\)_job-id\(\rangle\)_ is stored in a macro \(\langle\)VfdParserId\(\rangle\). The default for \(\langle\)_changes_\(\rangle\) is _nothing_. ``` 108\newcommand*{\(\backslash\)StartFDsetup\(\}\)[1]{% 109\(\backslash\)let\(\backslash\)FD_do_setup#1% 110\(\backslash\)afterassignment\(\backslash\)FD_prepare_pattern 111\(\backslash\)def\(\backslash\)fdParserId\(\rangle\) 112\(\backslash\)newcommand*{\(\backslash\)FD_prepare_pattern}[1][]{% 113\(\backslash\)begingroup \(\backslash\)PatternCodes #1\(\backslash\)FD_do_setup\(\rangle\) So \(\langle\)_setup-cmd\(\rangle\)_ should be set up about as follows: \(\langle\)newcommand*{\(\langle\)_setup-cmd\(\rangle\)}{\(\backslash\)StartFDsetup\(\langle\)_do-setup\(\rangle\)} \(\langle\)newcommand*{\(\langle\)_do-setup\(\rangle\)}{\(\{\langle\)_args\(\rangle\}\)}{\(\{\langle\)_action\(\rangle\}\)} \(\langle\)_do-setup\(\rangle\)_'s first argument will be the \(\langle\)_pattern\(\rangle\)_ argument of \(\langle\)_setup-cmd\(\rangle\)_.--With v0.5, we learn from the previous and provide ``` 114\(\backslash\)newcommand*{\(\backslash\)MakeSetupCommand}[2]{\(\backslash\)newcommand*#1{\(\backslash\)StartFDsetup#2}% 115\(\backslash\)newcommand*#2} ``` ### Setup for conditionals substr_cond is the "name space" for substring conditionals. A colon separates it from _"job identifiers"_ in the actual macro names. called_, not right here at the _definition_ of the job. For this reason, a variant of the sandbox builder expanding some macro was given up. setup_substr_cond is the name space for macros that build sandboxes and initialize arguments for conditional macros. 120\def\setup_substr_cond{setup_substr_cond:} MakeSetupSubstringCondition{_id_}[\(changes)]{_pattern_}{_more-args_}] --same _id_, _changes_, _pattern_) as for \MakeSubstringConditional (this is bad, there may be \MakeSubstringConditional*{_more-args_})--creates the corresponding sandbox, by default without tilde wrap. _(more-args_) may contain {#1} to store the string that was tested, also {_id_} for calling repetitions and {_pattern_} for screen or log informations. 121\MakeSetupCommand{MakeSetupSubstringCondition} 122\mk_setup_substr_cond[2]{% \mk_setup_substr_cond{_pattern_}{_more-args_}] can be directly called by other programmer setup commands after \fdParserId and _pattern_} have been read. 123%%#1patternstring 124%%#2additionalarguments,e.g., '{#1}'tokeeptestedstring 125\endgroup 126\expandafter\protected@edef %%protected2011/11/21... keeps \protect instead of just not expanding, but I cannot implement \UseBlogLigs otherwise right now. 127\csname\setup_substr_cond\fdParserId\endcsname##1% 128\noexpandcsname\substr_cond\fdParserId\endcsname By \edef, the name of the substring conditional is stored here as a single token. The rest of the sandbox follows. 129\FF1\FD_noexpand~#1\dollar_tilde&#2}% \noexpand~ as before v0.5 replaced for v0.51 according to Sec. 4.7. 130\let\dollar_tilde\sandbox_dollar} If a tilde ~ has been used instead of $, the default is restored. 131\def\sandbox_dollar{$} 132\let\dollar_tilde\sandbox_dollar The following general tool \noexpandcsname has been used (many definitions in latex.ltx could have used it): 133%\def\make_not_expanding_cs#1{% %expandafter\noexpand\csname#1\endcsname} \def\noexpand\csname{expandafter\noexpand\csname} \newcommand*{\CopyFDconditionFromTo}[2]{% \expandafter\let \csname\setup_substr_cond #2\expandafter\endcsname \csname\setup_substr_cond #1\endcsname} ``` (Only the _sandbox_ is copied here--what about changing conditionals?) An "almost" example is typesetting documentation from a package file where the "Legalese" header might be typeset verbatim although it is marked as "comment." (The present example changes "hand-made" macros instead.) This feature could have been placed more below as a "programming tool." ## 5 Programming tools ### Tails of conditionals When creating complex _expandable_ conditionals, this may amount to have primitive \if...\fi conditionals nested quite deeply, once perhaps too deep for TeX's memory. To avoid this, you can apply the common \expandafter trick which finishes the current \if...\fi before an inside macro is executed (cf. TeXbook p. 219 on "tail recursion"). Internally tests whether certain strings are present at certain places will be carried out by tests on emptiness or on starting with \f. E.g., "#1 = (_split1_) empty" indicates that either the \(_pattern_) starts a line or the line is empty altogether (this must be decided by another test). ``` \leftDepntyt{\(\mathit{arg})\f{\(\mathit{when-empty})\f{\(\mathit{when-not-empty})\}} \right.\) is used to test \(\langle\mathit{arg}\rangle\) on emptyness (without expanding it): ``` \newcommand*{\IfPDempty}[1]{% \ifx$#1$\expandafter\@firstoftwo\else \expandafter\@secondoftwo\fi} ``` ``` \IfPDindurl{\(\mathit{when-empty})\f{\(\mathit{when-not-empty})\}} is a variant of the previous to execute \(\langle\mathit{when-empty}\rangle\) if the loop processing \(\langle\mathit{input}\rangle\) finds an empty line--otherwise \(\langle\mathit{when-not-empty}\rangle\). ``` \newcommand*{\IfPDinputEmpty}{% \ifx\fdfInputLine\@empty\expandafter\@firstoftwo\else \expandafter\@secondoftwo\fi} ``` ``` \IfPDindurl{\(\mathit{arg})\f{\(\mathit{when-dollar})\f{\(\mathit{when-not-dollar})\}} is another variant, testing \(\langle\mathit{split2}\rangle\) for being $, main indicator of there is a match anywhere in \(\langle\mathit{target}\rangle\) (as opposed to starting or ending match): ``` \newcommand*{\IfPDindurl{1}[1]{% \ifx$#1$\expandafter\@firstoftwo\else \expandafter\@secondoftwo\fi} ``` It is exemplified and explained in section 6. (The whole policy requires that \f remains active in any testing macros here!)However, you might always just type the replacement text (in one line) instead of such an \If... (for efficiency...) If expandability is not desired, you can just chain macros that rework (so re-define) \OutputString or so. 2009/04/11: tending towards combining... Keeping empty input and empty arguments apart is useful in that _one_ test of emptiness per input line should suffice--it may be left open whether this should be the first of all tests... [IfFDpreviousInputEmpty{_when-empty_}]{_when-not-empty_}] (v0.42) is a companion of \IfFDpreviousInputEmpty referring to \fdInputLine as of the _previous_ run of the loop in \ProcessFileWith, cf. section 3.2, where its choice among its two arguments is determined. It is initialized as follows: ``` 175\newcommand*{_IfFDpreviousInputEmpty}[2]{#2} --which is same as 176\let{_IfFDpreviousInputEmpty}@secondoftwo...working like false, somewhat. Together with \IfFDinputEmpty, it can be used to compress multiple adjacent empty lines into a single one when copying a file. ### Line counter A LaTeX counter [fdInputLine] may be useful for screen or log messages, moreover you can use it to control processing of the \(\mathit{input}\) file "from outside," not dependent on what the parsing macros find. The header of the file might be typeset verbatim, but we may be too lazy to define the "header" in terms of what is in the file. We just decide that the first... lines are the "header," even without counting just trying whether the output is fine. It may be necessary to change that number manually when the header changes. You also can insert lines in \(\mathit{output}\) which have no counterpart in \(\langle\mathit{input}\rangle\)--if you know what you are doing. With makedoc, there is a hook \EveryComment that can be used to issue commands "from outside" at a place where executing the command is safe or appropriate. ``` 177\newcounter{fdInputLine} ``` You then must insert \CountInputLines in the second argument of \ProcessFileWith (or in a macro called from there) so that the counter is stepped. ``` 178\newcommand*{_CountInputLines}{_global_advance}c@fdInputLine\@ne} ``` At present the counter is reset by \ProcessFileWith, this may change. [IfInputLine{_relation_}\(\langle\mathit{number}\rangle\)]{_true_}{_false_}], when called from the processing loop (second argument of \ProcessFileWith) issues \(\langle\mathit{true}\rangle\) commands if \value{fdInputLine}\(\langle\mathit{relation}\rangle\langle\mathit{number}\rangle\) is true, otherwise \(\langle\mathit{false}\rangle\). \(\langle\mathit{relation}\rangle\) is one out of <, =, >. \newcommand*{\IfInputLine}[1]{% \ifnum\cC@fdInputLine#1\relax\expandafter\@firstoftwo \else\expandafter\@secondoftwo\fi} ### "Identity job" LEAVE and "default job" * The job with identifier LEAVE _leaves_ an (expandable) chain of jobs (as expandable replacement in section 6) and _leaves_ the processed string without changing it and without the braces enclosing it: ``` \expandafter\let \csname\setup_substr_condLEAVE\endcsname\@firstofone ``` I.e., \ProcessStringWith{_string_}{LEAVE} expands to _string_}... (Indeed!) \LEAVE is used for "chaining" jobs--there will be a routine (Sec. 6.3) to define the action of a job, including what job to run _next_ after the present one has been finished. Using this routine, the final job will call LEAVE. ``` \@namedef{\setup_substr_cond*}{% \csname\setup_substr_cond\fdParserId\endcsname} ``` As an important example, when all the jobs in the chain are expandable, you can call the chain by ``` \WriteResult{\ProcessInputWith{*}} ``` in the body of the file processing loop (Sec. 3.2). todo: test! ## 6 Setup for expandable chains of replacements By the following means, you can create macros (\Transform among them) such that, e.g., ``` \edef\OutputString{\Transform{_string}} ``` renders \OutputString the result of applying a chain (sequence) of stringwise replacements to _string_). You can even write a transformed input _string_) to a file without defining anything after \read_to... In this case however, you don't get any statistical message about what happened or not. With \edef\OutputString you can at least issue some changed! or left! (maybe \message{!} vs. \message{.}). There is an application in makedoc for "typographical upgrading" from plain text to TeX input. ### The backbone macro ``` \repl_all_chain_expandable_will be the backbone of the replacements. It is called by some parsing macro \(\langle\mathit{parser}\rangle\) and receives from the latter \(\langle\mathit{split1}\rangle=\)#1 and \(\langle\mathit{split2}\rangle=\)#2.#3 is the result of what happened so far. ``` \def\repl_all_chain_expandable#1#2#3#4#5#6{% %%#1,#2splits,#3past,#4substitute, %%#5repeatparser,#6passto %%\ifx"#2\expandafter\firstoftwo\else\expandafter\@secondoftwo\fi ``` The previous line (or something similar!?) would be somewhat faster, but let us exemplify \IfFDdollar from section 5.1 instead: ``` \IfFDdollar{#2}% ``` If #2 starts with $--with category code 3, "math shift"!, it _is_$, due to not reading $ from input with its standard category code 3 and the sandbox construction (where $ appears with its standard category code). And this is the case _exactly_ when the \(\langle\mathit{pattern}\rangle\) from \(\langle\mathit{parser}\rangle\) didn't match, again due to the input category codes. Now on _no_ match, the sandbox builder #6 is called with target string #3#1 where the last tested string is attached to previous results. The ending ~ is removed, #6 inserts a new wrap for the new dummy pattern. ``` \{\RemoveTildeArg#6{#3#1}}% ``` Otherwise... the _sandbox builder_\(\langle\mathit{sandbox}\rangle\) (that will be shown below) that called \(\langle\mathit{parser}\rangle\) initialized #5 to be that \(\langle\mathit{parser}\rangle\) itself. (\(\langle\mathit{parser}\rangle\) otherwise wouldn't know who it is.) So \(\langle\mathit{parser}\rangle\) calls itself with another sandbox #2&. Note that #2 contains '~\(\langle\mathit{pattern}\rangle\)$' due to the initial \(\langle\mathit{sandbox}\rangle\) building. ``` \{\#5#2&{#3#1#4}{#4}#5#6} ``` #4 is the replacement string that \(\langle\mathit{sandbox}\rangle\) passed to \(\langle\mathit{parse}\rangle\). The first argument after the & is previous stuff plus the recently skipped \(\langle\mathit{split1}\rangle\) plus #4 replacing the string \(\langle\mathit{pattern}\rangle\) that was matched. Finally, #5 and #6 again "recall" \(\langle\mathit{parser}\rangle\) and the sandbox builder to which to change in case of no other match. ### The basic setup interface macro ``` \(\{\)MakeExpandableAllReplacer{\(\mathit{id}\)}{\(\{\)_\(\mathit{ching}\)}}{\(\{\)_\(\mathit{find}\)}}{\{\)_\(\{\)_\(\{\)\(\}\)\(\}\)\(\}\)\(\}\)\(\}\) ``` creates sandbox and parser with common identifier \(\langle\mathit{id}\rangle\) and search pattern \(\langle\mathit{find}\rangle\). Each occurrence of \(\langle\mathit{find}\rangle\) will be replaced by \(\langle\mathit{replace}\rangle\). When \(\langle\mathit{find}\rangle\) is not found, the sandbox builder for \(\langle\mathit{id-next}\rangle\) is called. This may be another replacing macro of the same kind. To return the result without further transformations, call job LEAVE (section 5.3). Optional argument \(\langle\mathit{chng}\rangle\) changes category codes locally for reading \(\langle\mathit{find}\rangle\) and \(\langle\mathit{replace}\rangle\). ``` \MakeSetupCommand{\MakeExpandableAllReplacer} {\mk_setup_xpdbl_all_repl}[3]{% %% #1 pattern, #2 substitute, #3 pass to \endgroup ``` We take pains to call next jobs by single command strings and store them this way, not by \csname, as \ProcessStringWith would do it. \edef\@tempa is used for this purpose, but... ``` \protected@edef\@tempa{% %% protected2011/11/21 \noexpand\mk_setup_substr_cond{#1}{% \{#2}% \noexpand\noexpand That \edef\@tempa must _not expand_ tokens computed from \csname etc. Moreover, expansion of the parser commands must be avoided another time when \@tempa is executed. ``` \noexpandcsname\substr_cond\fdParserId\endcsname \noexpand\noexpand \noexpandcsname\setup_substr_cond\#3\endcsname}% ``` Those internal setup commands start with \endgroup to switch back to standard category codes. We must match them here by \begingroup. ``` \begingroup\@tempa \mkg_substr_cond{#1}{% \repl_all_chain_expandable{#1}{#2}}} ``` The final command is the one that we explained first. ### Automatic chaining With v0.31, ``` \PrependExpandableAllReplacer{\(id)}{\(cat)}{\(find)}{\(replace)} ``` was hoped to be a slight relief in composing replacement chains. It does something like invoking \MakeExpandableAllReplacer with \(prev-setup-id) for the last \(next-id) argument where \(prev-setup-id) is the \(id) of the job that was set up most recently. If you have adjacent lines ``` \MakeExpandableAllReplacer{\(id-0)}{\(find-0)}{\(subst-0)}{LEAVE} \PrependExpandableAllReplacer{\(id-1)}{\(find-1)}{\(subst-1)} \PrependExpandableAllReplacer{\(id-2)}{\(find-2)}{\(subst-2)} and call \(id-2)\), it will call \(id-1), and the latter will call \(id-0). So you can reorder the chain by moving \Prepend... lines. With v0.5, \PrependExpandableAllReplacer*[(cat)]{\(find)}{\(replace)} saves you from inventing and typing \(id), it is automatically generated; or the * replaces the \(id) argument. \newcommand*{\PrependExpandableAllReplacer}% 208 \let\fdParserId_before\fdParserId 209 \@ifstar{\stepcounter{fd_line_job}% 210 \edef\@tempa(% 211 \noexpand\StartFDsetup 212 \noexpand\prep_xpdbl_all_repl 213 \number{value{fd_line_job}}}% 214 \@tempa)% 215 \StartFDsetup\prep_xpdbl_all_repl}% 216 \newcommand*{\prep_xpdbl_all_repl}[2]{% 217 \mk_setup_xpdbl_all_repl{#1}{#2}{\fdParserId_before}}% 218 %% #1 pattern, #2 substitute, #3 pass to As of 2012/11/13, mdoccorr.cfg uses \do as a shorthand for \PrependExpandableAllReplacer* \do sometimes has not been defined at that moment, then \renewcommand*{\do}{\PrependExpandableAllReplacer*} fails. To make it working (or superfluous): ``` 19\gdef\do{\PrependExpandableAllReplacer*} 21\StartPreendingChain makes \MakeExpandableReplacer superfluous, in the sense that the above chain setup can be achieved as well like this: \StartPreendingChain 22 \PrependExpandableAllReplacer{_id-0_}{_find-0_}{_subst-0_} 23 \PrependExpandableAllReplacer{_id-1_}{_find-1_}{_subst-1_} 24 \PrependExpandableAllReplacer{_id-2_}{_find-2_}{_subst-2_} 25 26or with v0.5: 27 \StartPreendingChain 28 \PrependExpandableAllReplacer*{_find-0_}{_subst-0_} 29 \PrependExpandableAllReplacer*{_find-1_}{_subst-1_} 30 \PrependExpandableAllReplacer{_start_}{_find-2_}{_subst-2_}} ``` This adds a code line, but this way you can choose the final "real" job more easily. So you can think of \StartPreendingChain as "initializing a chain of prependments." As to the * version, the example suggests using an explicit \(id\) argument finally if you want to invoke the chain explicitly by a line job identity (without counting the declaration lines--however, note job * according to Sec. 5.3). ``` 220 \newcommand*{\StartPrependingChain}{% 221 \def\fdParserId{LEAVE}% 222 \setcounter{fd_line_job}{0}} %% 2011/11/13; TODO \Nameprefix... 223 \newcounter{fd_line_job} * %newcommand*{reversed_apply_substr_cond}[2]{% * %ApplySubstringConditional{#2}{#1}} * %%ODER: * %newcommand*{expand_attach_arg}[2]{%% 2009/03/31 * %%#1commandwithpreviousargs,TODOcf.LaTeX3 * %expandafter{}attach_arg}expandafter{#1}{#2}} * %%actually#1maycontainmorethanonetoken, * %%onlyfirstexpanded * %newcommand*{attach_arg}[2]{#2{#1}} * %newcommand*{ApplySubstringConditionalToExpanded}[2]{% * %expandafter{}attach_arg}expandafter * %{#2}{ApplySubstringConditional{#1}}} ## 9 Version History * 260 v0.1 2009/04/03 very first version, tested on morgan.sty * 261 v0.2 2009/04/05 counter fdInputLine, %ProvidesFile moved from \ProcessFile to \ResultFile, \CopyFD..., * 263 category section first,moresectioning, * 264 suppressingemptycodelinesbeforesection * 265 titles; discussion, \Delimiters * 266 2009/04/06 more discussion * 267 2009/04/07 more discussion, factored \WriteProvidesoutfrom * 268 resultFile, \ProcessExpandedWithcorrected * 269 2009/04/08 \InputString-> \fdInputline; * 270 removed \ignorespaces * 271 2009/04/09 \WhenInputLine[2]-> \IfInputline[3], * 272 \ProcessInputWith,typos, * 273 WriteProvidesmessage'with' * 274 2009/04/10 \make_not_expanding_cs * 275 DISCOVERED ''IF SUBSTRING" ALGORITHM WRONG * 276 (<str1><str2><str1> in <str1><str2>) * 277 v0.3 2009/04/11 SOMETHINGS GIVENUP EARLIER WILL BE REMOVED, * 278 TO BE STORED IN THE COPY AS OF 2009/04/10 * 279 mainly: sandbox setup (tilde/dollar) * 280 REAL ADDITION: setup for expandable replacing * 281 2009/04/12 played with 'chain' vs.'sequence'; * 282 plain '...', 'cf.', 'etc.' for'mdcorr.cfg' * 283 2009/04/13 \RemoveTitle... * 284 2009/04/15 reworkedtext,samemistake \in@ * 285 v0.31 2009/04/21f commentsonted,stringstrings * 286 2009/12/28 "onwards)"!?"safer",not"moresafe" * 287 2010/03/10 theloopstarts * 288 2010/03/17 corr. t'ete;setup->setupfor * 289 2010/03/18 TODOEOF,ctan.org/pkg/newfile;non-ASCII * 290 2010/03/19 extendeddescriptionof \MakeExpandableAll...; * 291 '->" * 292 2010/03/20 \ctanpkgref * 293 2010/03/22 \StartFDsetup, \Prepend... 294 2010/03/23 URL for'substr.sty' 295 SENT TO CTAN 296 297 v0.4 2010/03/24 removed \pagebreak before "substrings"; 298 <relation> with \IfInputLine precisely 299 2010/03/25 todo \ProcessExp... more precisely, etc. 300 2010/03/26... was wrong, removed 301 2010/03/29 \SetPatternCodes, \ResetPatternCodes, 302 \SetCorrectHookJob, \SetCorrectHookJobLast; 303 <relation> with \HardNverb; 304 don't mention \begingroup with 305 \mk_setup_substr_cond; renamed v0.4 306 belonged to nicetext RELEASE 0.4 307 v0.4a 2010/04/04 copyright 2010 308 belonged to nicetext RELEASE 0.41 309 310 v0.41 2010/04/06 more on \ProcessExpanded...; 311 \ProcessFile... gets opt arg 312 2010/04/13 \ProcessFile{<file>}... shows <file> 313 used by blog.sty v0.1, v0.2 314 v0.42 2010/11/09 typo corr. 315 2010/11/10 \IfFDpreviousInputEmpty 316 2010/11/11 \BasicNormalCatcodes from blog.sty, 317 \CopyFile*, \CopyLine; v3. -> v0.3; 318 LPPL v1.3c 319 2010/11/12 \CatCode replaced (implemented in niceverb only) 320 2010/11/13 \CopyFile with \message{.} 321 2010/11/24 reworked doc. of replacement setup; 322 \StartPrependingChain 323 2010/11/25 corr. typo \@backslash...; doc. changes; 324 \CopyLine indeed, not \fdCopyLine 325 2010/11/27 footnote on "parser", other doc. corr.s 326 2011/01/20 corr. "period" AMSTERDAM 327 2011/01/25 updated (C); footnotes to'substring theory'; 328 TODO with \RemoveTilde; some manual line spacings (adding '\ ') 330 -> r0.42 331 v0.43 2011/08/06 doc.: mistake \WriteResult/\ResultFile, 332 2011/08/22 use \acro 333 2011/09/12f. \CorrectedInputLine - reworded for breaking 334 -> r0.44 335 v0.44 2011/10/23 messages from \ResultFile and \CloseResultFile 336 -> r0.46 337 v0.45 2011/10/26 little modification of \CloseResultFile message, 338 "sacrificing" \pagebreak before Sec. 4 -- fine! 339 340 v0.5 2011/11/13 \PrependExpandableAllReplacer*, \MakeSetupCommand; 341 doc.: \center with too long verbatim quote 342 2011/11/19 input check fixed, doc. there adjusted, 343 \ifFinalInputFile, \ProcessFinalFileWith, job '*'* [344] 2011/11/20 \noexpandcsname; "default job" lowercase * [345] 2011/11/21 \ProcessInputWith "less efficient", * [346] \protected@edef, "pseudo-tilde" * [347] -> r0.5 * [348] v0.51 2012/01/20 updated (C); TODO on pseudo-tilde * [349] 2012/03/17 fixed \FDnormalTilde/\FDpseudoTilde * [350] -> r0.53 * [351] v0.6 2012/08/27 using 'catcodes', introducing \CatCode * [352] -> r0.62 * [353] v0.61 2012/11/17. \gdef\do... * [354] \gdef\do... * [355] TODO: cleveref 2010/03/18 * [356]
nobject-rs
rust
Rust
Crate nobject_rs === Overview --- `nobject-rs` is a library for parsing wavefront .obj and .mtl content. To this end, the crate exposes two methos: * `load_obj` * `load_mtl` Both methods take the content of the respective files (.obj and .mtl), parse and then return a result with either some kind of parse error, or a struct containing the data. Note that this crate leaves the responsibility of file I/O to the consuming application. For example, it’s possible to specify file names as attributes in the material, or file names as material libraries in the obj file. This library will NOT attempt to open and parse those files. It is left to the consuming application/library to take the file information from the results of the parse methods, find and open the appropriate files, and then pass on the contents to be parsed. Reference --- Parsing is done based on the specification for Obj’s and Mtl’s found at: * Obj * Mtl Examples --- ### Obj parsing ``` fn main() { let input = " o 1 v -0.5 -0.5 0.5 v -0.5 -0.5 -0.5 v -0.5 0.5 -0.5 v -0.5 0.5 0.5 v 0.5 -0.5 0.5 v 0.5 -0.5 -0.5 v 0.5 0.5 -0.5 v 0.5 0.5 0.5 usemtl Default f 4 3 2 1 f 2 6 5 1 f 3 7 6 2 f 8 7 3 4 f 5 8 4 1 f 6 7 8 5 "; let res = nobject_rs::load_obj(&input).unwrap(); let group = &res.groups["default"]; let face_group = &res.faces["default"]; assert_eq!(res.vertices.len(), 8); assert_eq!(group.material_name, "Default".to_string()); assert_eq!(res.normals.len(), 0); assert_eq!(res.faces.len(), 1); assert_eq!(face_group.len(), 6);; } ``` ### Mtl parsing ``` fn main() { let input = "newmtl frost_wind Ka 0.2 0.2 0.2 Kd 0.6 0.6 0.6 Ks 0.1 0.1 0.1 d 1 Ns 200 illum 2 map_d -mm 0.200 0.800 window.mps"; let res = nobject_rs::load_mtl(&input).unwrap(); assert_eq!(res.len(), 1); } ``` Structs --- BumpMapContains information specific to bump maps. ColorCorrectedMapCommon settings for texture maps which can be color corrected. FaceThe primary purpose is to store the collection of elements (vertices/normals/texture coordinates) that compose a face. This also contains a smoothing group identifier, as specified by the obj file. FaceElementHolds the vertex/texture/normal indicies for a part of a face. GroupDefines the settings that get applied to a group of faces. LineContains the set of elements which compose a line. LineElementContains the indicies for a line element. MaterialDefines a single material. ModelThis holds the end result of parsing an obj file. The default group for all models is “default”. That is to say, if no group is defined in a file, a “default” group will be used. NonColorCorrectedMapCommon settings for texture maps which can not be color corrected. NormalRepresentation of normal data. PointContains a set of id’s for the verticies which compose the point collection. ReflectionMapReflection specific information. TextureRepresentation of texture data. v/w are optional. VertexRepresentation of vertex data. The w component is optional. Enums --- ColorTypeAn enum for possible ways of specifying a material color DisolveTypeEnum for the possible ways to specify the disolve MaterialErrorA wrapper for an underlying error which occurred while parsing the token stream. ModelErrorA wrapper for an underlying error which occurred while parsing the token stream. ObjErrorThe set of errors which might be generated. Functions --- load_mtlTakes the content of an mtl file and parses it. load_objTakes the content of an obj file and parses it. Crate nobject_rs === Overview --- `nobject-rs` is a library for parsing wavefront .obj and .mtl content. To this end, the crate exposes two methos: * `load_obj` * `load_mtl` Both methods take the content of the respective files (.obj and .mtl), parse and then return a result with either some kind of parse error, or a struct containing the data. Note that this crate leaves the responsibility of file I/O to the consuming application. For example, it’s possible to specify file names as attributes in the material, or file names as material libraries in the obj file. This library will NOT attempt to open and parse those files. It is left to the consuming application/library to take the file information from the results of the parse methods, find and open the appropriate files, and then pass on the contents to be parsed. Reference --- Parsing is done based on the specification for Obj’s and Mtl’s found at: * Obj * Mtl Examples --- ### Obj parsing ``` fn main() { let input = " o 1 v -0.5 -0.5 0.5 v -0.5 -0.5 -0.5 v -0.5 0.5 -0.5 v -0.5 0.5 0.5 v 0.5 -0.5 0.5 v 0.5 -0.5 -0.5 v 0.5 0.5 -0.5 v 0.5 0.5 0.5 usemtl Default f 4 3 2 1 f 2 6 5 1 f 3 7 6 2 f 8 7 3 4 f 5 8 4 1 f 6 7 8 5 "; let res = nobject_rs::load_obj(&input).unwrap(); let group = &res.groups["default"]; let face_group = &res.faces["default"]; assert_eq!(res.vertices.len(), 8); assert_eq!(group.material_name, "Default".to_string()); assert_eq!(res.normals.len(), 0); assert_eq!(res.faces.len(), 1); assert_eq!(face_group.len(), 6);; } ``` ### Mtl parsing ``` fn main() { let input = "newmtl frost_wind Ka 0.2 0.2 0.2 Kd 0.6 0.6 0.6 Ks 0.1 0.1 0.1 d 1 Ns 200 illum 2 map_d -mm 0.200 0.800 window.mps"; let res = nobject_rs::load_mtl(&input).unwrap(); assert_eq!(res.len(), 1); } ``` Structs --- BumpMapContains information specific to bump maps. ColorCorrectedMapCommon settings for texture maps which can be color corrected. FaceThe primary purpose is to store the collection of elements (vertices/normals/texture coordinates) that compose a face. This also contains a smoothing group identifier, as specified by the obj file. FaceElementHolds the vertex/texture/normal indicies for a part of a face. GroupDefines the settings that get applied to a group of faces. LineContains the set of elements which compose a line. LineElementContains the indicies for a line element. MaterialDefines a single material. ModelThis holds the end result of parsing an obj file. The default group for all models is “default”. That is to say, if no group is defined in a file, a “default” group will be used. NonColorCorrectedMapCommon settings for texture maps which can not be color corrected. NormalRepresentation of normal data. PointContains a set of id’s for the verticies which compose the point collection. ReflectionMapReflection specific information. TextureRepresentation of texture data. v/w are optional. VertexRepresentation of vertex data. The w component is optional. Enums --- ColorTypeAn enum for possible ways of specifying a material color DisolveTypeEnum for the possible ways to specify the disolve MaterialErrorA wrapper for an underlying error which occurred while parsing the token stream. ModelErrorA wrapper for an underlying error which occurred while parsing the token stream. ObjErrorThe set of errors which might be generated. Functions --- load_mtlTakes the content of an mtl file and parses it. load_objTakes the content of an obj file and parses it. Struct nobject_rs::BumpMap === ``` pub struct BumpMap { pub bump_multiplier: Option<f32>, pub map_settings: Option<NonColorCorrectedMap>, } ``` Contains information specific to bump maps. Fields --- `bump_multiplier: Option<f32>`Specifies a bump multiplier `map_settings: Option<NonColorCorrectedMap>`Additional map settings. Trait Implementations --- source### impl Clone for BumpMap source#### fn clone(&self) -> BumpMap Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for BumpMap source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for BumpMap source#### fn default() -> BumpMap Returns the “default value” for a type. Read more source### impl PartialEq<BumpMap> for BumpMap source#### fn eq(&self, other: &BumpMap) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &BumpMap) -> bool This method tests for `!=`. source### impl StructuralPartialEq for BumpMap Auto Trait Implementations --- ### impl RefUnwindSafe for BumpMap ### impl Send for BumpMap ### impl Sync for BumpMap ### impl Unpin for BumpMap ### impl UnwindSafe for BumpMap Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::ColorCorrectedMap === ``` pub struct ColorCorrectedMap { pub file_name: String, pub blend_u: Option<bool>, pub blend_v: Option<bool>, pub color_correct: Option<bool>, pub clamp: Option<bool>, pub texture_range: Option<(f32, f32)>, pub offset: Option<(f32, Option<f32>, Option<f32>)>, pub scale: Option<(f32, Option<f32>, Option<f32>)>, pub turbulance: Option<(f32, Option<f32>, Option<f32>)>, pub texture_res: Option<i32>, } ``` Common settings for texture maps which can be color corrected. Fields --- `file_name: String`The name of the texture map file. `blend_u: Option<bool>`Enable horizontal texture blending `blend_v: Option<bool>`Enable vertical texture blending `color_correct: Option<bool>`Enable color correction `clamp: Option<bool>`Enables clamping. `texture_range: Option<(f32, f32)>`Specifies the range over which scalar or color texture values may vary. Corresponds to the `-mm` option. `offset: Option<(f32, Option<f32>, Option<f32>)>`Offset the position in the texture map. `scale: Option<(f32, Option<f32>, Option<f32>)>`Scale the size of the texture pattern. `turbulance: Option<(f32, Option<f32>, Option<f32>)>`A turbulance value to apply to the texture. `texture_res: Option<i32>`Allows the specification of a specific resolution to use when an image is used as a texture. Trait Implementations --- source### impl Clone for ColorCorrectedMap source#### fn clone(&self) -> ColorCorrectedMap Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ColorCorrectedMap source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for ColorCorrectedMap source#### fn default() -> ColorCorrectedMap Returns the “default value” for a type. Read more source### impl PartialEq<ColorCorrectedMap> for ColorCorrectedMap source#### fn eq(&self, other: &ColorCorrectedMap) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ColorCorrectedMap) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ColorCorrectedMap Auto Trait Implementations --- ### impl RefUnwindSafe for ColorCorrectedMap ### impl Send for ColorCorrectedMap ### impl Sync for ColorCorrectedMap ### impl Unpin for ColorCorrectedMap ### impl UnwindSafe for ColorCorrectedMap Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Face === ``` pub struct Face { pub elements: Vec<FaceElement>, pub smoothing_group: i32, } ``` The primary purpose is to store the collection of elements (vertices/normals/texture coordinates) that compose a face. This also contains a smoothing group identifier, as specified by the obj file. Fields --- `elements: Vec<FaceElement>`Collection of `FaceElement`. `smoothing_group: i32`The smoothing group identifier. Implementations --- source### impl Face source#### pub fn new(elements: Vec<FaceElement>, smoothing_group: i32) -> Face Trait Implementations --- source### impl Clone for Face source#### fn clone(&self) -> Face Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Face source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Face source#### fn default() -> Face Returns the “default value” for a type. Read more source### impl From<(Vec<FaceElement, Global>, i32)> for Face source#### fn from(original: (Vec<FaceElement>, i32)) -> Face Converts to this type from the input type. source### impl From<Face> for (Vec<FaceElement>, i32) source#### fn from(original: Face) -> Self Converts to this type from the input type. source### impl PartialEq<Face> for Face source#### fn eq(&self, other: &Face) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Face) -> bool This method tests for `!=`. source### impl StructuralPartialEq for Face Auto Trait Implementations --- ### impl RefUnwindSafe for Face ### impl Send for Face ### impl Sync for Face ### impl Unpin for Face ### impl UnwindSafe for Face Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::FaceElement === ``` pub struct FaceElement { pub vertex_index: i32, pub texture_index: Option<i32>, pub normal_index: Option<i32>, } ``` Holds the vertex/texture/normal indicies for a part of a face. Fields --- `vertex_index: i32`Vertex index. Note that these START at 1, NOT 0. `texture_index: Option<i32>`Optional texture index. Note that these START at 1, NOT 0. `normal_index: Option<i32>`Optional normal index. Note that these START at 1, NOT 0. Implementations --- source### impl FaceElement source#### pub fn new(    vertex_index: i32,    texture_index: Option<i32>,    normal_index: Option<i32>) -> FaceElement Trait Implementations --- source### impl Clone for FaceElement source#### fn clone(&self) -> FaceElement Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for FaceElement source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for FaceElement source#### fn default() -> FaceElement Returns the “default value” for a type. Read more source### impl From<(i32, Option<i32>, Option<i32>)> for FaceElement source#### fn from(original: (i32, Option<i32>, Option<i32>)) -> FaceElement Converts to this type from the input type. source### impl From<FaceElement> for (i32, Option<i32>, Option<i32>) source#### fn from(original: FaceElement) -> Self Converts to this type from the input type. source### impl PartialEq<FaceElement> for FaceElement source#### fn eq(&self, other: &FaceElement) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &FaceElement) -> bool This method tests for `!=`. source### impl Copy for FaceElement source### impl StructuralPartialEq for FaceElement Auto Trait Implementations --- ### impl RefUnwindSafe for FaceElement ### impl Send for FaceElement ### impl Sync for FaceElement ### impl Unpin for FaceElement ### impl UnwindSafe for FaceElement Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Group === ``` pub struct Group { pub material_name: String, pub bevel: bool, pub c_interp: bool, pub d_interp: bool, pub lod: u8, pub texture_map: Option<String>, } ``` Defines the settings that get applied to a group of faces. Fields --- `material_name: String`The name of the material to apply to the group. `bevel: bool`Bevel interpolation setting. `c_interp: bool`Color interpolation setting. `d_interp: bool`Disolve interpolation setting. `lod: u8`Level of detail setting. `texture_map: Option<String>`The name of the texture map file. Implementations --- source### impl Group source#### pub fn new(    material_name: String,    bevel: bool,    c_interp: bool,    d_interp: bool,    lod: u8,    texture_map: Option<String>) -> Group Trait Implementations --- source### impl Clone for Group source#### fn clone(&self) -> Group Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Group source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Group source#### fn default() -> Group Returns the “default value” for a type. Read more source### impl From<(String, bool, bool, bool, u8, Option<String>)> for Group source#### fn from(original: (String, bool, bool, bool, u8, Option<String>)) -> Group Converts to this type from the input type. source### impl From<Group> for (String, bool, bool, bool, u8, Option<String>) source#### fn from(original: Group) -> Self Converts to this type from the input type. source### impl PartialEq<Group> for Group source#### fn eq(&self, other: &Group) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Group) -> bool This method tests for `!=`. source### impl StructuralPartialEq for Group Auto Trait Implementations --- ### impl RefUnwindSafe for Group ### impl Send for Group ### impl Sync for Group ### impl Unpin for Group ### impl UnwindSafe for Group Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Line === ``` pub struct Line { pub elements: Vec<LineElement>, } ``` Contains the set of elements which compose a line. Fields --- `elements: Vec<LineElement>`Set of line elements. Implementations --- source### impl Line source#### pub fn new(elements: Vec<LineElement>) -> Line Trait Implementations --- source### impl Clone for Line source#### fn clone(&self) -> Line Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Line source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Line source#### fn default() -> Line Returns the “default value” for a type. Read more source### impl From<Line> for Vec<LineElementsource#### fn from(original: Line) -> Self Converts to this type from the input type. source### impl From<Vec<LineElement, Global>> for Line source#### fn from(original: Vec<LineElement>) -> Line Converts to this type from the input type. source### impl PartialEq<Line> for Line source#### fn eq(&self, other: &Line) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Line) -> bool This method tests for `!=`. source### impl StructuralPartialEq for Line Auto Trait Implementations --- ### impl RefUnwindSafe for Line ### impl Send for Line ### impl Sync for Line ### impl Unpin for Line ### impl UnwindSafe for Line Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::LineElement === ``` pub struct LineElement { pub vertex_index: i32, pub texture_index: Option<i32>, } ``` Contains the indicies for a line element. Fields --- `vertex_index: i32`Vertex index. Note that these START at 1, NOT 0. `texture_index: Option<i32>`Optional texture index. Note that these START at 1, NOT 0. Implementations --- source### impl LineElement source#### pub fn new(vertex_index: i32, texture_index: Option<i32>) -> LineElement Trait Implementations --- source### impl Clone for LineElement source#### fn clone(&self) -> LineElement Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for LineElement source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for LineElement source#### fn default() -> LineElement Returns the “default value” for a type. Read more source### impl From<(i32, Option<i32>)> for LineElement source#### fn from(original: (i32, Option<i32>)) -> LineElement Converts to this type from the input type. source### impl From<LineElement> for (i32, Option<i32>) source#### fn from(original: LineElement) -> Self Converts to this type from the input type. source### impl PartialEq<LineElement> for LineElement source#### fn eq(&self, other: &LineElement) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &LineElement) -> bool This method tests for `!=`. source### impl Copy for LineElement source### impl StructuralPartialEq for LineElement Auto Trait Implementations --- ### impl RefUnwindSafe for LineElement ### impl Send for LineElement ### impl Sync for LineElement ### impl Unpin for LineElement ### impl UnwindSafe for LineElement Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Model === ``` pub struct Model { pub vertices: Vec<Vertex>, pub normals: Vec<Normal>, pub textures: Vec<Texture>, pub faces: HashMap<String, Vec<Face>>, pub lines: HashMap<String, Vec<Line>>, pub points: HashMap<String, Vec<Point>>, pub groups: HashMap<String, Group>, pub material_libs: Vec<String>, pub texture_libs: Vec<String>, pub shadow_obj: Option<String>, pub trace_obj: Option<String>, /* private fields */ } ``` This holds the end result of parsing an obj file. The default group for all models is “default”. That is to say, if no group is defined in a file, a “default” group will be used. Everything will fall under the “default” group until another group is specified. Fields --- `vertices: Vec<Vertex>`Collection of vertex data `normals: Vec<Normal>``textures: Vec<Texture>`Collection of texture coordinate data `faces: HashMap<String, Vec<Face>>`A map of group name to a collection of faces which belong to the group Everything will fall under the “default” group until another group is specified. `lines: HashMap<String, Vec<Line>>`A map of group name to a collection of lines. Everything will fall under the “default” group until another group is specified. `points: HashMap<String, Vec<Point>>`A map of group name to a collection of points. Everything will fall under the “default” group until another group is specified. `groups: HashMap<String, Group>`A map of group name to the groups specific data. Everything will fall under the “default” group until another group is specified. `material_libs: Vec<String>`The material library files to use with this obj. `texture_libs: Vec<String>`The texture library files to use with this obj. `shadow_obj: Option<String>`The file name for the shadow object `trace_obj: Option<String>`The file name for the ray trace object Trait Implementations --- source### impl Clone for Model source#### fn clone(&self) -> Model Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Model source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Model source#### fn default() -> Self Returns the “default value” for a type. Read more source### impl From<(Vec<Vertex, Global>, Vec<Normal, Global>, Vec<Texture, Global>, HashMap<String, Vec<Face, Global>, RandomState>, HashMap<String, Vec<Line, Global>, RandomState>, HashMap<String, Vec<Point, Global>, RandomState>, HashMap<String, Group, RandomState>, Vec<String, Global>, Vec<String, Global>, Option<String>, Option<String>, Vec<String, Global>, i32)> for Model source#### fn from(    original: (Vec<Vertex>, Vec<Normal>, Vec<Texture>, HashMap<String, Vec<Face>>, HashMap<String, Vec<Line>>, HashMap<String, Vec<Point>>, HashMap<String, Group>, Vec<String>, Vec<String>, Option<String>, Option<String>, Vec<String>, i32)) -> Model Converts to this type from the input type. source### impl From<Model> for (Vec<Vertex>, Vec<Normal>, Vec<Texture>, HashMap<String, Vec<Face>>, HashMap<String, Vec<Line>>, HashMap<String, Vec<Point>>, HashMap<String, Group>, Vec<String>, Vec<String>, Option<String>, Option<String>, Vec<String>, i32) source#### fn from(original: Model) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for Model ### impl Send for Model ### impl Sync for Model ### impl Unpin for Model ### impl UnwindSafe for Model Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::NonColorCorrectedMap === ``` pub struct NonColorCorrectedMap { pub file_name: String, pub blend_u: Option<bool>, pub blend_v: Option<bool>, pub clamp: Option<bool>, pub imf_chan: Option<String>, pub texture_range: Option<(f32, f32)>, pub offset: Option<(f32, Option<f32>, Option<f32>)>, pub scale: Option<(f32, Option<f32>, Option<f32>)>, pub turbulance: Option<(f32, Option<f32>, Option<f32>)>, pub texture_res: Option<i32>, } ``` Common settings for texture maps which can not be color corrected. Fields --- `file_name: String`The name of the texture map file. `blend_u: Option<bool>`Enable horizontal texture blending `blend_v: Option<bool>`Enable vertical texture blending `clamp: Option<bool>`Enables clamping. `imf_chan: Option<String>`Specifies the channel used to create a scalar or bump texture. `texture_range: Option<(f32, f32)>`Specifies the range over which scalar or color texture values may vary. Corresponds to the `-mm` option. `offset: Option<(f32, Option<f32>, Option<f32>)>`Offset the position in the texture map. `scale: Option<(f32, Option<f32>, Option<f32>)>`Scale the size of the texture pattern. `turbulance: Option<(f32, Option<f32>, Option<f32>)>`A turbulance value to apply to the texture. `texture_res: Option<i32>`Allows the specification of a specific resolution to use when an image is used as a texture. Trait Implementations --- source### impl Clone for NonColorCorrectedMap source#### fn clone(&self) -> NonColorCorrectedMap Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for NonColorCorrectedMap source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for NonColorCorrectedMap source#### fn default() -> NonColorCorrectedMap Returns the “default value” for a type. Read more source### impl PartialEq<NonColorCorrectedMap> for NonColorCorrectedMap source#### fn eq(&self, other: &NonColorCorrectedMap) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &NonColorCorrectedMap) -> bool This method tests for `!=`. source### impl StructuralPartialEq for NonColorCorrectedMap Auto Trait Implementations --- ### impl RefUnwindSafe for NonColorCorrectedMap ### impl Send for NonColorCorrectedMap ### impl Sync for NonColorCorrectedMap ### impl Unpin for NonColorCorrectedMap ### impl UnwindSafe for NonColorCorrectedMap Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Normal === ``` pub struct Normal { pub x: f32, pub y: f32, pub z: f32, } ``` Representation of normal data. Fields --- `x: f32`X coordinate `y: f32`Y coordinate `z: f32`Z coordinate Implementations --- source### impl Normal source#### pub fn new(x: f32, y: f32, z: f32) -> Normal Trait Implementations --- source### impl Clone for Normal source#### fn clone(&self) -> Normal Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Normal source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Normal source#### fn default() -> Normal Returns the “default value” for a type. Read more source### impl From<(f32, f32, f32)> for Normal source#### fn from(original: (f32, f32, f32)) -> Normal Converts to this type from the input type. source### impl From<Normal> for (f32, f32, f32) source#### fn from(original: Normal) -> Self Converts to this type from the input type. source### impl PartialEq<Normal> for Normal source#### fn eq(&self, other: &Normal) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Normal) -> bool This method tests for `!=`. source### impl Copy for Normal source### impl StructuralPartialEq for Normal Auto Trait Implementations --- ### impl RefUnwindSafe for Normal ### impl Send for Normal ### impl Sync for Normal ### impl Unpin for Normal ### impl UnwindSafe for Normal Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Point === ``` pub struct Point { pub elements: Vec<i32>, } ``` Contains a set of id’s for the verticies which compose the point collection. Fields --- `elements: Vec<i32>`Set of vertex indices. Note that these START at 1, NOT 0. Implementations --- source### impl Point source#### pub fn new(elements: Vec<i32>) -> Point Trait Implementations --- source### impl Clone for Point source#### fn clone(&self) -> Point Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Point source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Point source#### fn default() -> Point Returns the “default value” for a type. Read more source### impl From<Point> for Vec<i32source#### fn from(original: Point) -> Self Converts to this type from the input type. source### impl From<Vec<i32, Global>> for Point source#### fn from(original: Vec<i32>) -> Point Converts to this type from the input type. source### impl PartialEq<Point> for Point source#### fn eq(&self, other: &Point) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Point) -> bool This method tests for `!=`. source### impl StructuralPartialEq for Point Auto Trait Implementations --- ### impl RefUnwindSafe for Point ### impl Send for Point ### impl Sync for Point ### impl Unpin for Point ### impl UnwindSafe for Point Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::ReflectionMap === ``` pub struct ReflectionMap { pub reflection_type: String, pub map_settings: Option<ColorCorrectedMap>, } ``` Reflection specific information. Fields --- `reflection_type: String`This contains the name of the type of reflection to use. Corresponds to `-type` in the specification. `map_settings: Option<ColorCorrectedMap>`Additional map settings. Trait Implementations --- source### impl Clone for ReflectionMap source#### fn clone(&self) -> ReflectionMap Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ReflectionMap source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for ReflectionMap source#### fn default() -> ReflectionMap Returns the “default value” for a type. Read more source### impl PartialEq<ReflectionMap> for ReflectionMap source#### fn eq(&self, other: &ReflectionMap) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ReflectionMap) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ReflectionMap Auto Trait Implementations --- ### impl RefUnwindSafe for ReflectionMap ### impl Send for ReflectionMap ### impl Sync for ReflectionMap ### impl Unpin for ReflectionMap ### impl UnwindSafe for ReflectionMap Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Texture === ``` pub struct Texture { pub u: f32, pub v: Option<f32>, pub w: Option<f32>, } ``` Representation of texture data. v/w are optional. Fields --- `u: f32`U coordinate `v: Option<f32>`Optional V coordinate `w: Option<f32>`Optional W coordinate Implementations --- source### impl Texture source#### pub fn new(u: f32, v: Option<f32>, w: Option<f32>) -> Texture Trait Implementations --- source### impl Clone for Texture source#### fn clone(&self) -> Texture Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Texture source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Texture source#### fn default() -> Texture Returns the “default value” for a type. Read more source### impl From<(f32, Option<f32>, Option<f32>)> for Texture source#### fn from(original: (f32, Option<f32>, Option<f32>)) -> Texture Converts to this type from the input type. source### impl From<Texture> for (f32, Option<f32>, Option<f32>) source#### fn from(original: Texture) -> Self Converts to this type from the input type. source### impl PartialEq<Texture> for Texture source#### fn eq(&self, other: &Texture) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Texture) -> bool This method tests for `!=`. source### impl Copy for Texture source### impl StructuralPartialEq for Texture Auto Trait Implementations --- ### impl RefUnwindSafe for Texture ### impl Send for Texture ### impl Sync for Texture ### impl Unpin for Texture ### impl UnwindSafe for Texture Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Struct nobject_rs::Vertex === ``` pub struct Vertex { pub x: f32, pub y: f32, pub z: f32, pub w: Option<f32>, } ``` Representation of vertex data. The w component is optional. Fields --- `x: f32`X coordinate `y: f32`Y coordinate `z: f32`Z coordinate `w: Option<f32>`Optional W coordinate Implementations --- source### impl Vertex source#### pub fn new(x: f32, y: f32, z: f32, w: Option<f32>) -> Vertex Trait Implementations --- source### impl Clone for Vertex source#### fn clone(&self) -> Vertex Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for Vertex source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Default for Vertex source#### fn default() -> Vertex Returns the “default value” for a type. Read more source### impl From<(f32, f32, f32, Option<f32>)> for Vertex source#### fn from(original: (f32, f32, f32, Option<f32>)) -> Vertex Converts to this type from the input type. source### impl From<Vertex> for (f32, f32, f32, Option<f32>) source#### fn from(original: Vertex) -> Self Converts to this type from the input type. source### impl PartialEq<Vertex> for Vertex source#### fn eq(&self, other: &Vertex) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &Vertex) -> bool This method tests for `!=`. source### impl Copy for Vertex source### impl StructuralPartialEq for Vertex Auto Trait Implementations --- ### impl RefUnwindSafe for Vertex ### impl Send for Vertex ### impl Sync for Vertex ### impl Unpin for Vertex ### impl UnwindSafe for Vertex Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum nobject_rs::ColorType === ``` pub enum ColorType { Rgb(f32, f32, f32), Spectral(String, f32), CieXyz(f32, f32, f32), } ``` An enum for possible ways of specifying a material color Variants --- ### `Rgb(f32, f32, f32)` RGB ### `Spectral(String, f32)` Reflectivity using a spectral curve. This is specified as a filename and a multiplier (defaults to 1.0) ### `CieXyz(f32, f32, f32)` CIEXYZ color space Trait Implementations --- source### impl Clone for ColorType source#### fn clone(&self) -> ColorType Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for ColorType source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl PartialEq<ColorType> for ColorType source#### fn eq(&self, other: &ColorType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &ColorType) -> bool This method tests for `!=`. source### impl StructuralPartialEq for ColorType Auto Trait Implementations --- ### impl RefUnwindSafe for ColorType ### impl Send for ColorType ### impl Sync for ColorType ### impl Unpin for ColorType ### impl UnwindSafe for ColorType Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum nobject_rs::DisolveType === ``` pub enum DisolveType { Alpha(f32), Halo(f32), } ``` Enum for the possible ways to specify the disolve Variants --- ### `Alpha(f32)` The amount this material dissolves into the background. 1.0 is fully opaque ### `Halo(f32)` Specifies that the disolve is based on the orientation of the viewer. The value is the minimum to apply to a material. Trait Implementations --- source### impl Clone for DisolveType source#### fn clone(&self) -> DisolveType Returns a copy of the value. Read more 1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more source### impl Debug for DisolveType source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl PartialEq<DisolveType> for DisolveType source#### fn eq(&self, other: &DisolveType) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more source#### fn ne(&self, other: &DisolveType) -> bool This method tests for `!=`. source### impl Copy for DisolveType source### impl StructuralPartialEq for DisolveType Auto Trait Implementations --- ### impl RefUnwindSafe for DisolveType ### impl Send for DisolveType ### impl Sync for DisolveType ### impl Unpin for DisolveType ### impl UnwindSafe for DisolveType Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToOwned for T where    T: Clone, #### type Owned = T The resulting type after obtaining ownership. source#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more source#### fn clone_into(&self, target: &mutT) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum nobject_rs::MaterialError === ``` pub enum MaterialError { Parse(String), NewMaterial, } ``` A wrapper for an underlying error which occurred while parsing the token stream. Variants --- ### `Parse(String)` ### `NewMaterial` The specification generally requires a newmtl statement to come before all other statements. If this error occurs it’s because we also expect a newmtl statement first. Trait Implementations --- source### impl Debug for MaterialError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for MaterialError source#### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for MaterialError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source#### fn provide(&'a self, req: &mut Demand<'a>) 🔬 This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. Read more source### impl From<MaterialError> for ObjError source#### fn from(source: MaterialError) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for MaterialError ### impl Send for MaterialError ### impl Sync for MaterialError ### impl Unpin for MaterialError ### impl UnwindSafe for MaterialError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum nobject_rs::ModelError === ``` pub enum ModelError { Parse(String), } ``` A wrapper for an underlying error which occurred while parsing the token stream. Variants --- ### `Parse(String)` Trait Implementations --- source### impl Debug for ModelError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for ModelError source#### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for ModelError 1.30.0 · source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source#### fn provide(&'a self, req: &mut Demand<'a>) 🔬 This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. Read more source### impl From<ModelError> for ObjError source#### fn from(source: ModelError) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for ModelError ### impl Send for ModelError ### impl Sync for ModelError ### impl Unpin for ModelError ### impl UnwindSafe for ModelError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Enum nobject_rs::ObjError === ``` pub enum ObjError { Tokenize(TokenizeError), ModelParse(ModelError), MaterialParse(MaterialError), UnexpectedToken(Token), InvalidOnOffValue(String), } ``` The set of errors which might be generated. Variants --- ### `Tokenize(TokenizeError)` A tokenization error, typically something in the file is not as the parser expects it. ### `ModelParse(ModelError)` The result of an error constructing a `Model` from the token stream. ### `MaterialParse(MaterialError)` The result of an error constructing a `Material` collection from the token stream. ### `UnexpectedToken(Token)` An unexpected token was encountered in the token stream. ### `InvalidOnOffValue(String)` The specification for obj/mtl files has some settings either being “on” or “off”. If there is an issue parsing those values, this error will occur. Trait Implementations --- source### impl Debug for ObjError source#### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Display for ObjError source#### fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read more source### impl Error for ObjError source#### fn source(&self) -> Option<&(dyn Error + 'static)The lower-level source of this error, if any. Read more source#### fn backtrace(&self) -> Option<&Backtrace🔬 This is a nightly-only experimental API. (`backtrace`)Returns a stack backtrace, if available, of where this error occurred. Read more 1.0.0 · source#### fn description(&self) -> &str 👎 Deprecated since 1.42.0: use the Display impl or to_string() Read more1.0.0 · source#### fn cause(&self) -> Option<&dyn Error👎 Deprecated since 1.33.0: replaced by Error::source, which can support downcasting source#### fn provide(&'a self, req: &mut Demand<'a>) 🔬 This is a nightly-only experimental API. (`error_generic_member_access`)Provides type based access to context intended for error reports. Read more source### impl From<MaterialError> for ObjError source#### fn from(source: MaterialError) -> Self Converts to this type from the input type. source### impl From<ModelError> for ObjError source#### fn from(source: ModelError) -> Self Converts to this type from the input type. Auto Trait Implementations --- ### impl RefUnwindSafe for ObjError ### impl Send for ObjError ### impl Sync for ObjError ### impl Unpin for ObjError ### impl UnwindSafe for ObjError Blanket Implementations --- source### impl<T> Any for T where    T: 'static + ?Sized, source#### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more source### impl<T> Borrow<T> for T where    T: ?Sized, const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more source### impl<T> BorrowMut<T> for T where    T: ?Sized, const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into `T` using `Into<T>`. Read more ### impl<T> Conv for T #### fn conv<T>(self) -> T where    Self: Into<T>, Converts `self` into a target type. Read more ### impl<T> FmtForward for T #### fn fmt_binary(self) -> FmtBinary<Self> where    Self: Binary, Causes `self` to use its `Binary` implementation when `Debug`-formatted. #### fn fmt_display(self) -> FmtDisplay<Self> where    Self: Display, Causes `self` to use its `Display` implementation when `Debug`-formatted. Read more #### fn fmt_lower_exp(self) -> FmtLowerExp<Self> where    Self: LowerExp, Causes `self` to use its `LowerExp` implementation when `Debug`-formatted. Read more #### fn fmt_lower_hex(self) -> FmtLowerHex<Self> where    Self: LowerHex, Causes `self` to use its `LowerHex` implementation when `Debug`-formatted. Read more #### fn fmt_octal(self) -> FmtOctal<Self> where    Self: Octal, Causes `self` to use its `Octal` implementation when `Debug`-formatted. #### fn fmt_pointer(self) -> FmtPointer<Self> where    Self: Pointer, Causes `self` to use its `Pointer` implementation when `Debug`-formatted. Read more #### fn fmt_upper_exp(self) -> FmtUpperExp<Self> where    Self: UpperExp, Causes `self` to use its `UpperExp` implementation when `Debug`-formatted. Read more #### fn fmt_upper_hex(self) -> FmtUpperHex<Self> where    Self: UpperHex, Causes `self` to use its `UpperHex` implementation when `Debug`-formatted. Read more source### impl<T> From<T> for T const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. source### impl<T, U> Into<U> for T where    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> Pipe for T where    T: ?Sized, #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes by value. This is generally the method you want to use. Read more #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Mutably borrows `self` and passes that borrow into the pipe function. Read more #### fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'aB) -> R) -> R where    Self: Borrow<B>,    B: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.borrow()` into the pipe function. Read more #### fn pipe_borrow_mut<'a, B, R>(    &'a mut self,    func: impl FnOnce(&'a mutB) -> R) -> R where    Self: BorrowMut<B>,    B: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.borrow_mut()` into the pipe function. Read more #### fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'aU) -> R) -> R where    Self: AsRef<U>,    U: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.as_ref()` into the pipe function. #### fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mutU) -> R) -> R where    Self: AsMut<U>,    U: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.as_mut()` into the pipe function. Read more #### fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Deref<Target = T>,    T: 'a + ?Sized,    R: 'a, Borrows `self`, then passes `self.deref()` into the pipe function. #### fn pipe_deref_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: DerefMut<Target = T> + Deref,    T: 'a + ?Sized,    R: 'a, Mutably borrows `self`, then passes `self.deref_mut()` into the pipe function. Read more ### impl<T> Pipe for T #### fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R Pipes a value into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> PipeAsRef for T #### fn pipe_as_ref<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: AsRef<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_as_mut<'a, T, R>(&'a mut self, func: impl FnOnce(&'a mutT) -> R) -> R where    Self: AsMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeBorrow for T #### fn pipe_borrow<'a, T, R>(&'a self, func: impl FnOnce(&'aT) -> R) -> R where    Self: Borrow<T>,    T: 'a,    R: 'a, Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more #### fn pipe_borrow_mut<'a, T, R>(    &'a mut self,    func: impl FnOnce(&'a mutT) -> R) -> R where    Self: BorrowMut<T>,    T: 'a,    R: 'a, Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeDeref for T #### fn pipe_deref<'a, R>(&'a self, func: impl FnOnce(&'a Self::Target) -> R) -> R where    Self: Deref,    R: 'a, Pipes a dereference into a function that cannot normally be called in suffix position. Read more #### fn pipe_deref_mut<'a, R>(    &'a mut self,    func: impl FnOnce(&'a mut Self::Target) -> R) -> R where    Self: DerefMut,    R: 'a, Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more ### impl<T> PipeRef for T #### fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'aSelf) -> R) -> R where    R: 'a, Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more #### fn pipe_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mutSelf) -> R) -> R where    R: 'a, Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more ### impl<T> Tap for T #### fn tap(self, func: impl FnOnce(&Self)) -> Self Immutable access to a value. Read more #### fn tap_mut(self, func: impl FnOnce(&mutSelf)) -> Self Mutable access to a value. Read more #### fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Immutable access to the `Borrow<B>` of a value. Read more #### fn tap_borrow_mut<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Mutable access to the `BorrowMut<B>` of a value. Read more #### fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Immutable access to the `AsRef<R>` view of a value. Read more #### fn tap_ref_mut<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Mutable access to the `AsMut<R>` view of a value. Read more #### fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Immutable access to the `Deref::Target` of a value. Read more #### fn tap_deref_mut<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Mutable access to the `Deref::Target` of a value. Read more #### fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self Calls `.tap()` only in debug builds, and is erased in release builds. #### fn tap_mut_dbg(self, func: impl FnOnce(&mutSelf)) -> Self Calls `.tap_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self where    Self: Borrow<B>,    B: ?Sized, Calls `.tap_borrow()` only in debug builds, and is erased in release builds. Read more #### fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mutB)) -> Self where    Self: BorrowMut<B>,    B: ?Sized, Calls `.tap_borrow_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self where    Self: AsRef<R>,    R: ?Sized, Calls `.tap_ref()` only in debug builds, and is erased in release builds. Read more #### fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mutR)) -> Self where    Self: AsMut<R>,    R: ?Sized, Calls `.tap_ref_mut()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self where    Self: Deref<Target = T>,    T: ?Sized, Calls `.tap_deref()` only in debug builds, and is erased in release builds. Read more #### fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mutT)) -> Self where    Self: DerefMut<Target = T> + Deref,    T: ?Sized, Calls `.tap_deref_mut()` only in debug builds, and is erased in release builds. Read more ### impl<T> Tap for T #### fn tap<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Provides immutable access for inspection. Read more #### fn tap_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&Self) -> R, Calls `tap` in debug builds, and does nothing in release builds. #### fn tap_mut<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Provides mutable access for modification. Read more #### fn tap_mut_dbg<F, R>(self, func: F) -> Self where    F: FnOnce(&mutSelf) -> R, Calls `tap_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapAsRef<U> for T where    U: ?Sized, #### fn tap_ref<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Provides immutable access to the reference for inspection. #### fn tap_ref_dbg<F, R>(self, func: F) -> Self where    Self: AsRef<T>,    F: FnOnce(&T) -> R, Calls `tap_ref` in debug builds, and does nothing in release builds. #### fn tap_ref_mut<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the reference for modification. #### fn tap_ref_mut_dbg<F, R>(self, func: F) -> Self where    Self: AsMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_ref_mut` in debug builds, and does nothing in release builds. ### impl<T, U> TapBorrow<U> for T where    U: ?Sized, #### fn tap_borrow<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Provides immutable access to the borrow for inspection. Read more #### fn tap_borrow_dbg<F, R>(self, func: F) -> Self where    Self: Borrow<T>,    F: FnOnce(&T) -> R, Calls `tap_borrow` in debug builds, and does nothing in release builds. #### fn tap_borrow_mut<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Provides mutable access to the borrow for modification. #### fn tap_borrow_mut_dbg<F, R>(self, func: F) -> Self where    Self: BorrowMut<T>,    F: FnOnce(&mutT) -> R, Calls `tap_borrow_mut` in debug builds, and does nothing in release builds. Read more ### impl<T> TapDeref for T #### fn tap_deref<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Immutably dereferences `self` for inspection. #### fn tap_deref_dbg<F, R>(self, func: F) -> Self where    Self: Deref,    F: FnOnce(&Self::Target) -> R, Calls `tap_deref` in debug builds, and does nothing in release builds. #### fn tap_deref_mut<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Mutably dereferences `self` for modification. #### fn tap_deref_mut_dbg<F, R>(self, func: F) -> Self where    Self: DerefMut,    F: FnOnce(&mut Self::Target) -> R, Calls `tap_deref_mut` in debug builds, and does nothing in release builds. Read more source### impl<T> ToString for T where    T: Display + ?Sized, source#### default fn to_string(&self) -> String Converts the given value to a `String`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into `T` using `TryInto<T>`. Read more ### impl<T> TryConv for T #### fn try_conv<T>(self) -> Result<T, Self::Error> where    Self: TryInto<T>, Attempts to convert `self` into a target type. Read more source### impl<T, U> TryFrom<U> for T where    U: Into<T>, #### type Error = Infallible The type returned in the event of a conversion error. const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion. source### impl<T, U> TryInto<U> for T where    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error. const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Function nobject_rs::load_mtl === ``` pub fn load_mtl(input: &str) -> Result<Vec<Material>, ObjError> ``` Takes the content of an mtl file and parses it. Arguments --- * input - The content of the mtl file as a string Returns --- Returns a `Result` of either ObjError on parse errors or a collection of `Material`. Function nobject_rs::load_obj === ``` pub fn load_obj(input: &str) -> Result<Model, ObjError> ``` Takes the content of an obj file and parses it. Arguments --- * input - The content of the obj file as a string Returns --- Returns a `Result` of either ObjError on parse errors or a constructed `Model`.
github.com/kubernetes/kops
go
Go
README [¶](#section-readme) --- ![kops logo](https://github.com/kubernetes/kops/raw/v1.11.0/docs/img/logo.jpg) ### kops - Kubernetes Operations [![Build Status](https://travis-ci.org/kubernetes/kops.svg?branch=master)](https://travis-ci.org/kubernetes/kops) [![Go Report Card](https://goreportcard.com/badge/k8s.io/kops)](https://goreportcard.com/report/k8s.io/kops) [![GoDoc Widget](https://godoc.org/k8s.io/kops?status.svg)](https://godoc.org/k8s.io/kops) The easiest way to get a production grade Kubernetes cluster up and running. #### What is kops? We like to think of it as `kubectl` for clusters. `kops` helps you create, destroy, upgrade and maintain production-grade, highly available, Kubernetes clusters from the command line. AWS (Amazon Web Services) is currently officially supported, with GCE in beta support , and VMware vSphere in alpha, and other platforms planned. #### Can I see it in action? [![](https://asciinema.org/a/97298.png)](https://asciinema.org/a/97298) #### Launching a Kubernetes cluster hosted on AWS, GCE or DigitalOcean To replicate the above demo, check out our [tutorial](https://github.com/kubernetes/kops/blob/v1.11.0/docs/aws.md) for launching a Kubernetes cluster hosted on AWS. To install a Kubernetes cluster on GCE please follow this [guide](https://github.com/kubernetes/kops/blob/v1.11.0/docs/tutorial/gce.md). To install a Kubernetes cluster on DigitalOcean, follow this [guide](https://github.com/kubernetes/kops/blob/v1.11.0/docs/tutorial/digitalocean.md). #### Features * Automates the provisioning of Kubernetes clusters in [AWS](https://github.com/kubernetes/kops/blob/v1.11.0/docs/aws.md) and [GCE](https://github.com/kubernetes/kops/blob/v1.11.0/docs/tutorial/gce.md) * Deploys Highly Available (HA) Kubernetes Masters * Built on a state-sync model for **dry-runs** and automatic **idempotency** * Ability to generate [Terraform](https://github.com/kubernetes/kops/blob/v1.11.0/docs/terraform.md) * Supports custom Kubernetes [add-ons](https://github.com/kubernetes/kops/blob/v1.11.0/docs/addons.md) * Command line [autocompletion](https://github.com/kubernetes/kops/blob/v1.11.0/docs/cli/kops_completion.md) * YAML Manifest Based API [Configuration](https://github.com/kubernetes/kops/blob/v1.11.0/docs/manifests_and_customizing_via_api.md) * [Templating](https://github.com/kubernetes/kops/blob/v1.11.0/docs/cluster_template.md) and dry-run modes for creating Manifests * Choose from eight different CNI [Networking](https://github.com/kubernetes/kops/blob/v1.11.0/docs/networking.md) providers out-of-the-box * Supports upgrading from [kube-up](https://github.com/kubernetes/kops/blob/v1.11.0/docs/upgrade_from_kubeup.md) * Capability to add containers, as hooks, and files to nodes via a [cluster manifest](https://github.com/kubernetes/kops/blob/v1.11.0/docs/cluster_spec.md) #### Documentation Documentation is in the `/docs` directory, [and the index is here.](https://github.com/kubernetes/kops/blob/v1.11.0/docs/README.md) #### Kubernetes Release Compatibility ##### Kubernetes Version Support kops is intended to be backward compatible. It is always recommended to use the latest version of kops with whatever version of Kubernetes you are using. Always use the latest version of kops. One exception, in regards to compatibility, kops supports the equivalent Kubernetes minor release number. A minor version is the second digit in the release number. kops version 1.8.0 has a minor version of 8. The numbering follows the semantic versioning specification, MAJOR.MINOR.PATCH. For example, kops 1.8.0 does not support Kubernetes 1.9.2, but kops 1.9.0 supports Kubernetes 1.9.2 and previous Kubernetes versions. Only when kops minor version matches, the Kubernetes minor version does kops officially support the Kubernetes release. kops does not stop a user from installing mismatching versions of K8s, but Kubernetes releases always require kops to install specific versions of components like docker, that tested against the particular Kubernetes version. ###### Compatibility Matrix | kops version | k8s 1.5.x | k8s 1.6.x | k8s 1.7.x | k8s 1.8.x | k8s 1.9.x | k8s 1.10.x | | --- | --- | --- | --- | --- | --- | --- | | 1.10.x | Y | Y | Y | Y | Y | Y | | 1.9.x | Y | Y | Y | Y | Y | N | | 1.8.x | Y | Y | Y | Y | N | N | | 1.7.x | Y | Y | Y | N | N | N | | 1.6.x | Y | Y | N | N | N | N | Use the latest version of kops for all releases of Kubernetes, with the caveat that higher versions of Kubernetes are not *officially* supported by kops. ##### kops Release Schedule This project does not follow the Kubernetes release schedule. `kops` aims to provide a reliable installation experience for kubernetes, and typically releases about a month after the corresponding Kubernetes release. This time allows for the Kubernetes project to resolve any issues introduced by the new version and ensures that we can support the latest features. kops will release alpha and beta pre-releases for people that are eager to try the latest Kubernetes release. Please only use pre-GA kops releases in environments that can tolerate the quirks of new releases, and please do report any issues encountered. #### Installing ##### Prerequisite `kubectl` is required, see [here](http://kubernetes.io/docs/user-guide/prereqs/). ##### OSX From Homebrew ``` brew update && brew install kops ``` The `kops` binary is also available via our [releases](https://github.com/kubernetes/kops/releases/latest). ##### Linux ``` curl -LO https://github.com/kubernetes/kops/releases/download/$(curl -s https://api.github.com/repos/kubernetes/kops/releases/latest | grep tag_name | cut -d '"' -f 4)/kops-linux-amd64 chmod +x kops-linux-amd64 sudo mv kops-linux-amd64 /usr/local/bin/kops ``` #### Release History See the [releases](https://github.com/kubernetes/kops/releases) for more information on changes between releases. #### Getting Involved and Contributing Are you interested in contributing to kops? We, the maintainers and community, would love your suggestions, contributions, and help! We have a quick-start guide on [adding a feature](https://github.com/kubernetes/kops/blob/v1.11.0/docs/development/adding_a_feature.md). Also, the maintainers can be contacted at any time to learn more about how to get involved. In the interest of getting more new folks involved with kops, we are starting to tag issues with `good-starter-issue`. These are typically issues that have smaller scope but are good ways to start to get acquainted with the codebase. We also encourage ALL active community participants to act as if they are maintainers, even if you don't have "official" write permissions. This is a community effort, we are here to serve the Kubernetes community. If you have an active interest and you want to get involved, you have real power! Don't assume that the only people who can get things done around here are the "maintainers". We also would love to add more "official" maintainers, so show us what you can do! What this means: **Issues** * Help read and triage issues, assist when possible. * Point out issues that are duplicates, out of date, etc. + Even if you don't have tagging permissions, make a note and tag maintainers (`/close`,`/dupe #127`). **Pull Requests** * Read and review the code. Leave comments, questions, and critiques (`/lgtm` ). * Download, compile, and run the code and make sure the tests pass (make test). + Also verify that the new feature seems sane, follows best architectural patterns, and includes tests. This repository uses the Kubernetes bots. See a full list of the commands [here](https://github.com/kubernetes/test-infra/blob/master/commands.md). #### Office Hours Kops maintainers set aside one hour every other week for **public** office hours. This time is used to gather with community members interested in kops. This session is open to both developers and users. Office hours are hosted on a [zoom video chat](https://zoom.us/my/k8ssigaws) on Fridays at [12 noon (Eastern Time)/9 am (Pacific Time)](http://www.worldtimebuddy.com/?pl=1&lid=100,5,8,12) during weeks with odd "numbers". To check this weeks' number, run: `date +%V`. If the response is odd, join us on Friday for office hours! ##### Office Hours Topics We do maintain an [agenda](https://docs.google.com/document/d/12QkyL0FkNbWPcLFxxRGSPt_tNPBHbmni3YLY-lHny7E/edit) and stick to it as much as possible. If you want to hold the floor, put your item in this doc. Bullet/note form is fine. Even if your topic gets in late, we do our best to cover it. Our office hours call is recorded, but the tone tends to be casual. First-timers are always welcome. Typical areas of discussion can include: * Contributors with a feature proposal seeking feedback, assistance, etc * Members planning for what we want to get done for the next release * Strategizing for larger initiatives, such as those that involve more than one sig or potentially more moving pieces * Help wanted requests * Demonstrations of cool stuff. PoCs. Fresh ideas. Show us how you use kops to go beyond the norm- help us define the future! Office hours are designed for ALL of those contributing to kops or the community. Contributions are not limited to those who commit source code. There are so many important ways to be involved- * helping in the slack channels * triaging/writing issues * thinking about the topics raised at office hours and forming and advocating for your good ideas forming opinions * testing pre-(and official) releases Although not exhaustive, the above activities are extremely important to our continued success and are all worth contributions. If you want to talk about kops and you have doubt, just come. ##### Other Ways to Communicate with the Contributors Please check in with us in the [#kops-users](https://kubernetes.slack.com/messages/kops-users/) or [#kops-dev](https://kubernetes.slack.com/messages/kops-dev/) channel. Often-times, a well crafted question or potential bug report in slack will catch the attention of the right folks and help quickly get the ship righted. #### GitHub Issues ##### Bugs If you think you have found a bug please follow the instructions below. * Please spend a small amount of time giving due diligence to the issue tracker. Your issue might be a duplicate. * Set `-v 10` command line option and save the log output. Please paste this into your issue. * Note the version of kops you are running (from `kops version`), and the command line options you are using. * Open a [new issue](https://github.com/kubernetes/kops/issues/new). * Remember users might be searching for your issue in the future, so please give it a meaningful title to helps others. * Feel free to reach out to the kops community on [kubernetes slack](https://github.com/kubernetes/community/blob/master/communication.md#social-media). ##### Features We also use the issue tracker to track features. If you have an idea for a feature, or think you can help kops become even more awesome follow the steps below. * Open a [new issue](https://github.com/kubernetes/kops/issues/new). * Remember users might be searching for your issue in the future, so please give it a meaningful title to helps others. * Clearly define the use case, using concrete examples. EG: I type `this` and kops does `that`. * Some of our larger features will require some design. If you would like to include a technical design for your feature please include it in the issue. * After the new feature is well understood, and the design agreed upon we can start coding the feature. We would love for you to code it. So please open up a **WIP** *(work in progress)* pull request, and happy coding. Documentation [¶](#section-documentation) --- ### Overview [¶](#pkg-overview) Package kops is the parent package for the kops kubernetes-ops tool.. ### Index [¶](#pkg-index) * [Constants](#pkg-constants) * [Variables](#pkg-variables) * [func DefaultProtokubeImageName() string](#DefaultProtokubeImageName) ### Constants [¶](#pkg-constants) ``` const ( KOPS_RELEASE_VERSION = "1.11.0" KOPS_CI_VERSION = "1.11.1-alpha.1" ) ``` These constants are parsed by build tooling - be careful about changing the formats ### Variables [¶](#pkg-variables) ``` var GitVersion = "" ``` GitVersion should be replaced by the makefile ``` var Version = [KOPS_RELEASE_VERSION](#KOPS_RELEASE_VERSION) ``` Version can be replaced by build tooling ### Functions [¶](#pkg-functions) #### func [DefaultProtokubeImageName](https://github.com/kubernetes/kops/blob/v1.11.0/version.go#L34) [¶](#DefaultProtokubeImageName) ``` func DefaultProtokubeImageName() [string](/builtin#string) ``` DefaultProtokubeImageName is the name of the protokube image, as we would pass to "docker run" ### Types [¶](#pkg-types) This section is empty.
bluebird
devdocs
JavaScript
API Reference ============= * [Core](api/core) + [new Promise](api/new-promise) + [.then](api/then) + [.spread](api/spread) + [.catch](api/catch) + [.error](api/error) + [.finally](api/finally) + [.bind](api/bind) + [Promise.join](api/promise.join) + [Promise.try](api/promise.try) + [Promise.method](api/promise.method) + [Promise.resolve](api/promise.resolve) + [Promise.reject](api/promise.reject) * [Synchronous inspection](api/synchronous-inspection) + [PromiseInspection](api/promiseinspection) + [.isFulfilled](api/isfulfilled) + [.isRejected](api/isrejected) + [.isPending](api/ispending) + [.isCancelled](api/iscancelled) + [.value](api/value) + [.reason](api/reason) * [Collections](api/collections) + [Promise.all](api/promise.all) + [Promise.props](api/promise.props) + [Promise.any](api/promise.any) + [Promise.some](api/promise.some) + [Promise.map](api/promise.map) + [Promise.reduce](api/promise.reduce) + [Promise.filter](api/promise.filter) + [Promise.each](api/promise.each) + [Promise.mapSeries](api/promise.mapseries) + [Promise.race](api/promise.race) + [.all](api/all) + [.props](api/props) + [.any](api/any) + [.some](api/some) + [.map](api/map) + [.reduce](api/reduce) + [.filter](api/filter) + [.each](api/each) + [.mapSeries](api/mapseries) * [Resource management](api/resource-management) + [Promise.using](api/promise.using) + [.disposer](api/disposer) * [Promisification](api/promisification) + [Promise.promisify](api/promise.promisify) + [Promise.promisifyAll](api/promise.promisifyall) + [Promise.fromCallback](api/promise.fromcallback) + [.asCallback](api/ascallback) * [Timers](api/timers) + [Promise.delay](api/promise.delay) + [.delay](api/delay) + [.timeout](api/timeout) * [Cancellation](api/cancellation) + [.cancel](api/cancel) * [Generators](api/generators) + [Promise.coroutine](api/promise.coroutine) + [Promise.coroutine.addYieldHandler](api/promise.coroutine.addyieldhandler) * [Utility](api/utility) + [.tap](api/tap) + [.tapCatch](api/tapcatch) + [.call](api/call) + [.get](api/get) + [.return](api/return) + [.throw](api/throw) + [.catchReturn](api/catchreturn) + [.catchThrow](api/catchthrow) + [.reflect](api/reflect) + [Promise.getNewLibraryCopy](api/promise.getnewlibrarycopy) + [Promise.noConflict](api/promise.noconflict) + [Promise.setScheduler](api/promise.setscheduler) * [Built-in error types](api/built-in-error-types) + [OperationalError](api/operationalerror) + [TimeoutError](api/timeouterror) + [CancellationError](api/cancellationerror) + [AggregateError](api/aggregateerror) * [Configuration](api/error-management-configuration) + [Global rejection events](api/error-management-configuration#global-rejection-events) + [Local rejection events](api/promise.onpossiblyunhandledrejection) + [Promise.config](api/promise.config) + [.suppressUnhandledRejections](api/suppressunhandledrejections) + [.done](api/done) * [Progression migration](api/progression-migration) * [Deferred migration](api/deferred-migration) * [Environment variables](api/environment-variables) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api-reference.htmlGetting Started =============== > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/getting-started.md) to help completing this article. Node.js -------- ``` npm install bluebird ``` Then: ``` var Promise = require("bluebird"); ``` Alternatively in ES6 ``` import * as Promise from "bluebird"; ``` If that ES6 import [doesn't work](https://github.com/petkaantonov/bluebird/pull/1594) ``` import {Promise} from "bluebird"; ``` Browsers --------- (See also [Installation](install).) There are many ways to use bluebird in browsers: * Direct downloads + Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js) + Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js) + Core build [bluebird.core.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.js) + Core build minified [bluebird.core.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.min.js) * You may use browserify on the main export * You may use the [bower](http://bower.io) package. When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available. Bluebird runs on a wide variety of browsers including older versions. We'd like to thank BrowserStack for giving us a free account which helps us test that. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/getting-started.htmlInstallation ============ * [Browser installation](#browser-installation) * [Node installation](#node-installation) * [Supported platforms](#supported-platforms) Browser installation --------------------- Download [bluebird 3.7.2 (development)](https://cdn.jsdelivr.net/npm/[email protected]/js/browser/bluebird.js) Unminified source file meant to be used in development. Warnings and long stack traces are enabled which are taxing on performance. ``` <script src="//cdn.jsdelivr.net/npm/[email protected]/js/browser/bluebird.js"></script``` Download [bluebird 3.7.2 (production)](https://cdn.jsdelivr.net/npm/[email protected]/js/browser/bluebird.min.js) Minified source file meant to be used in production. Warnings and long straces are disabled. The gzipped size is 17.76KB. ``` <script src="//cdn.jsdelivr.net/npm/[email protected]/js/browser/bluebird.min.js"></script``` Unless an AMD loader is installed, the script tag installation exposes the library in the `Promise` and `P` namespaces. If you want to restore the `Promise` namespace, use `var Bluebird = Promise.noConflict()`. ### Bower ``` $ bower install --save bluebird ``` ### Browserify and Webpack ``` $ npm install bluebird ``` Using webpack for development/debugging: ``` var Promise = require("bluebird"); // Configure webpack and browserify for development/debugging Promise.config({ longStackTraces: true, warnings: true // note, run node with --trace-warnings to see full stack traces for warnings }) ``` Using webpack for production/performance: ``` var Promise = require("bluebird"); // Configure webpack and browserify for production/performance Promise.config({ longStackTraces: false, warnings: false }) ``` Node installation ------------------ ``` $ npm install bluebird ``` ``` var Promise = require("bluebird"); ``` To enable long stack traces and warnings in node development: ``` $ NODE_ENV=development node server.js ``` To enable long stack traces and warnings in node production: ``` $ BLUEBIRD_DEBUG=1 node server.js ``` See [`Environment Variables`](api/environment-variables). Supported platforms -------------------- Bluebird officially supports and is tested on node.js, iojs and browsers starting from IE7. Unofficial platforms are supported with best effort only. IE7 and IE8 do not support using keywords as property names, so if supporting these browsers is required you need to use the compatibility aliases: * [`Promise.try()`](api/promise.try) -> `Promise.attempt()` * [`.catch()`](api/catch) -> `.caught()` * [`.finally()`](api/finally) -> `.lastly()` * [`.return()`](api/return) -> `.thenReturn()` * [`.throw()`](api/throw) -> `.thenThrow()` Long stack traces are only supported in Chrome, recent Firefoxes and Internet Explorer 10+ [![Selenium Test Status] © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/install.htmlBenchmarks ========== Benchmarks have been ran with the following versions of modules. ``` ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] └── [email protected] ``` ### 1. DoxBee sequential This is <NAME> benchmark used in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where N=10000 requests are being made concurrently to execute some mixed async/sync action with fast I/O response times. This is a throughput benchmark. Every implementation runs in a freshly created isolated process which is warmed up to the benchmark code before timing it. The memory column represents the highest snapshotted RSS memory (as reported by `process.memoryUsage().rss`) during processing. Command: `./bench doxbee` ([needs cloned repository](http://bluebirdjs.com/docs/contribute.html#benchmarking)) The implementations for this benchmark are found in [`benchmark/doxbee-sequential`](https://github.com/petkaantonov/bluebird/tree/master/benchmark/doxbee-sequential) directory. ``` results for 10000 parallel executions, 1 ms per I/O op file time(ms) memory(MB) callbacks-baseline.js 116 33.98 callbacks-suguru03-neo-async-waterfall.js 145 43.81 promises-bluebird-generator.js 183 42.35 promises-bluebird.js 214 43.41 promises-cujojs-when.js 312 64.37 promises-then-promise.js 396 74.33 promises-tildeio-rsvp.js 414 84.80 promises-native-async-await.js 422 104.23 promises-ecmascript6-native.js 424 92.12 generators-tj-co.js 444 90.98 promises-lvivski-davy.js 480 114.46 callbacks-caolan-async-waterfall.js 520 109.01 promises-dfilatov-vow.js 612 134.38 promises-obvious-kew.js 725 208.63 promises-calvinmetcalf-lie.js 730 164.96 streamline-generators.js 809 154.36 promises-medikoo-deferred.js 913 178.51 observables-pozadi-kefir.js 991 194.00 streamline-callbacks.js 1127 196.54 observables-Reactive-Extensions-RxJS.js 1906 268.41 observables-caolan-highland.js 6887 662.08 promises-kriskowal-q.js 8533 435.51 observables-baconjs-bacon.js.js 21282 882.61 Platform info: Linux 4.4.0-79-generic x64 Node.JS 8.6.0 V8 6.0.287.53 Intel(R) Core(TM) i5-6600K CPU @ 3.50GHz × 4 ``` ### 2. Parallel This made-up scenario runs 25 shimmed queries in parallel per each request (N=10000) with fast I/O response times. This is a throughput benchmark. Every implementation runs in a freshly created isolated process which is warmed up to the benchmark code before timing it. The memory column represents the highest snapshotted RSS memory (as reported by `process.memoryUsage().rss`) during processing. Command: `./bench parallel` ([needs cloned repository](http://bluebirdjs.com/docs/contribute.html#benchmarking)) The implementations for this benchmark are found in [`benchmark/madeup-parallel`](https://github.com/petkaantonov/bluebird/tree/master/benchmark/madeup-parallel) directory. ``` results for 10000 parallel executions, 1 ms per I/O op file time(ms) memory(MB) callbacks-baseline.js 274 75.11 callbacks-suguru03-neo-async-parallel.js 320 88.84 promises-bluebird.js 407 107.25 promises-bluebird-generator.js 432 113.19 callbacks-caolan-async-parallel.js 550 154.27 promises-cujojs-when.js 648 168.65 promises-ecmascript6-native.js 1145 308.87 promises-lvivski-davy.js 1153 257.36 promises-native-async-await.js 1260 323.68 promises-then-promise.js 1372 313.24 promises-tildeio-rsvp.js 1435 398.73 promises-medikoo-deferred.js 1626 306.02 promises-calvinmetcalf-lie.js 1805 351.21 promises-dfilatov-vow.js 2492 558.25 promises-obvious-kew.js 3403 784.61 streamline-generators.js 13068 919.24 streamline-callbacks.js 25509 1141.57 Platform info: Linux 4.4.0-79-generic x64 Node.JS 8.6.0 V8 6.0.287.53 Intel(R) Core(TM) i5-6600K CPU @ 3.50GHz × 4 ``` ### 3. Latency benchmarks For reasonably fast promise implementations latency is going to be fully determined by the scheduler being used and is therefore not interesting to benchmark. [JSPerfs](https://jsperf.com/) that benchmark promises tend to benchmark latency. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/benchmarks.htmlWhy bluebird? ============= There are many third party promise libraries available for JavaScript and even the standard library contains a promise implementation in newer versions of browsers and node/io.js. This page will explore why one might use bluebird promises over other third party or the standard library implementations. For reasons to use promises in general, see the [Why Promises?](why-promises) article. ### Bluebird design principles Bluebird is built with the following design principles in mind: * **Pragmatic and not theoretical.** - Bluebird will always pick the pragmatic route vs the theoretically elegant one when there is a conflict. The library's API was created based on real-life use cases and after a lot of consideration. * **Fully featured without bloat** - Bluebird provides all the tools and utilities needed to realize a highly expressive and fluent DSL for asynchronous JavaScript without suffering from bloat by avoiding incorporating features that are solely motivated by theoretical arguments, have extremely narrow applicability, or have limited synergy and composability with existing features. * **Easy to debug** - A major consequence of choosing pragmatism over theoretical elegance, a property that is unique to bluebird among promise libraries taken to this extent. + Bluebird ships with the best cross-platform long stack traces out there and a warning system. This helps you recognize common and devastating promise usage mistakes early before they lead to hard to debug code later. + Unhandled errors are not silently swallowed by default but reported along with helpful stack traces where applicable. All of this is of course configurable. * **Zero overhead abstraction** - In server-side applications the performance of a promise implementation matters. Bluebird's server-side performance is measured with highly relevant and realistic end-to-end macro <benchmarks>, and consistently comes out on top. We understand that if bluebird is as close to a zero cost abstraction as possible, developers won't be tempted to short-circuit and absorb complexity themselves. * **Runs everywhere** - Bluebird runs on pretty much every platform. This makes bluebird ideal for projects who care about providing consistent cross-platform and cross-version experience. It runs on old IE, it has even been known to run on Netscape 7. * **Spec compatible** - Bluebird can work as a drop-in replacement for native promises for an instant performance boost. It passes the Promises/A+ test suite and is fully spec compliant. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/why-bluebird.htmlWhy Performance? ================ > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/why-performance.md) to help completing this article. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/why-performance.htmlWhat About Generators? ====================== There is an [excellent article](https://www.promisejs.org/generators/) on promisejs.org detailing how to combine promises with generators to achieve much cleaner code. Instead of the `async` function the article proposes, you can use [`Promise.coroutine`](api/promise.coroutine). > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/what-about-generators.md) to help completing this article. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/what-about-generators.htmlBeginner's Guide ================ > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/beginners-guide.md) to help completing this article. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/beginners-guide.htmlComing from Other Languages =========================== This page describes parallels of using promises in other languages. Promises as a pattern are very common in other languages and knowing what they map to in other languages might help you with grasping them conceptually * [C#](#c) * [Scala](#scala) * [Python](#python) * [C++](#c) * [Haskell](#haskell) * [Java](#java) * [Android Java](#android-java) * [Objective-C](#objective-c) C# --- A promise is similar to a C# `Task`. They both represent the result of an operation. A promise's `then` method is similar to a Task's `ContinueWith` method in that both allow attaching a continuation to the promise. Bluebird's [`Promise.coroutine`](api/promise.coroutine) is analogous to C#'s `async/await` syntax. A `TaskCompletionSource` is analogous to the promise constructor. Although usually promisification is preferred (see the API reference or working with callbacks section). `Task.FromResult` is analogous to [`Promise.resolve`](api/promise.resolve). The difference between a `Task` and a promise are that a task might not be started and might require a `.Start` call where a promise always represents an already started operation. In addition promises are always unwrapped. A promise implicitly has `Task.Unwrap` called on it - that is, promises perform recursive assimilation of promises within them. See [this question on StackOverflow](http://stackoverflow.com/questions/26136389/how-can-i-realize-pattern-promise-deffered) for more differences. Scala ------ A bluebird promise is similar to a Scala `Future`. A scala `Promise` is similar to how the promise constructor can be used (previously, to a bluebird Deferred). Just like a future, a promise represents a value over time. The value can resolve to either a fulfilled (ok completion) or rejected (error completion) state. Where blocking on a Future in scala is discouraged, in JavaScript it's downright impossible. In addition promises are always unwrapped. That is, promises perform recursive assimilation of promises within them. You can't have a `Promise<Promise<T>>` where a `Future[Future[T]]` is valid in Scala. See [this question on StackOverflow](http://stackoverflow.com/questions/22724883/js-deferred-promise-future-compared-to-functional-languages-like-scala) for more differences. Python ------- A promise is similar to a Twisted Deferred object. In fact the first JavaScript implementations of promises were based on it. However, the APIs have diverged since. The mental model is still very similar. A promise is *not* similar to a Python `concurrent.Future` which does not chain actions. Asyncio coroutines are similar to bluebird coroutines in what they let you do, however bluebird coroutines also enable functional-style chaining. C++ ---- A bluebird promise is similar to a `std::future` and the promise constructor is similar to an `std::promise` although it should rarely be used in practice (see the promisification section). However, a bluebird promise is more powerful than the current implementation of `std::future` since while chaining has been discussed it is not yet implemented. Promises can be chained together. Boost futures expose a `.then` method similar to promises and allow this functionality. Haskell -------- A promise is a monadic construct with `.then` filling the role of `>>=` (bind). The major difference is that `.then` performs recursive assimilation which acts like a `flatMap` or a map. The type signature of `then` is quote complicated. If we omit the error argument and not throw - it's similar to: ``` then::Promise a -> (a -> (Either (Promise b) b)) -> Promise b ``` That is, you can return either a promise *or a plain value* from a `then` without wrapping it. Promises perform a role similar to `IO` in that they allow for easy chaining of asynchronous non-blocking operations. `Promise.coroutine` can be seen as similar to `do` notation although in practice it's not an accurate comparison. Java ----- A promise is similar to a guava `Future` with `chain` being similar to `then`. If your'e familiar with Java 8 lambdas, you can think of a promise as a `Future` you can `map` to another future. Android Java ------------- Several popular Android libraries use promises - for example the Parse Java API returns `Task`s which are similar to JavaScript promises. Objective-C ------------ If you're familiar with PromiseKit, it is based on a same specification bluebird is based on so the API should feel familiar right away. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/coming-from-other-languages.htmlCore ===== Core methods of `Promise` instances and core static methods of the Promise class. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/core.htmlNew in bluebird 3.0 =================== Cancellation overhaul ---------------------- Cancellation has been redesigned for bluebird 3.0. Any code that relies on 2.x cancellation semantics won't work in 3.0 or later. See [`Cancellation`](api/cancellation) for more information. Promisification API changes ---------------------------- Both promisification ([`Promise.promisify`](api/promise.promisify) and [`Promise.promisifyAll`](api/promise.promisifyall)) methods and [`Promise.fromCallback`](api/promise.fromcallback) now by default ignore multiple arguments passed to the callback adapter and instead only the first argument is used to resolve the promise. The behavior in 2.x is to construct an array of the arguments and resolve the promise with it when more than one argument is passed to the callback adapter. The problems with this approach and reasons for the change are discussed in [`#307`](https://github.com/petkaantonov/bluebird/issues/307). [`Promise.promisify`](api/promise.promisify)'s second argument is now an options object, so any code using the second argument needs to change: ``` // 2.x Promise.promisify(fn, ctx); // 3.0 Promise.promisify(fn, {context: ctx}); ``` Both promisification ([`Promise.promisify`](api/promise.promisify) and [`Promise.promisifyAll`](api/promise.promisifyall)) methods and [`Promise.fromCallback`](api/promise.fromcallback) all take a new boolean option `multiArgs` which defaults to `false`. Enabling this option will make the adapter callback *always* construct an array of the passed arguments regardless of amount of arguments. This can be used to reliably get access to all arguments rather than just the first one. Collection method changes -------------------------- All collection methods now support objects that implement [ES6's *iterable*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) protocol along with regular arrays. [`Promise.props`](api/promise.props) and [`.props`](api/props) now support [ES6 `Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) objects along with normal objects. Actual `Map` objects are only considered for their entries in the map instead of both entries and properties. Warnings --------- Warnings have been added to report usages which are very likely to be programmer errors. See [`Promise.config`](api/promise.config) for how to enable warnings. See [Warning Explanations](warning-explanations) for list of the warnings and their explanations. Feature additions ------------------ * [`.catch()`](api/catch) now supports an object predicate as a filter: `.catch({code: 'ENOENT'}, e => ...)`. * Added [`.suppressUnhandledRejections()`](api/suppressunhandledrejections). * Added [`.catchThrow()`](api/catchthrow). * Added [`.catchReturn()`](api/catchreturn). * Added [`Promise.mapSeries()`](api/promise.mapseries) and [`.mapSeries()`](api/mapseries) Deprecations ------------- * `Promise.settle` has been deprecated. Use [`.reflect`](api/reflect) instead. * `Promise.spawn` has been deprecated. Use [`Promise.coroutine`](api/promise.coroutine) instead. * [`Promise.try`](api/promise.try)'s `ctx` and `arg` arguments have been deprecated. * `.nodeify` is now better known as [`.asCallback`](api/ascallback) * `.fromNode` is now better known as [`Promise.fromCallback`](api/promise.fromcallback) Summary of breaking changes ---------------------------- * Promisifier APIs. * Cancellation redesign. * Promise progression has been completely removed. * [`.spread`](api/spread)'s second argument has been removed. * [`.done`](api/done) causes an irrecoverable fatal error in Node.js environments now. See [`#471`](https://github.com/petkaantonov/bluebird/issues/471) for rationale. * Errors created with [`Promise.reject`](api/promise.reject) or `reject` callback of [`new Promise`](api/new-promise) are no longer marked as [`OperationalError`](api/operationalerror)s. 3.0.1 update ------------- Note that the 3.0.1 update is strictly speaking backward-incompatible with 3.0.0. Version 3.0.0 changed the previous behavior of the `.each` method and made it work the same as the new `.mapSeries` - 3.0.1 unrolls this change by reverting to the `.tap`-like behavior found in 2.x However, this would only affect users who updated to 3.0.0 during the short time that it wasn't deprecated and started relying on the new `.each` behavior. This seems unlikely, and therefore the major version was not changed. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/new-in-bluebird-3.htmlWarning Explanations ==================== > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/warning-explanations.md) to help completing this article. * [Warning: .then() only accepts functions](#warning-then-only-accepts-functions) * [Warning: a promise was rejected with a non-error](#warning-a-promise-was-rejected-with-a-non-error) * [Warning: a promise was created in a handler but was not returned from it](#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it) Note - in order to get full stack traces with warnings in Node 6.x+ you need to enable to `--trace-warnings` flag which will give you a full stack trace of where the warning is coming from. Warning: .then() only accepts functions ---------------------------------------- If you see this warning your code is probably not doing what you expect it to, the most common reason is passing the *result* of calling a function to [`.then()`](api/then) instead of the function *itself*: ``` function processImage(image) { // Code that processes image } getImage().then(processImage()); ``` The above calls the function `processImage()` *immediately* and passes the result to [`.then()`](api/then) (which is most likely `undefined` - the default return value when a function doesn't return anything). To fix it, simply pass the function reference to [`.then()`](api/then) as is: ``` getImage().then(processImage) ``` *If you are wondering why this is a warning and not a simple TypeError it is because the due to historic reasons Promises/A+ specification requires that incorrect usage is silently ignored.* Warning: a promise was rejected with a non-error ------------------------------------------------- Due to a historic mistake in JavaScript, the `throw` statement is allowed to be used with any value, not just errors, and Promises/A+ choosing to inherit this mistake, it is possible to reject a promise with a value that is not an error. An error is an object that is a `instanceof Error`. It will at minimum have the properties `.stack` and `.message`, which are an absolute *must* have for any value that is being used in an automatic propagation mechanism, such as exceptions and rejections. This is because errors are usually handled many levels above where they actually originate - the error object must have sufficient metadata about it so that its ultimate handler (possibly many levels above) will have all the information needed for creating a useful high level error report. Since all objects support having properties you might still wonder why exactly does it have to be an error object and not just any object. In addition to supporting properties, an equally important feature necessary for values that are automatically propagated is the stack trace property (`.stack`). A stack trace allows you easily find where an error originated from as it gives the code's call stack - along with line numbers for reference in code files. You should heed this warning because rejecting a promise with a non-error makes debugging extremely hard and costly. Additionally, if you reject with simple primitives such as `undefined` (commonly caused by simply calling `reject()`) you cannot handle errors at all because it's impossible to tell from `undefined` what exactly went wrong. All you can tell the user is that "something went wrong" and lose them forever. Warning: a promise was created in a handler but was not returned from it ------------------------------------------------------------------------- This usually means that you simply forgot a `return` statement somewhere, which will cause a runaway promise that is not connected to any promise chain. For example: ``` getUser().then(function(user) { getUserData(user); }).then(function(userData) { // userData is undefined }); ``` Because the result of `getUserData()` is not returned from the first then handler, it becomes a runaway promise that is not awaited for by the second then. The second [`.then()`](api/then) simply gets immediately called with `undefined` (because `undefined` is the default return value when you don't return anything). To fix it, you need to `return` the promise: ``` getUser().then(function(user) { return getUserData(user); }).then(function(userData) { // userData is the user's data }); ``` If you know what you're doing and don't want to silence all warnings, you can create runaway promises without causing this warning by returning e.g. `null`: ``` getUser().then(function(user) { // Perform this in the "background" and don't care about its result at all saveAnalytics(user); // return a non-undefined value to signal that we didn't forget to return return null; }); ``` © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/warning-explanations.htmlDeprecated APIs =============== > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/deprecated-apis.md) to help completing this article. This file contains documentation for APIs that are no longer supported by Bluebird. These APIs still work in Bluebird but will be removed at a future version of the library. For every use case that the methods below solve there exists a better alternative in [the API reference](index). * [Progression](#progression) + [`.progressed(Function handler)`](#progressedfunction-handler---promise) + [`.then([Function fulfilledHandler] [, Function rejectedHandler ] [, Function progressHandler ])`](#thenfunction-fulfilledhandler--function-rejectedhandler---function-progresshandler----promise) + [`.done([Function fulfilledHandler] [, Function rejectedHandler ] [, Function progressHandler ])`](#donefunction-fulfilledhandler--function-rejectedhandler---function-progresshandler----promise) * [Promise resolution](#promise-resolution) + [`.resolve(dynamic value)`](#resolvedynamic-value---undefined) + [`.reject(dynamic reason)`](#rejectdynamic-reason---undefined) + [`.progress(dynamic value)`](#progressdynamic-value---undefined) + [`.callback`](#callback---function) + [Old Promise Cancellation](#old-promise-cancellation) Progression ------------ The old progression API was meant to be used for tracking the progress of promise resolution. In retrospect, it did not work or compose very well. We understand that problem better now and the use case could be better solved without it. See [Progression Migration](api/progression-migration) for migration assistance and examples of how to convert APIs that use progression to ones that do not. ##### `.progressed(Function handler)` -> `Promise` Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. ##### `.then([Function fulfilledHandler] [, Function rejectedHandler ] [, Function progressHandler ])` -> `Promise` The standard [Promises/A+ `.then()`](http://promises-aplus.github.io/promises-spec/) is still supported by Bluebird and support for it will continue indefinitely . However, the variant accepting a third `progressHandler` argument is no longer supported. ##### `.done([Function fulfilledHandler] [, Function rejectedHandler ] [, Function progressHandler ])` -> `void` Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. Again, only the variant with the progression handler is deprecated here. `.done` is still fully supported. Promise resolution ------------------- A `PromiseResolver` can be used to control the fate of a promise. It is like "Deferred" in jQuery or `$q.defer` in $q. The `PromiseResolver` objects have a `.promise` property which returns a reference to the controlled promise that can be passed to clients. `.promise` of a `PromiseResolver` is not a getter function to match other implementations. The methods of a `PromiseResolver` have no effect if the fate of the underlying promise is already decided (follow, reject, fulfill). **The use of `Promise.defer` and deferred objects is discouraged - it is much more awkward and error-prone than using `new Promise`.** ##### `.resolve(dynamic value)` -> `undefined` Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. ##### `.reject(dynamic reason)` -> `undefined` Reject the underlying promise with `reason` as the rejection reason. ##### `.progress(dynamic value)` -> `undefined` Progress the underlying promise with `value` as the progression value. Example ``` function delay(ms) { var resolver = Promise.defer(); var now = Date.now(); setTimeout(function(){ resolver.resolve(Date.now() - now); }, ms); return resolver.promise; } delay(500).then(function(ms){ console.log(ms + " ms passed"); }); ``` Old Promise Cancellation ------------------------- In 2.x, promise cancellation looked very differently. Promise cancellation received a major overhaul for version 3 in order to create a sound variant of cancellable promises. You can still use 2.x cancellation with bluebird 2.x (which is still supported - but not recommended). See [Cancellation](http://bluebirdjs.com/cancellation.html) for more details. The 2.x docs are [still accessible under the 2.x branch](https://github.com/petkaantonov/bluebird/blob/2.x/API.md). © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/deprecated-apis.htmlWhy Promises? ============= Promises are a concurrency primitive with a proven track record and language integration in most modern programming languages. They have been extensively studied since the 80s and will make your life much easier. You should use promises to turn this: ``` fs.readFile("file.json", function (err, val) { if (err) { console.error("unable to read file"); } else { try { val = JSON.parse(val); console.log(val.success); } catch (e) { console.error("invalid json in file"); } } }); ``` Into this: ``` fs.readFileAsync("file.json").then(JSON.parse).then(function (val) { console.log(val.success); }) .catch(SyntaxError, function (e) { console.error("invalid json in file"); }) .catch(function (e) { console.error("unable to read file"); }); ``` *If you're thinking, "There's no `readFileAsync` method on `fs` that returns a promise!" see [promisification](api/promisification)* You might notice that the promise approach looks very similar to using synchronous I/O: ``` try { var val = JSON.parse(fs.readFileSync("file.json")); console.log(val.success); } // Gecko-only syntax; used for illustrative purposes catch (e if e instanceof SyntaxError) { console.error("invalid json in file"); } catch (e) { console.error("unable to read file"); } ``` This is the point—to have something that works like `return` and `throw` in synchronous code. You can also use promises to improve code that was written with callbacks: ``` //Copyright Plato http://stackoverflow.com/a/19385911/995876 //CC BY-SA 2.5 mapSeries(URLs, function (URL, done) { var options = {}; needle.get(URL, options, function (error, response, body) { if (error) { return done(error); } try { var ret = JSON.parse(body); return done(null, ret); } catch (e) { done(e); } }); }, function (err, results) { if (err) { console.log(err); } else { console.log('All Needle requests successful'); // results is a 1 to 1 mapping in order of URLs > needle.body processAndSaveAllInDB(results, function (err) { if (err) { return done(err); } console.log('All Needle requests saved'); done(null); }); } }); ``` This is far more readable when done with promises: ``` Promise.promisifyAll(needle); var options = {}; var current = Promise.resolve(); Promise.map(URLs, function (URL) { current = current.then(function () { return needle.getAsync(URL, options); }); return current; }).map(function (responseAndBody) { return JSON.parse(responseAndBody[1]); }).then(function (results) { return processAndSaveAllInDB(results); }).then(function () { console.log('All Needle requests saved'); }).catch(function (e) { console.log(e); }); ``` Also, promises don't just give you correspondences for synchronous features; they can also be used as limited event emitters or callback aggregators. More reading: * [Promise nuggets](https://promise-nuggets.github.io/) * [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html) * [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1) * [Aren't Promises Just Callbacks?](http://stackoverflow.com/questions/22539815/arent-promises-just-callbacks) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/why-promises.htmlAnti-patterns ============= This page will contain common promise anti-patterns that are exercised in the wild. * [The explicit construction anti-pattern](#the-explicit-construction-anti-pattern) * [The `.then(success, fail)` anti-pattern](#the-.then) The Explicit Construction Anti-Pattern --------------------------------------- This is the most common anti-pattern. It is easy to fall into this when you don't really understand promises and think of them as glorified event emitters or callback utility. It's also sometimes called the promise constructor anti-pattern. Let's recap: promises are about making asynchronous code retain most of the lost properties of synchronous code such as flat indentation and one exception channel. This pattern is also called the deferred anti-pattern. In the explicit construction anti-pattern, promise objects are created for no reason, complicating code. First example is creating deferred object when you already have a promise or thenable: ``` //Code copyright by Twisternha http://stackoverflow.com/a/19486699/995876 CC BY-SA 2.5 myApp.factory('Configurations', function (Restangular, MotorRestangular, $q) { var getConfigurations = function () { var deferred = $q.defer(); MotorRestangular.all('Motors').getList().then(function (Motors) { //Group by Config var g = _.groupBy(Motors, 'configuration'); //Map values var mapped = _.map(g, function (m) { return { id: m[0].configuration, configuration: m[0].configuration, sizes: _.map(m, function (a) { return a.sizeMm }) } }); deferred.resolve(mapped); }); return deferred.promise; }; return { config: getConfigurations() } }); ``` This superfluous wrapping is also dangerous, any kind of errors and rejections are swallowed and not propagated to the caller of this function. Instead of using the Deferred anti-pattern, the code should simply return the promise it already has and propagate values using `return`: ``` myApp.factory('Configurations', function (Restangular, MotorRestangular, $q) { var getConfigurations = function () { //Just return the promise we already have! return MotorRestangular.all('Motors').getList().then(function (Motors) { //Group by Cofig var g = _.groupBy(Motors, 'configuration'); //Return the mapped array as the value of this promise return _.map(g, function (m) { return { id: m[0].configuration, configuration: m[0].configuration, sizes: _.map(m, function (a) { return a.sizeMm }) } }); }); }; return { config: getConfigurations() } }); ``` Not only is the code shorter but more importantly, if there is any error it will propagate properly to the final consumer. Second example is creating a function that does nothing but manually wrap a callback API and doing a poor job at that: ``` function applicationFunction(arg1) { return new Promise(function(resolve, reject){ //Or Q.defer() in Q libraryFunction(arg1, function (err, value) { if (err) { reject(err); } else { resolve(value); } }); } ``` This is reinventing the square wheel because any callback API wrapping can and should be done immediately using the promise library's promisification methods: ``` var applicationFunction = Promise.promisify(libraryFunction); ``` The generic promisification is likely to be faster because it can use internals directly but also handles edge cases like `libraryFunction` throwing synchronously or using multiple success values. **So when should deferred be used?** Well simply, when you have to. You might have to use a deferred object when wrapping a callback API that doesn't follow the standard convention. Like `setTimeout`: ``` //setTimeout that returns a promise function delay(ms) { var deferred = Promise.defer(); // warning, defer is deprecated, use the promise constructor setTimeout(function(){ deferred.fulfill(); }, ms); return deferred.promise; } ``` Such wrappers should be rare, if they're common for the reason that the promise library cannot generically promisify them, you should file an issue. If you cannot do static promisification (promisify and promisifyAll perform too slowly to use at runtime), you may use [`Promise.fromCallback`](api/promise.fromcallback). Also see [this StackOverflow question](http://stackoverflow.com/questions/23803743/what-is-the-deferred-antipattern-and-how-do-i-avoid-it) for more examples and a debate around it. The `.then(success, fail)` anti-pattern ---------------------------------------- *Almost* a sure sign of using promises as glorified callbacks. Instead of `doThat(function(err, success))` you do `doThat().then(success, err)` and rationalize to yourself that at least the code is "less coupled" or something. The `.then` signature is mostly about interop, there is *almost* never a reason to use `.then(success, fail)` in application code. It is even awkward to express it in the sync parallel: ``` var t0; try { t0 = doThat(); } catch(e) { } //deal with t0 here and waste the try-catch var stuff = JSON.parse(t0); ``` It is more likely that you would write this instead in the sync world: ``` try { var stuff = JSON.parse(doThat()); } catch(e) { } ``` So please write the same when using promises too: ``` doThat() .then(function(v) { return JSON.parse(v); }) .catch(function(e) { }); ``` `.catch` is specified for built-in Javascript promises and is "sugar" for `.then(null, function(){})`. Since the way errors work in promises is almost the entire point (and the only thing jQuery never got right, even if it used `.pipe` as a `.then`), I really hope the implementation you are using provides this method for readability. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/anti-patterns.htmlnew Promise ============ ``` new Promise(function(function resolve, function reject) resolver) -> Promise ``` Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. *Note: See [explicit construction anti-pattern](../anti-patterns#the-explicit-construction-anti-pattern) before creating promises yourself* Example: ``` function ajaxGetAsync(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest; xhr.addEventListener("error", reject); xhr.addEventListener("load", resolve); xhr.open("GET", url); xhr.send(null); }); } ``` If you pass a promise object to the `resolve` function, the created promise will follow the state of that promise. To make sure a function that returns a promise is following the implicit but critically important contract of promises, you can start a function with `new Promise` if you cannot start a chain immediately: ``` function getConnection(urlString) { return new Promise(function(resolve) { //Without new Promise, this throwing will throw an actual exception var params = parse(urlString); resolve(getAdapter(params).getConnection()); }); } ``` The above ensures `getConnection` fulfills the contract of a promise-returning function of never throwing a synchronous exception. Also see [`Promise.try`](promise.try) and [`Promise.method`](promise.method) The resolver is called synchronously (the following is for documentation purposes and not idiomatic code): ``` function getPromiseResolveFn() { var res; new Promise(function (resolve) { res = resolve; }); // res is guaranteed to be set return res; } ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/new-promise.htmlFeatures ======== > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/features.md) to help completing this article. * [Synchronous inspection](#synchronous-inspection) * [Concurrency coordination](#concurrency-coordination) * [Promisification on steroids](#promisification-on-steroids) * [Debuggability and error handling](#debuggability-and-error-handling) * [Resource management](#resource-management) * [Cancellation and timeouts](#cancellation-and-timeouts) * [Scoped prototypes](#scoped-prototypes) * [Promise monitoring](#promise-monitoring) * [Async/Await](#async-await) Synchronous inspection ----------------------- Synchronous inspection allows you to retrieve the fulfillment value of an already fulfilled promise or the rejection reason of an already rejected promise synchronously. Often it is known in certain code paths that a promise is guaranteed to be fulfilled at that point - it would then be extremely inconvenient to use [`.then`](api/then) to get at the promise's value as the callback is always called asynchronously. See the API on [`synchronous inspection`](api/synchronous-inspection) for more information. Concurrency coordination ------------------------- Through the use of [`.each`](api/each) and [`.map`](api/map) doing things just at the right concurrency level becomes a breeze. Promisification on steroids ---------------------------- Promisification means converting an existing promise-unaware API to a promise-returning API. The usual way to use promises in node is to [`Promise.promisifyAll`](api/promise.promisifyall) some API and start exclusively calling promise returning versions of the APIs methods. E.g. ``` var fs = require("fs"); Promise.promisifyAll(fs); // Now you can use fs as if it was designed to use bluebird promises from the beginning fs.readFileAsync("file.js", "utf8").then(...) ``` Note that the above is an exceptional case because `fs` is a singleton instance. Most libraries can be promisified by requiring the library's classes (constructor functions) and calling promisifyAll on the `.prototype`. This only needs to be done once in the entire application's lifetime and after that you may use the library's methods exactly as they are documented, except by appending the `"Async"`-suffix to method calls and using the promise interface instead of the callback interface. As a notable exception in `fs`, `fs.existsAsync` doesn't work as expected, because Node's `fs.exists` doesn't call back with error as first argument. More at [`#418`](https://github.com/petkaantonov/bluebird/issues/418). One possible workaround is using `fs.statAsync`. Some examples of the above practice applied to some popular libraries: ``` // The most popular redis module var Promise = require("bluebird"); Promise.promisifyAll(require("redis")); ``` ``` // The most popular mongodb module var Promise = require("bluebird"); Promise.promisifyAll(require("mongodb")); ``` ``` // The most popular mysql module var Promise = require("bluebird"); // Note that the library's classes are not properties of the main export // so we require and promisifyAll them manually Promise.promisifyAll(require("mysql/lib/Connection").prototype); Promise.promisifyAll(require("mysql/lib/Pool").prototype); ``` ``` // Mongoose var Promise = require("bluebird"); Promise.promisifyAll(require("mongoose")); ``` ``` // Request var Promise = require("bluebird"); Promise.promisifyAll(require("request")); // Use request.getAsync(...) not request(..), it will not return a promise ``` ``` // mkdir var Promise = require("bluebird"); Promise.promisifyAll(require("mkdirp")); // Use mkdirp.mkdirpAsync not mkdirp(..), it will not return a promise ``` ``` // winston var Promise = require("bluebird"); Promise.promisifyAll(require("winston")); ``` ``` // rimraf var Promise = require("bluebird"); // The module isn't promisified but the function returned is var rimrafAsync = Promise.promisify(require("rimraf")); ``` ``` // xml2js var Promise = require("bluebird"); Promise.promisifyAll(require("xml2js")); ``` ``` // jsdom var Promise = require("bluebird"); Promise.promisifyAll(require("jsdom")); ``` ``` // fs-extra var Promise = require("bluebird"); Promise.promisifyAll(require("fs-extra")); ``` ``` // prompt var Promise = require("bluebird"); Promise.promisifyAll(require("prompt")); ``` ``` // Nodemailer var Promise = require("bluebird"); Promise.promisifyAll(require("nodemailer")); ``` ``` // ncp var Promise = require("bluebird"); Promise.promisifyAll(require("ncp")); ``` ``` // pg var Promise = require("bluebird"); Promise.promisifyAll(require("pg")); ``` In all of the above cases the library made its classes available in one way or another. If this is not the case, you can still promisify by creating a throwaway instance: ``` var ParanoidLib = require("..."); var throwAwayInstance = ParanoidLib.createInstance(); Promise.promisifyAll(Object.getPrototypeOf(throwAwayInstance)); // Like before, from this point on, all new instances + even the throwAwayInstance suddenly support promises ``` See also [`Promise.promisifyAll`](api/promise.promisifyall). Debuggability and error handling --------------------------------- * [Surfacing unhandled errors](#surfacing-unhandled-errors) * [Long stack traces](#long-stack-traces) * [Error pattern matching](#error-pattern-matching) * [Warnings](#warnings) ### Surfacing unhandled errors The default approach of bluebird is to immediately log the stack trace when there is an unhandled rejection. This is similar to how uncaught exceptions cause the stack trace to be logged so that you have something to work with when something is not working as expected. However because it is possible to handle a rejected promise at any time in the indeterminate future, some programming patterns will result in false positives. Because such programming patterns are not necessary and can always be refactored to never cause false positives, we recommend doing that to keep debugging as easy as possible . You may however feel differently so bluebird provides hooks to implement more complex failure policies. Such policies could include: * Logging after the promise became GCd (requires a native node.js module) * Showing a live list of rejected promises * Using no hooks and using [`.done`](api/done) to manually to mark end points where rejections will not be handled * Swallowing all errors (challenge your debugging skills) * ... See [global rejection events](api/error-management-configuration#global-rejection-events) to learn more about the hooks. ### Long stack traces Normally stack traces don't go beyond asynchronous boundaries so their utility is greatly reduced in asynchronous code: ``` setTimeout(function() { setTimeout(function() { setTimeout(function() { a.b.c; }, 1); }, 1) }, 1) ``` ``` ReferenceError: a is not defined at null._onTimeout file.js:4:13 at Timer.listOnTimeout (timers.js:90:15) ``` Of course you could use hacks like monkey patching or domains but these break down when something can't be monkey patched or new apis are introduced. Since in bluebird [`promisification`](api/promisification) is made trivial, you can get long stack traces all the time: ``` var Promise = require("bluebird"); Promise.delay(1) .delay(1) .delay(1).then(function() { a.b.c; }); ``` ``` Unhandled rejection ReferenceError: a is not defined at file.js:6:9 at processImmediate [as _immediateCallback] (timers.js:321:17) From previous event: at Object.<anonymous> (file.js:5:15) at Module._compile (module.js:446:26) at Object.Module._extensions..js (module.js:464:10) at Module.load (module.js:341:32) at Function.Module._load (module.js:296:12) at Function.Module.runMain (module.js:487:10) at startup (node.js:111:16) at node.js:799:3 ``` And there is more. Bluebird's long stack traces additionally eliminate cycles, don't leak memory, are not limited to a certain amount of asynchronous boundaries and are fast enough for most applications to be used in production. All these are non-trivial problems that haunt straight-forward long stack trace implementations. See [installation](install) on how to enable long stack traces in your environment. ### Error pattern matching Perhaps the greatest thing about promises is that it unifies all error handling into one mechanism where errors propagate automatically and have to be explicitly ignored. ### Warnings Promises can have a steep learning curve and it doesn't help that promise standards go out of their way to make it even harder. Bluebird works around the limitations by providing warnings where the standards disallow throwing errors when incorrect usage is detected. See [Warning Explanations](warning-explanations) for the possible warnings that bluebird covers. See [installation](install) on how to enable warnings in your environment. Note - in order to get full stack traces with warnings in Node 6.x+ you need to enable to `--trace-warnings` flag which will give you a full stack trace of where the warning is coming from. ### Promise monitoring This feature enables subscription to promise lifecycle events via standard global events mechanisms in browsers and Node.js. The following lifecycle events are available: * `"promiseCreated"` - Fired when a promise is created through the constructor. * `"promiseChained"` - Fired when a promise is created through chaining (e.g. [`.then`](api/then)). * `"promiseFulfilled"` - Fired when a promise is fulfilled. * `"promiseRejected"` - Fired when a promise is rejected. * `"promiseResolved"` - Fired when a promise adopts another's state. * `"promiseCancelled"` - Fired when a promise is cancelled. This feature has to be explicitly enabled by calling [`Promise.config`](api/promise.config) with `monitoring: true`. The actual subscription API depends on the environment. 1. In Node.js, use `process.on`: ``` // Note the event name is in camelCase, as per Node.js convention. process.on("promiseChained", function(promise, child) { // promise - The parent promise the child was chained from // child - The created child promise. }); ``` 2. In modern browsers use `window.addEventListener` (window context) or `self.addEventListener()` (web worker or window context) method: ``` // Note the event names are in mashedtogetherlowercase, as per DOM convention. self.addEventListener("promisechained", function(event) { // event.details.promise - The parent promise the child was chained from // event.details.child - The created child promise. }); ``` 3. In legacy browsers use `window.oneventname = handlerFunction;`. ``` // Note the event names are in mashedtogetherlowercase, as per legacy convention. window.onpromisechained = function(promise, child) { // event.details.promise - The parent promise the child was chained from // event.details.child - The created child promise. }; ``` Resource management -------------------- Cancellation and timeouts -------------------------- See [`Cancellation`](api/cancellation) for how to use cancellation. ``` // Enable cancellation Promise.config({cancellation: true}); var fs = Promise.promisifyAll(require("fs")); // In 2000ms or less, load & parse a file 'config.json' var p = Promise.resolve('./config.json') .timeout(2000) .catch(console.error.bind(console, 'Failed to load config!')) .then(fs.readFileAsync) .then(JSON.parse); // Listen for exception event to trigger promise cancellation process.on('unhandledException', function(event) { // cancel config loading p.cancel(); }); ``` Scoped prototypes ------------------ Building a library that depends on bluebird? You should know about the "scoped prototype" feature. If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains: ``` //NOTE the function call right after module.exports = require("bluebird/js/main/promise")(); ``` Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic. Async/Await ------------ © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/features.htmlError Explanations ================== * [Error: Promise.promisify called on an object](#error-promise.promisify-called-on-an-object) * [Error: the promise constructor requires a resolver function](#error-the-promise-constructor-requires-a-resolver-function) * [Error: the promise constructor cannot be invoked directly](#error-the-promise-constructor-cannot-be-invoked-directly) * [Error: expecting an array, a promise or a thenable](#error-expecting-an-array-a-promise-or-a-thenable) * [Error: generatorFunction must be a function](#error-generatorfunction-must-be-a-function) * [Error: fn must be a function](#error-fn-must-be-a-function) * [Error: cannot enable long stack traces after promises have been created](#error-cannot-enable-long-stack-traces-after-promises-have-been-created) * [Error: cannot get fulfillment value of a non-fulfilled promise](#error-cannot-get-fulfillment-value-of-a-non-fulfilled-promise) * [Error: cannot get rejection reason of a non-rejected promise](#error-cannot-get-rejection-reason-of-a-non-rejected-promise) * [Error: the target of promisifyAll must be an object or a function](#error-the-target-of-promisifyall-must-be-an-object-or-a-function) * [Error: circular promise resolution chain](#error-circular-promise-resolution-chain) * [Error: cannot await properties of a non-object](#error-cannot-await-properties-of-a-non-object) * [Error: expecting a positive integer](#error-expecting-a-positive-integer) * [Error: A value was yielded that could not be treated as a promise](#error-a-value-was-yielded-that-could-not-be-treated-as-a-promise) * [Error: cannot await properties of a non object](#error-cannot-await-properties-of-a-non-object) * [Error: Cannot promisify an API that has normal methods](#error-cannot-promisify-an-api-that-has-normal-methods) * [Error: Catch filter must inherit from Error or be a simple predicate function](#error-catch-filter-must-inherit-from-error-or-be-a-simple-predicate-function) * [Error: No async scheduler available](#error-no-async-scheduler-available) Error: Promise.promisify called on an object --------------------------------------------- You got this this error because you've used `Promise.promisify` on an object, for example: ``` var fs = Promise.promisify(require("fs")); ``` Instead, use [`Promise.promisifyAll`](api/promise.promisifyall) : ``` var fs = Promise.promisifyAll(require("fs")); ``` Error: the promise constructor requires a resolver function ------------------------------------------------------------ You got this error because you used `new Promise()` or `new Promise(something)` without passing a function as the parameter. If you want to wrap an API with a promise manually, the correct syntax is: ``` function wrapWithPromise(parameter) { return new Promise(function (resolve, reject) { doSomethingAsync({ error:reject, success:resolve }); }); } ``` Please consider reading about [`new Promise`](api/new-promise) and also consider checking out automatic [`promisification`](api/promisification) as well as [`Promise.method`](api/promise.method) Error: the promise constructor cannot be invoked directly ---------------------------------------------------------- You can get this error for several reasons: #### 1. You forgot to use `new` when creating a new promise using `new Promise(resolver)` syntax. This can happen when you tried to do something like: ``` return Promise(function(resolve,reject){ //... }) ``` You can correct this by doing: ``` return new Promise(function(resolve,reject){ //... }) ``` Please consider reading about [`new Promise`](api/new-promise) and also consider checking out automatic [`promisification`](api/promisification) as well as [`Promise.method`](api/promise.method) #### 2. You are trying to subclass `Promise` Bluebird does not support extending promises this way. Instead, see [scoped prototypes](features#scoped-prototypes). Error: expecting an array, a promise or a thenable --------------------------------------------------- The function being called expects a Promise, but is given something different. There are two main reasons why this may occur. **1. Working with collections (like arrays) but pass a single, non-collection element instead** Example: ``` function returnThree(){ return 3;} Promise.resolve(5).map(returnThree).then(function(val){ console.log("Hello Value!",val); }); ``` The `map` operation is expecting an array here (or a promise on one) and instead gets the number `5`. ``` function returnThree(){ return 3;} Promise.resolve([5]).map(returnThree).then(function(val){ console.log("Hello Value!",val); }); ``` `map` is given an array with a single element (see `[5]` instead of `5`), so this statement will work (but is bad practice). **2.`return` is forgotten in a 'fat' arrow / anonymous function call `=>`:** When debugging or performing a one-time operation on a variable before passing it to a function, a return variable is forgotten. Example: ``` function nextFunction(something){ return Promise.resolve(something*3); } myFunction() .then(result => nextFunction(result)); // We are implicitly returning a Promise ``` Debugging, we want to see the value of result, so we add a `console.log()` line: ``` function nextFunction(something){ return Promise.resolve(something*3); } myFunction().then(result => { console.log("Debug:", result); nextFunction(result)); // The chain is broken! We don't return anything to the .then() call }); ``` As this is an anonymous function call, we need to **return** something, which is not currently happening. To fix, simply remember to add `return` in front of your promise-complying function: ``` function nextFunction(something){ return Promise.resolve(something*3); } myFunction().then(result => { console.log("Debug:", result); return nextFunction(result)); // The anonymous function returns the function which returns the promise .then() needs }); ``` Error: generatorFunction must be a function -------------------------------------------- You are getting this error when trying to use [`Promise.coroutine`](api/promise.coroutine) and not passing it a generator function as a parameter. For example: ``` Promise.coroutine(function* () { // Note the * var data = yield $.get("http://www.example.com"); var moreUrls = data.split("\n"); var contents = []; for( var i = 0, len = moreUrls.length; i < len; ++i ) { contents.push(yield $.get(moreUrls[i])); } return contents; }); ``` Please refer to the relevant section in the documentation about [`Generators`](api/generators) in order to get usage instructions: **Note**: Bluebird used to eagerly check for generators which caused problems with transpilers. Because of this, you might get an error similar to `TypeError: Cannot read property 'next' of undefined` if you pass a function instead of a generator function to Bluebird. [`Promise.coroutine`](api/promise.coroutine) is built to work with generators to form C# like `async/await` Error: fn must be a function ----------------------------- You passed a non-function where a function was expected. Error: cannot enable long stack traces after promises have been created ------------------------------------------------------------------------ You are getting this error because you are enabling long stack traces after a promise has already been created. When using `longStackTraces` the first line in your code after requiring Bluebird should be: ``` Promise.config({ longStackTraces: true }); ``` See the API page about [`Promise.longStackTraces`](api/promise.longstacktraces) Error: cannot get fulfillment value of a non-fulfilled promise --------------------------------------------------------------- You can get this error when you're trying to call `.value` or `.error` when inspecting a promise where the promise has not been fulfilled or rejected yet. For example: ``` var p = Promise.delay(1000); p.inspect().value(); ``` Consider using [`.isPending()`](api/ispending) [`.isFulfilled()`](api/isfulfilled) and [`.isRejected()`](api/isrejected) in order to inspect the promise for status. Please consider reading more about [`synchronous inspection`](api/synchronous-inspection) Error: cannot get rejection reason of a non-rejected promise ------------------------------------------------------------- You can get this error when you're trying to call `.value` or `.error` when inspecting a promise where the promise has not been fulfilled or rejected yet. For example: ``` var p = Promise.delay(1000); p.inspect().value(); ``` Consider using [`.isPending()`](api/ispending) [`.isFulfilled()`](api/isfulfilled) and [`.isRejected()`](api/isrejected) in order to inspect the promise for status. Please consider reading more about [`synchronous inspection`](api/synchronous-inspection) Error: the target of promisifyAll must be an object or a function ------------------------------------------------------------------ This can happen when you are calling [`Promise.promisifyAll`](api/promise.promisifyall) on a function and invoking it instead of passing it. In general, the usage of [`Promise.promisifyAll`](api/promise.promisifyall) is along the lines of `var fs = Promise.promisifyAll(require("fs"))`. Consider reading the section about [`promisification`](api/promisification) Error: circular promise resolution chain ----------------------------------------- This usually happens when you have a promise that resolves or rejects with itself. For example: `var p = Promise.delay(100).then(function(){ return p});` . In this case, the promise resolves with itself which was is not intended. This also happens when implementing live-updating models with a `.then` method that indicates when the model is "ready". A promise is a process, it starts and it ends. Promises do not aim to solve such live updating problems directly. One option would be to use an intermediate promise - for example a `.loaded` property on the model that fulfills with nothing. resolving it with itself tells it "it is done when it is done" Error: cannot await properties of a non-object ----------------------------------------------- The `.props` method expects to receive an object. For example: ``` Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result){ console.log(result.tweets, result.pictures, result.comments); }); ``` This happens when a non object value or a promise that resolves with something that is not an object is being passed instead. Error: expecting a positive integer ------------------------------------ This happens when you call `.some` passing it a negative value or a non-integer. One possible cause is using `.indexOf` which returns `-1` when it doesn't find the value being searched for. Please consider reading the API docs for [`.some`](api/some) Error: A value was yielded that could not be treated as a promise ------------------------------------------------------------------ You are getting this error because you have tried to `yield` something in a coroutine without a yield handler, for example: ``` var coroutine = Promise.coroutine(function*(){ var bar = yield "Foo"; console.log(bar); }); ``` The solution is to either convert it to a promise by calling `Promise.resolve` on it or `Promise.promisify` if it's a callback: ``` var coroutine = Promise.coroutine(function*(){ var bar = yield Promise.resolve("Foo"); console.log(bar); }); ``` Or to use [`Promise.coroutine.addYieldHandler``](api/promise.coroutine.addyieldhandler) to teach [`Promise.coroutine`](api/promise.coroutine) to accept these sort of values. Error: cannot await properties of a non object ----------------------------------------------- The `.props` method expects to receive an object. For example: ``` Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result){ console.log(result.tweets, result.pictures, result.comments); }); ``` This happens when a non object value or a promise that resolves with something that is not an object is being passed instead. Error: Cannot promisify an API that has normal methods ------------------------------------------------------- This error indicates you have tried to call [`Promise.promisifyAll`](api/promise.promisifyall) on an object that already has a property with the `Async` suffix: ``` var myApi = { foo: function(cb){ ... }, fooAsync(cb) { ... } ``` This is because Bluebird adds the `Async` suffix to distinguish the original method from the promisified one, so `fooAsync` would have been overridden. In order to avoid this - either rename `fooAsync` before promisifying the API, or call [`Promise.promisify`](api/promise.promisify) manually on select properties. You may also use the custom suffix option to choose another suffix that doesn't result in conflicts. If you find this issue in a common library please [open an issue](https://github.com/petkaantonov/bluebird/issues/new). Error: Catch filter must inherit from Error or be a simple predicate function ------------------------------------------------------------------------------ Bluebird supports typed and predicate [`.catch()`](api/catch) calls]. However in order to use the typed/predicate catch syntax for error handling you must do one of two things. Pass it a constructor that inherits from `Error`: ``` }).catch(ReferenceError, function(e) { // this is fine }).catch(Array, function(e) { // arrays don't capture stack traces ``` This is to enable better stack trace support and to have more consistent and logical code. Alternatively, if you provide it a predicate be sure it's a simple function: ``` }).catch(function(e){ return false; }, function(e) { // this catches nothing }).catch(function(e){ return e.someProp = 5; }, function(e) { // this is fine ``` Please see the API docs of [`.catch()`](api/catch) on how to use predicate catches. Error: No async scheduler available ------------------------------------ Async scheduler is a function that takes a callback function and calls the callback function as soon as possible, but asynchronously. For example `setTimeout`. By default bluebird only tries a few common async schedulers, such as `setTimeout`, `process.nextTick` and `MutationObserver`. However if your JavaScript runtime environment doesn't expose any of these, you will see this error. You may use [`Promise.setScheduler`](api/promise.setscheduler) to pass a custom scheduler that your environment supports. For example in DukTape: ``` Promise.setScheduler(function(fn){ // fn is what to execute var timer = uv.new_timer.call({}); uv.timer_start(timer, 0, 0, fn); // add the function as a callback to the timer }); ``` © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/error-explanations.htmlComing from Other Libraries =========================== This page is a reference for migrating to bluebird from other flow control or promise libraries. See [installation](install) on how to use bluebird in your environment. * [Coming from native promises](#coming-from-native-promises) * [Coming from jQuery deferreds](#coming-from-jquery-deferreds) * [Coming from `async` module](#coming-from-async-module) * [Coming from Q](#coming-from-q) * [Coming from co/koa](#coming-from-co) * [Coming from highland, RxJS or BaconJS](#coming-from-highland) Coming from native promises ---------------------------- Bluebird promises are a drop-in replacement for native promises except for subclassing. Additionally you might want to replace usages of the often incorrectly used [`Promise.race`](api/promise.race) with bluebird's [`Promise.any`](api/promise.any) which does what is usually mistakenly expected from [`Promise.race`](api/promise.race). For maximum compatibility, bluebird does provide [`Promise.race`](api/promise.race) with ES6 semantics. You can also refactor some looping patterns to a more natural form that would [leak memory when using native promises](https://github.com/promises-aplus/promises-spec/issues/179). Coming from jQuery deferreds ----------------------------- Bluebird treats jQuery deferreds and promises interchangeably. Wherever you can take a promise or return a promise, you can take or return a jQuery deferred instead and it works the same. For instance, there is no need to write something like this: ``` var firstRequest = new Promise(function(resolve, reject) { $.ajax({...}).done(resolve).fail(reject); }); var secondRequest = new Promise(function(resolve, reject) { $.ajax({...}).done(resolve).fail(reject); }); Promise.all([firstRequest, secondRequest]).then(function() { // ... }); ``` Since [`Promise.all`](api/promise.all) takes promises, it must also take jQuery deferreds, so the above can be shortened to: ``` var firstRequest = $.ajax({...}); var secondRequest = $.ajax({...}); Promise.all([firstRequest, secondRequest]).then(function() { // ... }); ``` That said, if you have code written using jQuery deferred methods, such as `.then`, `.done` and so on, you cannot drop-in replace the jQuery deferred with a bluebird promise in that code. Despite having the same names, jQuery deferred methods have different semantics than bluebird promise methods. These differences are due to the completely different goals of the implementations. Bluebird is [an internal DSL](http://en.wikipedia.org/wiki/Domain-specific_language) for the domain of asynchronous control flow while jQuery deferreds are a callback aggregator utility ("glorified event emitters"). If you do have some code using jQuery deferred methods extensively try to see if some of these jQuery deferred patterns and their replacements can be applied: ``` // jQuery $.when.apply($, someArray).then(...) // bluebird Promise.all(someArray).then(...) ``` ``` // jQuery var data = [1,2,3,4]; var processItemsDeferred = []; for(var i = 0; i < data.length; i++) { processItemsDeferred.push(processItem(data[i])); } $.when.apply($, processItemsDeferred).then(everythingDone); // bluebird var data = [1,2,3,4]; Promise.map(data, function(item) { return processItem(item); }).then(everythingDone); ``` ``` // jQuery var d = $.Deferred(); d.resolve("value"); // bluebird var d = Promise.resolve("value"); ``` ``` // jQuery var d = $.Deferred(); d.reject(new Error("error")); // bluebird var d = Promise.reject(new Error("error")); ``` ``` // jQuery var clicked = $.Deferred(); $("body").one("click", function(e) { clicked.resolve(e); }); // bluebird var clicked = new Promise(function(resolve) { $("body").one("click", resolve); }); ``` ``` // jQuery .always(removeSpinner); // bluebird .finally(removeSpinner); ``` Coming from `async` module --------------------------- When working with promises the philosophy is basically a complete opposite than when using `async`. Async provides a huge bag of uncomposable helper functions that work at a very low level of abstraction. When using promises you can get the utility otherwise provided by uncountable amount of inflexible helper functions by just combining and composing a few existing functions and concepts. That means when you have a problem there probably isn't an existing function tailored exactly to that problem but instead you can just combine the existing utilities to arrive at a solution. The upside of this is that you don't need to come up with all these different functions to solve problems that are not that different from each other. The most important thing to do when migrating from async to bluebird is this profound shift in philosophy. This section lists the most common async module replacements. ### `async.waterfall` If the waterfall elements are static, you can just replace it with a normal promise chain. For waterfalls with dynamic steps, use [`Promise.each`](api/promise.each). Multiple arguments can be ferried in an array. Implementing the example from [async homepage](https://github.com/caolan/async#waterfalltasks-callback) ``` async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); }, function(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' }); ``` Since the array passed to waterfall is static (always the same 3 functions) a plain old promise chain is used: ``` Promise.resolve(['one', 'two']).spread(function(arg1, arg2) { // arg1 now equals 'one' and arg2 now equals 'two' return 'three'; }).then(function(arg1) { // arg1 now equals 'three' return 'done'; }).then(function(result) { // result now equals 'done' }); ``` If destructuring parameters are supported, `.spread(function(arg1, arg2) {})` can be replaced with `.then(function([arg1, arg2]){})`. ### `async.series` Using [`Promise.mapSeries`](api/promise.mapseries) to implement the example from [async homepage](https://github.com/caolan/async#seriestasks-callback): ``` async.series([ function(callback){ setTimeout(function(){ callback(null, 1); }, 200); }, function(callback){ setTimeout(function(){ callback(null, 2); }, 100); } ], // optional callback function(err, results){ // results is now equal to [1, 2] }); ``` ``` Promise.mapSeries([{timeout: 200, value: 1}, {timeout: 100, value: 2}], function(item) { return Promise.delay(item.timeout, item.value); }).then(function(results) { // results is now equal to [1, 2] }); ``` ### `async.parallel` Using [`Promise.all`](api/promise.all) to implement the example from [async homepage](https://github.com/caolan/async#parallel): ``` async.parallel([ function(callback){ setTimeout(function(){ callback(null, 'one'); }, 200); }, function(callback){ setTimeout(function(){ callback(null, 'two'); }, 100); } ], // optional callback function(err, results){ // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }); ``` ``` Promise.all([Promise.delay(200, 'one'), Promise.delay(100, 'two')]).then(function(results) { // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }); ``` ### `async.mapSeries` Using [`Promise.each`](api/promise.each) to implement the example from [async homepage](https://github.com/caolan/async#maparr-iterator-callback): ``` var fs = require('fs'); async.mapSeries(['file1','file2','file3'], fs.stat, function(err, results){ // results is now an array of stats for each file }); ``` ``` var fs = Promise.promisifyAll(require('fs')); Promise.each(['file1','file2','file3'], function(fileName, index, length) { return fs.statAsync(fileName); }).then(function(results) { // results is now an array of stats for each file }); ``` ### `async.map` Using [`Promise.map`](api/promise.map) to implement the example from [async homepage](https://github.com/caolan/async#maparr-iterator-callback): ``` var fs = require('fs'); async.map(['file1','file2','file3'], fs.stat, function(err, results){ // results is now an array of stats for each file }); ``` ``` var fs = Promise.promisifyAll(require('fs')); Promise.map(['file1','file2','file3'], function(fileName, index, length) { return fs.statAsync(fileName); }).then(function(results) { // results is now an array of stats for each file }); ``` ### `async.whilst` Using recursion to implement the example from [async homepage](https://github.com/caolan/async#whilsttest-fn-callback): ``` var count = 0; async.whilst( function () { return count < 5; }, function (callback) { count++; setTimeout(callback, 1000); }, function (err) { // 5 seconds have passed } ); ``` ``` (function loop() { if (count < 5) { count++; return Promise.delay(1000).then(loop); } return Promise.resolve(); })().then(function() { // 5 seconds have passed }); ``` Be warned that the above example implementations are only superficially equivalent. Callbacks, even with the help of async, require too much boilerplate code to provide the same guarantees as promises. Coming from Q -------------- Q and bluebird share a lot of common methods that nevertheless have different names: * `Q(...)` -> [`Promise.resolve()`](api/promise.resolve) * `.fail()` -> [`.catch()`](api/catch) or `.caught()` * `.fin()` -> [`.finally()`](api/finally) or `.lastly()` * `Q.fcall()` -> [`Promise.try`](api/promise.try) or `Promise.attempt()` * `.thenResolve()` -> [`.return()`](api/return) or `.thenReturn()` * `.thenReject()` -> [`.throw()`](api/throw) or `thenThrow()` Coming from co/koa ------------------- In recent versions generator libraries started abandoning old ideas of special tokens passed to callbacks and started using promises for what's being yielded. Bluebird's [`Promise.coroutine`](api/promise.coroutine) is a superset of the `co` library, being more extensible as well as supporting cancellation (in environments where [`Generator#return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return) is implemented). Coming from highland, RxJS or BaconJS -------------------------------------- Stream libraries tend to serve a different purpose than promise libraries. Unlike promise libraries streams can represent multiple values. Check out the benchmarks section for examples of transitioning an API from Bacon/Rx to promises. © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/coming-from-other-libraries.html.then ====== ``` .then( [function(any value) fulfilledHandler], [function(any error) rejectedHandler] ) -> Promise ``` [Promises/A+ `.then`](http://promises-aplus.github.io/promises-spec/). If you are new to promises, see the [Beginner's Guide](../beginners-guide). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/then.html.spread ======== ``` .spread( [function(any values...) fulfilledHandler] ) -> Promise ``` Like calling `.then`, but the fulfillment value *must be* an array, which is flattened to the formal parameters of the fulfillment handler. ``` Promise.all([ fs.readFileAsync("file1.txt"), fs.readFileAsync("file2.txt") ]).spread(function(file1text, file2text) { if (file1text === file2text) { console.log("files are equal"); } else { console.log("files are not equal"); } }); ``` When chaining `.spread`, returning an array of promises also works: ``` Promise.delay(500).then(function() { return [fs.readFileAsync("file1.txt"), fs.readFileAsync("file2.txt")] ; }).spread(function(file1text, file2text) { if (file1text === file2text) { console.log("files are equal"); } else { console.log("files are not equal"); } }); ``` Note that if using ES6, the above can be replaced with [`.then()`](then) and destructuring: ``` Promise.delay(500).then(function() { return [fs.readFileAsync("file1.txt"), fs.readFileAsync("file2.txt")] ; }).all().then(function([file1text, file2text]) { if (file1text === file2text) { console.log("files are equal"); } else { console.log("files are not equal"); } }); ``` Note that [`.spread()`](spread) implicitly does [`.all()`](all) but the ES6 destructuring syntax doesn't, hence the manual `.all()` call in the above code. If you want to coordinate several discrete concurrent promises, use [`Promise.join`](promise.join) Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/spread.html.error ======= ``` .error([function(any error) rejectedHandler]) -> Promise ``` Like [`.catch`](catch) but instead of catching all types of exceptions, it only catches operational errors. *Note, "errors" mean errors, as in objects that are `instanceof Error` - not strings, numbers and so on. See [a string is not an error](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/).* It is equivalent to the following [`.catch`](catch) pattern: ``` // Assumes OperationalError has been made global function isOperationalError(e) { if (e == null) return false; return (e instanceof OperationalError) || (e.isOperational === true); } // Now this bit: .catch(isOperationalError, function(e) { // ... }) // Is equivalent to: .error(function(e) { // ... }); ``` For example, if a promisified function errbacks the node-style callback with an error, that could be caught with [`.error`](error). However if the node-style callback **throws** an error, only `.catch` would catch that. In the following example you might want to handle just the `SyntaxError` from JSON.parse and Filesystem errors from `fs` but let programmer errors bubble as unhandled rejections: ``` var fs = Promise.promisifyAll(require("fs")); fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { console.log("Successful json") }).catch(SyntaxError, function (e) { console.error("file contains invalid json"); }).error(function (e) { console.error("unable to read file, because: ", e.message); }); ``` Now, because there is no catch-all handler, if you typed `console.lag` (causes an error you don't expect), you will see: ``` Possibly unhandled TypeError: Object #<Console> has no method 'lag' at application.js:8:13 From previous event: at Object.<anonymous> (application.js:7:4) at Module._compile (module.js:449:26) at Object.Module._extensions..js (module.js:467:10) at Module.load (module.js:349:32) at Function.Module._load (module.js:305:12) at Function.Module.runMain (module.js:490:10) at startup (node.js:121:16) at node.js:761:3 ``` *( If you don't get the above - you need to enable [long stack traces](promise.config) )* And if the file contains invalid JSON: ``` file contains invalid json ``` And if the `fs` module causes an error like file not found: ``` unable to read file, because: ENOENT, open 'not_there.txt' ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/error.html.bind ====== ``` .bind(any|Promise<any> thisArg) -> BoundPromise ``` Same as calling [`Promise.bind(thisArg, thisPromise)`](promise.bind). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/bind.htmlPromise.try ============ ``` Promise.try(function() fn) -> Promise ``` ``` Promise.attempt(function() fn) -> Promise ``` Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. ``` function getUserById(id) { return Promise.try(function() { if (typeof id !== "number") { throw new Error("id must be a number"); } return db.getUserById(id); }); } ``` Now if someone uses this function, they will catch all errors in their Promise `.catch` handlers instead of having to handle both synchronous and asynchronous exception flows. *For compatibility with earlier ECMAScript version, an alias `Promise.attempt` is provided for [`Promise.try`](promise.try).* Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.try.htmlAsync Dialogs ============= > This article is partially or completely unfinished. You are welcome to create [pull requests](https://github.com/petkaantonov/bluebird/edit/master/docs/docs/async-dialogs.md) to help completing this article. Typically *promises* are used in conjunction with asynchronous tasks such as a network request or a `setTimeout`; a lesser explored use is dealing with user input. Since a program has to wait for a user to continue some actions it makes sense to consider it an asynchronous event. For comparison I'll start with an example of a *synchronous* user interaction using `window.prompt` and then move to an *asynchronous* interaction by making our own DOM based prompt. To begin, here is a template for a simple HTML page: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Async Dislogs Example</title> <script src="//cdn.jsdelivr.net/bluebird/3.7.2/bluebird.js"></script> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { var time = document.getElementById('time-stamp'); clockTick(); setInterval(clockTick, 1000); function clockTick() { time.innerHTML = new Date().toLocaleTimeString(); } }); </script> </head> <body> <p>The current time is <span id="time-stamp"></span>.</p> <p>Your name is <span id="prompt"></span>.</p> <button id="action">Set Name</button> </body> </html``` `window.prompt` blocks the web page from processing while it waits for the user to enter in data. It has to block because the input is returned and the next line of code needs that result. But for sake of this tutorial we are going to convert the typical conditional code into a promise API using a [promise constructor](api/new-promise). ``` function promptPromise(message) { return new Promise(function(resolve, reject) { var result = window.prompt(message); if (result != null) { resolve(result); } else { reject(new Error('User cancelled')); } }); } var button = document.getElementById('action'); var output = document.getElementById('prompt'); button.addEventListener('click', function() { promptPromise('What is your name?') .then(function(name) { output.innerHTML = String(name); }) .catch(function() { output.innerHTML = '¯\_(ツ)_/¯'; }); }); ``` [Run example on JSBin](http://jsbin.com/kowama/edit?js,output) This doesn't add much much using `window.prompt`; however, one advantage is the API that promises provide. In the case where we call `promptPromise(…)` we can easily react to the result of the dialog without having to worry about how it is implemented. In our example we've implemented the `window.prompt` but our call to `promptPromise()` doesn't care. This makes a change to an *asynchronous* dialog a little more future proof. To drive home the synchronous nature of the `window.prompt` notice that the time stops ticking when the prompt dialog is displayed. Let's fix that by making our own prompt. Since our dialog is just DOM manipulation the page won't be blocked while waiting for user input. First add the prompt dialog to the HTML: ``` <style type="text/css"> #dialog { width: 200px; margin: auto; padding: 10px; border: thin solid black; background: lightgreen; } .hidden { display: none; } </style> <div id="dialog" class="hidden"> <div class="message">foobar</div> <input type="text"> <div> <button class="ok">Ok</button> <button class="cancel">Cancel</button> </div> </div``` We will want to keep the same API so our change will be only to the `promisePrompt`. It will find the dialog DOM elements, attach events to the elements, show the dialog box, return a promise that is resolved based on the attached events, and finally detaches the events and cleans up after itself (hiding the dialog box for another use later). ``` function promptPromise(message) { var dialog = document.getElementById('dialog'); var input = dialog.querySelector('input'); var okButton = dialog.querySelector('button.ok'); var cancelButton = dialog.querySelector('button.cancel'); dialog.querySelector('.message').innerHTML = String(message); dialog.className = ''; return new Promise(function(resolve, reject) { dialog.addEventListener('click', function handleButtonClicks(e) { if (e.target.tagName !== 'BUTTON') { return; } dialog.removeEventListener('click', handleButtonClicks); dialog.className = 'hidden'; if (e.target === okButton) { resolve(input.value); } else { reject(new Error('User cancelled')); } }); }); } ``` [Run example on JSBin](http://jsbin.com/fucofu/edit?js,output) Now when the user presses the **Set Name** button the clock continues to update while the dialog is visible. Because the `removeEventListener` requires a reference to the original function that was used with the `addEventListener` it makes it difficult to clean up after itself without storing the references in a scope higher then the handler itself. Using a named function we can reference it when a user clicks the button. To help with performance and to avoid duplicating code the example uses [event delegation](https://davidwalsh.name/event-delegate) to capture both buttons in one *click* handler. The same thing can be done with less code using jQuery's [event namespacing](https://api.jquery.com/on/#event-names). ``` return new Promise(function(resolve, reject) { $('#okButton').on('click.promptDialog', function() { resolve(input.value); }); $('#cancelButton').on('click.promptDialog', reject); }) .finally(function() { $('#okButton').off('click.promptDialog'); $('#cancelButton').off('click.promptDialog'); }); ``` There are still a few problems with the earlier code example. It feels like it is doing too much. A *squint* test reveals behavior for showing the dialog, set the dialog's message, attach two DOM events, construct a promise, event delegation, hide the dialog, and finally detach DOM events. That is a lot for one little function. A refactoring can help. Abstraction is the key here. We will make an *object* (or class) that is responsible for managing the dialog box. Its interface will manage only two function references (callbacks): when the user clicks ok and when user clicks cancel. And it will offer the value when asked. Using an abstraction like this the `promisePrompt` no longer needs to know anything about the DOM and concentrates on just providing a promise. This will also make things easier to create a promised version of a progress bar or confirmation dialog or any other type of UI that we want to have a value for. All we will need to do is write a class for that dialog type with the same interface and just pass that class into our promise making method. The dialog interface might look like this: ``` var noop = function() { return this; }; function Dialog() { this.setCallbacks(noop, noop); } Dialog.prototype.setCallbacks = function(okCallback, cancelCallback) { this._okCallback = okCallback; this._cancelCallback = cancelCallback; return this; }; Dialog.prototype.waitForUser = function() { var _this = this; return new Promise(function(resolve, reject) { _this.setCallbacks(resolve, reject); }); }; Dialog.prototype.show = noop; Dialog.prototype.hide = noop; ``` Initially the Dialog class sets the two callbacks to *noop* functions. It is up to the child class to call them when necessary. We break down the promise creation to one function `waitForUser()` that sets the callbacks and returns a promise. At this level the `show()` and `hide()` are just *noop* functions as well and will be implemented by the child classes. Our `PromptDialog` class is responsible for inheriting from `Dialog` and setting up the required DOM scaffolding and eventually call `this._okCallback` or `this._cancelCallback` as appropriate. It might look like this: ``` function PromptDialog() { Dialog.call(this); this.el = document.getElementById('dialog'); this.inputEl = this.el.querySelector('input'); this.messageEl = this.el.querySelector('.message'); this.okButton = this.el.querySelector('button.ok'); this.cancelButton = this.el.querySelector('button.cancel'); this.attachDomEvents(); } PromptDialog.prototype = Object.create(Dialog.prototype); PromptDialog.prototype.attachDomEvents = function() { var _this = this; this.okButton.addEventListener('click', function() { _this._okCallback(_this.inputEl.value); }); this.cancelButton.addEventListener('click', function() { _this._cancelCallback(); }); }; PromptDialog.prototype.show = function(message) { this.messageEl.innerHTML = String(message); this.el.className = ''; return this; }; PromptDialog.prototype.hide = function() { this.el.className = 'hidden'; return this; }; ``` Notice that use of `return this;` in most of the functions? That pattern will allow method chaining as you'll see shortly. This inherits from `Dialog` and stores references to the required DOM elements that this dialog uses. It then attaches the require DOM events (`attachDomEvents()`) which eventually call the callbacks. Then it implements the `show()` and `hide()` methods. Its usage is more flexible and verbose: ``` var output = document.getElementById('prompt'); var prompt = new PromptDialog(); prompt.show('What is your name?') .waitForUser() .then(function(name) { output.innerHTML = String(name); }) .catch(function() { output.innerHTML = '¯\_(ツ)_/¯'; }) .finally(function() { prompt.hide(); }); ``` [Run example on JSBin](http://jsbin.com/wupixi/edit?js,output) This abstraction can be expanded on in other ways. For example a notification dialog: ``` function NotifyDialog() { Dialog.call(this); var _this = this; this.el = document.getElementById('notify-dialog'); this.messageEl = this.el.querySelector('.message'); this.okButton = this.el.querySelector('button.ok'); this.okButton.addEventListener('click', function() { _this._okCallback(); }); } NotifyDialog.prototype = Object.create(Dialog.prototype); NotifyDialog.prototype.show = function(message) { this.messageEl.innerHTML = String(message); this.el.className = ''; return this; }; NotifyDialog.prototype.show = function() { this.el.className = 'hidden'; return this; }; ``` #### Exercises for the student 1. Write a function that takes a `Dialog` instance and a default value. Have it return a promise that resolves to the default value if the user clicks cancel. 2. With the use of abstract classes can the similarities between `PromptDialog` and `NotifyDialog` be abstracted? Make a sub class of `Dialog` that abstracts the common DOM code (`DOMDialog`). Then refactor the `PromptDialog` and `NotifyDialog` to inherate from `DOMDialog` but references the correct DOM selectors. Cancellation ------------- Something missing from the above example is proper error handling. When it comes to promises it is a best practise to always *reject a promise with an Error* and not with plain data such as an object, string, number, or null/undefined. The reasoning for this is promises are best used as a way to regain some of the syntax you have with the standard `try {} catch() {}` blocks with asynchronous code. An advantage of using `Error`s is the ability to test why a promise was rejected and make decisions on that. This ability is also baked into how Bluebird works. You can pass in a predicate to the `catch()` block allowing you to have more than one block based on what `Error` it was rejected with. For example: ``` doSomething().then(function(value) { // Do something with value or fail with an error. throw new Error('testing errors'); }) .catch(ArgumentError, function(e) { console.log('You buggered up something with the arguments.', e); }) .catch(SyntaxError, function(e) { console.log('Check your syntax!', e); }) .catch(function(e) { // e is an Error object. console.log('Well something genaric happened.', e); }); ``` In our dialog example perhaps we want to differentiate between a rejected promise because of some problem (bad AJAX, programming error, etc.) or because the user pressed the cancel button. To do this we will have two `catch()` functions one for `UserCanceledError` and one for any other `Error`. We can make a custom error like so: ``` function UserCanceledError() { this.name = 'UserCanceledError'; this.message = 'Dialog cancelled'; } UserCanceledError.prototype = Object.create(Error.prototype); ``` See [this StackOverflow answer](http://stackoverflow.com/a/17891099/227176) for a more detailed and feature complete way to make custom errors. Now we can add a `cancel()` reject with this in our event listener: ``` Dialog.prototype.cancel = function() { this._cancelCallback(new UserCanceledError()); }; … PromptDialog.prototype.attachDomEvents = function() { var _this = this; this.okButton.addEventListener('click', function() { _this._okCallback(_this.inputEl.value); }); this.cancelButton.addEventListener('click', function() { _this.cancel(); }); }; ``` And in our usage case we can test for it: ``` // Timeout the dialog in five seconds. setTimeout(function() { prompt.cancel(); }, 5000); prompt.show('What is your name?') .waitForUser() .then(function(name) { output.innerHTML = String(name); }) .catch(UserCanceledError, function() { output.innerHTML = '¯\_(ツ)_/¯'; }) .catch(function(e) { console.log('Something bad happened!', e); }) .finally(function() { prompt.hide(); }); ``` [Run example on JSBin](http://jsbin.com/yaropo/edit?js,output) **NOTE:** Bluebird supports [cancellation](api/cancellation) as an optional feature that is turned off by default. However, its implementation (since version 3.0) is meant to stop the then and catch callbacks from firing. It is not helpful in the example of a user cancellation as described here. Progress bar ------------- When there are asynchronous tasks that have the ability to notify progress as they complete it can be tempting to want that in the promise that represents that task. Unfortunately this is a bit of an anti-pattern. That is because the point of promises is to represent a value as if it was natural (like it is in normal synchronous code) and not to be over glorified callback management. So how then could we represent a progress bar like dialog? Well the answer is to manage the progress through callbacks outside the promise API. Bluebird has since [deprecated the progression feature](deprecated-apis#progression) and offers an alternative which I hope to illustrate here. Another key difference between a *progress bar* dialog and any other dialog we've discussed here is that a progress bar represents information on another task and *not* user import. Instead of the program waiting for the user to provide a value the dialog box is waiting on the program to provide a value (resolved: 100% complete, rejected: aborted half way through). Because of this the *progress bar* dialog would have a different interface then the previous dialogs we've covered. However, there can still be some user interaction so in essence we are dealing with two promises. Bluebird has a way to manage more than one promise simultaneously. When you want to know if more then one promise completes there is a `Promise.all()` function that takes an array of promises and returns a new promise waiting for them all to resolve. But if any one is rejected the returned promise is immediately rejected. Bluebird also has a `Promise.race()` function which does the same thing but doesn't wait for all of them to finish. That is what we want. An example how this might look: ``` function showProgress(otherPromise) { var progress = new ProgressbarDialog().show('Uploading…'); return Promise.race([otherPromise, promise.waitForUser()]) .finally(function() { progress.hide(); }); } ``` Here is some example HTML for the Progress Dialog: ``` <style type="text/css"> #progress-dialog { width: 200px; margin: auto; border: thin solid black; padding: 10px; background: lightgreen; } #progress-dialog .progress-bar { border: 1px solid black; margin: 10px auto; padding: 0; height: 20px; } #progress-dialog .progress-bar>div { background-color: blue; margin: 0; padding: 0; border: none; height: 20px; } </style> <div id="progress-dialog"> <div class="message"></div> <div class="progress-bar"><div></div></div> <div> <button class="cancel">Cancel</button> </div> </div``` The JavaScript is the same as the `PromptDialog` only we will add a `setProgress()` method: ``` function ProgressDialog() { Dialog.call(this); this.el = document.getElementById('progress-dialog'); this.messageEl = this.el.querySelector('.message'); this.progressBar = this.el.querySelector('.progress-bar>div'); this.cancelButton = this.el.querySelector('button.cancel'); this.attachDomEvents(); } ProgressDialog.prototype = Object.create(Dialog.prototype); ProgressDialog.prototype.attachDomEvents = function() { var _this = this; this.cancelButton.addEventListener('click', function() { _this.cancel(); }); }; ProgressDialog.prototype.show = function(message) { this.messageEl.innerHTML = String(message); this.el.className = ''; return this; }; ProgressDialog.prototype.hide = function() { this.el.className = 'hidden'; return this; }; ProgressDialog.prototype.setProgress = function(percent) { this.progressBar.style.width = percent + '%'; }; ``` A common misconception is that promises are a form of callback management. This is not the case and is why the idea of having a progress callback is not part of the Promise spec. However, much like the Promise library passes in a `resolve` and `reject` callback when you create a new promise (`new Promise(…)`) we can do the same patter for a progress callback. Now to the fun part. For this tutorial we will *fake* a lengthy file upload by using `setTimeout`. The intent is to provide a promise and to allow a progress to be periodically ticked away. We will expect a function to be passed which is called whenever the progress needs updating. And it returns a promise. ``` function delayedPromise(progressCallback) { var step = 10; return new Promise(function(resolve, reject) { var progress = 0 - step; // So first run of nextTick will set progress to 0 function nextTick() { if (progress >= 100 ) { resolve('done'); } else { progress += step; progressCallback(progress); setTimeout(nextTick, 500); } } nextTick(); }); } ``` When we construct our `ProgressDialog` we use the `waitForUser()` method to capture the user interaction promise and then use `delayedPromise()` to capture the fake network promise and finally `Promise.reace()` to manage the two simultaneously and end with a single promise as usual. ``` document.addEventListener('DOMContentLoaded', function() { var button = document.getElementById('action'); var output = document.getElementById('output'); var prompt = new ProgressDialog(); button.addEventListener('click', function() { var pendingProgress = true; var waitForPromise = delayedPromise(function(progress) { if (pendingProgress) { prompt.setProgress(progress); } }); // Prevent user from pressing button while dialog is visible. button.disabled = true; prompt.show('Simulating a file upload.'); Promise.race([waitForPromise, prompt.waitForUser()]) .then(function() { output.innerHTML = 'Progress completed'; }) .catch(UserCanceledError, function() { output.innerHTML = 'Progress canceled by user'; }) .catch(function(e) { console.log('Error', e); }) .finally(function() { pendingProgress = false; button.disabled = false; prompt.hide(); }); }); }); ``` [Run example on JSBin](http://jsbin.com/bipeve/edit?js,output) I hope this helps illustrate some concepts available with Promises and a different perspective on how promises can represent more then just AJAX data. Although the code may look verbose it does provide the benefit that it is modular and can be easily changed. A trait difficult to achieve with a more procedural style. Happy coding, [@sukima](https://github.com/sukima). © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/async-dialogs.htmlWorking with Callbacks ====================== This page explains how to interface your code with existing callback APIs and libraries you're using. We'll see that making bluebird work with callback APIs is not only easy - it's also fast. We'll cover several subjects. If you want to get the tl;dr what you need is likely the [Working with callback APIs using the Node convention](#working-with-callback-apis-using-the-node-convention) section. First to make sure we're on the same page: Promises have state, they start as pending and can settle to: * **fulfilled** meaning that the computation completed successfully. * **rejected** meaning that the computation failed. Promise returning functions *should never throw*, they should always successfully return a promise which is rejected in the case of an error. Throwing from a promise returning function will force you to use both a `} catch {` *and* a `.catch`. People using promisified APIs do not expect promises to throw. If you're not sure how async APIs work in JS - please [see this answer](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/16825593#16825593) first. * [Automatic vs. Manual conversion](#automatic-vs.-manual-conversion) * [Working with callback APIs using the Node convention](#working-with-callback-apis-using-the-node-convention) * [Working with one time events.](#working-with-one-time-events) * [Working with delays](#working-with-delays/setTimeout) * [Working with browser APIs](#working-with-browser-apis) * [Working with databases](#working-with-databases) * [More Common Examples](#more-common-examples) * [Working with any other APIs](#working-with-any-other-apis) There is also [this more general StackOverflow question](http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) about conversion of callback APIs to promises. If you find anything missing in this guide however, please do open an issue or pull request. ### Automatic vs. Manual conversion There are two primary methods of converting callback based APIs into promise based ones. You can either manually map the API calls to promise returning functions or you can let the bluebird do it for you. We **strongly** recommend the latter. Promises provide a lot of really cool and powerful guarantees like throw safety which are hard to provide when manually converting APIs to use promises. Thus, whenever it is possible to use the `Promise.promisify` and `Promise.promisifyAll` methods - we recommend you use them. Not only are they the safest form of conversion - they also use techniques of dynamic recompilation to introduce very little overhead. ### Working with callback APIs using the Node convention In Node/io.js most APIs follow a convention of ['error-first, single-parameter'](https://gist.github.com/CrabDude/10907185) as such: ``` function getStuff(data, callback) { ... } getStuff("dataParam", function(err, data) { if (!err) { } }); ``` This APIs are what most core modules in Node/io use and bluebird comes with a fast and efficient way to convert them to promise based APIs through the `Promise.promisify` and `Promise.promisifyAll` function calls. * [`Promise.promisify`](api/promise.promisify) - converts a *single* callback taking function into a promise returning function. It does not alter the original function and returns the modified version. * [`Promise.promisifyAll`](api/promise.promisifyall) - takes an *object* full of functions and *converts each function* into the new one with the `Async` suffix (by default). It does not change the original functions but instead adds new ones. > **Note** - please check the linked docs for more parameters and usage examples. Here's an example of `fs.readFile` with or without promises: ``` // callbacks var fs = require("fs"); fs.readFile("name", "utf8", function(err, data) { }); ``` Promises: ``` var fs = Promise.promisifyAll(require("fs")); fs.readFileAsync("name", "utf8").then(function(data) { }); ``` Note the new method is suffixed with `Async`, as in `fs.readFileAsync`. It did not replace the `fs.readFile` function. Single functions can also be promisified for example: ``` var request = Promise.promisify(require("request")); request("foo.bar").then(function(result) { }); ``` > **Note** `Promise.promisify` and `Promise.promisifyAll` use dynamic recompilation for really fast wrappers and thus calling them should be done only once. [`Promise.fromCallback`](api/promise.fromcallback) exists for cases where this is not possible. ### Working with one time events Sometimes we want to find out when a single one time event has finished. For example - a stream is done. For this we can use [`new Promise`](api/new-promise). Note that this option should be considered only if [automatic conversion](#working-with-callback-apis-using-the-node-convention) isn't possible. Note that promises model a *single value through time*, they only resolve *once* - so while they're a good fit for a single event, they are not recommended for multiple event APIs. For example, let's say you have a window `onload` event you want to bind to. We can use the promise construction and resolve when the window has loaded as such: ``` // onload example, the promise constructor takes a // 'resolver' function that tells the promise when // to resolve and fire off its `then` handlers. var loaded = new Promise(function(resolve, reject) { window.addEventListener("load", resolve); }); loaded.then(function() { // window is loaded here }); ``` Here is another example with an API that lets us know when a connection is ready. The attempt here is imperfect and we'll describe why soon: ``` function connect() { var connection = myConnector.getConnection(); // Synchronous. return new Promise(function(resolve, reject) { connection.on("ready", function() { // When a connection has been established // mark the promise as fulfilled. resolve(connection); }); connection.on("error", function(e) { // If it failed connecting, mark it // as rejected. reject(e); // e is preferably an `Error`. }); }); } ``` The problem with the above is that `getConnection` itself might throw for some reason and if it does we'll get a synchronous rejection. An asynchronous operation should always be asynchronous to prevent double guarding and race conditions so it's best to always put the sync parts inside the promise constructor as such: ``` function connect() { return new Promise(function(resolve, reject) { // If getConnection throws here instead of getting // an exception we're getting a rejection thus // producing a much more consistent API. var connection = myConnector.getConnection(); connection.on("ready", function() { // When a connection has been established // mark the promise as fulfilled. resolve(connection); }); connection.on("error", function(e) { // If it failed connecting, mark it // as rejected. reject(e); // e is preferably an `Error` }); }); } ``` ### Working with delays/setTimeout There is no need to convert timeouts/delays to a bluebird API, bluebird already ships with the [`Promise.delay`](api/promise.delay) function for this use case. Please consult the [`timers`](api/timers) section of the docs on usage and examples. ### Working with browser APIs Often browser APIs are nonstandard and automatic promisification will fail for them. If you're running into an API that you can't promisify with [`promisify`](api/promisify) and [`promisifyAll`](api/promisifyall) - please consult the [working with other APIs section](#working-with-any-other-apis) ### Working with databases For resource management in general and databases in particular, bluebird includes the powerful [`Promise.using`](api/promise.using) and disposers system. This is similar to `with` in Python, `using` in C#, try/resource in Java or RAII in C++ in that it lets you handle resource management in an automatic way. Several examples of databases follow. > **Note** for more examples please see the [`Promise.using`](api/promise.using) section. #### Mongoose/MongoDB Mongoose works with persistent connections and the driver takes care of reconnections/disposals. For this reason using `using` with it isn't required - instead connect on server startup and use promisification to expose promises. Note that Mongoose already ships with promise support but the promises it offers are significantly slower and don't report unhandled rejections so it is recommended to use automatic promisification with it anyway: ``` var Mongoose = Promise.promisifyAll(require("mongoose")); ``` #### Sequelize Sequelize already uses Bluebird promises internally and has promise returning APIs. Use those. #### RethinkDB Rethink already uses Bluebird promises internally and has promise returning APIs. Use those. #### Bookshelf Bookshelf already uses Bluebird promises internally and has promise returning APIs. Use those. #### PostgreSQL Here is how to create a disposer for the PostgreSQL driver: ``` var pg = require("pg"); // Uncomment if pg has not been properly promisified yet. //var Promise = require("bluebird"); //Promise.promisifyAll(pg, { // filter: function(methodName) { // return methodName === "connect" // }, // multiArgs: true //}); // Promisify rest of pg normally. //Promise.promisifyAll(pg); function getSqlConnection(connectionString) { var close; return pg.connectAsync(connectionString).spread(function(client, done) { close = done; return client; }).disposer(function() { if (close) close(); }); } module.exports = getSqlConnection; ``` Which would allow you to use: ``` var using = Promise.using; using(getSqlConnection(), function(conn) { // use connection here and _return the promise_ }).then(function(result) { // connection already disposed here }); ``` It's also possible to use a disposer pattern (but not actual disposers) for transaction management: ``` function withTransaction(fn) { return Promise.using(pool.acquireConnection(), function(connection) { var tx = connection.beginTransaction() return Promise .try(fn, tx) .then(function(res) { return connection.commit().thenReturn(res) }, function(err) { return connection.rollback() .catch(function(e) {/* maybe add the rollback error to err */}) .thenThrow(err); }); }); } exports.withTransaction = withTransaction; ``` Which would let you do: ``` withTransaction(tx => { return tx.queryAsync(...).then(function() { return tx.queryAsync(...) }).then(function() { return tx.queryAsync(...) }); }); ``` #### MySQL Here is how to create a disposer for the MySQL driver: ``` var mysql = require("mysql"); // Uncomment if mysql has not been properly promisified yet // var Promise = require("bluebird"); // Promise.promisifyAll(mysql); // Promise.promisifyAll(require("mysql/lib/Connection").prototype); // Promise.promisifyAll(require("mysql/lib/Pool").prototype); var pool = mysql.createPool({ connectionLimit: 10, host: 'example.org', user: 'bob', password: 'secret' }); function getSqlConnection() { return pool.getConnectionAsync().disposer(function(connection) { connection.release(); }); } module.exports = getSqlConnection; ``` The usage pattern is similar to the PostgreSQL example above. You can also use a disposer pattern (but not an actual .disposer). See the PostgreSQL example above for instructions. ### More common examples Some examples of the above practice applied to some popular libraries: ``` // The most popular redis module var Promise = require("bluebird"); Promise.promisifyAll(require("redis")); ``` ``` // The most popular mongodb module var Promise = require("bluebird"); Promise.promisifyAll(require("mongodb")); ``` ``` // The most popular mysql module var Promise = require("bluebird"); // Note that the library's classes are not properties of the main export // so we require and promisifyAll them manually Promise.promisifyAll(require("mysql/lib/Connection").prototype); Promise.promisifyAll(require("mysql/lib/Pool").prototype); ``` ``` // Mongoose var Promise = require("bluebird"); Promise.promisifyAll(require("mongoose")); ``` ``` // Request var Promise = require("bluebird"); Promise.promisifyAll(require("request")); // Use request.getAsync(...) not request(..), it will not return a promise ``` ``` // mkdir var Promise = require("bluebird"); Promise.promisifyAll(require("mkdirp")); // Use mkdirp.mkdirpAsync not mkdirp(..), it will not return a promise ``` ``` // winston var Promise = require("bluebird"); Promise.promisifyAll(require("winston")); ``` ``` // rimraf var Promise = require("bluebird"); // The module isn't promisified but the function returned is var rimrafAsync = Promise.promisify(require("rimraf")); ``` ``` // xml2js var Promise = require("bluebird"); Promise.promisifyAll(require("xml2js")); ``` ``` // jsdom var Promise = require("bluebird"); Promise.promisifyAll(require("jsdom")); ``` ``` // fs-extra var Promise = require("bluebird"); Promise.promisifyAll(require("fs-extra")); ``` ``` // prompt var Promise = require("bluebird"); Promise.promisifyAll(require("prompt")); ``` ``` // Nodemailer var Promise = require("bluebird"); Promise.promisifyAll(require("nodemailer")); ``` ``` // ncp var Promise = require("bluebird"); Promise.promisifyAll(require("ncp")); ``` ``` // pg var Promise = require("bluebird"); Promise.promisifyAll(require("pg")); ``` In all of the above cases the library made its classes available in one way or another. If this is not the case, you can still promisify by creating a throwaway instance: ``` var ParanoidLib = require("..."); var throwAwayInstance = ParanoidLib.createInstance(); Promise.promisifyAll(Object.getPrototypeOf(throwAwayInstance)); // Like before, from this point on, all new instances + even the throwAwayInstance suddenly support promises ``` ### Working with any other APIs Sometimes you have to work with APIs that are inconsistent and do not follow a common convention. > **Note** Promise returning function should never throw For example, something like: ``` function getUserData(userId, onLoad, onFail) { ... ``` We can use the promise constructor to convert it to a promise returning function: ``` function getUserDataAsync(userId) { return new Promise(function(resolve, reject) { // Put all your code here, this section is throw-safe. getUserData(userId, resolve, reject); }); } ``` © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/working-with-callbacks.html.catch ======= `.catch` is a convenience method for handling errors in promise chains. It comes in two variants - A catch-all variant similar to the synchronous `catch(e) {` block. This variant is compatible with native promises. - A filtered variant (like other non-JS languages typically have) that lets you only handle specific errors. **This variant is usually preferable and is significantly safer**. ### A note on promise exception handling. Promise exception handling mirrors native exception handling in JavaScript. A synchronous function `throw`ing is similar to a promise rejecting. Here is an example to illustrate it: ``` function getItems(param) { try { var items = getItemsSync(); if(!items) throw new InvalidItemsError(); } catch(e) { // can address the error here, either from getItemsSync returning a falsey value or throwing itself throw e; // need to re-throw the error unless I want it to be considered handled. } return process(items); } ``` Similarly, with promises: ``` function getItems(param) { return getItemsAsync().then(items => { if(!items) throw new InvalidItemsError(); return items; }).catch(e => { // can address the error here and recover from it, from getItemsAsync rejects or returns a falsey value throw e; // Need to rethrow unless we actually recovered, just like in the synchronous version }).then(process); } ``` ### Catch-all ``` .catch(function(any error) handler) -> Promise ``` ``` .caught(function(any error) handler) -> Promise ``` This is a catch-all exception handler, shortcut for calling [`.then(null, handler)`](then) on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. *For compatibility with earlier ECMAScript versions, an alias `.caught` is provided for [`.catch`](catch).* ### Filtered Catch ``` .catch( class ErrorClass|function(any error)|Object predicate..., function(any error) handler ) -> Promise ``` ``` .caught( class ErrorClass|function(any error)|Object predicate..., function(any error) handler ) -> Promise ``` This is an extension to [`.catch`](catch) to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. Example: ``` somePromise.then(function() { return a.b.c.d(); }).catch(TypeError, function(e) { //If it is a TypeError, will end up here because //it is a type error to reference property of undefined }).catch(ReferenceError, function(e) { //Will end up here if a was never declared at all }).catch(function(e) { //Generic catch-the rest, error wasn't TypeError nor //ReferenceError }); ``` You may also add multiple filters for a catch handler: ``` somePromise.then(function() { return a.b.c.d(); }).catch(TypeError, ReferenceError, function(e) { //Will end up here on programmer error }).catch(NetworkError, TimeoutError, function(e) { //Will end up here on expected everyday network errors }).catch(function(e) { //Catch any unexpected errors }); ``` For a parameter to be considered a type of error that you want to filter, you need the constructor to have its `.prototype` property be `instanceof Error`. Such a constructor can be minimally created like so: ``` function MyCustomError() {} MyCustomError.prototype = Object.create(Error.prototype); ``` Using it: ``` Promise.resolve().then(function() { throw new MyCustomError(); }).catch(MyCustomError, function(e) { //will end up here now }); ``` However if you want stack traces and cleaner string output, then you should do: *in Node.js and other V8 environments, with support for `Error.captureStackTrace`* ``` function MyCustomError(message) { this.message = message; this.name = "MyCustomError"; Error.captureStackTrace(this, MyCustomError); } MyCustomError.prototype = Object.create(Error.prototype); MyCustomError.prototype.constructor = MyCustomError; ``` Using CoffeeScript's `class` for the same: ``` class MyCustomError extends Error constructor: (@message) -> @name = "MyCustomError" Error.captureStackTrace(this, MyCustomError) ``` This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. Predicates should allow for very fine grained control over caught errors: pattern matching, error-type sets with set operations and many other techniques can be implemented on top of them. Example of using a predicate-based filter: ``` var Promise = require("bluebird"); var request = Promise.promisify(require("request")); function ClientError(e) { return e.code >= 400 && e.code < 500; } request("http://www.google.com").then(function(contents) { console.log(contents); }).catch(ClientError, function(e) { //A client error like 400 Bad Request happened }); ``` Predicate functions that only check properties have a handy shorthand. In place of a predicate function, you can pass an object, and its properties will be checked against the error object for a match: ``` fs.readFileAsync(...) .then(...) .catch({code: 'ENOENT'}, function(e) { console.log("file not found: " + e.path); }); ``` The object predicate passed to `.catch` in the above code (`{code: 'ENOENT'}`) is shorthand for a predicate function `function predicate(e) { return isObject(e) && e.code == 'ENOENT' }`, I.E. loose equality is used. *For compatibility with earlier ECMAScript version, an alias `.caught` is provided for [`.catch`](catch).* By not returning a rejected value or `throw`ing from a catch, you "recover from failure" and continue the chain: ``` Promise.reject(Error('fail!')) .catch(function(e) { // fallback with "recover from failure" return Promise.resolve('success!'); // promise or value }) .then(function(result) { console.log(result); // will print "success!" }); ``` This is exactly like the synchronous code: ``` var result; try { throw Error('fail'); } catch(e) { result = 'success!'; } console.log(result); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/catch.html.finally ========= ``` .finally(function() handler) -> Promise ``` ``` .lastly(function() handler) -> Promise ``` Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for [`.finally`](finally) in that the final value cannot be modified from the handler. *Note: using [`.finally`](finally) for resource management has better alternatives, see [resource management](resource-management)* Consider the example: ``` function anyway() { $("#ajax-loader-animation").hide(); } function ajaxGetAsync(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest; xhr.addEventListener("error", reject); xhr.addEventListener("load", resolve); xhr.open("GET", url); xhr.send(null); }).then(anyway, anyway); } ``` This example doesn't work as intended because the `then` handler actually swallows the exception and returns `undefined` for any further chainers. The situation can be fixed with `.finally`: ``` function ajaxGetAsync(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest; xhr.addEventListener("error", reject); xhr.addEventListener("load", resolve); xhr.open("GET", url); xhr.send(null); }).finally(function() { $("#ajax-loader-animation").hide(); }); } ``` Now the animation is hidden but, unless it throws an exception, the function has no effect on the fulfilled or rejected value of the returned promise. This is similar to how the synchronous `finally` keyword behaves. If the handler function passed to `.finally` returns a promise, the promise returned by `.finally` will not be settled until the promise returned by the handler is settled. If the handler fulfills its promise, the returned promise will be fulfilled or rejected with the original value. If the handler rejects its promise, the returned promise will be rejected with the handler's value. This is similar to throwing an exception in a synchronous `finally` block, causing the original value or exception to be forgotten. This delay can be useful if the actions performed by the handler are done asynchronously. For example: ``` function ajaxGetAsync(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest; xhr.addEventListener("error", reject); xhr.addEventListener("load", resolve); xhr.open("GET", url); xhr.send(null); }).finally(function() { return Promise.fromCallback(function(callback) { $("#ajax-loader-animation").fadeOut(1000, callback); }); }); } ``` If the fade out completes successfully, the returned promise will be fulfilled or rejected with the value from `xhr`. If `.fadeOut` throws an exception or passes an error to the callback, the returned promise will be rejected with the error from `.fadeOut`. *For compatibility with earlier ECMAScript version, an alias `.lastly` is provided for [`.finally`](finally).* Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/finally.htmlPromise.join ============= ``` Promise.join( Promise<any>|any values..., function handler ) -> Promise ``` For coordinating multiple concurrent discrete promises. While [`.all`](all) is good for handling a dynamically sized list of uniform promises, `Promise.join` is much easier (and more performant) to use when you have a fixed amount of discrete promises that you want to coordinate concurrently. The final parameter, handler function, will be invoked with the result values of all of the fufilled promises. For example: ``` var Promise = require("bluebird"); var join = Promise.join; join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length); }); ``` ``` var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); var pg = require("pg"); Promise.promisifyAll(pg, { filter: function(methodName) { return methodName === "connect" }, multiArgs: true }); // Promisify rest of pg normally Promise.promisifyAll(pg); var join = Promise.join; var connectionString = "postgres://username:password@localhost/database"; var fContents = fs.readFileAsync("file.txt", "utf8"); var fStat = fs.statAsync("file.txt"); var fSqlClient = pg.connectAsync(connectionString).spread(function(client, done) { client.close = done; return client; }); join(fContents, fStat, fSqlClient, function(contents, stat, sqlClient) { var query = " \ INSERT INTO files (byteSize, contents) \ VALUES ($1, $2) \ "; return sqlClient.queryAsync(query, [stat.size, contents]).thenReturn(query); }) .then(function(query) { console.log("Successfully ran the Query: " + query); }) .finally(function() { // This is why you want to use Promise.using for resource management if (fSqlClient.isFulfilled()) { fSqlClient.value().close(); } }); ``` *Note: In 1.x and 0.x `Promise.join` used to be a `Promise.all` that took the values in as arguments instead of an array. This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply* Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.join.htmlPromise.method =============== ``` Promise.method(function(...arguments) fn) -> function ``` Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. This method is convenient when a function can sometimes return synchronously or throw synchronously. Example without using `Promise.method`: ``` MyClass.prototype.method = function(input) { if (!this.isValid(input)) { return Promise.reject(new TypeError("input is not valid")); } if (this.cache(input)) { return Promise.resolve(this.someCachedValue); } return db.queryAsync(input).bind(this).then(function(value) { this.someCachedValue = value; return value; }); }; ``` Using the same function `Promise.method`, there is no need to manually wrap direct return or throw values into a promise: ``` MyClass.prototype.method = Promise.method(function(input) { if (!this.isValid(input)) { throw new TypeError("input is not valid"); } if (this.cache(input)) { return this.someCachedValue; } return db.queryAsync(input).bind(this).then(function(value) { this.someCachedValue = value; return value; }); }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.method.htmlPromise.resolve ================ ``` Promise.resolve(Promise<any>|any value) -> Promise ``` Create a promise that is resolved with the given value. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled Promise is returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted Promise that assimilates the state of the thenable. This can be useful if a function returns a promise (say into a chain) but can optionally return a static value. Say, for a lazy-loaded value. Example: ``` var someCachedValue; var getValue = function() { if (someCachedValue) { return Promise.resolve(someCachedValue); } return db.queryAsync().then(function(value) { someCachedValue = value; return value; }); }; ``` Another example with handling jQuery castable objects (`$` is jQuery) ``` Promise.resolve($.get("http://www.google.com")).then(function() { //Returning a thenable from a handler is automatically //cast to a trusted Promise as per Promises/A+ specification return $.post("http://www.yahoo.com"); }).then(function() { }).catch(function(e) { //jQuery doesn't throw real errors so use catch-all console.log(e.statusText); }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.resolve.htmlPromise.reject =============== ``` Promise.reject(any error) -> Promise ``` Create a promise that is rejected with the given `error`. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.reject.htmlSynchronous inspection ======================= Often it is known in certain code paths that a promise is guaranteed to be fulfilled at that point - it would then be extremely inconvenient to use [`.then`](then) to get at the promise's value as the callback is always called asynchronously. **Note**: In recent versions of Bluebird a design choice was made to expose [`.reason()`](reason) and [`.value()`](value) as well as other inspection methods on promises directly in order to make the below use case easier to work with. Every promise implements the [`PromiseInspection`](promiseinspection) interface. For example, if you need to use values of earlier promises in the chain, you could nest: ``` // From Q Docs https://github.com/kriskowal/q/#chaining // MIT License Copyright 2009–2014 <NAME>. function authenticate() { return getUsername().then(function (username) { return getUser(username); // chained because we will not need the user name in the next event }).then(function (user) { // nested because we need both user and password next return getPassword().then(function (password) { if (user.passwordHash !== hash(password)) { throw new Error("Can't authenticate"); } }); }); } ``` Or you could take advantage of the fact that if we reach password validation, then the user promise must be fulfilled: ``` function authenticate() { var user = getUsername().then(function(username) { return getUser(username); }); return user.then(function(user) { return getPassword(); }).then(function(password) { // Guaranteed that user promise is fulfilled, so .value() can be called here if (user.value().passwordHash !== hash(password)) { throw new Error("Can't authenticate"); } }); } ``` In the latter the indentation stays flat no matter how many previous variables you need, whereas with the former each additional previous value would require an additional nesting level. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/synchronous-inspection.htmlPromiseInspection ================== ``` interface PromiseInspection { any reason() any value() boolean isPending() boolean isRejected() boolean isFulfilled() boolean isCancelled() } ``` This interface is implemented by `Promise` instances as well as the `PromiseInspection` result given by [`.reflect()`](reflect). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promiseinspection.html.isFulfilled ============= ``` .isFulfilled() -> boolean ``` See if this promise has been fulfilled. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/isfulfilled.html.isRejected ============ ``` .isRejected() -> boolean ``` See if this promise has been rejected. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/isrejected.html.isPending =========== ``` .isPending() -> boolean ``` See if this `promise` is pending (not fulfilled or rejected or cancelled). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/ispending.html.isCancelled ============= ``` .isCancelled() -> boolean ``` See if this `promise` has been cancelled. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/iscancelled.html.value ======= ``` .value() -> any ``` Get the fulfillment value of this promise. Throws an error if the promise isn't fulfilled - it is a bug to call this method on an unfulfilled promise. You should check if this promise is [`.isFulfilled()`](isfulfilled) in code paths where it's not guaranteed that this promise is fulfilled. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/value.html.reason ======== ``` .reason() -> any ``` Get the rejection reason of this promise. Throws an error if the promise isn't rejected - it is a bug to call this method on an unrejected promise. You should check if this promise is [`.isRejected()`](isrejected) in code paths where it's guaranteed that this promise is rejected. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/reason.htmlCollections ============ Methods of `Promise` instances and core static methods of the Promise class to deal with collections of promises or mixed promises and values. All collection methods have a static equivalent on the Promise object, e.g. `somePromise.map(...)...` is same as `Promise.map(somePromise, ...)...`, `somePromise.all` is same as [`Promise.all`](promise.all) and so on. None of the collection methods modify the original input. Holes in arrays are treated as if they were defined with the value `undefined`. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/collections.htmlPromise.all ============ ``` Promise.all(Iterable<any>|Promise<Iterable<any>> input) -> Promise<Array<any>``` This method is useful for when you want to wait for more than one promise to complete. Given an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)(arrays are `Iterable`), or a promise of an `Iterable`, which produces promises (or a mix of promises and values), iterate over all the values in the `Iterable` into an array and return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. ``` var files = []; for (var i = 0; i < 100; ++i) { files.push(fs.writeFileAsync("file-" + i + ".txt", "", "utf-8")); } Promise.all(files).then(function() { console.log("all the files were created"); }); ``` This method is compatible with [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) from native promises. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.all.htmlPromise.props ============== ``` Promise.props(Object|Map|Promise<Object|Map> input) -> Promise ``` Like [`.all`](all) but for object properties or `Map`s* entries instead of iterated values. Returns a promise that is fulfilled when all the properties of the object or the `Map`'s' values** are fulfilled. The promise's fulfillment value is an object or a `Map` with fulfillment values at respective keys to the original object or a `Map`. If any promise in the object or `Map` rejects, the returned promise is rejected with the rejection reason. If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects (except `Map`s) are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. **Only the native [ECMAScript 6 `Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) implementation that is provided by the environment as is is supported* ***If the map's keys happen to be `Promise`s, they are not awaited for and the resulting `Map` will still have those same `Promise` instances as keys* ``` Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result) { console.log(result.tweets, result.pictures, result.comments); }); ``` ``` var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); var _ = require("lodash"); var path = require("path"); var util = require("util"); function directorySizeInfo(root) { var counts = {dirs: 0, files: 0}; var stats = (function reader(root) { return fs.readdirAsync(root).map(function(fileName) { var filePath = path.join(root, fileName); return fs.statAsync(filePath).then(function(stat) { stat.filePath = filePath; if (stat.isDirectory()) { counts.dirs++; return reader(filePath) } counts.files++; return stat; }); }).then(_.flatten); })(root).then(_.chain); var smallest = stats.call("min", "size").call("pick", "size", "filePath").call("value"); var largest = stats.call("max", "size").call("pick", "size", "filePath").call("value"); var totalSize = stats.call("pluck", "size").call("reduce", function(a, b) { return a + b; }, 0); return Promise.props({ counts: counts, smallest: smallest, largest: largest, totalSize: totalSize }); } directorySizeInfo(process.argv[2] || ".").then(function(sizeInfo) { console.log(util.format(" \n\ %d directories, %d files \n\ Total size: %d bytes \n\ Smallest file: %s with %d bytes \n\ Largest file: %s with %d bytes \n\ ", sizeInfo.counts.dirs, sizeInfo.counts.files, sizeInfo.totalSize, sizeInfo.smallest.filePath, sizeInfo.smallest.size, sizeInfo.largest.filePath, sizeInfo.largest.size)); }); ``` Note that if you have no use for the result object other than retrieving the properties, it is more convenient to use [`Promise.join`](promise.join): ``` Promise.join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log(pictures, comments, tweets); }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.props.htmlChangelog ========= 3.7.2 (2019-11-28) ------------------- Bugfixes: * Fixes firefox settimeout not initialized error ([`#1623`](https://github.com/petkaantonov/bluebird/issues/1623)) 3.7.1 (2019-10-15) ------------------- Features: * feature Bugfixes: * Fix ([`#1614`](https://github.com/petkaantonov/bluebird/issues/1614)) * Fix ([`#1613`](https://github.com/petkaantonov/bluebird/issues/1613)) * Fix ([`#1616`](https://github.com/petkaantonov/bluebird/issues/1616)) 3.7.0 (2019-10-01) ------------------- Features: * Add [`Promise.allSettled`](api/promise.allsettled) method ([`#1606`](https://github.com/petkaantonov/bluebird/issues/1606)) 3.6.0 (2019-10-01) ------------------- Features: * Add support for AsyncResource ([`#1403`](https://github.com/petkaantonov/bluebird/issues/1403)) Bugfixes: * Fix [`.reduce`](api/reduce) generating unhandled rejection events ([`#1501`](https://github.com/petkaantonov/bluebird/issues/1501)) * Fix [`Promise.reduce`](api/promise.reduce) generating unhandled rejction events ([`#1502`](https://github.com/petkaantonov/bluebird/issues/1502)) * Fix [`.map`](api/map) and [`.filter`](api/filter) generating unhandled rejection events ([`#1487`](https://github.com/petkaantonov/bluebird/issues/1487)) * Fix [`Promise.map`](api/promise.map) unhandled rejection events ([`#1489`](https://github.com/petkaantonov/bluebird/issues/1489)) * Fix cancel skipping upward propagation ([`#1459`](https://github.com/petkaantonov/bluebird/issues/1459)) * Fix loadTimes deprecation ([`#1505`](https://github.com/petkaantonov/bluebird/issues/1505)) * Fix [`Promise.each`](api/promise.each) maximum stack exceeded error ([`#1326`](https://github.com/petkaantonov/bluebird/issues/1326)) * Make PromiseRejectionEvent confrom to spec ([`#1509`](https://github.com/petkaantonov/bluebird/issues/1509)) * Fix false unhandled rejection events ([`#1468`](https://github.com/petkaantonov/bluebird/issues/1468)) 3.5.5 (2019-05-24) ------------------- Features: * Added Symbol.toStringTag support to Promise ([`#1421`](https://github.com/petkaantonov/bluebird/issues/1421)) Bugfixes: * Fix error in IE9 ([`#1591`](https://github.com/petkaantonov/bluebird/issues/1591), [`#1592`](https://github.com/petkaantonov/bluebird/issues/1592)) * Fix error with undefined stack trace ([`#1537`](https://github.com/petkaantonov/bluebird/issues/1537)) * Fix [`.catch`](api/catch) throwing an error later rather than immediately when passed non-function handler ([`#1517`](https://github.com/petkaantonov/bluebird/issues/1517)) 3.5.4 (2019-04-03) ------------------- * Proper version check supporting VSCode([`#1576`](https://github.com/petkaantonov/bluebird/issues/1576)) 3.5.3 (2018-11-06) ------------------- Bugfixes: * Update acorn dependency 3.5.2 (2018-09-03) ------------------- Bugfixes: * Fix `PromiseRejectionEvent` to contain `.reason` and `.promise` properties. ([`#1509`](https://github.com/petkaantonov/bluebird/issues/1509), [`#1464`](https://github.com/petkaantonov/bluebird/issues/1464)) * Fix promise chain retaining memory until the entire chain is resolved ([`#1544`](https://github.com/petkaantonov/bluebird/issues/1544), [`#1529`](https://github.com/petkaantonov/bluebird/issues/1529)) 3.5.1 (2017-10-04) ------------------- Bugfixes: * Fix false positive unhandled rejection when using async await ([`#1404`](https://github.com/petkaantonov/bluebird/issues/1404)) * Fix false positive when reporting error as non-error ([`#990`](https://github.com/petkaantonov/bluebird/issues/990)) 3.5.0 (2017-03-03) ------------------- Features: * Added new method: [`.tapCatch`](api/tapcatch) ([`#1220`](https://github.com/petkaantonov/bluebird/issues/1220)) Bugfixes: * Fixed streamline benchmarks ([`#1233`](https://github.com/petkaantonov/bluebird/issues/1233)) * Fixed yielding a function calling the function ([`#1314`](https://github.com/petkaantonov/bluebird/issues/1314), [`#1315`](https://github.com/petkaantonov/bluebird/issues/1315)) * Fixed confusing error message when calling [`.catch`](api/catch) with non function predicate ([`#1350`](https://github.com/petkaantonov/bluebird/issues/1350)) * Fixed [`.props`](api/props) resolving to empty object when called with empty `Map` ([`#1338`](https://github.com/petkaantonov/bluebird/issues/1338)) * Fixed confusing error message when invoking `Promise` directly without `new` ([`#1320`](https://github.com/petkaantonov/bluebird/issues/1320)) * Added dedicated webpack entry point ([`#1318`](https://github.com/petkaantonov/bluebird/issues/1318)) 3.4.7 (2016-12-22) ------------------- * Promise config returns reference to Bluebird library * Updated logo * Benchmark fix * Don't drop syntaxerror context from stack traces * Fix environment variables sometimes causing long stack traces to be enabled 3.4.6 (2016-09-01) ------------------- Bugfixes: * Fix [`Promise.map`](api/promise.map) and [`.map`](api/map) not always calling the callback asynchronously ([`#1148`](https://github.com/petkaantonov/bluebird/issues/1148)) 3.4.5 (2016-08-31) ------------------- Bugfixes: * Fix unhandled error regression introduced in 3.4.3 [`#1217`](https://github.com/petkaantonov/bluebird/issues/1217) 3.4.4 (2016-08-30) ------------------- Bugfixes: * Fix benchmark parallel in node 6 [`#1165`](https://github.com/petkaantonov/bluebird/issues/1165) * Fix memory leak with Promise.each [`#1057`](https://github.com/petkaantonov/bluebird/issues/1057) * Fix thenable passed to .return being evaluated too early [`#1210`](https://github.com/petkaantonov/bluebird/issues/1210) * Fix "unhandledrejection" event not having .detail field when using DOM3 event listener api [`#1209`](https://github.com/petkaantonov/bluebird/issues/1209) * Fix [`Promise.join`](api/promise.join) not ensuring asynchronous callback [`#1153`](https://github.com/petkaantonov/bluebird/issues/1153) * Fix domains leaking when synchronous error is thrown while a domain is active [`#1125`](https://github.com/petkaantonov/bluebird/issues/1125) 3.4.3 (2016-08-25) ------------------- Bugfixes: * The "a promise was created in a handler but not returned from it" warning now highlights the file, line and column where the return statement is missing. + The "a promise was created in a handler but not returned from it" warning now adds the bluebird API method used to create the non-returned promise at the top of the warning stack 3.4.2 (2016-08-24) ------------------- Bugfixes: * Add missing link to unhandled warning docs ([`#1205`](https://github.com/petkaantonov/bluebird/issues/1205)) * Fix [`Promise.delay`](api/promise.delay) not having a long stack trace ([`#1182`](https://github.com/petkaantonov/bluebird/issues/1182)) * Fix false unhandled rejection when a rejected promise originating from one copy of bluebird is passed to another copy's [`.return`](api/return) or [`.catchReturn`](api/catchreturn) ([`#1186`](https://github.com/petkaantonov/bluebird/issues/1186)) * Fix Promise.resolve is not a function error ([`#1192`](https://github.com/petkaantonov/bluebird/issues/1192)) * Fix global events not being fired through DOM 3 API inside a worker ([`#1190`](https://github.com/petkaantonov/bluebird/issues/1190)) * Fix .cancel() not immediately marking a promise as being cancelled if it has cancellable parent ([`#1187`](https://github.com/petkaantonov/bluebird/issues/1187)) * Fix maximum callstack exceeded with [`Promise.coroutine`](api/promise.coroutine) ([`#1170`](https://github.com/petkaantonov/bluebird/issues/1170)) 3.4.1 (2016-06-17) ------------------- Features: * Added [`Promise.getNewLibraryCopy`](api/promise.getnewlibrarycopy) 3.4.0 (2016-05-17) ------------------- Features: * Add `Promise.version` which tells the bluebird version as a string e.g. `"3.4.0"` ([`#1042`](https://github.com/petkaantonov/bluebird/issues/1042)). * [`.map`](api/map), [`Promise.map`](api/promise.map), [`.filter`](api/filter) and [`Promise.filter`](api/promise.filter) now return rejected promise when inappropriate options argument is passed ([`#1097`](https://github.com/petkaantonov/bluebird/issues/1097)). Bugfixes: * Fix bug where callback to [`.disposer`](api/disposer) is not called if the resource is `null` ([`#1099`](https://github.com/petkaantonov/bluebird/issues/1099)). * Fix bug where assimilating thenable throws unexpectedly when using hostile host objects as thenables ([`#1104`](https://github.com/petkaantonov/bluebird/issues/1104)). 3.3.5 (2016-04-12) ------------------- Bugfixes: * Fix then sometimes not being called on iOS/Firefox ([`#1022`](https://github.com/petkaantonov/bluebird/issues/1022)). * Fix custom schedulers not being called when using promisified functions ([`#1023`](https://github.com/petkaantonov/bluebird/issues/1023)). * Fix unexpected error being thrown when promisifed function is called with no arguments ([`#1063`](https://github.com/petkaantonov/bluebird/issues/1063)). 3.3.4 (2016-03-07) ------------------- Features: * Warnings about created promises that are not returned are no longer given if the handler promise has not been chained. This should reduce the amount of false positives with this warning. 3.3.3 (2016-02-25) ------------------- Bugfixes: * Fix stack overflow error when a promise returned by promisified function rejects early in a huge array when using [`Promise.mapSeries`](api/promise.mapseries) or [`Promise.each`](api/promise.each) 3.3.2 (2016-02-25) ------------------- Bugfixes: * Fix missing newline in stack trace reported by [`.done()`](api/done) ([`#1020`](https://github.com/petkaantonov/bluebird/issues/1020)). * Detect deep circular resolutions 3.3.1 (2016-02-13) ------------------- Bugfixes: * Fix crash when cancelling a [`.tap()`](api/tap) handler promise ([`#1006`](https://github.com/petkaantonov/bluebird/issues/1006)). 3.3.0 (2016-02-12) ------------------- Features: * Cancelling Promise returned from [`Promise.delay()`](api/promise.delay) and [`.delay()`](api/delay) now calls `clearTimeout` ([`#1000`](https://github.com/petkaantonov/bluebird/issues/1000)) * Add [monitoring and lifecycle hooks](features#promise-monitoring) * Add `'warning'` hook for warnings ([`#980`](https://github.com/petkaantonov/bluebird/issues/980)) Bugfixes: * Fix warnings for "promise was rejected with non-error" being output when promises are rejected with errors from different realm ([`#990`](https://github.com/petkaantonov/bluebird/issues/990)) 3.2.2 (2016-02-05) ------------------- Bugfixes: * Make build script's output work without TTY 3.2.1 (2016-02-01) ------------------- Bugfixes: * Revert monitoring feature due to crash in browser 3.2.0 (2016-02-01) ------------------- * Broken build 3.1.5 (2016-01-26) ------------------- Dummy release to trigger CDN update. 3.1.4 (2016-01-25) ------------------- Bugfixes: * Fix broken npm prepublish script release 3.1.3 (2016-01-25) ------------------- Bugfixes: * Fix generators crashing in node 0.12 ([`#978`](https://github.com/petkaantonov/bluebird/issues/978)) * Add minimal build files to build ([`#976`](https://github.com/petkaantonov/bluebird/issues/976), [`#757`](https://github.com/petkaantonov/bluebird/issues/757)) 3.1.2 (2016-01-23) ------------------- Features: * [`.timeout()`](api/timeout) now `clearTimeout`s the timer if the resulting promise is cancelled ([`#926`](https://github.com/petkaantonov/bluebird/issues/926)) * [`Promise.coroutine`](api/promise.coroutine) now returns function with same `.length` as the original function ([`#927`](https://github.com/petkaantonov/bluebird/issues/927), [`#933`](https://github.com/petkaantonov/bluebird/issues/933)) Bugfixes: * Fix long stack traces not working when promise is created from [`Promise.fromCallback`](api/promise.fromcallback) ([`#971`](https://github.com/petkaantonov/bluebird/issues/971)) * Fix [`.finally()`](api/finally) handlers not being called when promise is cancelled while a domain is active ([`#963`](https://github.com/petkaantonov/bluebird/issues/963)) * Fix [`.timeout()`](api/timeout) trying to cancel a promise even if cancellation is disabled ([`#970`](https://github.com/petkaantonov/bluebird/issues/970)) 3.1.1 (2015-12-16) ------------------- Bugfixes: * Disable wForgottenWarning when all warnings are disabled 3.1.0 (2015-12-16) ------------------- Features: * Added ability to configure the [forgotten return statement](warning-explanations#warning-a-promise-was-created-in-a-handler-but-none-were-returned-from-it) warning separately ([`#920`](https://github.com/petkaantonov/bluebird/issues/920)). Bugfixes: * Fixed the bug where returning a value from [`.finally`](api/finally) or [`.tap`](api/tap) handler did not make a warning about a forgotten return go away ([`#846`](https://github.com/petkaantonov/bluebird/issues/846)). * Fixed the bug where setTimeout is used in Chrome instead of MutationObserver ([`#915`](https://github.com/petkaantonov/bluebird/issues/915)) * Fixed the bug where using [`.bind`](api/bind) suppressed unhandled rejections ([`#841`](https://github.com/petkaantonov/bluebird/issues/841)) 3.0.6 (2015-12-01) ------------------- Bugfixes: * Fix [`.timeout()`](api/timeout) not cancelling parent ([`#891`](https://github.com/petkaantonov/bluebird/issues/891)) * Fix long stack traces when using [`Promise.resolve()`](api/promise.resolve) ([`#861`](https://github.com/petkaantonov/bluebird/issues/861)) * Fix [`Promise.config()`](api/promise.config) not disabling long stack traces when passing `longStackTraces: false` ([`#897`](https://github.com/petkaantonov/bluebird/issues/897)) 3.0.5 (2015-11-01) ------------------- Bugfixes: * Added [forgotten return warnings](warning-explanations#warning-a-promise-was-created-in-a-handler-but-none-were-returned-from-it) to [`Promise.try`](api/promise.try) and [`Promise.method`](api/promise.method) 3.0.4 (2015-11-01) ------------------- Bugfixes: * The stack trace for [forgotten return warnings](warning-explanations#warning-a-promise-was-created-in-a-handler-but-none-were-returned-from-it) is more useful now. 3.0.3 (2015-11-01) ------------------- Bugfixes: * 3rd party libraries rejecting promises with non-errors no longer causes warnings * When `NODE_ENV` environment variable is `"development"` setting `BLUEBIRD_DEBUG` environment variable to `0` can now be used to disable debug mode 3.0.2 (2015-10-29) ------------------- Bugfixes: * Fix crash when using node.js domains [`#829`](https://github.com/petkaantonov/bluebird/issues/829) 3.0.1 (2015-10-28) ------------------- See [New in 3.0](new-in-bluebird-3). 3.0.0 (2015-10-27) ------------------- See [New in 3.0](new-in-bluebird-3). 2.11.0 (2016-08-30) -------------------- Features: * feature Bugfixes: * bugfix 2.10.2 (2015-10-01) -------------------- Features: * [`.timeout()`](api/timeout) now takes a custom error object as second argument 2.10.1 (2015-09-21) -------------------- * Fix error "Cannot promisify an API that has normal methods with 'Async'-suffix" when promisifying certain objects with a custom promisifier 2.10.0 (2015-09-08) -------------------- Features: * `Promise.using` can now take the promises-for-resources as an array ([`#733`](https://github.com/petkaantonov/bluebird/issues/733)). * Browser builds for minimal core are now hosted on CDN ([`#724`](https://github.com/petkaantonov/bluebird/issues/724)). Bugfixes: * Disabling debug mode with `BLUEBIRD_DEBUG=0` environment variable now works ([`#719`](https://github.com/petkaantonov/bluebird/issues/719)). * Fix unhandled rejection reporting when passing rejected promise to `.return()` ([`#721`](https://github.com/petkaantonov/bluebird/issues/721)). * Fix unbound promise's then handlers being called with wrong `this` value ([`#738`](https://github.com/petkaantonov/bluebird/issues/738)). 2.9.34 (2015-07-15) -------------------- Bugfixes: * Correct domain for .map, .each, .filter, .reduce callbacks ([`#701`](https://github.com/petkaantonov/bluebird/issues/701)). + Preserve bound-with-promise promises across the entire chain ([`#702`](https://github.com/petkaantonov/bluebird/issues/702)). 2.9.33 (2015-07-09) -------------------- Bugfixes: * Methods on `Function.prototype` are no longer promisified ([`#680`](https://github.com/petkaantonov/bluebird/issues/680)). 2.9.32 (2015-07-03) -------------------- Bugfixes: * Fix `.return(primitiveValue)` returning a wrapped version of the primitive value when a Node.js domain is active ([`#689`](https://github.com/petkaantonov/bluebird/issues/689)). 2.9.31 (2015-07-03) -------------------- Bugfixes: * Fix Promises/A+ compliance issue regarding circular thenables: the correct behavior is to go into an infinite loop instead of warning with an error (Fixes [`#682`](https://github.com/petkaantonov/bluebird/issues/682)). * Fix "(node) warning: possible EventEmitter memory leak detected" ([`#661`](https://github.com/petkaantonov/bluebird/issues/661)). * Fix callbacks sometimes being called with a wrong node.js domain ([`#664`](https://github.com/petkaantonov/bluebird/issues/664)). * Fix callbacks sometimes not being called at all in iOS 8.1 WebApp mode ([`#666`](https://github.com/petkaantonov/bluebird/issues/666), [`#687`](https://github.com/petkaantonov/bluebird/issues/687)). 2.9.30 (2015-06-14) -------------------- Bugfixes: * Fix regression with `promisifyAll` not promisifying certain methods 2.9.29 (2015-06-14) -------------------- Bugfixes: * Improve `promisifyAll` detection of functions that are class constructors. Fixes mongodb 2.x promisification. 2.9.28 (2015-06-14) -------------------- Bugfixes: * Fix handled rejection being reported as unhandled in certain scenarios when using [`.all`](api/all) or [`Promise.join`](api/promise.join) ([`#645`](https://github.com/petkaantonov/bluebird/issues/645)) * Fix custom scheduler not being called in Google Chrome when long stack traces are enabled ([`#650`](https://github.com/petkaantonov/bluebird/issues/650)) 2.9.27 (2015-05-30) -------------------- Bugfixes: * Fix `sinon.useFakeTimers()` breaking scheduler ([`#631`](https://github.com/petkaantonov/bluebird/issues/631)) Misc: * Add nw testing facilities (`node tools/test --nw`) 2.9.26 (2015-05-25) -------------------- Bugfixes: * Fix crash in NW [`#624`](https://github.com/petkaantonov/bluebird/issues/624) * Fix [`.return()`](api/return) not supporting `undefined` as return value [`#627`](https://github.com/petkaantonov/bluebird/issues/627) 2.9.25 (2015-04-28) -------------------- Bugfixes: * Fix crash in node 0.8 2.9.24 (2015-04-02) -------------------- Bugfixes: * Fix not being able to load multiple bluebird copies introduced in 2.9.22 ([`#559`](https://github.com/petkaantonov/bluebird/issues/559), [`#561`](https://github.com/petkaantonov/bluebird/issues/561), [`#560`](https://github.com/petkaantonov/bluebird/issues/560)). 2.9.23 (2015-04-02) -------------------- Bugfixes: * Fix node.js domain propagation ([`#521`](https://github.com/petkaantonov/bluebird/issues/521)). 2.9.22 (2015-04-02) -------------------- * Fix `.promisify` crashing in phantom JS ([`#556`](https://github.com/petkaantonov/bluebird/issues/556)) 2.9.21 (2015-03-30) -------------------- * Fix error object's `'stack'`' overwriting causing an error when its defined to be a setter that throws an error ([`#552`](https://github.com/petkaantonov/bluebird/issues/552)). 2.9.20 (2015-03-29) -------------------- Bugfixes: * Fix regression where there is a long delay between calling `.cancel()` and promise actually getting cancelled in Chrome when long stack traces are enabled 2.9.19 (2015-03-29) -------------------- Bugfixes: * Fix crashing in Chrome when long stack traces are disabled 2.9.18 (2015-03-29) -------------------- Bugfixes: * Fix settlePromises using trampoline 2.9.17 (2015-03-29) -------------------- Bugfixes: * Fix Chrome DevTools async stack traceability ([`#542`](https://github.com/petkaantonov/bluebird/issues/542)). 2.9.16 (2015-03-28) -------------------- Features: * Use setImmediate if available 2.9.15 (2015-03-26) -------------------- Features: * Added `.asCallback` alias for `.nodeify`. Bugfixes: * Don't always use nextTick, but try to pick up setImmediate or setTimeout in NW. Fixes [`#534`](https://github.com/petkaantonov/bluebird/issues/534), [`#525`](https://github.com/petkaantonov/bluebird/issues/525) * Make progress a core feature. Fixes [`#535`](https://github.com/petkaantonov/bluebird/issues/535) Note that progress has been removed in 3.x - this is only a fix necessary for 2.x custom builds. 2.9.14 (2015-03-12) -------------------- Bugfixes: * Always use process.nextTick. Fixes [`#525`](https://github.com/petkaantonov/bluebird/issues/525) 2.9.13 (2015-02-27) -------------------- Bugfixes: * Fix .each, .filter, .reduce and .map callbacks being called synchornously if the input is immediate. ([`#513`](https://github.com/petkaantonov/bluebird/issues/513)) 2.9.12 (2015-02-19) -------------------- Bugfixes: * Fix memory leak introduced in 2.9.0 ([`#502`](https://github.com/petkaantonov/bluebird/issues/502)) 2.9.11 (2015-02-19) -------------------- Bugfixes: * Fix [`#503`](https://github.com/petkaantonov/bluebird/issues/503) 2.9.10 (2015-02-18) -------------------- Bugfixes: * Fix [`#501`](https://github.com/petkaantonov/bluebird/issues/501) 2.9.9 (2015-02-12) ------------------- Bugfixes: * Fix `TypeError: Cannot assign to read only property 'length'` when jsdom has declared a read-only length for all objects to inherit. 2.9.8 (2015-02-10) ------------------- Bugfixes: * Fix regression introduced in 2.9.7 where promisify didn't properly dynamically look up methods on `this` 2.9.7 (2015-02-08) ------------------- Bugfixes: * Fix `promisify` not retaining custom properties of the function. This enables promisifying the `"request"` module's export function and its methods at the same time. * Fix `promisifyAll` methods being dependent on `this` when they are not originally dependent on `this`. This enables e.g. passing promisified `fs` functions directly as callbacks without having to bind them to `fs`. * Fix `process.nextTick` being used over `setImmediate` in node. 2.9.6 (2015-02-02) ------------------- Bugfixes: * Node environment detection can no longer be fooled 2.9.5 (2015-02-02) ------------------- Misc: * Warn when [`.then()`](api/then) is passed non-functions 2.9.4 (2015-01-30) ------------------- Bugfixes: * Fix [`.timeout()`](api/timeout) not calling `clearTimeout` with the proper handle in node causing the process to wait for unneeded timeout. This was a regression introduced in 2.9.1. 2.9.3 (2015-01-27) ------------------- Bugfixes: * Fix node-webkit compatibility issue ([#467](https://github.com/petkaantonov/bluebird/pull/467)) * Fix long stack trace support in recent firefox versions 2.9.2 (2015-01-26) ------------------- Bugfixes: * Fix critical bug regarding to using promisifyAll in browser that was introduced in 2.9.0 ([#466](https://github.com/petkaantonov/bluebird/issues/466)). Misc: * Add `"browser"` entry point to package.json 2.9.1 (2015-01-24) ------------------- Features: * If a bound promise is returned by the callback to [`Promise.method`](api/promise.method) and [`Promise.try`](api/promise.try), the returned promise will be bound to the same value 2.9.0 (2015-01-24) ------------------- Features: * Add [`Promise.fromNode`](api/promise.fromnode) * Add new paramter `value` for [`Promise.bind`](api/promise.bind) Bugfixes: * Fix several issues with [`cancellation`](api/cancellation) and [`.bind()`](api/bind) interoperation when `thisArg` is a promise or thenable * Fix promises created in [`disposers`](api/disposers) not having proper long stack trace context * Fix [`Promise.join`](api/promise.join) sometimes passing the passed in callback function as the last argument to itself. Misc: * Reduce minified full browser build file size by not including unused code generation functionality. * Major internal refactoring related to testing code and source code file layout 2.8.2 (2015-01-20) ------------------- Features: * [Global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) are now fired both as DOM3 events and as legacy events in browsers 2.8.1 (2015-01-20) ------------------- Bugfixes: * Fix long stack trace stiching consistency when rejected from thenables 2.8.0 (2015-01-19) ------------------- Features: * Major debuggability improvements: + Long stack traces have been re-designed. They are now much more readable, succint, relevant and consistent across bluebird features. + Long stack traces are supported now in IE10+ 2.7.1 (2015-01-15) ------------------- Bugfixes: * Fix [`#447`](https://github.com/petkaantonov/bluebird/issues/447) 2.7.0 (2015-01-15) ------------------- Features: * Added more context to stack traces originating from coroutines ([#421](https://github.com/petkaantonov/bluebird/issues/421)) * Implemented [global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) ([#428](https://github.com/petkaantonov/bluebird/issues/428), [#357](https://github.com/petkaantonov/bluebird/issues/357)) * [Custom promisifiers](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-promisifier) are now passed the default promisifier which can be used to add enhancements on top of normal node promisification * [Promisification filters](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-filter) are now passed `passesDefaultFilter` boolean Bugfixes: * Fix `.noConflict()` call signature ([#446](changelog)) * Fix `Promise.method`ified functions being called with `undefined` when they were called with no arguments 2.6.4 (2015-01-12) ------------------- Bugfixes: * `OperationalErrors` thrown by promisified functions retain custom properties, such as `.code` and `.path`. 2.6.3 (2015-01-12) ------------------- Bugfixes: * Fix [#429](https://github.com/petkaantonov/bluebird/issues/429) * Fix [#432](https://github.com/petkaantonov/bluebird/issues/432) * Fix [#433](https://github.com/petkaantonov/bluebird/issues/433) 2.6.2 (2015-01-07) ------------------- Bugfixes: * Fix [#426](https://github.com/petkaantonov/bluebird/issues/426) 2.6.1 (2015-01-07) ------------------- Bugfixes: * Fixed built browser files not being included in the git tag release for bower 2.6.0 (2015-01-06) ------------------- Features: * Significantly improve parallel promise performance and memory usage (+50% faster, -50% less memory) 2.5.3 (2014-12-30) ------------------- 2.5.2 (2014-12-29) ------------------- Bugfixes: * Fix bug where already resolved promise gets attached more handlers while calling its handlers resulting in some handlers not being called * Fix bug where then handlers are not called in the same order as they would run if Promises/A+ 2.3.2 was implemented as adoption * Fix bug where using `Object.create(null)` as a rejection reason would crash bluebird 2.5.1 (2014-12-29) ------------------- Bugfixes: * Fix `.finally` throwing null error when it is derived from a promise that is resolved with a promise that is resolved with a promise 2.5.0 (2014-12-28) ------------------- Features: * [`.get`](api/get) now supports negative indexing. Bugfixes: * Fix bug with `Promise.method` wrapped function returning a promise that never resolves if the function returns a promise that is resolved with another promise * Fix bug with `Promise.delay` never resolving if the value is a promise that is resolved with another promise 2.4.3 (2014-12-28) ------------------- Bugfixes: * Fix memory leak as described in [this Promises/A+ spec issue](https://github.com/promises-aplus/promises-spec/issues/179). 2.4.2 (2014-12-21) ------------------- Bugfixes: * Fix bug where spread rejected handler is ignored in case of rejection * Fix synchronous scheduler passed to `setScheduler` causing infinite loop 2.4.1 (2014-12-20) ------------------- Features: * Error messages now have links to wiki pages for additional information * Promises now clean up all references (to handlers, child promises etc) as soon as possible. 2.4.0 (2014-12-18) ------------------- Features: * Better filtering of bluebird internal calls in long stack traces, especially when using minified file in browsers * Small performance improvements for all collection methods * Promises now delete references to handlers attached to them as soon as possible * Additional stack traces are now output on stderr/`console.warn` for errors that are thrown in the process/window from rejected `.done()` promises. See [#411](https://github.com/petkaantonov/bluebird/issues/411) 2.3.11 (2014-10-31) -------------------- Bugfixes: * Fix [#371](https://github.com/petkaantonov/bluebird/issues/371), [#373](https://github.com/petkaantonov/bluebird/issues/373) 2.3.10 (2014-10-28) -------------------- Features: * `Promise.method` no longer wraps primitive errors * `Promise.try` no longer wraps primitive errors 2.3.7 (2014-10-25) ------------------- Bugfixes: * Fix [#359](https://github.com/petkaantonov/bluebird/issues/359), [#362](https://github.com/petkaantonov/bluebird/issues/362) and [#364](https://github.com/petkaantonov/bluebird/issues/364) 2.3.6 (2014-10-15) ------------------- Features: * Implement [`.reflect()`](api/reflect) 2.3.5 (2014-10-06) ------------------- Bugfixes: * Fix issue when promisifying methods whose names contain the string 'args' 2.3.4 (2014-09-27) ------------------- * `P` alias was not declared inside WebWorkers 2.3.3 (2014-09-27) ------------------- Bugfixes: * Fix [#318](https://github.com/petkaantonov/bluebird/issues/318), [#314](https://github.com/petkaantonov/bluebird/issues/#314) 2.3.2 (2014-08-25) ------------------- Bugfixes: * `P` alias for `Promise` now exists in global scope when using browser builds without a module loader, fixing an issue with firefox extensions 2.3.1 (2014-08-23) ------------------- Features: * `.using` can now be used with disposers created from different bluebird copy 2.3.0 (2014-08-13) ------------------- Features: * [`.bind()`](api/bind) and [`Promise.bind()`](api/promise.bind) now await for the resolution of the `thisArg` if it's a promise or a thenable Bugfixes: * Fix [#276](https://github.com/petkaantonov/bluebird/issues/276) 2.2.2 (2014-07-14) ------------------- * Fix [#259](https://github.com/petkaantonov/bluebird/issues/259) 2.2.1 (2014-07-07) ------------------- * Fix multiline error messages only showing the first line 2.2.0 (2014-07-07) ------------------- Bugfixes: * `.any` and `.some` now consistently reject with RangeError when input array contains too few promises * Fix iteration bug with `.reduce` when input array contains already fulfilled promises 2.1.3 (2014-06-18) ------------------- Bugfixes: * Fix [#235](https://github.com/petkaantonov/bluebird/issues/235) 2.1.2 (2014-06-15) ------------------- Bugfixes: * Fix [#232](https://github.com/petkaantonov/bluebird/issues/232) 2.1.1 (2014-06-11) ------------------- 2.1.0 (2014-06-11) ------------------- Features: * Add [`promisifier`](api/promisifier) option to `Promise.promisifyAll()` * Improve performance of `.props()` and collection methods when used with immediate values Bugfixes: * Fix a bug where .reduce calls the callback for an already visited item * Fix a bug where stack trace limit is calculated to be too small, which resulted in too short stack traces Add undocumented experimental `yieldHandler` option to `Promise.coroutine` 2.0.7 (2014-06-08) ------------------- 2.0.6 (2014-06-07) ------------------- 2.0.5 (2014-06-05) ------------------- 2.0.4 (2014-06-05) ------------------- 2.0.3 (2014-06-05) ------------------- 2.0.2 (2014-06-04) ------------------- 2.0.1 (2014-06-04) ------------------- 2.0.0 (2014-06-04) ------------------- What's new in 2.0 ================== * [Resource management](api-reference#resource-management) - never leak resources again * [Promisification](api-reference#promisification) on steroids - entire modules can now be promisified with one line of code * [`.map()`](api/map), [`.each()`](api/each), [`.filter()`](api/filter), [`.reduce()`](api/reduce) reimagined from simple sugar to powerful concurrency coordination tools * [API Documentation](index) has been reorganized and more elaborate examples added * Deprecated [progression](#progression-migration) and [deferreds](#deferred-migration) * Improved performance and readability Features: * Added [`using()`](api/using) and [`disposer()`](api/disposer) * [`.map()`](api/map) now calls the handler as soon as items in the input array become fulfilled * Added a concurrency option to [`.map()`](api/map) * [`.filter()`](api/filter) now calls the handler as soon as items in the input array become fulfilled * Added a concurrency option to [`.filter()`](api/filter) * [`.reduce()`](api/reduce) now calls the handler as soon as items in the input array become fulfilled, but in-order * Added [`.each()`](api/each) * [`Promise.resolve()`](api/promise.resolve) behaves like `Promise.cast`. `Promise.cast` deprecated. * [Synchronous inspection](api-reference#synchronous-inspection): Removed `.inspect()`, added [`.value()`](api/value) and [`.reason()`](api/reason) * [`Promise.join()`](api/promise.join) now takes a function as the last argument * Added [`Promise.setScheduler()`](api/promise.setscheduler) * [`.cancel()`](api/cancel) supports a custom cancellation reason * [`.timeout()`](api/timeout) now cancels the promise instead of rejecting it * [`.nodeify()`](api/nodeify) now supports passing multiple success results when mapping promises to nodebacks * Added `suffix` and `filter` options to [`Promise.promisifyAll()`](api/promise.promisifyall) Breaking changes: * Sparse array holes are not skipped by collection methods but treated as existing elements with `undefined` value * `.map()` and `.filter()` do not call the given mapper or filterer function in any specific order * Removed the `.inspect()` method * Yielding an array from a coroutine is not supported by default. You can use [`coroutine.addYieldHandler()`](api/coroutine.addyieldhandler) to configure the old behavior (or any behavior you want). * [`.any()`](api/any) and [`.some()`](api/some) no longer use an array as the rejection reason. [`AggregateError`](api/aggregateerror) is used instead. 1.2.4 (2014-04-27) ------------------- Bugfixes: * Fix promisifyAll causing a syntax error when a method name is not a valid identifier * Fix syntax error when es5.js is used in strict mode 1.2.3 (2014-04-17) ------------------- Bugfixes: * Fix [#179](https://github.com/petkaantonov/bluebird/issues/179) 1.2.2 (2014-04-09) ------------------- Bugfixes: * Promisified methods from promisifyAll no longer call the original method when it is overriden * Nodeify doesn't pass second argument to the callback if the promise is fulfilled with `undefined` 1.2.1 (2014-03-31) ------------------- Bugfixes: * Fix [#168](https://github.com/petkaantonov/bluebird/issues/168) 1.2.0 (2014-03-29) ------------------- Features: * New method: [`.value()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#value---dynamic) * New method: [`.reason()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#reason---dynamic) * New method: [`Promise.onUnhandledRejectionHandled()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseonunhandledrejectionhandledfunction-handler---undefined) * `Promise.map()`, `.map()`, `Promise.filter()` and `.filter()` start calling their callbacks as soon as possible while retaining a correct order. See [`8085922f`](https://github.com/petkaantonov/bluebird/commit/8085922fb95a9987fda0cf2337598ab4a98dc315). Bugfixes: * Fix [#165](https://github.com/petkaantonov/bluebird/issues/165) * Fix [#166](https://github.com/petkaantonov/bluebird/issues/166) 1.1.1 (2014-03-18) ------------------- Bugfixes: * [#138](https://github.com/petkaantonov/bluebird/issues/138) * [#144](https://github.com/petkaantonov/bluebird/issues/144) * [#148](https://github.com/petkaantonov/bluebird/issues/148) * [#151](https://github.com/petkaantonov/bluebird/issues/151) 1.1.0 (2014-03-08) ------------------- Features: * Implement [`Promise.prototype.tap()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#tapfunction-handler---promise) * Implement [`Promise.coroutine.addYieldHandler()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisecoroutineaddyieldhandlerfunction-handler---void) * Deprecate `Promise.prototype.spawn` Bugfixes: * Fix already rejected promises being reported as unhandled when handled through collection methods * Fix browserisfy crashing from checking `process.version.indexOf` 1.0.8 (2014-03-03) ------------------- Bugfixes: * Fix active domain being lost across asynchronous boundaries in Node.JS 10.xx 1.0.7 (2014-02-25) ------------------- Bugfixes: * Fix handled errors being reported 1.0.6 (2014-02-17) ------------------- Bugfixes: * Fix bug with unhandled rejections not being reported when using `Promise.try` or `Promise.method` without attaching further handlers 1.0.5 (2014-02-15) ------------------- Features: * Node.js performance: promisified functions try to check amount of passed arguments in most optimal order * Node.js promisified functions will have same `.length` as the original function minus one (for the callback parameter) 1.0.4 (2014-02-09) ------------------- Features: * Possibly unhandled rejection handler will always get a stack trace, even if the rejection or thrown error was not an error * Unhandled rejections are tracked per promise, not per error. So if you create multiple branches from a single ancestor and that ancestor gets rejected, each branch with no error handler with the end will cause a possibly unhandled rejection handler invocation Bugfixes: * Fix unhandled non-writable objects or primitives not reported by possibly unhandled rejection handler 1.0.3 (2014-02-05) ------------------- Bugfixes: * [#93](https://github.com/petkaantonov/bluebird/issues/88) 1.0.2 (2014-02-04) ------------------- Features: * Significantly improve performance of foreign bluebird thenables Bugfixes: * [#88](https://github.com/petkaantonov/bluebird/issues/88) 1.0.1 (2014-01-28) ------------------- Features: * Error objects that have property `.isAsync = true` will now be caught by `.error()` Bugfixes: * Fix TypeError and RangeError shims not working without `new` operator 1.0.0 (2014-01-12) ------------------- Features: * `.filter`, `.map`, and `.reduce` no longer skip sparse array holes. This is a backwards incompatible change. * Like `.map` and `.filter`, `.reduce` now allows returning promises and thenables from the iteration function. Bugfixes: * [#58](https://github.com/petkaantonov/bluebird/issues/58) * [#61](https://github.com/petkaantonov/bluebird/issues/61) * [#64](https://github.com/petkaantonov/bluebird/issues/64) * [#60](https://github.com/petkaantonov/bluebird/issues/60) 0.11.6-1 (2013-12-29) ---------------------- 0.11.6-0 (2013-12-29) ---------------------- Features: * You may now return promises and thenables from the filterer function used in `Promise.filter` and `Promise.prototype.filter`. * `.error()` now catches additional sources of rejections: + Rejections originating from `Promise.reject` + Rejections originating from thenables using the `reject` callback + Rejections originating from promisified callbacks which use the `errback` argument + Rejections originating from `new Promise` constructor where the `reject` callback is called explicitly + Rejections originating from `PromiseResolver` where `.reject()` method is called explicitly Bugfixes: * Fix `captureStackTrace` being called when it was `null` * Fix `Promise.map` not unwrapping thenables 0.11.5-1 (2013-12-15) ---------------------- 0.11.5-0 (2013-12-03) ---------------------- Features: * Improve performance of collection methods * Improve performance of promise chains 0.11.4-1 (2013-12-02) ---------------------- 0.11.4-0 (2013-12-02) ---------------------- Bugfixes: * Fix `Promise.some` behavior with arguments like negative integers, 0... * Fix stack traces of synchronously throwing promisified functions' 0.11.3-0 (2013-12-02) ---------------------- Features: * Improve performance of generators Bugfixes: * Fix critical bug with collection methods. 0.11.2-0 (2013-12-02) ---------------------- Features: * Improve performance of all collection methods 0.11.1-0 (2013-12-02) ---------------------- Features: * Improve overall performance. * Improve performance of promisified functions. * Improve performance of catch filters. * Improve performance of .finally. Bugfixes: * Fix `.finally()` rejecting if passed non-function. It will now ignore non-functions like `.then`. * Fix `.finally()` not converting thenables returned from the handler to promises. * `.spread()` now rejects if the ultimate value given to it is not spreadable. 0.11.0-0 (2013-12-02) ---------------------- Features: * Improve overall performance when not using `.bind()` or cancellation. * Promises are now not cancellable by default. This is backwards incompatible change - see [`.cancellable()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellable---promise) * [`Promise.delay`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise) * [`.delay()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#delayint-ms---promise) * [`.timeout()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#timeoutint-ms--string-message---promise) 0.10.14-0 (2013-12-01) ----------------------- Bugfixes: * Fix race condition when mixing 3rd party asynchrony. 0.10.13-1 (2013-11-30) ----------------------- 0.10.13-0 (2013-11-30) ----------------------- Bugfixes: * Fix another bug with progression. 0.10.12-0 (2013-11-30) ----------------------- Bugfixes: * Fix bug with progression. 0.10.11-4 (2013-11-29) ----------------------- 0.10.11-2 (2013-11-29) ----------------------- Bugfixes: * Fix `.race()` not propagating bound values. 0.10.11-1 (2013-11-29) ----------------------- Features: * Improve performance of `Promise.race` 0.10.11-0 (2013-11-29) ----------------------- Bugfixes: * Fixed `Promise.promisifyAll` invoking property accessors. Only data properties with function values are considered. 0.10.10-0 (2013-11-28) ----------------------- Features: * Disable long stack traces in browsers by default. Call `Promise.longStackTraces()` to enable them. 0.10.9-1 (2013-11-27) ---------------------- Bugfixes: * Fail early when `new Promise` is constructed incorrectly 0.10.9-0 (2013-11-27) ---------------------- Bugfixes: * Promise.props now takes a [thenable-for-collection](https://github.com/petkaantonov/bluebird/blob/f41edac61b7c421608ff439bb5a09b7cffeadcf9/test/mocha/props.js#L197-L217) * All promise collection methods now reject when a promise-or-thenable-for-collection turns out not to give a collection 0.10.8-0 (2013-11-25) ---------------------- Features: * All static collection methods take thenable-for-collection 0.10.7-0 (2013-11-25) ---------------------- Features: * throw TypeError when thenable resolves with itself * Make .race() and Promise.race() forever pending on empty collections 0.10.6-0 (2013-11-25) ---------------------- Bugfixes: * Promise.resolve and PromiseResolver.resolve follow thenables too. 0.10.5-0 (2013-11-24) ---------------------- Bugfixes: * Fix infinite loop when thenable resolves with itself 0.10.4-1 (2013-11-24) ---------------------- Bugfixes: * Fix a file missing from build. (Critical fix) 0.10.4-0 (2013-11-24) ---------------------- Features: * Remove dependency of es5-shim and es5-sham when using ES3. 0.10.3-0 (2013-11-24) ---------------------- Features: * Improve performance of `Promise.method` 0.10.2-1 (2013-11-24) ---------------------- Features: * Rename PromiseResolver#asCallback to PromiseResolver#callback 0.10.2-0 (2013-11-24) ---------------------- Features: * Remove memoization of thenables 0.10.1-0 (2013-11-21) ---------------------- Features: * Add methods `Promise.resolve()`, `Promise.reject()`, `Promise.defer()` and `.resolve()`. 0.10.0-1 (2013-11-17) ---------------------- 0.10.0-0 (2013-11-17) ---------------------- Features: * Implement `Promise.method()` * Implement `.return()` * Implement `.throw()` Bugfixes: * Fix promises being able to use themselves as resolution or follower value 0.9.11-1 (2013-11-14) ---------------------- Features: * Implicit `Promise.all()` when yielding an array from generators 0.9.11-0 (2013-11-13) ---------------------- Bugfixes: * Fix `.spread` not unwrapping thenables 0.9.10-2 (2013-11-13) ---------------------- Features: * Improve performance of promisified functions on V8 Bugfixes: * Report unhandled rejections even when long stack traces are disabled * Fix `.error()` showing up in stack traces 0.9.10-1 (2013-11-05) ---------------------- Bugfixes: * Catch filter method calls showing in stack traces 0.9.10-0 (2013-11-05) ---------------------- Bugfixes: * Support primitives in catch filters 0.9.9-0 (2013-11-05) --------------------- Features: * Add `Promise.race()` and `.race()` 0.9.8-0 (2013-11-01) --------------------- Bugfixes: * Fix bug with `Promise.try` not unwrapping returned promises and thenables 0.9.7-0 (2013-10-29) --------------------- Bugfixes: * Fix bug with build files containing duplicated code for promise.js 0.9.6-0 (2013-10-28) --------------------- Features: * Improve output of reporting unhandled non-errors * Implement RejectionError wrapping and `.error()` method 0.9.5-0 (2013-10-27) --------------------- Features: * Allow fresh copies of the library to be made 0.9.4-1 (2013-10-27) --------------------- 0.9.4-0 (2013-10-27) --------------------- Bugfixes: * Rollback non-working multiple fresh copies feature 0.9.3-0 (2013-10-27) --------------------- Features: * Allow fresh copies of the library to be made * Add more components to customized builds 0.9.2-1 (2013-10-25) --------------------- 0.9.2-0 (2013-10-25) --------------------- Features: * Allow custom builds 0.9.1-1 (2013-10-22) --------------------- Bugfixes: * Fix unhandled rethrown exceptions not reported 0.9.1-0 (2013-10-22) --------------------- Features: * Improve performance of `Promise.try` * Extend `Promise.try` to accept arguments and ctx to make it more usable in promisification of synchronous functions. 0.9.0-0 (2013-10-18) --------------------- Features: * Implement `.bind` and `Promise.bind` Bugfixes: * Fix `.some()` when argument is a pending promise that later resolves to an array 0.8.5-1 (2013-10-17) --------------------- Features: * Enable process wide long stack traces through BLUEBIRD_DEBUG environment variable 0.8.5-0 (2013-10-16) --------------------- Features: * Improve performance of all collection methods Bugfixes: * Fix .finally passing the value to handlers * Remove kew from benchmarks due to bugs in the library breaking the benchmark * Fix some bluebird library calls potentially appearing in stack traces 0.8.4-1 (2013-10-15) --------------------- Bugfixes: * Fix .pending() call showing in long stack traces 0.8.4-0 (2013-10-15) --------------------- Bugfixes: * Fix PromiseArray and its sub-classes swallowing possibly unhandled rejections 0.8.3-3 (2013-10-14) --------------------- Bugfixes: * Fix AMD-declaration using named module. 0.8.3-2 (2013-10-14) --------------------- Features: * The mortals that can handle it may now release Zalgo by `require("bluebird/zalgo");` 0.8.3-1 (2013-10-14) --------------------- Bugfixes: * Fix memory leak when using the same promise to attach handlers over and over again 0.8.3-0 (2013-10-13) --------------------- Features: * Add `Promise.props()` and `Promise.prototype.props()`. They work like `.all()` for object properties. Bugfixes: * Fix bug with .some returning garbage when sparse arrays have rejections 0.8.2-2 (2013-10-13) --------------------- Features: * Improve performance of `.reduce()` when `initialValue` can be synchronously cast to a value 0.8.2-1 (2013-10-12) --------------------- Bugfixes: * Fix .npmignore having irrelevant files 0.8.2-0 (2013-10-12) --------------------- Features: * Improve performance of `.some()` 0.8.1-0 (2013-10-11) --------------------- Bugfixes: * Remove uses of dynamic evaluation (`new Function`, `eval` etc) when strictly not necessary. Use feature detection to use static evaluation to avoid errors when dynamic evaluation is prohibited. 0.8.0-3 (2013-10-10) --------------------- Features: * Add `.asCallback` property to `PromiseResolver`s 0.8.0-2 (2013-10-10) --------------------- 0.8.0-1 (2013-10-09) --------------------- Features: * Improve overall performance. Be able to sustain infinite recursion when using promises. 0.8.0-0 (2013-10-09) --------------------- Bugfixes: * Fix stackoverflow error when function calls itself "synchronously" from a promise handler 0.7.12-2 (2013-10-09) ---------------------- Bugfixes: * Fix safari 6 not using `MutationObserver` as a scheduler * Fix process exceptions interfering with internal queue flushing 0.7.12-1 (2013-10-09) ---------------------- Bugfixes: * Don't try to detect if generators are available to allow shims to be used 0.7.12-0 (2013-10-08) ---------------------- Features: * Promisification now consider all functions on the object and its prototype chain * Individual promisifcation uses current `this` if no explicit receiver is given * Give better stack traces when promisified callbacks throw or errback primitives such as strings by wrapping them in an `Error` object. Bugfixes: * Fix runtime APIs throwing synchronous errors 0.7.11-0 (2013-10-08) ---------------------- Features: * Deprecate `Promise.promisify(Object target)` in favor of `Promise.promisifyAll(Object target)` to avoid confusion with function objects * Coroutines now throw error when a non-promise is `yielded` 0.7.10-1 (2013-10-05) ---------------------- Features: * Make tests pass Internet Explorer 8 0.7.10-0 (2013-10-05) ---------------------- Features: * Create browser tests 0.7.9-1 (2013-10-03) --------------------- Bugfixes: * Fix promise cast bug when thenable fulfills using itself as the fulfillment value 0.7.9-0 (2013-10-03) --------------------- Features: * More performance improvements when long stack traces are enabled 0.7.8-1 (2013-10-02) --------------------- Features: * Performance improvements when long stack traces are enabled 0.7.8-0 (2013-10-02) --------------------- Bugfixes: * Fix promisified methods not turning synchronous exceptions into rejections 0.7.7-1 (2013-10-02) --------------------- Features: * feature Bugfixes: * bugfix 0.7.7-0 (2013-10-01) --------------------- Features: * feature Bugfixes: * bugfix 0.7.6-0 (2013-09-29) --------------------- Features: * feature Bugfixes: * bugfix 0.7.5-0 (2013-09-28) --------------------- Features: * feature Bugfixes: * bugfix 0.7.4-1 (2013-09-28) --------------------- Features: * feature Bugfixes: * bugfix 0.7.4-0 (2013-09-28) --------------------- Features: * feature Bugfixes: * bugfix 0.7.3-1 (2013-09-28) --------------------- Features: * feature Bugfixes: * bugfix 0.7.3-0 (2013-09-27) --------------------- Features: * feature Bugfixes: * bugfix 0.7.2-0 (2013-09-27) --------------------- Features: * feature Bugfixes: * bugfix 0.7.1-5 (2013-09-26) --------------------- Features: * feature Bugfixes: * bugfix 0.7.1-4 (2013-09-25) --------------------- Features: * feature Bugfixes: * bugfix 0.7.1-3 (2013-09-25) --------------------- Features: * feature Bugfixes: * bugfix 0.7.1-2 (2013-09-24) --------------------- Features: * feature Bugfixes: * bugfix 0.7.1-1 (2013-09-24) --------------------- Features: * feature Bugfixes: * bugfix 0.7.1-0 (2013-09-24) --------------------- Features: * feature Bugfixes: * bugfix 0.7.0-1 (2013-09-23) --------------------- Features: * feature Bugfixes: * bugfix 0.7.0-0 (2013-09-23) --------------------- Features: * feature Bugfixes: * bugfix 0.6.5-2 (2013-09-20) --------------------- Features: * feature Bugfixes: * bugfix 0.6.5-1 (2013-09-18) --------------------- Features: * feature Bugfixes: * bugfix 0.6.5-0 (2013-09-18) --------------------- Features: * feature Bugfixes: * bugfix 0.6.4-1 (2013-09-18) --------------------- Features: * feature Bugfixes: * bugfix 0.6.4-0 (2013-09-18) --------------------- Features: * feature Bugfixes: * bugfix 0.6.3-4 (2013-09-18) --------------------- Features: * feature Bugfixes: * bugfix 0.6.3-3 (2013-09-18) --------------------- Features: * feature Bugfixes: * bugfix 0.6.3-2 (2013-09-16) --------------------- Features: * feature Bugfixes: * bugfix 0.6.3-1 (2013-09-16) --------------------- Features: * feature Bugfixes: * bugfix 0.6.3-0 (2013-09-15) --------------------- Features: * feature Bugfixes: * bugfix 0.6.2-1 (2013-09-14) --------------------- Features: * feature Bugfixes: * bugfix 0.6.2-0 (2013-09-14) --------------------- Features: * feature Bugfixes: * bugfix 0.6.1-0 (2013-09-14) --------------------- Features: * feature Bugfixes: * bugfix 0.6.0-0 (2013-09-13) --------------------- Features: * feature Bugfixes: * bugfix 0.5.9-6 (2013-09-12) --------------------- Features: * feature Bugfixes: * bugfix 0.5.9-5 (2013-09-12) --------------------- Features: * feature Bugfixes: * bugfix 0.5.9-4 (2013-09-12) --------------------- Features: * feature Bugfixes: * bugfix 0.5.9-3 (2013-09-11) --------------------- Features: * feature Bugfixes: * bugfix 0.5.9-2 (2013-09-11) --------------------- Features: * feature Bugfixes: * bugfix 0.5.9-1 (2013-09-11) --------------------- Features: * feature Bugfixes: * bugfix 0.5.9-0 (2013-09-11) --------------------- Features: * feature Bugfixes: * bugfix 0.5.8-1 (2013-09-11) --------------------- Features: * feature Bugfixes: * bugfix 0.5.8-0 (2013-09-11) --------------------- Features: * feature Bugfixes: * bugfix 0.5.7-0 (2013-09-11) --------------------- Features: * feature Bugfixes: * bugfix 0.5.6-1 (2013-09-10) --------------------- Features: * feature Bugfixes: * bugfix 0.5.6-0 (2013-09-10) --------------------- Features: * feature Bugfixes: * bugfix 0.5.5-1 (2013-09-10) --------------------- Features: * feature Bugfixes: * bugfix 0.5.5-0 (2013-09-09) --------------------- Features: * feature Bugfixes: * bugfix 0.5.4-1 (2013-09-08) --------------------- Features: * feature Bugfixes: * bugfix 0.5.4-0 (2013-09-08) --------------------- Features: * feature Bugfixes: * bugfix 0.5.3-0 (2013-09-07) --------------------- Features: * feature Bugfixes: * bugfix 0.5.2-0 (2013-09-07) --------------------- Features: * feature Bugfixes: * bugfix 0.5.1-0 (2013-09-07) --------------------- Features: * feature Bugfixes: * bugfix 0.5.0-0 (2013-09-07) --------------------- Features: * feature Bugfixes: * bugfix 0.4.0-0 (2013-09-06) --------------------- Features: * feature Bugfixes: * bugfix 0.3.0-1 (2013-09-06) --------------------- Features: * feature Bugfixes: * bugfix 0.3.0 (2013-09-06) ------------------- © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/changelog.htmlPromise.any ============ ``` Promise.any(Iterable<any>|Promise<Iterable<any>> input) -> Promise ``` Like [`Promise.some`](promise.some), with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.any.htmlPromise.some ============= ``` Promise.some( Iterable<any>|Promise<Iterable<any>> input, int count ) -> Promise ``` Given an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)(arrays are `Iterable`), or a promise of an `Iterable`, which produces promises (or a mix of promises and values), iterate over all the values in the `Iterable` into an array and return a promise that is fulfilled as soon as `count` promises are fulfilled in the array. The fulfillment value is an array with `count` values in the order they were fulfilled. This example pings 4 nameservers, and logs the fastest 2 on console: ``` Promise.some([ ping("ns1.example.com"), ping("ns2.example.com"), ping("ns3.example.com"), ping("ns4.example.com") ], 2).spread(function(first, second) { console.log(first, second); }); ``` If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an [`AggregateError`](aggregateerror) of the rejection reasons in the order they were thrown in. You can get a reference to [`AggregateError`](aggregateerror) from `Promise.AggregateError`. ``` Promise.some(...) .then(...) .then(...) .catch(Promise.AggregateError, function(err) { err.forEach(function(e) { console.error(e.stack); }); }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.some.htmlPromise.reduce =============== ``` Promise.reduce( Iterable<any>|Promise<Iterable<any>> input, function(any accumulator, any item, int index, int length) reducer, [any initialValue] ) -> Promise ``` Given an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)(arrays are `Iterable`), or a promise of an `Iterable`, which produces promises (or a mix of promises and values), iterate over all the values in the `Iterable` into an array and [reduce the array to a value](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) using the given `reducer` function. If the reducer function returns a promise, then the result of the promise is awaited, before continuing with next iteration. If any promise in the array is rejected or a promise returned by the reducer function is rejected, the result is rejected as well. Read given files sequentially while summing their contents as an integer. Each file contains just the text `10`. ``` Promise.reduce(["file1.txt", "file2.txt", "file3.txt"], function(total, fileName) { return fs.readFileAsync(fileName, "utf8").then(function(contents) { return total + parseInt(contents, 10); }); }, 0).then(function(total) { //Total is 30 }); ``` *If `initialValue` is `undefined` (or a promise that resolves to `undefined`) and the iterable contains only 1 item, the callback will not be called and the iterable's single item is returned. If the iterable is empty, the callback will not be called and `initialValue` is returned (which may be `undefined`).* `Promise.reduce` will start calling the reducer as soon as possible, this is why you might want to use it over `Promise.all` (which awaits for the entire array before you can call [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) on it). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.reduce.htmlPromise.filter =============== ``` Promise.filter( Iterable<any>|Promise<Iterable<any>> input, function(any item, int index, int length) filterer, [Object {concurrency: int=Infinity} options] ) -> Promise ``` Given an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)(arrays are `Iterable`), or a promise of an `Iterable`, which produces promises (or a mix of promises and values), iterate over all the values in the `Iterable` into an array and [filter the array to another](http://en.wikipedia.org/wiki/Filter_(higher-order_function)) using the given `filterer` function. It is essentially an efficient shortcut for doing a [`.map`](map) and then [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter): ``` Promise.map(valuesToBeFiltered, function(value, index, length) { return Promise.all([filterer(value, index, length), value]); }).then(function(values) { return values.filter(function(stuff) { return stuff[0] == true }).map(function(stuff) { return stuff[1]; }); }); ``` Example for filtering files that are accessible directories in the current directory: ``` var Promise = require("bluebird"); var E = require("core-error-predicates"); var fs = Promise.promisifyAll(require("fs")); fs.readdirAsync(process.cwd()).filter(function(fileName) { return fs.statAsync(fileName) .then(function(stat) { return stat.isDirectory(); }) .catch(E.FileAccessError, function() { return false; }); }).each(function(directoryName) { console.log(directoryName, " is an accessible directory"); }); ``` #### Filter Option: concurrency See [Map Option: concurrency](#map-option-concurrency) Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.filter.htmlPromise.race ============= ``` Promise.race(Iterable<any>|Promise<Iterable<any>> input) -> Promise ``` Given an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)(arrays are `Iterable`), or a promise of an `Iterable`, which produces promises (or a mix of promises and values), iterate over all the values in the `Iterable` into an array and return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. This method is only implemented because it's in the ES6 standard. If you want to race promises to fulfillment the [`.any`](any) method is more appropriate as it doesn't qualify a rejected promise as the winner. It also has less surprises: `.race` must become infinitely pending if an empty array is passed but passing an empty array to [`.any`](any) is more usefully a `RangeError` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.race.html.all ===== ``` .all() -> Promise ``` Consume the resolved [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and wait for all items to fulfill similar to [`Promise.all()`](promise.all). [`Promise.resolve(iterable).all()`](promise.resolve) is the same as [`Promise.all(iterable)`](promise.all). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/all.html.props ======= ``` .props() -> Promise ``` Same as [`Promise.props(this)`](promise.props). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/props.html.any ===== ``` .any() -> Promise ``` Same as [`Promise.any(this)`](promise.any). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/any.html.some ====== ``` .some(int count) -> Promise ``` Same as [`Promise.some(this, count)`](promise.some). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/some.html.map ===== ``` .map( function(any item, int index, int length) mapper, [Object {concurrency: int=Infinity} options] ) -> Promise ``` Same as [`Promise.map(this, mapper, options)`](promise.map). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/map.html.reduce ======== ``` .reduce( function(any accumulator, any item, int index, int length) reducer, [any initialValue] ) -> Promise ``` Same as [`Promise.reduce(this, reducer, initialValue)`](promise.reduce). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/reduce.html.filter ======== ``` .filter( function(any item, int index, int length) filterer, [Object {concurrency: int=Infinity} options] ) -> Promise ``` Same as [`Promise.filter(this, filterer, options)`](promise.filter). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/filter.html.each ====== ``` .each(function(any item, int index, int length) iterator) -> Promise ``` Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given `iterator` function with the signature `(value, index, length)` where `value` is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, then the result of the promise is awaited, before continuing with next iteration. Example where you might want to utilize `.each`: ``` // Source: http://jakearchibald.com/2014/es7-async-functions/ function loadStory() { return getJSON('story.json') .then(function(story) { addHtmlToPage(story.heading); return story.chapterURLs.map(getJSON); }) .each(function(chapter) { addHtmlToPage(chapter.html); }) .then(function() { addTextToPage("All done"); }) .catch(function(err) { addTextToPage("Argh, broken: " + err.message); }) .then(function() { document.querySelector('.spinner').style.display = 'none'; }); } ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/each.html.mapSeries =========== ``` .mapSeries(function(any item, int index, int length) mapper) -> Promise ``` Same as [`Promise.mapSeries(this, iterator)`](promise.mapseries). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/mapseries.htmlResource management ==================== Managing resources properly without leaks can be challenging. Simply using `.finally` is not enough as the following example demonstrates: ``` function doStuff() { return Promise.all([ connectionPool.getConnectionAsync(), fs.readFileAsync("file.sql", "utf8") ]).spread(function(connection, fileContents) { return connection.query(fileContents).finally(function() { connection.close(); }); }).then(function() { console.log("query successful and connection closed"); }); } ``` It is very subtle but over time this code will exhaust the entire connection pool and the server needs to be restarted. This is because reading the file may fail and then of course `.spread` is not called at all and thus the connection is not closed. One could solve this by either reading the file first or connecting first, and only proceeding if the first step succeeds. However, this would lose a lot of the benefits of using asynchronity and we might almost as well go back to using simple synchronous code. We can do better, retaining concurrency and not leaking resources, by using: * [disposers](disposer), objects that wrap a resource and a method to release that resource, together with * [`Promise.using`](promise.using), a function to safely use disposers in a way that automatically calls their release method ``` var using = Promise.using; using(getConnection(), fs.readFileAsync("file.sql", "utf8"), function(connection, fileContents) { return connection.query(fileContents); }).then(function() { console.log("query successful and connection closed"); }); ``` Continue by reading about [disposers](disposer) and [`Promise.using`](promise.using) Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/resource-management.htmlPromise.map ============ ``` Promise.map( Iterable<any>|Promise<Iterable<any>> input, function(any item, int index, int length) mapper, [Object {concurrency: int=Infinity} options] ) -> Promise ``` Given a finite [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)(arrays are `Iterable`), or a promise of an `Iterable`, which produces promises (or a mix of promises and values), iterate over all the values in the `Iterable` into an array and [map the array to another](http://en.wikipedia.org/wiki/Map_(higher-order_function)) using the given `mapper` function. Promises returned by the `mapper` function are awaited for and the returned promise doesn't fulfill until all mapped promises have fulfilled as well. If any promise in the array is rejected, or any promise returned by the `mapper` function is rejected, the returned promise is rejected as well. The mapper function for a given item is called as soon as possible, that is, when the promise for that item's index in the input array is fulfilled. This doesn't mean that the result array has items in random order, it means that `.map` can be used for concurrency coordination unlike `.all`. A common use of `Promise.map` is to replace the `.push`+`Promise.all` boilerplate: ``` var promises = []; for (var i = 0; i < fileNames.length; ++i) { promises.push(fs.readFileAsync(fileNames[i])); } Promise.all(promises).then(function() { console.log("done"); }); // Using Promise.map: Promise.map(fileNames, function(fileName) { // Promise.map awaits for returned promises as well. return fs.readFileAsync(fileName); }).then(function() { console.log("done"); }); // Using Promise.map and async/await: await Promise.map(fileNames, function(fileName) { // Promise.map awaits for returned promises as well. return fs.readFileAsync(fileName); }); console.log("done"); ``` A more involved example: ``` var Promise = require("bluebird"); var join = Promise.join; var fs = Promise.promisifyAll(require("fs")); fs.readdirAsync(".").map(function(fileName) { var stat = fs.statAsync(fileName); var contents = fs.readFileAsync(fileName).catch(function ignore() {}); return join(stat, contents, function(stat, contents) { return { stat: stat, fileName: fileName, contents: contents } }); // The return value of .map is a promise that is fulfilled with an array of the mapped values // That means we only get here after all the files have been statted and their contents read // into memory. If you need to do more operations per file, they should be chained in the map // callback for concurrency. }).call("sort", function(a, b) { return a.fileName.localeCompare(b.fileName); }).each(function(file) { var contentLength = file.stat.isDirectory() ? "(directory)" : file.contents.length + " bytes"; console.log(file.fileName + " last modified " + file.stat.mtime + " " + contentLength) }); ``` #### Map Option: concurrency You may optionally specify a concurrency limit: ``` ...map(..., {concurrency: 3}); ``` The concurrency limit applies to Promises returned by the mapper function and it basically limits the number of Promises created. For example, if `concurrency` is `3` and the mapper callback has been called enough so that there are three returned Promises currently pending, no further callbacks are called until one of the pending Promises resolves. So the mapper function will be called three times and it will be called again only after at least one of the Promises resolves. Playing with the first example with and without limits, and seeing how it affects the duration when reading 20 files: ``` var Promise = require("bluebird"); var join = Promise.join; var fs = Promise.promisifyAll(require("fs")); var concurrency = parseFloat(process.argv[2] || "Infinity"); console.time("reading files"); fs.readdirAsync(".").map(function(fileName) { var stat = fs.statAsync(fileName); var contents = fs.readFileAsync(fileName).catch(function ignore() {}); return join(stat, contents, function(stat, contents) { return { stat: stat, fileName: fileName, contents: contents } }); // The return value of .map is a promise that is fulfilled with an array of the mapped values // That means we only get here after all the files have been statted and their contents read // into memory. If you need to do more operations per file, they should be chained in the map // callback for concurrency. }, {concurrency: concurrency}).call("sort", function(a, b) { return a.fileName.localeCompare(b.fileName); }).then(function() { console.timeEnd("reading files"); }); ``` ``` $ sync && echo 3 > /proc/sys/vm/drop_caches $ node test.js 1 reading files 35ms $ sync && echo 3 > /proc/sys/vm/drop_caches $ node test.js Infinity reading files: 9ms ``` The order `map` calls the mapper function on the array elements is not specified, there is no guarantee on the order in which it'll execute the `map`er on the elements. For order guarantee in sequential execution - see [`Promise.mapSeries`](promise.mapseries). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.map.htmlPromise.each ============= ``` Promise.each( Iterable<any>|Promise<Iterable<any>> input, function(any value, int index, int arrayLength) iterator ) -> Promise<Array<any>``` Given an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) (an array, for example), or a promise of an `Iterable`, iterates serially over all the values in it, executing the given `iterator` on each element. If an element is a promise, the iterator will wait for it before proceeding. The `iterator` function has signature `(value, index, arrayLength)` where `value` is the current element (or its resolved value if it is a promise). If, at any step: * The iterator returns a promise or a thenable, it is awaited before continuing to the next iteration. * The current element of the iteration is a *pending* promise, that promise will be awaited before running the iterator. * The current element of the iteration is a *rejected* promise, the iteration will stop and be rejected as well (with the same reason). If all iterations resolve successfully, the `Promise.each` call resolves to a new array containing the resolved values of the original input elements. `Promise.each` is very similar to [`Promise.mapSeries`](promise.mapseries). The difference between `Promise.each` and `Promise.mapSeries` is their resolution value. `Promise.each` resolves with an array as explained above, while `Promise.mapSeries` resolves with an array containing the *outputs* of the iterator function on each step. This way, `Promise.each` is meant to be mainly used for side-effect operations (since the outputs of the iterator are essentially discarded), just like the native `.forEach()` method of arrays, while `Promise.map` is meant to be used as an async version of the native `.map()` method of arrays. Basic example: ``` // The array to be iterated over can be a mix of values and promises. var fileNames = ["1.txt", Promise.resolve("2.txt"), "3.txt", Promise.delay(3000, "4.txt"), "5.txt"]; Promise.each(fileNames, function(fileName, index, arrayLength) { // The iteration will be performed sequentially, awaiting for any // promises in the process. return fs.readFileAsync(fileName).then(function(fileContents) { // ... // The final resolution value of the iterator is is irrelevant, // since the result of the `Promise.each` has nothing to do with // the outputs of the iterator. return "anything"; // Doesn't matter }); }).then(function(result) { // This will run after the last step is done console.log("Done!") console.log(result); // ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt"] }); ``` Example with a rejected promise in the array: ``` // If one of the promises in the original array rejects, // the iteration will stop once it reaches it var items = ["A", Promise.delay(8000, "B"), Promise.reject("C"), "D"]; Promise.each(items, function(item) { return Promise.delay(4000).then(function() { console.log("On iterator: " + item); }); }).then(function(result) { // This not run }).catch(function(rejection) { console.log("Catch: " + rejection); }); // The code above outputs the following after 12 seconds (not 16!): // On iterator: A // On iterator: B // Catch: C ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.each.htmlPromise.mapSeries ================== ``` Promise.mapSeries( Iterable<any>|Promise<Iterable<any>> input, function(any value, int index, int arrayLength) mapper ) -> Promise<Array<any>``` Given an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) (an array, for example), or a promise of an `Iterable`, iterates serially over all the values in it, executing the given `mapper` on each element. If an element is a promise, the mapper will wait for it before proceeding. The `mapper` function has signature `(value, index, arrayLength)` where `value` is the current element (or its resolved value if it is a promise). If, at any step: * The mapper returns a promise or a thenable, it is awaited before continuing to the next iteration. * The current element of the iteration is a *pending* promise, that promise will be awaited before running the mapper. * The current element of the iteration is a *rejected* promise, the iteration will stop and be rejected as well (with the same reason). If all iterations resolve successfully, the `Promise.mapSeries` call resolves to a new array containing the results of each `mapper` execution, in order. `Promise.mapSeries` is very similar to [`Promise.each`](promise.each). The difference between `Promise.each` and `Promise.mapSeries` is their resolution value. `Promise.mapSeries` resolves with an array as explained above, while `Promise.each` resolves with an array containing the *resolved values of the input elements* (ignoring the outputs of the iteration steps). This way, `Promise.each` is meant to be mainly used for side-effect operations (since the outputs of the iterator are essentially discarded), just like the native `.forEach()` method of arrays, while `Promise.map` is meant to be used as an async version of the native `.map()` method of arrays. Basic example: ``` // The array to be mapped over can be a mix of values and promises. var fileNames = ["1.txt", Promise.resolve("2.txt"), "3.txt", Promise.delay(3000, "4.txt"), "5.txt"]; Promise.mapSeries(fileNames, function(fileName, index, arrayLength) { // The iteration will be performed sequentially, awaiting for any // promises in the process. return fs.readFileAsync(fileName).then(function(fileContents) { // ... return fileName + "!"; }); }).then(function(result) { // This will run after the last step is done console.log("Done!") console.log(result); // ["1.txt!", "2.txt!", "3.txt!", "4.txt!", "5.txt!"] }); ``` Example with a rejected promise in the array: ``` // If one of the promises in the original array rejects, // the iteration will stop once it reaches it var items = ["A", Promise.delay(8000, "B"), Promise.reject("C"), "D"]; Promise.each(items, function(item) { return Promise.delay(4000).then(function() { console.log("On mapper: " + item); }); }).then(function(result) { // This not run }).catch(function(rejection) { console.log("Catch: " + rejection); }); // The code above outputs the following after 12 seconds (not 16!): // On mapper: A // On mapper: B // Catch: C ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.mapseries.htmlPromise.using ============== ``` Promise.using( Promise|Disposer|any resource, Promise|Disposer|any resource..., function(any resources...) handler ) -> Promise ``` ``` Promise.using( Array<Promise|Disposer|Any> resources, function(Array<any> resources) handler ) -> Promise ``` In conjunction with [`.disposer`](disposer), `using` will make sure that no matter what, the specified disposer will be called when the promise returned by the callback passed to `using` has settled. The disposer is necessary because there is no standard interface in node for disposing resources. Here is a simple example (where `getConnection()` has been defined to return a proper Disposer object) ``` using(getConnection(), function(connection) { // Don't leak the `connection` variable anywhere from here // it is only guaranteed to be open while the promise returned from // this callback is still pending return connection.queryAsync("SELECT * FROM TABLE"); // Code that is chained from the promise created in the line above // still has access to `connection` }).then(function(rows) { // The connection has been closed by now console.log(rows); }); ``` Using multiple resources: ``` using(getConnection(), function(conn1) { return using(getConnection(), function(conn2) { // use conn1 and conn 2 here }); }).then(function() { // Both connections closed by now }) ``` The above can also be written as (with a caveat, see below) ``` using(getConnection(), getConnection(), function(conn1, conn2) { // use conn1 and conn2 }).then(function() { // Both connections closed by now }) ``` However, if the second `getConnection` throws **synchronously**, the first connection is leaked. This will not happen when using APIs through bluebird promisified methods though. You can wrap functions that could throw in [`Promise.method`](promise.method) which will turn synchronous rejections into rejected promises. Note that you can mix promises and disposers, so that you can acquire all the things you need in parallel instead of sequentially ``` // The files don't need resource management but you should // still start the process of reading them even before you have the connection // instead of waiting for the connection // The connection is always closed, no matter what fails at what point using(readFile("1.txt"), readFile("2.txt"), getConnection(), function(txt1, txt2, conn) { // use conn and have access to txt1 and txt2 }); ``` You can also pass the resources in an array in the first argument. In this case the handler function will only be called with one argument that is the array containing the resolved resources in respective positions in the array. Example: ``` var connectionPromises = [getConnection(), getConnection()]; using(connectionPromises, function(connections) { var conn1 = connections[0]; var conn2 = connections[1]; // use conn1 and conn2 }).then(function() { // Both connections closed by now }) ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.using.html.disposer ========== ``` .disposer(function(any resource, Promise usingOutcomePromise) disposer) -> Disposer ``` A meta method used to specify the disposer method that cleans up a resource when using [`Promise.using`](promise.using). Returns a Disposer object which encapsulates both the resource as well as the method to clean it up. The user can pass this object to `Promise.using` to get access to the resource when it becomes available, as well as to ensure it's automatically cleaned up. The second argument passed to a disposer is the result promise of the using block, which you can inspect synchronously. Example: ``` // This function doesn't return a promise but a Disposer // so it's very hard to use it wrong (not passing it to `using`) function getConnection() { return db.connect().disposer(function(connection, promise) { connection.close(); }); } ``` In the above example, the connection returned by `getConnection` can only be used via `Promise.using`, like so: ``` function useConnection(query) { return Promise.using(getConnection(), function(connection) { return connection.sendQuery(query).then(function(results) { return process(results); }) }); } ``` This will ensure that `connection.close()` will be called once the promise returned from the `Promise.using` closure is resolved or if an exception was thrown in the closure body. Real example: ``` var pg = require("pg"); // Uncomment if pg has not been properly promisified yet //var Promise = require("bluebird"); //Promise.promisifyAll(pg, { // filter: function(methodName) { // return methodName === "connect" // }, // multiArgs: true //}); // Promisify rest of pg normally //Promise.promisifyAll(pg); function getSqlConnection(connectionString) { var close; return pg.connectAsync(connectionString).spread(function(client, done) { close = done; return client; }).disposer(function() { if (close) close(); }); } module.exports = getSqlConnection; ``` Real example 2: ``` var mysql = require("mysql"); // Uncomment if mysql has not been properly promisified yet // var Promise = require("bluebird"); // Promise.promisifyAll(mysql); // Promise.promisifyAll(require("mysql/lib/Connection").prototype); // Promise.promisifyAll(require("mysql/lib/Pool").prototype); var pool = mysql.createPool({ connectionLimit: 10, host: 'example.org', user: 'bob', password: 'secret' }); function getSqlConnection() { return pool.getConnectionAsync().disposer(function(connection) { connection.release(); }); } module.exports = getSqlConnection; ``` #### Note about disposers in node If a disposer method throws or returns a rejected promise, it's highly likely that it failed to dispose of the resource. In that case, Bluebird has two options - it can either ignore the error and continue with program execution or throw an exception (crashing the process in node.js). In bluebird we've chosen to do the latter because resources are typically scarce. For example, if a database connection cannot be disposed of and Bluebird ignores that, the connection pool will be quickly depleted and the process will become unusable (all requests that query the database will wait forever). Since Bluebird doesn't know how to handle that, the only sensible default is to crash the process. That way, rather than getting a useless process that cannot fulfill more requests, we can swap the faulty worker with a new one letting the OS clean up the resources for us. As a result, if you anticipate thrown errors or promise rejections while disposing of the resource you should use a `try..catch` block (or Promise.try) and write the appropriate catch code to handle the errors. If it's not possible to sensibly handle the error, letting the process crash is the next best option. This also means that disposers should not contain code that does anything other than resource disposal. For example, you cannot write code inside a disposer to commit or rollback a transaction, because there is no mechanism for the disposer to signal a failure of the commit or rollback action without crashing the process. For transactions, you can use the following similar pattern instead: ``` function withTransaction(fn) { return Promise.using(pool.acquireConnection(), function(connection) { var tx = connection.beginTransaction() return Promise .try(fn, tx) .then(function(res) { return connection.commit().thenReturn(res) }, function(err) { return connection.rollback() .catch(function(e) {/* maybe add the rollback error to err */}) .thenThrow(err); }); }); } // If the withTransaction block completes successfully, the transaction is automatically committed // Any error or rejection will automatically roll it back withTransaction(function(tx) { return tx.queryAsync(...).then(function() { return tx.queryAsync(...) }).then(function() { return tx.queryAsync(...) }); }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/disposer.html.timeout ========= ``` .timeout( int ms, [String message="operation timed out"] ) -> Promise ``` ``` .timeout( int ms, [Error error] ) -> Promise ``` Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a [`TimeoutError`](timeouterror) or the `error` as the reason. When using the first signature, you may specify a custom error message with the `message` parameter. ``` var Promise = require("bluebird"); var fs = Promise.promisifyAll(require('fs')); fs.readFileAsync("huge-file.txt").timeout(100).then(function(fileContents) { }).catch(Promise.TimeoutError, function(e) { console.log("could not read file within 100ms"); }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/timeout.htmlPromise.promisify ================== ``` Promise.promisify( function(any arguments..., function callback) nodeFunction, [Object { multiArgs: boolean=false, context: any=this } options] ) -> function ``` Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be the first fulfillment item. Setting `multiArgs` to `true` means the resulting promise will always fulfill with an array of the callback's success value(s). This is needed because promises only support a single success value while some callback API's have multiple success value. The default is to ignore all but the first success value of a callback function. If you pass a `context`, the `nodeFunction` will be called as a method on the `context`. Example of promisifying the asynchronous `readFile` of node.js `fs`-module: ``` var readFile = Promise.promisify(require("fs").readFile); readFile("myfile.js", "utf8").then(function(contents) { return eval(contents); }).then(function(result) { console.log("The result of evaluating myfile.js", result); }).catch(SyntaxError, function(e) { console.log("File had syntax error", e); //Catch any other error }).catch(function(e) { console.log("Error reading file", e); }); ``` Note that if the node function is a method of some object, you can pass the object as the second argument like so: ``` var redisGet = Promise.promisify(redisClient.get, {context: redisClient}); redisGet('foo').then(function() { //... }); ``` But this will also work: ``` var getAsync = Promise.promisify(redisClient.get); getAsync.call(redisClient, 'foo').then(function() { //... }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.promisify.htmlTimers ======= Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/timers.htmlPromise.delay ============== ``` Promise.delay( int ms, [any|Promise<any> value=undefined] ) -> Promise ``` Returns a promise that will be resolved with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. If `value` is a rejected promise, the resulting promise will be rejected immediately. ``` Promise.delay(500).then(function() { console.log("500 ms passed"); return "Hello world"; }).delay(500).then(function(helloWorldString) { console.log(helloWorldString); console.log("another 500 ms passed") ; }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.delay.html.delay ======= ``` .delay(int ms) -> Promise ``` Same as calling [`Promise.delay(ms, this)`](promise.delay). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/delay.html.cancel ======== ``` .cancel() -> undefined ``` Cancel this promise. Will not do anything if this promise is already settled or if the [`Cancellation`](cancellation) feature has not been enabled. See [`Cancellation`](cancellation) for how to use cancellation. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/cancel.htmlGenerators =========== Using ECMAScript6 generators feature to implement C# 5.0 `async/await` like syntax. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/generators.htmlPromise.coroutine ================== ``` Promise.coroutine(GeneratorFunction(...arguments) generatorFunction, Object options) -> function ``` Returns a function that can use `yield` to yield promises. Control is returned back to the generator when the yielded promise settles. This can lead to less verbose code when doing lots of sequential async calls with minimal processing in between. Requires node.js 0.12+, io.js 1.0+ or Google Chrome 40+. ``` var Promise = require("bluebird"); function PingPong() { } PingPong.prototype.ping = Promise.coroutine(function* (val) { console.log("Ping?", val); yield Promise.delay(500); this.pong(val+1); }); PingPong.prototype.pong = Promise.coroutine(function* (val) { console.log("Pong!", val); yield Promise.delay(500); this.ping(val+1); }); var a = new PingPong(); a.ping(0); ``` Running the example: ``` $ node test.js Ping? 0 Pong! 1 Ping? 2 Pong! 3 Ping? 4 Pong! 5 Ping? 6 Pong! 7 Ping? 8 ... ``` When called, the coroutine function will start an instance of the generator and returns a promise for its final value. Doing `Promise.coroutine` is almost like using the C# `async` keyword to mark the function, with `yield` working as the `await` keyword. Promises are somewhat like `Task`s. **Tip** You are able to yield non-promise values by adding your own yield handler using [`Promise.coroutine.addYieldHandler`](promise.coroutine.addyieldhandler) or calling `Promise.coroutine()` with a yield handler function as `options.yieldHandler`. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.coroutine.htmlUtility ======== Functions that could potentially be handy in some situations. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/utility.htmlPromisification ================ Promisification means converting an existing promise-unaware API to a promise-returning API. The usual way to use promises in node is to [`Promise.promisifyAll`](promise.promisifyall) some API and start exclusively calling promise returning versions of the APIs methods. E.g. ``` var fs = require("fs"); Promise.promisifyAll(fs); // Now you can use fs as if it was designed to use bluebird promises from the beginning fs.readFileAsync("file.js", "utf8").then(...) ``` Note that the above is an exceptional case because `fs` is a singleton instance. Most libraries can be promisified by requiring the library's classes (constructor functions) and calling promisifyAll on the `.prototype`. This only needs to be done once in the entire application's lifetime and after that you may use the library's methods exactly as they are documented, except by appending the `"Async"`-suffix to method calls and using the promise interface instead of the callback interface. As a notable exception in `fs`, `fs.existsAsync` doesn't work as expected, because Node's `fs.exists` doesn't call back with error as first argument. More at [`#418`](https://github.com/petkaantonov/bluebird/issues/418). One possible workaround is using `fs.statAsync`. Some examples of the above practice applied to some popular libraries: ``` // The most popular redis module var Promise = require("bluebird"); Promise.promisifyAll(require("redis")); ``` ``` // The most popular mongodb module var Promise = require("bluebird"); Promise.promisifyAll(require("mongodb")); ``` ``` // The most popular mysql module var Promise = require("bluebird"); // Note that the library's classes are not properties of the main export // so we require and promisifyAll them manually Promise.promisifyAll(require("mysql/lib/Connection").prototype); Promise.promisifyAll(require("mysql/lib/Pool").prototype); ``` ``` // Mongoose var Promise = require("bluebird"); Promise.promisifyAll(require("mongoose")); ``` ``` // Request var Promise = require("bluebird"); Promise.promisifyAll(require("request")); // Use request.getAsync(...) not request(..), it will not return a promise ``` ``` // mkdir var Promise = require("bluebird"); Promise.promisifyAll(require("mkdirp")); // Use mkdirp.mkdirpAsync not mkdirp(..), it will not return a promise ``` ``` // winston var Promise = require("bluebird"); Promise.promisifyAll(require("winston")); ``` ``` // rimraf var Promise = require("bluebird"); // The module isn't promisified but the function returned is var rimrafAsync = Promise.promisify(require("rimraf")); ``` ``` // xml2js var Promise = require("bluebird"); Promise.promisifyAll(require("xml2js")); ``` ``` // jsdom var Promise = require("bluebird"); Promise.promisifyAll(require("jsdom")); ``` ``` // fs-extra var Promise = require("bluebird"); Promise.promisifyAll(require("fs-extra")); ``` ``` // prompt var Promise = require("bluebird"); Promise.promisifyAll(require("prompt")); ``` ``` // Nodemailer var Promise = require("bluebird"); Promise.promisifyAll(require("nodemailer")); ``` ``` // ncp var Promise = require("bluebird"); Promise.promisifyAll(require("ncp")); ``` ``` // pg var Promise = require("bluebird"); Promise.promisifyAll(require("pg")); ``` In all of the above cases the library made its classes available in one way or another. If this is not the case, you can still promisify by creating a throwaway instance: ``` var ParanoidLib = require("..."); var throwAwayInstance = ParanoidLib.createInstance(); Promise.promisifyAll(Object.getPrototypeOf(throwAwayInstance)); // Like before, from this point on, all new instances + even the throwAwayInstance suddenly support promises ``` See also [`Promise.promisifyAll`](promise.promisifyall). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promisification.htmlPromise.promisifyAll ===================== ``` Promise.promisifyAll( Object target, [Object { suffix: String="Async", multiArgs: boolean=false, filter: boolean function(String name, function func, Object target, boolean passesDefaultFilter), promisifier: function(function originalFunction, function defaultPromisifier) } options] ) -> Object ``` Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name suffixed with `suffix` (default is `"Async"`). Any class properties of the object (which is the case for the main export of many modules) are also promisified, both static and instance methods. Class property is a property with a function value that has a non-empty `.prototype` object. Returns the input object. Note that the original methods on the object are not overwritten but new methods are created with the `Async`-suffix. For example, if you `promisifyAll` the node.js `fs` object use `fs.statAsync` to call the promisified `stat` method. Example: ``` Promise.promisifyAll(require("redis")); //Later on, all redis client instances have promise returning functions: redisClient.hexistsAsync("myhash", "field").then(function(v) { }).catch(function(e) { }); ``` It also works on singletons or specific instances: ``` var fs = Promise.promisifyAll(require("fs")); fs.readFileAsync("myfile.js", "utf8").then(function(contents) { console.log(contents); }).catch(function(e) { console.error(e.stack); }); ``` See [promisification](#promisification) for more examples. The entire prototype chain of the object is promisified on the object. Only enumerable are considered. If the object already has a promisified version of the method, it will be skipped. The target methods are assumed to conform to node.js callback convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. If the node method calls its callback with multiple success values, the fulfillment value will be an array of them. If a method name already has an `"Async"`-suffix, an exception will be thrown. #### Option: suffix Optionally, you can define a custom suffix through the options object: ``` var fs = Promise.promisifyAll(require("fs"), {suffix: "MySuffix"}); fs.readFileMySuffix(...).then(...); ``` All the above limitations apply to custom suffices: * Choose the suffix carefully, it must not collide with anything * PascalCase the suffix * The suffix must be a valid JavaScript identifier using ASCII letters * Always use the same suffix everywhere in your application, you could create a wrapper to make this easier: ``` module.exports = function myPromisifyAll(target) { return Promise.promisifyAll(target, {suffix: "MySuffix"}); }; ``` #### Option: multiArgs Setting `multiArgs` to `true` means the resulting promise will always fulfill with an array of the callback's success value(s). This is needed because promises only support a single success value while some callback API's have multiple success value. The default is to ignore all but the first success value of a callback function. If a module has multiple argument callbacks as an exception rather than the rule, you can filter out the multiple argument methods in first go and then promisify rest of the module in second go: ``` Promise.promisifyAll(something, { filter: function(name) { return name === "theMultiArgMethodIwant"; }, multiArgs: true }); // Rest of the methods Promise.promisifyAll(something); ``` #### Option: filter Optionally, you can define a custom filter through the options object: ``` Promise.promisifyAll(..., { filter: function(name, func, target, passesDefaultFilter) { // name = the property name to be promisified without suffix // func = the function // target = the target object where the promisified func will be put with name + suffix // passesDefaultFilter = whether the default filter would be passed // return boolean (return value is coerced, so not returning anything is same as returning false) return passesDefaultFilter && ... } }) ``` The default filter function will ignore properties that start with a leading underscore, properties that are not valid JavaScript identifiers and constructor functions (function which have enumerable properties in their `.prototype`). #### Option: promisifier Optionally, you can define a custom promisifier, so you could promisifyAll e.g. the chrome APIs used in Chrome extensions. The promisifier gets a reference to the original method and should return a function which returns a promise. ``` function DOMPromisifier(originalMethod) { // return a function return function promisified() { var args = [].slice.call(arguments); // Needed so that the original method can be called with the correct receiver var self = this; // which returns a promise return new Promise(function(resolve, reject) { args.push(resolve, reject); originalMethod.apply(self, args); }); }; } // Promisify e.g. chrome.browserAction Promise.promisifyAll(chrome.browserAction, {promisifier: DOMPromisifier}); // Later chrome.browserAction.getTitleAsync({tabId: 1}) .then(function(result) { }); ``` Combining `filter` with `promisifier` for the restler module to promisify event emitter: ``` var Promise = require("bluebird"); var restler = require("restler"); var methodNamesToPromisify = "get post put del head patch json postJson putJson".split(" "); function EventEmitterPromisifier(originalMethod) { // return a function return function promisified() { var args = [].slice.call(arguments); // Needed so that the original method can be called with the correct receiver var self = this; // which returns a promise return new Promise(function(resolve, reject) { // We call the originalMethod here because if it throws, // it will reject the returned promise with the thrown error var emitter = originalMethod.apply(self, args); emitter .on("success", function(data, response) { resolve([data, response]); }) .on("fail", function(data, response) { // Erroneous response like 400 resolve([data, response]); }) .on("error", function(err) { reject(err); }) .on("abort", function() { reject(new Promise.CancellationError()); }) .on("timeout", function() { reject(new Promise.TimeoutError()); }); }); }; }; Promise.promisifyAll(restler, { filter: function(name) { return methodNamesToPromisify.indexOf(name) > -1; }, promisifier: EventEmitterPromisifier }); // ... // Later in some other file var restler = require("restler"); restler.getAsync("http://...", ...,).spread(function(data, response) { }) ``` Using `defaultPromisifier` parameter to add enhancements on top of normal node promisification: ``` var fs = Promise.promisifyAll(require("fs"), { promisifier: function(originalFunction, defaultPromisifer) { var promisified = defaultPromisifier(originalFunction); return function() { // Enhance normal promisification by supporting promises as // arguments var args = [].slice.call(arguments); var self = this; return Promise.all(args).then(function(awaitedArgs) { return promisified.apply(self, awaitedArgs); }); }; } }); // All promisified fs functions now await their arguments if they are promises var version = fs.readFileAsync("package.json", "utf8").then(JSON.parse).get("version"); fs.writeFileAsync("the-version.txt", version, "utf8"); ``` #### Promisifying multiple classes in one go You can promisify multiple classes in one go by constructing an array out of the classes and passing it to `promisifyAll`: ``` var Pool = require("mysql/lib/Pool"); var Connection = require("mysql/lib/Connection"); Promise.promisifyAll([Pool, Connection]); ``` This works because the array acts as a "module" where the indices are the "module"'s properties for classes. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.promisifyall.htmlPromise.fromCallback ===================== ``` Promise.fromCallback( function(function callback) resolver, [Object {multiArgs: boolean=false} options] ) -> Promise ``` ``` Promise.fromNode( function(function callback) resolver, [Object {multiArgs: boolean=false} options] ) -> Promise ``` Returns a promise that is resolved by a node style callback function. This is the most fitting way to do on the fly promisification when libraries don't expose classes for automatic promisification by undefined. The resolver function is passed a callback that expects to be called back according to error-first node conventions. Setting `multiArgs` to `true` means the resulting promise will always fulfill with an array of the callback's success value(s). This is needed because promises only support a single success value while some callback API's have multiple success value. The default is to ignore all but the first success value of a callback function. Using manual resolver: ``` var Promise = require("bluebird"); // "email-templates" doesn't expose prototypes for promisification var emailTemplates = Promise.promisify(require('email-templates')); var templatesDir = path.join(__dirname, 'templates'); emailTemplates(templatesDir).then(function(template) { return Promise.fromCallback(function(callback) { return template("newsletter", callback); }, {multiArgs: true}).spread(function(html, text) { console.log(html, text); }); }); ``` The same can also be written more concisely with `Function.prototype.bind`: ``` var Promise = require("bluebird"); // "email-templates" doesn't expose prototypes for promisification var emailTemplates = Promise.promisify(require('email-templates')); var templatesDir = path.join(__dirname, 'templates'); emailTemplates(templatesDir).then(function(template) { return Promise.fromCallback(template.bind(null, "newsletter"), {multiArgs: true}) .spread(function(html, text) { console.log(html, text); }); }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.fromcallback.html.asCallback ============ ``` .asCallback( [function(any error, any value) callback], [Object {spread: boolean=false} options] ) -> this ``` ``` .nodeify( [function(any error, any value) callback], [Object {spread: boolean=false} options] ) -> this ``` Register a node-style callback on this promise. When this promise is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. This can be used to create APIs that both accept node-style callbacks and return promises: ``` function getDataFor(input, callback) { return dataFromDataBase(input).asCallback(callback); } ``` The above function can then make everyone happy. Promises: ``` getDataFor("me").then(function(dataForMe) { console.log(dataForMe); }); ``` Normal callbacks: ``` getDataFor("me", function(err, dataForMe) { if( err ) { console.error( err ); } console.log(dataForMe); }); ``` Promises can be rejected with falsy values (or no value at all, equal to rejecting with `undefined`), however `.asCallback` will call the callback with an `Error` object if the promise's rejection reason is a falsy value. You can retrieve the original falsy value from the error's `.cause` property. Example: ``` Promise.reject(null).asCallback(function(err, result) { // If is executed if (err) { // Logs 'null' console.log(err.cause); } }); ``` There is no effect on performance if the user doesn't actually pass a node-style callback function. #### Option: spread Some nodebacks expect more than 1 success value but there is no mapping for this in the promise world. You may specify the option `spread` to call the nodeback with multiple values when the fulfillment value is an array: ``` Promise.resolve([1,2,3]).asCallback(function(err, result) { // err == null // result is the array [1,2,3] }); Promise.resolve([1,2,3]).asCallback(function(err, a, b, c) { // err == null // a == 1 // b == 2 // c == 3 }, {spread: true}); Promise.resolve(123).asCallback(function(err, a, b, c) { // err == null // a == 123 // b == undefined // c == undefined }, {spread: true}); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/ascallback.htmlCancellation ============= Cancellation has been redesigned for bluebird 3.x, any code that relies on 2.x cancellation semantics won't work in 3.x. The cancellation feature is **by default turned off**, you can enable it using [`Promise.config`](promise.config). The new cancellation has "don't care" semantics while the old cancellation had abort semantics. Cancelling a promise simply means that its handler callbacks will not be called. The advantages of the new cancellation compared to the old cancellation are: * [`.cancel()`](cancel) is synchronous. * no setup code required to make cancellation work * composes with other bluebird features, like [`Promise.all`](promise.all). * [reasonable semantics for multiple consumer cancellation](#what-about-promises-that-have-multiple-consumers) As an optimization, the cancellation signal propagates upwards the promise chain so that an ongoing operation e.g. network request can be aborted. However, *not* aborting the network request still doesn't make any operational difference as the callbacks are still not called either way. You may register an optional cancellation hook at a root promise by using the `onCancel` argument that is passed to the executor function when cancellation is enabled: ``` function makeCancellableRequest(url) { return new Promise(function(resolve, reject, onCancel) { var xhr = new XMLHttpRequest(); xhr.on("load", resolve); xhr.on("error", reject); xhr.open("GET", url, true); xhr.send(null); // Note the onCancel argument only exists if cancellation has been enabled! onCancel(function() { xhr.abort(); }); }); } ``` Note that the `onCancel` hook is really an optional disconnected optimization, there is no real requirement to register any cancellation hooks for cancellation to work. As such, any errors that may occur while inside the `onCancel` callback are not caught and turned into rejections. While `cancel().` is synchronous - `onCancel()` is called asynchronously (in the next turn) just like `then` handlers. Example: ``` var searchPromise = Promise.resolve(); // Dummy promise to avoid null check. document.querySelector("#search-input").addEventListener("input", function() { // The handlers of the previous request must not be called searchPromise.cancel(); var url = "/search?term=" + encodeURIComponent(this.value.trim()); showSpinner(); searchPromise = makeCancellableRequest(url) .then(function(results) { return transformData(results); }) .then(function(transformedData) { document.querySelector("#search-results").innerHTML = transformedData; }) .catch(function(e) { document.querySelector("#search-results").innerHTML = renderErrorBox(e); }) .finally(function() { // This check is necessary because `.finally` handlers are always called. if (!searchPromise.isCancelled()) { hideSpinner(); } }); }); ``` As shown in the example the handlers registered with `.finally` are called even if the promise is cancelled. Another such exception is [`.reflect()`](reflect). No other types of handlers will be called in case of cancellation. This means that in `.then(onSuccess, onFailure)` neither `onSuccess` or `onFailure` handler is called. This is similar to how [`Generator#return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return) works - only active `finally` blocks are executed and then the generator exits. ### What about promises that have multiple consumers? It is often said that promises cannot be cancellable because they can have multiple consumers. For instance: ``` var result = makeCancellableRequest(...); var firstConsumer = result.then(...); var secondConsumer = result.then(...); ``` Even though in practice most users of promises will never have any need to take advantage of the fact that you can attach multiple consumers to a promise, it is nevertheless possible. The problem: "what should happen if [`.cancel()`](cancel) is called on `firstConsumer`?" Propagating the cancellation signal (and therefore making it abort the request) would be very bad as the second consumer might still be interested in the result despite the first consumer's disinterest. What actually happens is that `result` keeps track of how many consumers it has, in this case 2, and only if all the consumers signal cancel will the request be aborted. However, as far as `firstConsumer` can tell, the promise was successfully cancelled and its handlers will not be called. Note that it is an error to consume an already cancelled promise, doing such a thing will give you a promise that is rejected with `new CancellationError("late cancellation observer")` as the rejection reason. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/cancellation.html.tap ===== ``` .tap(function(any value) handler) -> Promise ``` Essentially like `.then()`, except that the value passed in is the value returned. This means you can insert `.tap()` into a `.then()` chain without affecting what is passed through the chain. (See example below). Unlike [`.finally`](finally) this is not called for rejections. ``` getUser().tap(function(user) { //Like in finally, if you return a promise from the handler //the promise is awaited for before passing the original value through return recordStatsAsync(); }).then(function(user) { //user is the user from getUser(), not recordStatsAsync() }); ``` Common case includes adding logging to an existing promise chain: ``` doSomething() .then(...) .then(...) .then(...) .then(...) ``` ``` doSomething() .then(...) .then(...) .tap(console.log) .then(...) .then(...) ``` *Note: in browsers it is necessary to call `.tap` with `console.log.bind(console)` because console methods can not be called as stand-alone functions.* Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/tap.html.get ===== ``` .get(String propertyName|int index) -> Promise ``` This is a convenience method for doing: ``` promise.then(function(obj) { return obj[propertyName]; }); ``` For example: ``` db.query("...") .get(0) .then(function(firstRow) { }); ``` If `index` is negative, the indexed load will become `obj.length + index`. So that -1 can be used to read last item in the array, -2 to read the second last and so on. For example: ``` Promise.resolve([1,2,3]).get(-1).then(function(value) { console.log(value); // 3 }); ``` If the `index` is still negative after `obj.length + index`, it will be clamped to 0. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/get.html.return ======== ``` .return(any value) -> Promise ``` ``` .thenReturn(any value) -> Promise ``` Convenience method for: ``` .then(function() { return value; }); ``` in the case where `value` doesn't change its value because its binding time is different than when using a closure. That means `value` is bound at the time of calling [`.return`](return) so this will not work as expected: ``` function getData() { var data; return query().then(function(result) { data = result; }).return(data); } ``` because `data` is `undefined` at the time `.return` is called. Function that returns the full path of the written file: ``` var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); var baseDir = process.argv[2] || "."; function writeFile(path, contents) { var fullpath = require("path").join(baseDir, path); return fs.writeFileAsync(fullpath, contents).return(fullpath); } writeFile("test.txt", "this is text").then(function(fullPath) { console.log("Successfully file at: " + fullPath); }); ``` *For compatibility with earlier ECMAScript version, an alias `.thenReturn` is provided for [`.return`](return).* Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/return.htmlPromise.coroutine.addYieldHandler ================================== ``` Promise.coroutine.addYieldHandler(function handler) -> undefined ``` By default you can only yield Promises and Thenables inside coroutines. You can use this function to add yielding support for arbitrary types. For example, if you wanted `yield 500` to be same as `yield Promise.delay`: ``` Promise.coroutine.addYieldHandler(function(value) { if (typeof value === "number") return Promise.delay(value); }); ``` Yield handlers are called when you yield something that is not supported by default. The first yield handler to return a promise or a thenable will be used. If no yield handler returns a promise or a thenable then an error is raised. An example of implementing callback support with `addYieldHandler`: *This is a demonstration of how powerful the feature is and not the recommended usage. For best performance you need to use `promisifyAll` and yield promises directly.* ``` var Promise = require("bluebird"); var fs = require("fs"); var _ = (function() { var promise = null; Promise.coroutine.addYieldHandler(function(v) { if (v === undefined && promise != null) { return promise; } promise = null; }); return function() { var def = Promise.defer(); promise = def.promise; return def.callback; }; })(); var readFileJSON = Promise.coroutine(function* (fileName) { var contents = yield fs.readFile(fileName, "utf8", _()); return JSON.parse(contents); }); ``` An example of implementing thunks support with `addYieldHandler`: *This is a demonstration of how powerful the feature is and not the recommended usage. For best performance you need to use `promisifyAll` and yield promises directly.* ``` var Promise = require("bluebird"); var fs = require("fs"); Promise.coroutine.addYieldHandler(function(v) { if (typeof v === "function") { return Promise.fromCallback(function(cb) { v(cb); }); } }); var readFileThunk = function(fileName, encoding) { return function(cb) { return fs.readFile(fileName, encoding, cb); }; }; var readFileJSON = Promise.coroutine(function* (fileName) { var contents = yield readFileThunk(fileName, "utf8"); return JSON.parse(contents); }); ``` An example of handling promises in parallel by adding an `addYieldHandler` for arrays : ``` var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); Promise.coroutine.addYieldHandler(function(yieldedValue) { if (Array.isArray(yieldedValue)) return Promise.all(yieldedValue); }); var readFiles = Promise.coroutine(function* (fileNames) { return yield fileNames.map(function (fileName) { return fs.readFileAsync(fileName, "utf8"); }); }); ``` A custom yield handler can also be used just for a single call to `Promise.coroutine()`: ``` var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); var readFiles = Promise.coroutine(function* (fileNames) { return yield fileNames.map(function (fileName) { return fs.readFileAsync(fileName, "utf8"); }); }, { yieldHandler: function(yieldedValue) { if (Array.isArray(yieldedValue)) return Promise.all(yieldedValue); } }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.coroutine.addyieldhandler.html.tapCatch ========== `.tapCatch` is a convenience method for reacting to errors without handling them with promises - similar to `finally` but only called on rejections. Useful for logging errors. It comes in two variants. - A tapCatch-all variant similar to [`.catch`](catch) block. This variant is compatible with native promises. - A filtered variant (like other non-JS languages typically have) that lets you only handle specific errors. **This variant is usually preferable**. ### `tapCatch` all ``` .tapCatch(function(any value) handler) -> Promise ``` Like [`.finally`](finally) that is not called for fulfillments. ``` getUser().tapCatch(function(err) { return logErrorToDatabase(err); }).then(function(user) { //user is the user from getUser(), not logErrorToDatabase() }); ``` Common case includes adding logging to an existing promise chain: #### Rate Limiting ``` Promise. try(logIn). then(respondWithSuccess). tapCatch(countFailuresForRateLimitingPurposes). catch(respondWithError); ``` #### Circuit Breakers ``` Promise. try(makeRequest). then(respondWithSuccess). tapCatch(adjustCircuitBreakerState). catch(respondWithError); ``` #### Logging ``` Promise. try(doAThing). tapCatch(logErrorsRelatedToThatThing). then(respondWithSuccess). catch(respondWithError); ``` *Note: in browsers it is necessary to call `.tapCatch` with `console.log.bind(console)` because console methods can not be called as stand-alone functions.* ### Filtered `tapCatch` ``` .tapCatch( class ErrorClass|function(any error), function(any error) handler ) -> Promise ``` ``` .tapCatch( class ErrorClass|function(any error), function(any error) handler ) -> Promise ``` This is an extension to [`.tapCatch`](tapcatch) to filter exceptions similarly to languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this tapCatch handler. The tapCatch handler that is first met that has eligible constructors specified, is the one that will be called. Usage examples include: #### Rate Limiting ``` Promise. try(logIn). then(respondWithSuccess). tapCatch(InvalidCredentialsError, countFailuresForRateLimitingPurposes). catch(respondWithError); ``` #### Circuit Breakers ``` Promise. try(makeRequest). then(respondWithSuccess). tapCatch(RequestError, adjustCircuitBreakerState). catch(respondWithError); ``` #### Logging ``` Promise. try(doAThing). tapCatch(logErrorsRelatedToThatThing). then(respondWithSuccess). catch(respondWithError); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/tapcatch.html.call ====== ``` .call( String methodName, [any args...] ) ``` This is a convenience method for doing: ``` promise.then(function(obj) { return obj[methodName].call(obj, arg...); }); ``` For example ([`some` is a built-in array method](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some)): ``` var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); var path = require("path"); var thisPath = process.argv[2] || "."; var now = Date.now(); fs.readdirAsync(thisPath) .map(function(fileName) { return fs.statAsync(path.join(thisPath, fileName)); }) .call("some", function(stat) { return (now - new Date(stat.mtime)) < 10000; }) .then(function(someFilesHaveBeenModifiedLessThanTenSecondsAgo) { console.log(someFilesHaveBeenModifiedLessThanTenSecondsAgo) ; }); ``` Chaining lo-dash or underscore methods (Copy-pasteable example): ``` var Promise = require("bluebird"); var pmap = Promise.map; var props = Promise.props; var _ = require("lodash"); var fs = Promise.promisifyAll(require("fs")); function getTotalSize(paths) { return pmap(paths, function(path) { return fs.statAsync(path).get("size"); }).reduce(function(a, b) { return a + b; }, 0); } fs.readdirAsync(".").then(_) .call("groupBy", function(fileName) { return fileName.charAt(0); }) .call("map", function(fileNames, firstCh) { return props({ firstCh: firstCh, count: fileNames.length, totalSize: getTotalSize(fileNames) }); }) // Since the currently wrapped array contains promises we need to unwrap it and call .all() before continuing the chain // If the currently wrapped thing was an object with properties that might be promises, we would call .props() instead .call("value").all().then(_) .call("sortBy", "count") .call("reverse") .call("map", function(data) { return data.count + " total files beginning with " + data.firstCh + " with total size of " + data.totalSize + " bytes"; }) .call("join", "\n") .then(console.log) ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/call.html.throw ======= ``` .throw(any reason) -> Promise ``` ``` .thenThrow(any reason) -> Promise ``` Convenience method for: ``` .then(function() { throw reason; }); ``` Same limitations regarding to the binding time of `reason` to apply as with [`.return`](return). *For compatibility with earlier ECMAScript version, an alias `.thenThrow` is provided for [`.throw`](throw).* Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/throw.html.catchReturn ============= ``` .catchReturn( [class ErrorClass|function(any error) predicate], any value ) -> Promise ``` Convenience method for: ``` .catch(function() { return value; }); ``` You may optionally prepend one predicate function or ErrorClass to pattern match the error (the generic [`.catch`](catch) methods accepts multiple) Same limitations regarding to the binding time of `value` to apply as with [`.return`](return). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/catchreturn.html.catchThrow ============ ``` .catchThrow( [class ErrorClass|function(any error) predicate], any reason ) -> Promise ``` Convenience method for: ``` .catch(function() { throw reason; }); ``` You may optionally prepend one predicate function or ErrorClass to pattern match the error (the generic [`.catch`](catch) methods accepts multiple) Same limitations regarding to the binding time of `reason` to apply as with [`.return`](return). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/catchthrow.html.reflect ========= ``` .reflect() -> Promise<PromiseInspection``` The [`.reflect`](reflect) method returns a promise that is always successful when this promise is settled. Its fulfillment value is an object that implements the [`PromiseInspection`](promiseinspection) interface and reflects the resolution of this promise. Using `.reflect()` to implement `settleAll` (wait until all promises in an array are either rejected or fulfilled) functionality ``` var promises = [getPromise(), getPromise(), getPromise()]; Promise.all(promises.map(function(promise) { return promise.reflect(); })).each(function(inspection) { if (inspection.isFulfilled()) { console.log("A promise in the array was fulfilled with", inspection.value()); } else { console.error("A promise in the array was rejected with", inspection.reason()); } }); ``` Using `.reflect()` to implement `settleProps` (like settleAll for an object's properties) functionality ``` var object = { first: getPromise1(), second: getPromise2() }; Promise.props(Object.keys(object).reduce(function(newObject, key) { newObject[key] = object[key].reflect(); return newObject; }, {})).then(function(object) { if (object.first.isFulfilled()) { console.log("first was fulfilled with", object.first.value()); } else { console.error("first was rejected with", object.first.reason()); } }) ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/reflect.htmlPromise.getNewLibraryCopy ========================== ``` Promise.getNewLibraryCopy() -> Object ``` Returns a new independent copy of the Bluebird library. This method should be used before you use any of the methods which would otherwise alter the global `Bluebird` object - to avoid polluting global state. A basic example: ``` var Promise = require('bluebird'); var Promise2 = Promise.getNewLibraryCopy(); Promise2.x = 123; console.log(Promise2 == Promise); // false console.log(Promise2.x); // 123 console.log(Promise.x); // undefined ``` `Promise2` is independent to `Promise`. Any changes to `Promise2` do not affect the copy of Bluebird returned by `require('bluebird')`. In practice: ``` var Promise = require('bluebird').getNewLibraryCopy(); Promise.coroutine.addYieldHandler( function() { /* */ } ); // alters behavior of `Promise.coroutine()` // somewhere in another file or module in same app var Promise = require('bluebird'); Promise.coroutine(function*() { // this code is unaffected by the yieldHandler defined above // because it was defined on an independent copy of Bluebird }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.getnewlibrarycopy.htmlPromise.noConflict =================== ``` Promise.noConflict() -> Object ``` This is relevant to browser environments with no module loader. Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. ``` <!-- the other promise library must be loaded first --> <script type="text/javascript" src="/scripts/other_promise.js"></script> <script type="text/javascript" src="/scripts/bluebird_debug.js"></script> <script type="text/javascript"> //Release control right after var Bluebird = Promise.noConflict(); //Cast a promise from some other Promise library using the Promise namespace to Bluebird: var promise = Bluebird.resolve(new Promise()); </script``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.noconflict.htmlPromise.setScheduler ===================== ``` Promise.setScheduler(function(function fn) scheduler) -> function ``` Scheduler should be a function that asynchronously schedules the calling of the passed in function: ``` // This is just an example of how to use the api, there is no reason to do this Promise.setScheduler(function(fn) { setTimeout(fn, 0); }); ``` Setting a custom scheduler could be necessary when you need a faster way to schedule functions than bluebird does by default. It also makes bluebird possible to use in platforms where normal timing constructs like `setTimeout` and `process.nextTick` are not available (like Nashhorn). You can also use it as a hook: ``` // This will synchronize bluebird promise queue flushing with angulars queue flushing // Angular is also now responsible for choosing the actual scheduler Promise.setScheduler(function(fn) { $rootScope.$evalAsync(fn); }); ``` > **Danger** - in order to keep bluebird promises [Promises/A+](https://promisesaplus.com/) compliant a scheduler that executes the function asynchronously (like the examples in this page) must be used. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.setscheduler.htmlOperationalError ================= ``` new OperationalError(String message) -> OperationalError ``` Represents an error is an explicit promise rejection as opposed to a thrown error. For example, if an error is errbacked by a callback API promisified through [`Promise.promisify`](promise.promisify) or [`Promise.promisifyAll`](promise.promisifyall) and is not a typed error, it will be converted to a `OperationalError` which has the original error in the `.cause` property. `OperationalError`s are caught in [`.error`](error) handlers. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/operationalerror.htmlBuilt-in error types ===================== Bluebird includes a few built-in error types for common usage. All error types have the same identity across different copies of bluebird module so that pattern matching works in [`.catch`](catch). All error types have a constructor taking a message string as their first argument, with that message becoming the `.message` property of the error object. By default the error types need to be referenced from the Promise constructor, e.g. to get a reference to [`TimeoutError`](timeouterror), do `var TimeoutError = Promise.TimeoutError`. However, for convenience you will probably want to just make the references global. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/built-in-error-types.htmlTimeoutError ============= ``` new TimeoutError(String message) -> TimeoutError ``` Signals that an operation has timed out. Used as a custom cancellation reason in [`.timeout`](timeout). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/timeouterror.htmlCancellationError ================== ``` new CancellationError(String message) -> CancellationError ``` Signals that an operation has been aborted or cancelled. The default reason used by [`.cancel`](cancel). Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/cancellationerror.htmlAggregateError =============== ``` new AggregateError() extends Array -> AggregateError ``` A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property. It supports all generic array methods such as `.forEach` directly. `AggregateError`s are caught in [`.error`](error) handlers, even if the contained errors are not operational. [`Promise.some`](promise.some) and [`Promise.any`](promise.any) use `AggregateError` as rejection reason when they fail. Example: ``` //Assumes AggregateError has been made global var err = new AggregateError(); err.push(new Error("first error")); err.push(new Error("second error")); throw err; ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/aggregateerror.htmlError management configuration =============================== The default approach of bluebird is to immediately log the stack trace when there is an unhandled rejection. This is similar to how uncaught exceptions cause the stack trace to be logged so that you have something to work with when something is not working as expected. However because it is possible to handle a rejected promise at any time in the indeterminate future, some programming patterns will result in false positives. Because such programming patterns are not necessary and can always be refactored to never cause false positives, we recommend doing that to keep debugging as easy as possible . You may however feel differently so bluebird provides hooks to implement more complex failure policies. Such policies could include: * Logging after the promise became GCd (requires a native node.js module) * Showing a live list of rejected promises * Using no hooks and using [`.done`](done) to manually to mark end points where rejections will not be handled * Swallowing all errors (challenge your debugging skills) * ... ### Global rejection events Starting from 2.7.0 all bluebird instances also fire rejection events globally so that applications can register one universal hook for them. The global events are: * `"unhandledRejection"` (corresponds to the local [`Promise.onPossiblyUnhandledRejection`](promise.onpossiblyunhandledrejection)) * `"rejectionHandled"` (corresponds to the local [`Promise.onUnhandledRejectionHandled`](promise.onunhandledrejectionhandled)) Attaching global rejection event handlers in **node.js**: ``` // NOTE: event name is camelCase as per node convention process.on("unhandledRejection", function(reason, promise) { // See Promise.onPossiblyUnhandledRejection for parameter documentation }); // NOTE: event name is camelCase as per node convention process.on("rejectionHandled", function(promise) { // See Promise.onUnhandledRejectionHandled for parameter documentation }); ``` Attaching global rejection event handlers in **browsers**: Using DOM3 `addEventListener` APIs (support starting from IE9+): ``` // NOTE: event name is all lower case as per DOM convention window.addEventListener("unhandledrejection", function(e) { // NOTE: e.preventDefault() must be manually called to prevent the default // action which is currently to log the stack trace to console.warn e.preventDefault(); // NOTE: parameters are properties of the event detail property var reason = e.detail.reason; var promise = e.detail.promise; // See Promise.onPossiblyUnhandledRejection for parameter documentation }); // NOTE: event name is all lower case as per DOM convention window.addEventListener("rejectionhandled", function(e) { // NOTE: e.preventDefault() must be manually called prevent the default // action which is currently unset (but might be set to something in the future) e.preventDefault(); // NOTE: parameters are properties of the event detail property var promise = e.detail.promise; // See Promise.onUnhandledRejectionHandled for parameter documentation }); ``` In Web Workers you may use `self.addEventListener`. Using legacy APIs (support starting from IE6+): ``` // NOTE: event name is all lower case as per legacy convention window.onunhandledrejection = function(reason, promise) { // See Promise.onPossiblyUnhandledRejection for parameter documentation }; // NOTE: event name is all lower case as per legacy convention window.onrejectionhandled = function(promise) { // See Promise.onUnhandledRejectionHandled for parameter documentation }; ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/error-management-configuration.htmlPromise.onPossiblyUnhandledRejection ===================================== ``` Promise.onPossiblyUnhandledRejection(function(any error, Promise promise) handler) -> undefined ``` *Note: this hook is specific to the bluebird instance it's called on, application developers should use [global rejection events](error-management-configuration#global-rejection-events)* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. ``` Promise.onPossiblyUnhandledRejection(function(e, promise) { throw e; }); ``` Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.onpossiblyunhandledrejection.html.suppressUnhandledRejections ============================= ``` .suppressUnhandledRejections() -> undefined ``` Basically sugar for doing: ``` somePromise.catch(function(){}); ``` Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting. Example: ``` var tweets = fetchTweets(); $(document).on("ready", function() { tweets.then(function() { // Render tweets }).catch(function(e) { alert("failed to fetch tweets because: " + e); }); }); ``` If fetching tweets fails before the document is ready the rejection is reported as unhandled even though it will be eventually handled when the document is ready. This is of course impossible to determine automatically, but you can explicitly do so using `.suppressUnhandledRejections()`: ``` var tweets = fetchTweets(); tweets.suppressUnhandledRejections(); $(document).on("ready", function() { tweets.then(function() { // Render tweets }).catch(function(e) { alert("failed to fetch tweets because: " + e); }); }); ``` It should be noted that there is no real need to attach the handlers asynchronously. Exactly the same effect can be achieved with: ``` fetchTweets() .finally(function() { return $.ready.promise(); }) // DOM guaranteed to be ready after this point .then(function() { // Render tweets }) .catch(function(e) { alert("failed to fetch tweets because: " + e); }); ``` The advantage of using `.suppressUnhandledRejections()` over `.catch(function(){})` is that it doesn't increment the branch count of the promise. Branch counts matter when using cancellation because a promise will only be cancelled if all of its branches want to cancel it. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/suppressunhandledrejections.html.done ====== ``` .done( [function(any value) fulfilledHandler], [function(any error) rejectedHandler] ) -> undefined ``` Like [`.then`](then), but any unhandled rejection that ends up here will crash the process (in node) or be thrown as an error (in browsers). The use of this method is heavily discouraged and it only exists for historical reasons. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/done.htmlPromise.config --------------- ``` Promise.config(Object { warnings: boolean=false, longStackTraces: boolean=false, cancellation: boolean=false, monitoring: boolean=false, asyncHooks: boolean=false } options) -> Object; ``` Configure long stack traces, warnings, monitoring, [async hooks](https://nodejs.org/api/async_hooks.html) and cancellation. Note that even though `false` is the default here, a development environment might be detected which automatically enables long stack traces and warnings. For **webpack** and **browserify** *development* environment is *always* enabled. See [installation](../install#browserify-and-webpack) on how to configure webpack and browserify for production. ``` Promise.config({ // Enable warnings warnings: true, // Enable long stack traces longStackTraces: true, // Enable cancellation cancellation: true, // Enable monitoring monitoring: true, // Enable async hooks asyncHooks: true, }); ``` You can configure the warning for checking forgotten return statements with `wForgottenReturn`: ``` Promise.config({ // Enables all warnings except forgotten return statements. warnings: { wForgottenReturn: false } }); ``` `wForgottenReturn` is the only warning type that can be separately configured. The corresponding environmental variable key is `BLUEBIRD_W_FORGOTTEN_RETURN`. In Node.js you may configure warnings and long stack traces for the entire process using environment variables: ``` BLUEBIRD_LONG_STACK_TRACES=1 BLUEBIRD_WARNINGS=1 node app.js ``` Both features are automatically enabled if the `BLUEBIRD_DEBUG` environment variable has been set or if the `NODE_ENV` environment variable is equal to `"development"`. Using the value `0` will explicitly disable a feature despite debug environment otherwise activating it: ``` # Warnings are disabled despite being in development environment NODE_ENV=development BLUEBIRD_WARNINGS=0 node app.js ``` Cancellation is always configured separately per bluebird instance. Async hooks ============ Bluebird supports [async hooks](https://nodejs.org/api/async_hooks.html) in node versions 9.6.0 and later. After it is enabled promises from the bluebird instance are assigned unique asyncIds: ``` // Async hooks disabled for bluebird const ah = require('async_hooks'); const Promise = require("bluebird"); Promise.resolve().then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); // }); ``` ``` // Async hooks enabled for bluebird const ah = require('async_hooks'); const Promise = require("bluebird"); Promise.config({asyncHooks: true}); Promise.resolve().then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); // }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.config.htmlEnvironment variables ====================== This section only applies to node.js or io.js. You can change bluebird behavior globally with various environment variables. These global variables affect all instances of bluebird that are running in your environment, rather than just the one you have `require`d in your application. The effect an environment variable has depends on the bluebird version. Environment variables supported by 2.x: * `BLUEBIRD_DEBUG` - Set to any truthy value this will enable long stack traces and warnings * `NODE_ENV` - If set exactly to `development` it will have the same effect as if the `BLUEBIRD_DEBUG` variable was set. Environment variables supported by 3.x: * `BLUEBIRD_DEBUG` - If set this will enable long stack traces and warnings, unless those are explicitly disabled. Setting this to exactly `0` can be used to override `NODE_ENV=development` enabling long stack traces and warnings. * `NODE_ENV` - If set exactly to `development` it will have the same effect as if the `BLUEBIRD_DEBUG` variable was set. * `BLUEBIRD_WARNINGS` - if set exactly to `0` it will explicitly disable warnings and this overrides any other setting that might enable warnings. If set to any truthy value, it will explicitly enable warnings. * `BLUEBIRD_LONG_STACK_TRACES` - if set exactly to `0` it will explicitly disable long stack traces and this overrides any other setting that might enable long stack traces. If set to any truthy value, it will explicitly enable long stack traces. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/environment-variables.htmlProgression migration ====================== Progression has been removed as there are composability and chaining issues with APIs that use promise progression handlers. Implementing the common use case of progress bars can be accomplished using a pattern similar to [IProgress](http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx) in C#. For old code that still uses it, see [the progression docs in the deprecated API documentation](../deprecated-apis#progression). Using jQuery before: ``` Promise.resolve($.get(...)) .progressed(function() { // ... }) .then(function() { // ... }) .catch(function(e) { // ... }) ``` Using jQuery after: ``` Promise.resolve($.get(...).progress(function() { // ... })) .then(function() { // ... }) .catch(function(e) { // ... }) ``` Implementing general progress interfaces like in C#: ``` function returnsPromiseWithProgress(progressHandler) { return doFirstAction().tap(function() { progressHandler(0.33); }).then(doSecondAction).tap(function() { progressHandler(0.66); }).then(doThirdAction).tap(function() { progressHandler(1.00); }); } returnsPromiseWithProgress(function(progress) { ui.progressbar.setWidth((progress * 200) + "px"); // update width on client side }).then(function(value) { // action complete // entire chain is complete. }).catch(function(e) { // error }); ``` Another example using `coroutine`: ``` var doNothing = function() {}; var progressSupportingCoroutine = Promise.coroutine(function* (progress) { progress = typeof progress === "function" ? progress : doNothing; var first = yield getFirstValue(); // 33% done progress(0.33); var second = yield getSecondValue(); progress(0.67); var third = yield getThirdValue(); progress(1); return [first, second, third]; }); var progressConsumingCoroutine = Promise.coroutine(function* () { var allValues = yield progressSupportingCoroutine(function(p) { ui.progressbar.setWidth((p * 200) + "px"); }); var second = allValues[1]; // ... }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/progression-migration.html~~Promise.longStackTraces~~ ============================ This method is deprecated. Use [Promise.config](promise.config) instead. ``` Promise.config({ longStackTraces: true }) ``` ``` Promise.longStackTraces() -> undefined ``` Call this right after the library is loaded to enable long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. Long stack traces are enabled by default in the debug build. To enable them in all instances of bluebird in node.js, use the environment variable `BLUEBIRD_DEBUG`: ``` BLUEBIRD_DEBUG=1 node server.js ``` Setting the environment variable `NODE_ENV` to `"development"` also automatically enables long stack traces. You should enabled long stack traces if you want better debugging experience. For example: ``` Promise.longStackTraces(); Promise.resolve().then(function outer() { return Promise.resolve().then(function inner() { return Promise.resolve().then(function evenMoreInner() { a.b.c.d() }).catch(function catcher(e) { console.error(e.stack); }); }); }); ``` Gives ``` ReferenceError: a is not defined at evenMoreInner (<anonymous>:6:13) From previous event: at inner (<anonymous>:5:24) From previous event: at outer (<anonymous>:4:20) From previous event: at <anonymous>:3:9 at Object.InjectedScript._evaluateOn (<anonymous>:581:39) at Object.InjectedScript._evaluateAndWrap (<anonymous>:540:52) at Object.InjectedScript.evaluate (<anonymous>:459:21) ``` While with long stack traces disabled, you would get: ``` ReferenceError: a is not defined at evenMoreInner (<anonymous>:6:13) at tryCatch1 (<anonymous>:41:19) at Promise$_resolvePromise [as _resolvePromise] (<anonymous>:1739:13) at Promise$_resolveLast [as _resolveLast] (<anonymous>:1520:14) at Async$_consumeFunctionBuffer [as _consumeFunctionBuffer] (<anonymous>:560:33) at Async$consumeFunctionBuffer (<anonymous>:515:14) at MutationObserver.Promise$_Deferred (<anonymous>:433:17) ``` On client side, long stack traces currently only work in recent Firefoxes, Chrome and Internet Explorer 10+. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.longstacktraces.htmlDeferred migration =================== Deferreds are deprecated in favor of the promise constructor. If you need deferreds for some reason, you can create them trivially using the constructor: ``` function defer() { var resolve, reject; var promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; }); return { resolve: resolve, reject: reject, promise: promise }; } ``` For old code that still uses deferred objects, see [the deprecated API docs](../deprecated-apis#promise-resolution) . Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/deferred-migration.htmlPromise.bind ============= ``` Promise.bind( any|Promise<any> thisArg, [any|Promise<any> value=undefined] ) -> BoundPromise ``` Create a promise that follows this promise or in the static method is resolved with the given `value`, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. If `thisArg` is a promise or thenable, its resolution will be awaited for and the bound value will be the promise's fulfillment value. If `thisArg` rejects then the returned promise is rejected with the `thisArg's` rejection reason. Note that this means you cannot use `this` without checking inside catch handlers for promises that bind to promise because in case of rejection of `thisArg`, `this` will be `undefined`. Without arrow functions that provide lexical `this`, the correspondence between async and sync code breaks down when writing object-oriented code. [`.bind`](bind) alleviates this. Consider: ``` MyClass.prototype.method = function() { try { var contents = fs.readFileSync(this.file); var url = urlParse(contents); var result = this.httpGetSync(url); var refined = this.refine(result); return this.writeRefinedSync(refined); } catch (e) { this.error(e.stack); } }; ``` The above has a direct translation: ``` MyClass.prototype.method = function() { return fs.readFileAsync(this.file).bind(this) .then(function(contents) { var url = urlParse(contents); return this.httpGetAsync(url); }).then(function(result) { var refined = this.refine(result); return this.writeRefinedAsync(refined); }).catch(function(e) { this.error(e.stack); }); }; ``` `.bind` is the most efficient way of utilizing `this` with promises. The handler functions in the above code are not closures and can therefore even be hoisted out if needed. There is literally no overhead when propagating the bound value from one promise to another. `.bind` also has a useful side purpose - promise handlers don't need to share a function to use shared state: ``` somethingAsync().bind({}) .spread(function (aValue, bValue) { this.aValue = aValue; this.bValue = bValue; return somethingElseAsync(aValue, bValue); }) .then(function (cValue) { return this.aValue + this.bValue + cValue; }); ``` The above without [`.bind`](bind) could be achieved with: ``` var scope = {}; somethingAsync() .spread(function (aValue, bValue) { scope.aValue = aValue; scope.bValue = bValue; return somethingElseAsync(aValue, bValue); }) .then(function (cValue) { return scope.aValue + scope.bValue + cValue; }); ``` However, there are many differences when you look closer: * Requires a statement so cannot be used in an expression context * If not there already, an additional wrapper function is required to undefined leaking or sharing `scope` * The handler functions are now closures, thus less efficient and not reusable Note that bind is only propagated with promise transformation. If you create new promise chains inside a handler, those chains are not bound to the "upper" `this`: ``` something().bind(var1).then(function() { //`this` is var1 here return Promise.all(getStuff()).then(function(results) { //`this` is undefined here //refine results here etc }); }).then(function() { //`this` is var1 here }); ``` However, if you are utilizing the full bluebird API offering, you will *almost never* need to resort to nesting promises in the first place. The above should be written more like: ``` something().bind(var1).then(function() { //`this` is var1 here return getStuff(); }).map(function(result) { //`this` is var1 here //refine result here }).then(function() { //`this` is var1 here }); ``` Also see this [Stackoverflow answer](http://stackoverflow.com/a/24412873/191693) as an additional example. If you don't want to return a bound promise to the consumers of a promise, you can rebind the chain at the end: ``` MyClass.prototype.method = function() { return fs.readFileAsync(this.file).bind(this) .then(function(contents) { var url = urlParse(contents); return this.httpGetAsync(url); }).then(function(result) { var refined = this.refine(result); return this.writeRefinedAsync(refined); }).catch(function(e) { this.error(e.stack); }).bind(); //The `thisArg` is implicitly undefined - I.E. the default promise `this` value }; ``` Rebinding can also be abused to do something gratuitous like this: ``` Promise.resolve("my-element") .bind(document) .then(document.getElementById) .bind(console) .then(console.log); ``` The above does a `console.log` of `my-element`. Doing it this way is necessary because neither of the methods (`getElementById`, `console.log`) can be called as stand-alone methods. Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.bind.htmlPromise.onUnhandledRejectionHandled ==================================== ``` Promise.onUnhandledRejectionHandled(function(Promise promise) handler) -> undefined ``` *Note: this hook is specific to the bluebird instance its called on, application developers should use [global rejection events](error-management-configuration#global-rejection-events)* Add `handler` as the handler to call when a rejected promise that was reported as "possibly unhandled rejection" became handled. Together with `onPossiblyUnhandledRejection` these hooks can be used to implement a debugger that will show a list of unhandled promise rejections updated in real time as promises become handled. For example: ``` var unhandledPromises = []; Promise.onPossiblyUnhandledRejection(function(reason, promise) { unhandledPromises.push(promise); //Update some debugger UI }); Promise.onUnhandledRejectionHandled(function(promise) { var index = unhandledPromises.indexOf(promise); unhandledPromises.splice(index, 1); //Update the debugger UI }); ``` Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript) © 2013–2018 <NAME> Licensed under the MIT License. <http://bluebirdjs.com/docs/api/promise.onunhandledrejectionhandled.htmlbluebird
GITHUB_dyp2000_Russian-Armstrong-Erlang.zip_unzipped_programming_erlang_ch14.pdf
free_programming_book
Unknown
14 14.1 TCP ... 14.1.1 ... 14.1.2 TCP ... 14.1.3 ... 14.1.4 ... 14.1.5 ... 14.1.6 ... 14.2 ... 14.2.1 () . . . . . . . . . . . . . . . 14.2.2 () . . . . . . . . . . . . . . . . 14.2.3 ( ) . . . . . . . . . . . . . . . . 14.3 ? ... 14.4 ... 14.5 UDP ... 14.5.1 UDP ... 14.5.2 UDP ... 14.5.3 UDP ... 14.6 ... 14.7 SHOUTcast ... 14.7.1 SHOUTcast ... 14.7.2 SHOUTcast ... 14.7.3 SHOUTcast ... 14.7.4 SHOUTcast ... 14.7.5 ... 14.7.6 SHOUTcast ... 14.7.7 ... 14.8 ... 1 3 3 3 5 8 9 9 9 10 11 11 11 12 12 13 13 14 15 16 17 17 18 18 23 23 23 23 24 14 , . , , Internet Protocol(IP). : Transmission Control Protocol(TCP) User Datagram Protocol(UDP) UDP ( ), . . TCP, , . ? , , . get_tcp, TCP , gen_udp UDP TCP UDP . : , , , , traffic-shaping , . 14.1 TCP TCP , . TCP , , . 14.1.1 1 2 , TCP HTML http://www.google.com: Download socket_examples.erl nano_get_url() -> nano_get_url("www.google.com"). nano_get_url(Host) -> {ok,Socket} = gen_tcp:connect(Host,80,[binary, {packet, 0}]), ok = gen_tcp:send(Socket, "GET / HTTP/1.0\r\n\r\n"), receive_data(Socket, []). 1 , http:request(Url). , gen_tcp. 2 http, httpc 2 14. 3 receive_data(Socket, SoFar) -> receive {tcp,Socket,Bin} -> receive_data(Socket, [Bin|SoFar]); {tcp_closed,Socket} -> list_to_binary(reverse(SoFar)) end. ? 1. TCP http://google.com 80 , gen_tcp:connect. binary connect . {packet,0} TCP , , . 2. get_tcp:send GET / HTTP/1.0\r\n\r\n . . , . , , , . 3. {tcp,Socket,Bin}. . , . , - . , , . 4. {tcp_closed,Socket}. , . 3 5. , , . , : 1> B = socket_examples:nano_get_url(). <<"HTTP/1.0 302 Found\r\nLocation: http://www.google.se/\r\n Cache-Control: private\r\nSet-Cookie: PREF=ID=b57a2c:TM"...>> : nano_get_url , . , , "pretty printed" . "pretty printed escape-. , (...>>) . , io:format , , string:tokens : 2> io:format("~p~n",[B]). <<"HTTP/1.0 302 Found\r\nLocation: http://www.google.se/\r\n Cache-Control: private\r\nSet-Cookie: PREF=ID=b57a2c:TM" TM=176575171639526:LM=1175441639526:S=gkfTrK6AFkybT3; expires=Sun, 17-Jan-2038 19:14:07 ... several lines omitted ... >> 3>string:tokens(binary_to_list(B),"\r\n"). ["HTTP/1.0 302 Found", 3 HTTP/1.0; 14. 4 "Location: http://www.google.se/", "Cache-Control: private", "Set-Cookie: PREF=ID=ec7f0c7234b852dece4:TM=11713424639526: LM=1171234639526:S=gsdertTrK6AEybT3; expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com", "Content-Type: text/html", "Server: GWS/2.1", "Content-Length: 218", "Date: Fri, 16 Feb 2007 15:25:26 GMT", "Connection: Keep-Alive", ... lines omitted ... , web-( , ). , , . , : - e-mail. . , , : receive_data(Socket, SoFar) -> receive {tcp,Socket,Bin} -> receive_data(Socket, [Bin|SoFar]); {tcp_closed,Socket} -> list_to_binary(reverse(SoFar)) end. SoFar . . , : receive_data(Socket, SoFar) -> receive {tcp,Socket,Bin} -> receive_data(Socket, list_to_binary([SoFar,Bin])); {tcp_closed,Socket} -> SoFar end. , , . , , . , . 14.1.2 TCP . . 2345 . , . , . , . ? - - . , , , , . . - . ? 14. 5 -, , , , , . , -. , 80 . , : GET / HTTP/1.0\r\n\r\? . request for comments(RFCs). HTTP/1.0 RFC 1945. - RFC http://www.ietf.org( Internet Engineering Task Force). - . IP . , , . Wireshark( , ethereal), http://www.wireshark.org. RFC, . (), : 1) ? , ? 2) ? TCP . . , . , 1,2 4 , . get_tcp:connect gen_tcp:listen, {packet,N} 4 . , packet . {packet,2}, {packet,4}, . {packet,N}, . , , , . . , term_to_binary binary_to_term . , ({packet,N}) , , : {packet,4}, , term_to_binary . , , text-based , HTTP XML. BIF term_to_binary binary_to_term ,, , , XML . . -, . Download socket_examples.erl start_nano_server() -> {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4}, {reuseaddr, true}, {active, true}]), {ok, Socket} = gen_tcp:accept(Listen), %% (7) gen_tcp:close(Listen), %% (8) loop(Socket). %% (6) loop(Socket) -> 4 packet , 14. 6 receive {tcp, Socket, Bin} -> io:format("Server received binary = ~p~n",[Bin]), Str = binary_to_term(Bin), %% (9) io:format("Server (unpacked) ~p~n",[Str]), Reply = lib_misc:string2value(Str), %% (10) io:format("Server replying = ~p~n",[Reply]), gen_tcp:send(Socket, term_to_binary(Reply)), %% (11) loop(Socket); {tcp_closed, Socket} -> io:format("Server socket closed~n") end. ? 1. gen_tcp:listen , 2345 , . {packet,4} , 4 . gen_tcp:listen(...) {ok,Socket} {error,Why}, , . : {ok, Listen} = gen_tcp:listen(...), , get_tcp:listen {error, ...}, . , Listen , geb_tcp:accept 2. gen_tcp:accept(Listen) . . , Socket, , , . 3. accept , gen_tcp:close(Listen). close , . ; . 4. . 5. . 6. , . , , . , , . , , , . : Download socket_examples.erl nano_client_eval(Str) -> {ok, Socket} = gen_tcp:connect("localhost", 2345, [binary, {packet, 4}]), ok = gen_tcp:send(Socket, term_to_binary(Str)), receive {tcp,Socket,Bin} -> io:format("Client received binary = ~p~n",[Bin]), Val = binary_to_term(Bin), 14. 7 io:format("Client result = ~p~n",[Val]), gen_tcp:close(Socket) end. , gen_tcp:connect , localhost. , term_to_binary binary_to_term , . . : 1> socket_examples:start_nano_server(). , . : 1> socket_examples:nano_client_eval("list_to_tuple([2+3*4,10+20])" : Server received binary = <<131,107,0,28,108,105,115,116,95,116, 111,95,116,117,112,108,101,40,91,50, 43,51,42,52,44,49,48,43,50,48,93,41>> Server (unpacked) "list_to_tuple([2+3*4,10+20])" Server replying = {14,30} : Client received binary = <<131,104,2,97,14,97,30>> Client result = {14,30} ok : Server socket closed 14.1.3 , , . - : 1. . 2. . : start_nano_server() -> {ok, Listen} = gen_tcp:listen(...), {ok, Socket} = gen_tcp:accept(Listen), loop(Socket). ... , . 14. 14.1.4 8 : start_seq_server() -> {ok, Listen} = gen_tcp:listen(...), seq_loop(Listen). seq_loop(Listen) -> {ok, Socket} = gen_tcp:accept(Listen), loop(Socket), seq_loop(Listen). loop(..) -> %% - , , gen_tcp:close(Listen) . , , loop(Socket) , seq_loop(Listen) , . , , , . listen backlog, . , . ( ); , . gen_tcp . , . 14.1.5 , gen_tcp:accept : start_parallel_server() -> {ok, Listen} = gen_tcp:listen(...), spawn(fun() -> par_connect(Listen) end). par_connect(Listen) -> {ok, Socket} = gen_tcp:accept(Listen), spawn(fun() -> par_connect(Listen) end), loop(Socket). loop(..) -> %% , . spawn, , . , spawn , . gen_tcp:listen gen_tcp:accept; , . 14.1.6 : , ( gen_tcp:accept gen_tcp:connect) , . ; , . NewPid gen_tcp:controlling_process(Socket,NewPid). 14. 9 . , . , . , , , . . , : {ok, Socket} = gen_tcp:accept(Listen), inet:setopts(Socket, [{packet,4},binary, {nodelay,true},{active, true}]), loop(Socket) R11B-3 gen_tcp:accept . , , gen_tcp:accept/1. 14.2 - : , , . {active,true|false|once} Options gen_tcp:connect(Adress,Port,Options) gen_tcp:listen(Port,Options). {active,true}, ;{active,false} . {active,once} , , ; , , , . , . , . , {tcp,Socket,Data} . . , . . , gen_tcp:recv(Socket,N). N . N = 0, . , , gen_tcp:recv. , . : () () ( ) 14. 14.2.1 10 () : {ok, Listen} = gen_tcp:listen(Port, [..,{active, true}...]), {ok, Socket} = gen_tcp:accept(Listen), loop(Socket). loop(Socket) -> receive {tcp, Socket, Data} -> ... - Data ... {tcp_closed, Socket} -> ... end. . , , (flooded) . , . , , , . 14.2.2 () . , {active,false}. - , . loop gen_tcp:recv , . , recv. , , , recv . {ok, Listen} = gen_tcp:listen(Port, [..,{active, false}...]), {ok, Socket} = gen_tcp:accept(Listen), loop(Socket). loop(Socket) -> case gen_tcp:recv(Socket, N) of {ok, B} -> ... - ... loop(Socket); {error, closed} ... end. 14.2.3 ( ) , . , , , . , . , , , . {active,once}. , . , , inet:setops, . , . , . : 14. 11 {ok, Listen} = gen_tcp:listen(Port, [..,{active, once}...]), {ok, Socket} = gen_tcp:accept(Listen), loop(Socket). loop(Socket) -> receive {tcp, Socket, Data} -> ... do something with the data ... %% inet:setopts(Sock, [{active, once}]), loop(Socket); {tcp_closed, Socket} -> ... end. {active,once} ( traffic-shaping) , , (flooded) . 14.3 ? , , - . ? , . inet:peername(Socket). @spec inet:peername(Socket) -> {ok, {IP_Address, Port}} | {error, Why} IP , . IP_Adress , IPv4 {N1,N2,N3,N4}, IPv6 {K1,K2,K3,K4,K5,K6}. Ni Ki 0 255. 14.4 , . , ( , ). , . , , , , - , , , {tcp_closed,Socket}. : Download socket_examples.erl error_test() -> spawn(fun() -> error_test_server() end), lib_misc:sleep(2000), {ok,Socket} = gen_tcp:connect("localhost",4321,[binary, {packet, 2}]), io:format("connected to:~p~n",[Socket]), gen_tcp:send(Socket, <<"123">>), receive Any -> io:format("Any=~p~n",[Any]) end. error_test_server() -> {ok, Listen} = gen_tcp:listen(4321, [binary,{packet,2}]), 14. 12 {ok, Socket} = gen_tcp:accept(Listen), error_test_server_loop(Socket). error_test_server_loop(Socket) -> receive {tcp, Socket, Data} -> io:format("received:~p~n",[Data]), atom_to_list(Data), error_test_server_loop(Socket) end. , : 1> socket_examples:error_test(). connected to:#Port<0.152> received:<<"123">> =ERROR REPORT==== 9-Feb-2007::15:18:15 === Error in process <0.77.0> with exit value: {badarg,[{erlang,atom_to_list,[<<3 bytes>>]}, {socket_examples,error_test_server_loop,1}]} Any={tcp_closed,#Port<0.152>} ok spawn , 2 ( ), , <<"123">>. , atom_to_list(Data), Data , 5 . , ( ) , . {tcp_closed,Socket}. 14.5 UDP User Datagram Protocol (UDP). UDP, , . UDP . UDP , , , , , , . , IP , . UDP , . , UDP , , . UDP , TCP, . 14.5.1 UDP . UDP : server(Port) -> {ok, Socket} = gen_udp:open(Port, [binary]), loop(Socket). loop(Socket) -> 5 , 14. 13 receive {udp, Socket, Host, Port, Bin} -> BinReply = ... , gen_udp:send(Socket, Host, Port, BinReply), loop(Socket) end. , , TCP, "socket closed". , , , . . UDP , , ( ), , . client(Request) -> {ok, Socket} = gen_udp:open(0, [binary]), ok = gen_udp:send(Socket, "localhost" , 4000, Request), Value = receive {udp, Socket, _, _, Bin} -> {ok, Bin} after 2000 -> error end, gen_udp:close(Socket), Value , UDP , . 14.5.2 UDP UDP , , . . Download udp_test.erl %% server(Port) -> {ok, Socket} = gen_udp:open(Port, [binary]), io:format("server opened socket:~p~n",[Socket]), loop(Socket). loop(Socket) -> receive {udp, Socket, Host, Port, Bin} = Msg -> io:format("server received:~p~n",[Msg]), N = binary_to_term(Bin), Fac = fac(N), gen_udp:send(Socket, Host, Port, term_to_binary(Fac)), loop(Socket) end. fac(0) -> 1; fac(N) -> N * fac(N-1). %% client(N) -> {ok, Socket} = gen_udp:open(0, [binary]), 14. 14 io:format("client opened socket=~p~n",[Socket]), ok = gen_udp:send(Socket, "localhost", 4000, term_to_binary(N)), Value = receive {udp, Socket, _, _, Bin} = Msg -> io:format("client received:~p~n",[Msg]), binary_to_term(Bin) after 2000 -> 0 end, gen_udp:close(Socket), Value. , , , . , , . . . 1> udp_test:start_server(). server opened socket:#Port<0.106> <0.34.0> , : 2> udp_test:client(40). client opened socket=#Port<0.105> server received:{udp,#Port<0.106>,{127,0,0,1},32785,<<131,97,40>>} client received:{udp,#Port<0.105>, {127,0,0,1}, 4000, <<131,110,20,0,0,0,0,0,64,37,5,255, 100,222,15,8,126,242,199,132,27, 232,234,142>>} 815915283247897734345611269596115894272000000000 14.5.3 UDP , UDP , , , . UDP , . , UDP maximum transfer unit (MTU), , . , , MTU 500 , . , , . UDP ( ), , . , . , , , . , BIF make_ref, . : client(Request) -> {ok, Socket} = gen_udp:open(0, [binary]), Ref = make_ref(), %% 14. 15 B1 = term_to_binary({Ref, Request}), ok = gen_udp:send(Socket, "localhost" , 4000, B1), wait_for_ref(Socket, Ref). wait_for_ref(Socket, Ref) -> receive {udp, Socket, _, _, Bin} -> case binary_to_term(Bin) of {Ref, Val} -> %% Val; {_SomeOtherRef, _} -> %% - . . wait_for_ref(Socket, Ref) end; after 1000 -> ... end. 14.6 , , . , , . Download broadcast.erl send(IoList) -> case inet:ifget("eth0", [broadaddr]) of {ok, [{broadaddr, Ip}]} -> {ok, S} = gen_udp:open(5010, [{broadcast, true}]), gen_udp:send(S, Ip, 6000, IoList), gen_udp:close(S); _ -> io:format("Bad interface name, or\n" "broadcasting not supported\n") end. listen() -> {ok, _} = gen_udp:open(6000), loop(). loop() -> receive Any -> io:format("received:~p~n", [Any]), loop() end. , , . 5010 6000 ( ; ). 5010 , , broadcast:listen(), 6000 . broadcast:send(IoList) IoList . 14. 16 : , , . iMac, , "en0" "eth0". , , , UDP , , . 14.7 SHOUTcast , SHOUTcast . SHOUTcast , Nullsoft, .6 . SHOUTcast MP3 AAC , HTTP, . , , SHOUTcast . , . 14.7.1 SHOUTcast SHOUTcast : 1. ( - XMMS, Winamp iTunes) HTTP SHOUTcast . , XMMS , SHOUTcast : GET / HTTP/1.1 Host: localhost User-Agent: xmms/1.2.10 Icy-MetaData:1 2. SHOUTcast : ICY 200 OK icy-notice1: <BR>This stream requires <a href=http://www.winamp.com/>;Winamp</a><BR> icy-notice2: Erlang Shoutcast server<BR> icy-name: Erlang mix icy-genre: Pop Top 40 Dance Rock icy-url: http://localhost:3000 content-type: audio/mpeg icy-pub: 1 icy-metaint: 24576 icy-br: 96 ... data ... 3. SHOUTcast . : H0 F H F H F H ...7 F MP3 , 24 576 ( icy-metaint ). H . H , 16*K ( ). : StreamTitle= ...;SreamUrl= ...; 16, . , <<0>>. . 6 http://www.shoutcast.com/ 7 : H ( ), 0 . , . H0 responce(). 14. 14.7.2 17 SHOUTcast , : 1. . ID3 , 13.2. . 2. , . , , 14.1( , 254). 3. , ID3 8 . ID3 , id3_tag_length; , 232, 5.3, MPEG , 92. . 14.7.3 SHOUTcast , , , : start_parallel_server(Port) -> {ok, Listen} = gen_tcp:listen(Port, ..), %% -- . PidSongServer = spawn(fun() -> songs() end), spawn(fun() -> par_connect(Listen, PidSongServer) end). %% par_connect(Listen, PidSongServer) -> {ok, Socket} = gen_tcp:accept(Listen), %% accept , %% . spawn(fun() -> par_connect(Listen, PidSongServer) end), inet:setopts(Socket, [{packet,0},binary, {nodelay,true}, {active, true}]), %% deal with the request get_request(Socket, PidSongServer, []). %% TCP get_request(Socket, PidSongServer, L) -> receive {tcp, Socket, Bin} -> ... Bin ... , loop ... ... ... got_request(Data, Socket, PidSongServer) {tcp_closed, Socket} -> ... , ... , () end. %% -- 8 , . , , ID3 -. , , , ID3 . 14. 18 got_request(Data, Socket, PidSongServer) -> .. data - ... .. ... .. .. gen_tcp:send(Socket, [response()]), play_songs(Socket, PidSongServer). %% , . play_songs(Socket, PidSongServer) -> ... PidSongServer MP3 Song = rpc(PidSongServer, random_song), ... Song - ... Header = make_header(Song), ... ... {ok, S} = file:open(File, [read,binary,raw]), send_file(1, S, Header, 1, Socket), file:close(S), play_songs(Socket, PidSongServer). send_file(K, S, Header, OffSet, Socket) -> ... ... ... , ... ... , ... , . , , , . : -module(shout). %% > shout:start() %% xmms http://localhost:3000/stream -export([start/0]). -import(lists, [map/2, reverse/1]). -define(CHUNKSIZE, 24576). start() -> spawn(fun() -> start_parallel_server(3000), %% , , %% . lib_misc:sleep(infinity) end). start_parallel_server(Port) -> {ok, Listen} = gen_tcp:listen(Port, [binary, {packet, 0}, {reuseaddr, true}, {active, true}]), PidSongServer = spawn(fun() -> songs() end), spawn(fun() -> par_connect(Listen, PidSongServer) end). par_connect(Listen, PidSongServer) -> 14. {ok, Socket} = gen_tcp:accept(Listen), spawn(fun() -> par_connect(Listen, PidSongServer) end), inet:setopts(Socket, [{packet,0},binary, {nodelay,true},{active, true}]), get_request(Socket, PidSongServer, []). get_request(Socket, PidSongServer, L) -> receive {tcp, Socket, Bin} -> L1 = L ++ binary_to_list(Bin), %% split checks if the header is complete case split(L1, []) of more -> %% , . get_request(Socket, PidSongServer, L1); {Request, _Rest} -> %% got_request_from_client(Request, Socket, PidSongServer) end; {tcp_closed, Socket} -> void; _Any -> %% get_request(Socket, PidSongServer, L) end. split("\r\n\r\n" ++ T, L) -> {reverse(L), T}; split([H|T], L) -> split(T, [H|L]); split([], _) -> more. got_request_from_client(Request, Socket, PidSongServer) -> Cmds = string:tokens(Request, "\r\n" ), Cmds1 = map(fun(I) -> string:tokens(I, " " ) end, Cmds), is_request_for_stream(Cmds1), gen_tcp:send(Socket, [response()]), play_songs(Socket, PidSongServer, <<>>). play_songs(Socket, PidSongServer, SoFar) -> Song = rpc(PidSongServer, random_song), {File,PrintStr,Header} = unpack_song_descriptor(Song), case id3_tag_lengths:file(File) of error -> play_songs(Socket, PidSongServer, SoFar); {Start, Stop} -> io:format("Playing:~p~n" ,[PrintStr]), {ok, S} = file:open(File, [read,binary,raw]), SoFar1 = send_file(S, {0,Header}, Start, Stop, Socket, SoFar), file:close(S), play_songs(Socket, PidSongServer, SoFar1) end. send_file(S, Header, OffSet, Stop, Socket, SoFar) -> %% OffSet = . 19 14. 20 %% Stop = . Need = ?CHUNKSIZE - size(SoFar), Last = OffSet + Need, if Last >= Stop -> %% , %% 24576, , %% play_songs Max = Stop - OffSet, {ok, Bin} = file:pread(S, OffSet, Max), list_to_binary([SoFar, Bin]); true -> {ok, Bin} = file:pread(S, OffSet, Need), write_data(Socket, SoFar, Bin, Header), send_file(S, bump(Header), OffSet + Need, Stop, Socket, <<>>) end. write_data(Socket, B0, B1, Header) -> %% , . %% , . case size(B0) + size(B1) of ?CHUNKSIZE -> case gen_tcp:send(Socket, [B0, B1, the_header(Header)]) of ok -> true; {error, closed} -> %% , %% . exit(playerClosed) end; _Other -> %% , . io:format("Block length Error: B0 = ~p b1=~p~n" , [size(B0), size(B1)]) end. bump({K, H}) -> {K+1, H}. the_header({K, H}) -> case K rem 5 of 0 -> H; _ -> <<0>> end. is_request_for_stream(_) -> true. response() -> ["ICY 200 OK\r\n" , 14. "icy-notice1: <BR>This stream requires" , "<a href=\" http://www.winamp.com/\">Winamp</a><BR>\r\n" , "icy-notice2: Erlang Shoutcast server<BR>\r\n" , "icy-name: Erlang mix\r\n" , "icy-genre: Pop Top 40 Dance Rock\r\n" , "icy-url: http://localhost:3000\r\n" , "content-type: audio/mpeg\r\n" , "icy-pub: 1\r\n" , "icy-metaint: " ,integer_to_list(?CHUNKSIZE),"\r\n" , "icy-br: 96\r\n\r\n" ]. songs() -> {ok,[SongList]} = file:consult("mp3data" ), lib_misc:random_seed(), songs_loop(SongList). songs_loop(SongList) -> receive {From, random_song} -> I = random:uniform(length(SongList)), Song = lists:nth(I, SongList), From ! {self(), Song}, songs_loop(SongList) end. rpc(Pid, Q) -> Pid ! {self(), Q}, receive {Pid, Reply} -> Reply end. unpack_song_descriptor({File, {_Tag,Info}}) -> PrintStr = list_to_binary(make_header1(Info)), L1 = ["StreamTitle=" ,PrintStr, ";StreamUrl=http://localhost:3000;" ], %% io:format("L1=~p~n",[L1]), Bin = list_to_binary(L1), Nblocks = ((size(Bin) - 1) div 16) + 1, NPad = Nblocks*16 - size(Bin), Extra = lists:duplicate(NPad, 0), Header = list_to_binary([Nblocks, Bin, Extra]), %% Header . {File, PrintStr, Header}. make_header1([{track,_}|T]) -> make_header1(T); make_header1([{Tag,X}|T]) -> [atom_to_list(Tag),": " ,X," " |make_header1(T)]; make_header1([]) -> []. 21 14. 14.7.4 22 SHOUTcast , , , : 1. . 2. . 3. . 14.7.5 : 1. , mp3_manager.erl9 2. start1, mp3_manager.erl, , MP3 . 3. mp3_manager, mp3_manager:start1(). - : 1> c(mp3_manager). {ok,mp3_manager} 2> mp3_manager:start1(). Dumping term to mp3data ok , mp3data, . 14.7.6 SHOUTcast : 1> shout:start(). ... 14.7.7 1. : http://localhost:3000 XMMS, : xmms http://localhost:3000 : , IP . , Windows , winamp, Play > URL http://192.168.1.168:3000 Open URL iMac iTunes, Advanced > Open Stream url. 2. , . 3. Enjoy! 9 , MP3 . 14. 14.8 23 . socket API , gen_tcp, gen_udp, inet.
BootstrapQTL
cran
R
Package ‘BootstrapQTL’ October 12, 2022 Type Package Title Bootstrap cis-QTL Method that Corrects for the Winner's Curse Version 1.0.5 Author <NAME> [aut], <NAME> [aut, cre] Maintainer <NAME> <<EMAIL>> BugReports https://github.com/sritchie73/bootstrapQTL/issues Description Identifies genome-related molecular traits with significant evidence of genetic regulation and performs a bootstrap procedure to correct estimated effect sizes for over-estimation present in cis-QTL mapping studies (The ``Winner's Curse''), described in Huang QQ *et al.* 2018 <doi:10.1093/nar/gky780>. Depends MatrixEQTL Imports foreach, data.table Suggests doMC, doParallel, qvalue, testthat License GPL-2 Encoding UTF-8 RoxygenNote 6.1.0 NeedsCompilation no Repository CRAN Date/Publication 2021-05-12 00:52:43 UTC R topics documented: BootstrapQT... 2 BootstrapQTL Bootstrap QTL analysis for accurate effect size estimation Description Performs cis-QTL mapping using MatrixEQTL then performs a bootstrap analysis to obtain unbi- ased effect size estimates for traits with significant evidence of genetic regulation correcting for the "Winner’s Curse" arising from lead-SNP selection. Usage BootstrapQTL(snps, gene, snpspos, genepos, cvrt = SlicedData$new(), n_bootstraps = 200, n_cores = 1, eGene_detection_file_name = NULL, bootstrap_file_directory = NULL, cisDist = 1e+06, local_correction = "bonferroni", global_correction = "fdr", correction_type = "shrinkage", errorCovariance = numeric(), useModel = modelLINEAR, eigenMT_tests_per_gene = NULL) Arguments snps SlicedData object containing genotype information used as input into Matrix_eQTL_main. gene SlicedData object containing gene expression information used as input into Matrix_eQTL_main. snpspos data.frame object with information about SNP locations. Used in conjunction with 'genespos' and 'cisDist' to determine SNPs in cis of each gene. Must have three columns: 1. ’snpid’ describing the name of the SNP and corresponding to rows in the ’snps’ matrix. 2. ’chr’ describing the chromosome for each SNP. 3. ’pos’ describing the position of the SNP on the chromosome. genepos data.frame object with information about transcript locations. Used in con- junction with 'snpspos' and 'cisDist' to determine SNPs in cis of each gene. Must have four columns: 1. ’geneid’ describing the name of the gene and corresponding to rows in the ’gene’ matrix. 2. ’chr’ describing the chromosome for each SNP. 3. ’left’ describing the start position of the transcript. 4. ’right’ describing the end position of the transcript. Note that Matrix_eQTL_main tests all variants within cisDist of the start or end of the gene. If you wish instead to test all variants within cisDist of the transcription start site, you should specify this location in both the ’left’ and ’right’ columns of the genepos data.frame. Similarly, when analysing a molec- ular phenotype that have a single chromosomal position then the ’left’ and ’right’ columns should both contain the same position. cvrt SlicedData object containing covariate information used as input into Matrix_eQTL_main. Argument can be ignored in the case of no covariates. n_bootstraps number of bootstraps to run. n_cores number of cores to parallise the bootstrap procedure over. eGene_detection_file_name character, connection or NULL. File to save local cis associations to in the eGene detection analysis. Corresponds to the output_file_name.cis argu- ment in Matrix_eQTL_main. If a file with this name exists it is overwritten, if NULL output is not saved to file. bootstrap_file_directory character or NULL. If not NULL, files will be saved in this directory storing local cis associations for the bootstrap eGene detection group (detection_bootstrapnumber.txt) and local cis associations the bootstrap left-out eGene effect size estimation group (estimation_bootstrapnumber.txt). Estimation group files will only be saved where signficant eGenes are also significant in the bootstrap detection group (see Details). Corresponds to the output_file_name.cis argument in the respective calls to Matrix_eQTL_main. Files in this directory will be over- written if they already exist. cisDist numeric. Argument to Matrix_eQTL_main controlling the maximum distance from a gene to consider tests for eQTL mapping. local_correction multiple testing correction method to use when correcting p-values across all SNPs at each gene (see EQTL mapping section in Details). Can be a method specified in p.adjust.methods, "qvalue" for the qvalue package, or "eigenMT" if EigenMT has been used to estimate the number effective independent tests (see eigenMT_tests_per_gene). global_correction multiple testing correction method to use when correcting p-values across all genes after performing local correction (see EQTL mapping section in Details). Must be a method specified in p.adjust.methods or "qvalue" for the qvalue package. correction_type character. One of "shrinkage", "out_of_sample" or "weighted". Determines which Winner’s Curse correction method is used (see Details). errorCovariance numeric matrix argument to Matrix_eQTL_main specifying the error covari- ance. useModel integer argument to Matrix_eQTL_main specifying the type of model to fit between each SNP and gene. Should be one of modelLINEAR, modelANOVA, or modelLINEAR_CROSS. eigenMT_tests_per_gene data.frame containing the number of effective independent tests for each gene estimated by the EigenMT (https://github.com/joed3/eigenMT). Ignore unless 'local_correction="eigenMT"'. Details Although the package interface and documentation describe the use of BootstrapQTL for cis-eQTL mapping, the package can be applied to any QTL study of quantitative traits with chromosomal positions, for example cis-QTL mapping of epigenetic modifications. Any matrix of molecular trait data can be provided to the 'gene' argument provided a corresponding 'genepos' ’data.frame’ detailing the chromosomal positions of each trait is provided. Cis-eQTL mapping:: EQTL mapping is performed using the MatrixEQTL package. A three step hieararchical multiple testing correction procedure is used to determine significant eGenes and eSNPs. At the first step, nominal p-values from MatrixEQTL for all cis-SNPs are adjusted for each gene separately using the method specified in the 'local_correction' argument (Bonferroni correction by default). In the second step, the best adjusted p-value is taken for each gene, and this set of locally adjusted p-values is corrected for multiple testing across all genes using the methods pecified in the 'global_correction' argument (FDR correction by default). In the third step, an eSNP significance threshold on the locally corrected p-values is determined as the locally corrected p-value corresponding to the globally corrected p-value threshold of 0.05. A gene is considered a significant eGene if its globally corrected p-value is < 0.05, and a SNP is considered a significant eSNP for that eGene if its locally corrected p-value < the eSNP signifi- cance threshold. The default settings for 'local_correction' and 'global_correction' were found to best control eGene false discovery rate without sacrificing sensitivity (see citation). Winner’s Curse correction:: EQTL effect sizes of significant eSNPs on significant eGenes are typically overestimated when compared to replication datasets (see citation). BootstrapEQTL removes this overestimation by performing a bootstrap procedure after eQTL mapping. Three Winner’s Curse correction methods are available: the Shrinkage method, the Out of Sample method, and the Weighted Estimator method. All three methods work on the same basic principle of performing repeated sample bootstrapping to partition the dataset into two groups: an eQTL detection group comprising study samples select via random sampling with replacement, and an eQTL effect size estimation group comprising the remaining samples not selected via the ran- dom sampling. The default estimator, 'correction_type = "shrinkage"', provided the most accurate corrected effect sizes in our simulation study (see citation). The shrinkage method ("shrinkage" in 'correction_type') corrects for the Winner’s Curse by measuring the average difference between the eQTL effect size in the bootstrap detection group and the bootstrap estimation group, then subtracting this difference from the naive eQTL effect size estimate obtained from the eGene detection analysis prior to the bootstrap procedure. The out of sample method ("out_of_sample" in 'correction_type') corrects for the Winner’s Curse by taking the average eQTL effect size across bootstrap estimation groups as an unbiased effect size estimate. The weighted estimator method ("weighted" in 'correction_type') corrects for the Winner’s Curse by taking a weighted average of the nominal estimate of the eQTL effect size and the average of eQTL effect sizes across the bootstrap estimation groups: 0.368 ∗ naivee stimate + 0.632 ∗ mean(bootstrapestimationgroupef f ectsizes). In all three methods bootstrap effect sizes only contribute to the Winner’s Curse correction if the corresponding eSNP is significantly associated with the eGene in the bootstrap detection group (locally corrected bootstrap P-value < eSNP significance threshold determing in the eQTL map- ping step). Note that eQTLs may not remain significant in all bootstraps, so the effective number of bootstraps used to obtain the Winner’s Curse estimate will typically be lower than the number of bootstraps specified in 'n_bootstraps'. The number of bootstraps that were significant for each eQTL are reported in the 'correction_boots' column of the returned table. Winner’s Curse corrected effect sizes: The user should be aware that ability to correct for Winner’s Curse can vary across significant eQTLs depending on their statistical power (i.e. minor allele frequency, true effect size, and study sample size). Users should be skeptical of corrected effect sizes that are larger than the nominal effect sizes estimated by MatrixEQTL, which likely reflects low power for eQTL detection rather than an underestimated effect size. Bootstrap warning messages:: It is possible for bootstrap analyses to fail due to the reduced sample sizes of the bootstrap detection and bootstrap estimation groups. For example, the boot- strap resampling may lead to an detection or estimation groups in which all individuals are ho- mozygous for an eSNP or have no variance in their supplied covariates (e.g. the estimation group may comprise individuals all of the same sex). In this case the bootstrap will fail for all eQTLs since MatrixEQTL will be unable to perform the model fitting. Failed bootstraps are reported after the bootstrap procedure in a series of warning messages indi- cating the number of bootstrap failures grouped by the reason for the bootstrap failure. Value A data.frame (or data.table if the user has the library loaded) containing the results for each significant eQTL: ’eGene’: The eQTL eGene. ’eSNP’: The eQTL eSNP. ’statistic’: The test statistic for the association between the eGene and eSNP. ’nominal_beta’: The eQTL effect size for the eGene-eSNP pair estimated by MatrixEQTL. ’corrected_beta’: The eQTL effect size after adjustment for the winners_curse. ’winners_curse’: The amount of effect size overestimation determined by the bootstrap analysis (See Details). ’correction_boots’: The number of bootstraps that contributed to the estimation of the winners_curse, i.e. the number of bootstraps in which the eSNP remained significantly associated with the eGene (see Details). ’nominal_pval’: The p-value for the eGene-eSNP pair from the MatrixEQTL analysis. ’eSNP_pval’: The locally corrected p-value for the eGene-eSNP pair (see Details). ’eGene_pval’: The globally corrected p-value for the eGene based on its top eSNP (see Details). Examples # Locations for example data from the MatrixEQTL package base.dir = find.package('MatrixEQTL'); SNP_file_name = paste(base.dir, "/data/SNP.txt", sep=""); snps_location_file_name = paste(base.dir, "/data/snpsloc.txt", sep=""); expression_file_name = paste(base.dir, "/data/GE.txt", sep=""); gene_location_file_name = paste(base.dir, "/data/geneloc.txt", sep=""); covariates_file_name = paste(base.dir, "/data/Covariates.txt", sep=""); # Load the SNP data snps = SlicedData$new(); snps$fileDelimiter = "\t"; # the TAB character snps$fileOmitCharacters = "NA"; # denote missing values; snps$fileSkipRows = 1; # one row of column labels snps$fileSkipColumns = 1; # one column of row labels snps$fileSliceSize = 2000; # read file in slices of 2,000 rows snps$LoadFile(SNP_file_name); # Load the data detailing the position of each SNP snpspos = read.table(snps_location_file_name, header = TRUE, stringsAsFactors = FALSE); # Load the gene expression data gene = SlicedData$new(); gene$fileDelimiter = "\t"; # the TAB character gene$fileOmitCharacters = "NA"; # denote missing values; gene$fileSkipRows = 1; # one row of column labels gene$fileSkipColumns = 1; # one column of row labels gene$fileSliceSize = 2000; # read file in slices of 2,000 rows gene$LoadFile(expression_file_name); # Load the data detailing the position of each gene genepos = read.table(gene_location_file_name, header = TRUE, stringsAsFactors = FALSE); # Load the covariates data cvrt = SlicedData$new(); cvrt$fileDelimiter = "\t"; # the TAB character cvrt$fileOmitCharacters = "NA"; # denote missing values; cvrt$fileSkipRows = 1; # one row of column labels cvrt$fileSkipColumns = 1; # one column of row labels if(length(covariates_file_name)>0) { cvrt$LoadFile(covariates_file_name); } # Run the BootstrapQTL analysis eQTLs <- BootstrapQTL(snps, gene, snpspos, genepos, cvrt, n_bootstraps=10, n_cores=2)
zmq-sys
rust
Rust
Struct zmq_sys::zmq_pollitem_t === ``` #[repr(C)]pub struct zmq_pollitem_t { pub socket: *mutc_void, pub fd: c_int, pub events: c_short, pub revents: c_short, } ``` Fields --- `socket: *mutc_void``fd: c_int``events: c_short``revents: c_short`Trait Implementations --- ### impl Clone for zmq_pollitem_t #### fn clone(&self) -> zmq_pollitem_t Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn default() -> Self Returns the “default value” for a type. Auto Trait Implementations --- ### impl RefUnwindSafe for zmq_pollitem_t ### impl !Send for zmq_pollitem_t ### impl !Sync for zmq_pollitem_t ### impl Unpin for zmq_pollitem_t ### impl UnwindSafe for zmq_pollitem_t Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Type Definition zmq_sys::RawFd === 1.0.0 · ``` pub type RawFd = i32; ``` Raw file descriptors.
anndata
cran
R
Package ‘anndata’ March 17, 2023 Type Package Title 'anndata' for R Version 0.7.5.6 Description A 'reticulate' wrapper for the Python package 'anndata'. Provides a scalable way of keeping track of data and learned annotations. Used to read from and write to the h5ad file format. License MIT + file LICENSE URL https://anndata.dynverse.org, https://github.com/dynverse/anndata BugReports https://github.com/dynverse/anndata/issues Depends R (>= 3.5.0) Imports assertthat, Matrix, methods, R6, reticulate (>= 1.17) Suggests stats, testthat, knitr, rmarkdown Encoding UTF-8 RoxygenNote 7.2.3 Config/reticulate list( packages = list( list(package = ``anndata'') ) ) VignetteBuilder knitr NeedsCompilation no Author <NAME> [ccp] (<https://orcid.org/0000-0002-0369-2888>, flying-sheep), <NAME> [ccp] (<https://orcid.org/0000-0002-8760-7838>, falexwolf), <NAME> [ccp] (ivirshup), <NAME> [ccp] (Koncopd), <NAME> [aut, cre, cph] (<https://orcid.org/0000-0003-3641-729X>, rcannood) Maintainer <NAME> <<EMAIL>> Repository CRAN Date/Publication 2023-03-17 14:50:06 UTC R topics documented: anndata-packag... 2 all.equal.AnnDataR... 4 AnnDat... 5 conca... 24 dimnames.AnnDataR... 27 dimnames.RawR... 29 install_anndat... 30 Layer... 31 names.LayersR... 34 r-py-conversio... 35 Ra... 36 read_cs... 41 read_exce... 42 read_h5a... 43 read_hd... 43 read_loo... 44 read_mt... 45 read_tex... 45 read_umi_tool... 46 write_csv... 47 write_h5a... 48 write_loo... 49 anndata-package anndata - Annotated Data Description anndata provides a scalable way of keeping track of data and learned annotations, and can be used to read from and write to the h5ad file format. AnnData() stores a data matrix X together with annotations of observations obs (obsm, obsp), variables var (varm, varp), and unstructured annotations uns. Details This package is, in essense, an R wrapper for the similarly named Python package anndata, with some added functionality to support more R-like syntax. The version number of the anndata R package is synced with the version number of the python version. Check out ?anndata for a full list of the functions provided by this package. Creating an AnnData object • AnnData() Concatenating two or more AnnData objects • concat() Reading an AnnData object from a file • read_csv() • read_excel() • read_h5ad() • read_hdf() • read_loom() • read_mtx() • read_text() • read_umi_tools() Writing an AnnData object to a file • write_csvs() • write_h5ad() • write_loom() Install the anndata Python package • install_anndata() Examples ## Not run: ad <- AnnData( X = matrix(1:6, nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L, 3L), row.names = c("var1", "var2", "var3")), layers = list( spliced = matrix(4:9, nrow = 2), unspliced = matrix(8:13, nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 12), nrow = 3), rand = matrix(rnorm(6), nrow = 3), zeros = matrix(rep(0L, 12), nrow = 3) ), uns = list( a = 1, b = data.frame(i = 1:3, j = 4:6, value = runif(3)), c = list(c.a = 3, c.b = 4) ) ) ad$X ad$obs ad$var ad$obsm["ones"] ad$varm["rand"] ad$layers["unspliced"] ad$layers["spliced"] ad$uns["b"] ad[,c("var1", "var2")] ad[-1, , drop = FALSE] ad[, 2] <- 10 ## End(Not run) all.equal.AnnDataR6 Test if two objects objects are equal Description Test if two objects objects are equal Usage ## S3 method for class 'equal.AnnDataR6' all(target, current, ...) ## S3 method for class 'equal.LayersR6' all(target, current, ...) ## S3 method for class 'equal.RawR6' all(target, current, ...) Arguments target R object. current other R object, to be compared with target. ... further arguments for different methods, notably the following two, for numeri- cal comparison: AnnData Create an Annotated Data Matrix Description AnnData stores a data matrix X together with annotations of observations obs (obsm, obsp), variables var (varm, varp), and unstructured annotations uns. An AnnData object adata can be sliced like a data frame, for instance adata_subset <- adata[, list_of_variable_names]. AnnData’s basic structure is similar to R’s ExpressionSet. If setting an h5ad-formatted HDF5 backing file filename, data remains on the disk but is automat- ically loaded into memory if needed. See this blog post for more details. Usage AnnData( X = NULL, obs = NULL, var = NULL, uns = NULL, obsm = NULL, varm = NULL, layers = NULL, raw = NULL, dtype = "float32", shape = NULL, filename = NULL, filemode = NULL, obsp = NULL, varp = NULL ) Arguments X A #observations × #variables data matrix. A view of the data is used if the data type matches, otherwise, a copy is made. obs Key-indexed one-dimensional observations annotation of length #observations. var Key-indexed one-dimensional variables annotation of length #variables. uns Key-indexed unstructured annotation. obsm Key-indexed multi-dimensional observations annotation of length #observations. If passing a ~numpy.ndarray, it needs to have a structured datatype. varm Key-indexed multi-dimensional variables annotation of length #variables. If passing a ~numpy.ndarray, it needs to have a structured datatype. layers Key-indexed multi-dimensional arrays aligned to dimensions of X. raw Store raw version of X and var as $raw$X and $raw$var. dtype Data type used for storage. shape Shape list (#observations, #variables). Can only be provided if X is NULL. filename Name of backing file. See h5py.File. filemode Open mode of backing file. See h5py.File. obsp Pairwise annotation of observations, a mutable mapping with array-like values. varp Pairwise annotation of observations, a mutable mapping with array-like values. Details AnnData stores observations (samples) of variables/features in the rows of a matrix. This is the con- vention of the modern classics of statistic and machine learning, the convention of dataframes both in R and Python and the established statistics and machine learning packages in Python (statsmod- els, scikit-learn). Single dimensional annotations of the observation and variables are stored in the obs and var at- tributes as data frames. This is intended for metrics calculated over their axes. Multi-dimensional annotations are stored in obsm and varm, which are aligned to the objects observation and variable dimensions respectively. Square matrices representing graphs are stored in obsp and varp, with both of their own dimensions aligned to their associated axis. Additional measurements across both observations and variables are stored in layers. Indexing into an AnnData object can be performed by relative position with numeric indices, or by labels. To avoid ambiguity with numeric indexing into observations or variables, indexes of the AnnData object are converted to strings by the constructor. Subsetting an AnnData object by indexing into it will also subset its elements according to the dimensions they were aligned to. This means an operation like adata[list_of_obs, ] will also subset obs, obsm, and layers. Subsetting an AnnData object returns a view into the original object, meaning very little additional memory is used upon subsetting. This is achieved lazily, meaning that the constituent arrays are subset on access. Copying a view causes an equivalent “real” AnnData object to be generated. Attempting to modify a view (at any attribute except X) is handled in a copy-on-modify manner, meaning the object is initialized in place. Here’s an example batch1 <- adata[adata$obs["batch"] == "batch1", ] batch1$obs["value"] = 0 # This makes batch1 a “real” AnnData object At the end of this snippet: adata was not modified, and batch1 is its own AnnData object with its own data. Similar to Bioconductor’s ExpressionSet and scipy.sparse matrices, subsetting an AnnData object retains the dimensionality of its constituent arrays. Therefore, unlike with the classes exposed by pandas, numpy, and xarray, there is no concept of a one dimensional AnnData object. AnnDatas always have two inherent dimensions, obs and var. Additionally, maintaining the dimensionality of the AnnData object allows for consistent handling of scipy.sparse matrices and numpy arrays. Active bindings X Data matrix of shape n_obs × n_vars. filename Name of the backing file. Change to backing mode by setting the filename of a .h5ad file. • Setting the filename writes the stored data to disk. • Setting the filename when the filename was previously another name moves the backing file from the previous file to the new file. If you want to copy the previous file, use copy(filename='new_filename'). layers A list-like object with values of the same dimensions as X. Layers in AnnData are inspired by loompy’s layers. Overwrite the layers: adata$layers <- list(spliced = spliced, unspliced = unspliced) Return the layer named "unspliced": adata$layers["unspliced"] Create or replace the "spliced" layer: adata$layers["spliced"] = example_matrix Assign the 10th column of layer "spliced" to the variable a: a <- adata$layers["spliced"][, 10] Delete the "spliced": adata$layers["spliced"] <- NULL Return layers’ names: names(adata$layers) T Transpose whole object. Data matrix is transposed, observations and variables are interchanged. Ignores .raw. is_view TRUE if object is view of another AnnData object, FALSE otherwise. isbacked TRUE if object is backed on disk, FALSE otherwise. n_obs Number of observations. obs One-dimensional annotation of observations (data.frame). obs_names Names of observations. obsm Multi-dimensional annotation of observations (matrix). Stores for each key a two or higher-dimensional matrix with n_obs rows. obsp Pairwise annotation of observations, a mutable mapping with array-like values. Stores for each key a two or higher-dimensional matrix whose first two dimensions are of length n_obs. n_vars Number of variables. var One-dimensional annotation of variables (data.frame). var_names Names of variables. varm Multi-dimensional annotation of variables (matrix). Stores for each key a two or higher-dimensional matrix with n_vars rows. varp Pairwise annotation of variables, a mutable mapping with array-like values. Stores for each key a two or higher-dimensional matrix whose first two dimensions are of length n_vars. shape Shape of data matrix (n_obs, n_vars). uns Unstructured annotation (ordered dictionary). raw Store raw version of X and var as $raw$X and $raw$var. The raw attribute is initialized with the current content of an object by setting: adata$raw = adata Its content can be deleted: adata$raw <- NULL Upon slicing an AnnData object along the obs (row) axis, raw is also sliced. Slicing an Ann- Data object along the vars (columns) axis leaves raw unaffected. Note that you can call: adata$raw[, 'orig_variable_name']$X to retrieve the data associated with a variable that might have been filtered out or "compressed awa Methods Public methods: • AnnDataR6$new() • AnnDataR6$obs_keys() • AnnDataR6$obs_names_make_unique() • AnnDataR6$obsm_keys() • AnnDataR6$var_keys() • AnnDataR6$var_names_make_unique() • AnnDataR6$varm_keys() • AnnDataR6$uns_keys() • AnnDataR6$chunk_X() • AnnDataR6$chunked_X() • AnnDataR6$concatenate() • AnnDataR6$copy() • AnnDataR6$rename_categories() • AnnDataR6$strings_to_categoricals() • AnnDataR6$to_df() • AnnDataR6$transpose() • AnnDataR6$write_csvs() • AnnDataR6$write_h5ad() • AnnDataR6$write_loom() • AnnDataR6$print() • AnnDataR6$.set_py_object() • AnnDataR6$.get_py_object() Method new(): Create a new AnnData object Usage: AnnDataR6$new(obj) Arguments: obj A Python anndata object Examples: \dontrun{ # use AnnData() instead of AnnDataR6$new() ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")) ) } Method obs_keys(): List keys of observation annotation obs. Usage: AnnDataR6$obs_keys() Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")) ) ad$obs_keys() } Method obs_names_make_unique(): Makes the index unique by appending a number string to each duplicate index element: 1, 2, etc. If a tentative name created by the algorithm already exists in the index, it tries the next integer in the sequence. The first occurrence of a non-unique value is ignored. Usage: AnnDataR6$obs_names_make_unique(join = "-") Arguments: join The connecting string between name and integer (default: "-"). Examples: \dontrun{ ad <- AnnData( X = matrix(rep(1, 6), nrow = 3), obs = data.frame(field = c(1, 2, 3)) ) ad$obs_names <- c("a", "a", "b") ad$obs_names_make_unique() ad$obs_names } Method obsm_keys(): List keys of observation annotation obsm. Usage: AnnDataR6$obsm_keys() Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ) ) ad$obs_keys() } Method var_keys(): List keys of variable annotation var. Usage: AnnDataR6$var_keys() Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")) ) ad$var_keys() } Method var_names_make_unique(): Makes the index unique by appending a number string to each duplicate index element: 1, 2, etc. If a tentative name created by the algorithm already exists in the index, it tries the next integer in the sequence. The first occurrence of a non-unique value is ignored. Usage: AnnDataR6$var_names_make_unique(join = "-") Arguments: join The connecting string between name and integer (default: "-"). Examples: \dontrun{ ad <- AnnData( X = matrix(rep(1, 6), nrow = 2), var = data.frame(field = c(1, 2, 3)) ) ad$var_names <- c("a", "a", "b") ad$var_names_make_unique() ad$var_names } Method varm_keys(): List keys of variable annotation varm. Usage: AnnDataR6$varm_keys() Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ) ) ad$varm_keys() } Method uns_keys(): List keys of unstructured annotation uns. Usage: AnnDataR6$uns_keys() Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) } Method chunk_X(): Return a chunk of the data matrix X with random or specified indices. Usage: AnnDataR6$chunk_X(select = 1000L, replace = TRUE) Arguments: select Depending on the values: • 1 integer: A random chunk with select rows will be returned. • multiple integers: A chunk with these indices will be returned. replace if select is an integer then TRUE means random sampling of indices with replacement, FALSE without replacement. Examples: \dontrun{ ad <- AnnData( X = matrix(runif(10000), nrow = 50) ) ad$chunk_X(select = 10L) # 10 random samples ad$chunk_X(select = 1:3) # first 3 samples } Method chunked_X(): Return an iterator over the rows of the data matrix X. Usage: AnnDataR6$chunked_X(chunk_size = NULL) Arguments: chunk_size Row size of a single chunk. Examples: \dontrun{ ad <- AnnData( X = matrix(runif(10000), nrow = 50) ) ad$chunked_X(10) } Method concatenate(): Concatenate along the observations axis. Usage: AnnDataR6$concatenate(...) Arguments: ... Deprecated Method copy(): Full copy, optionally on disk. Usage: AnnDataR6$copy(filename = NULL) Arguments: filename Path to filename (default: NULL). Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2) ) ad$copy() ad$copy("file.h5ad") } Method rename_categories(): Rename categories of annotation key in obs, var, and uns. Only supports passing a list/array-like categories argument. Besides calling self.obs[key].cat.categories = catego – similar for var - this also renames categories in unstructured annotation that uses the categorical annotation key. Usage: AnnDataR6$rename_categories(key, categories) Arguments: key Key for observations or variables annotation. categories New categories, the same number as the old categories. Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")) ) ad$rename_categories("group", c(a = "A", b = "B")) # ?? } Method strings_to_categoricals(): Transform string annotations to categoricals. Only affects string annotations that lead to less categories than the total number of observations. Usage: AnnDataR6$strings_to_categoricals(df = NULL) Arguments: df If df is NULL, modifies both obs and var, otherwise modifies df inplace. Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), ) ad$strings_to_categoricals() # ?? } Method to_df(): Generate shallow data frame. The data matrix X is returned as data frame, where obs_names are the rownames, and var_names the columns names. No annotations are maintained in the returned object. The data matrix is densified in case it is sparse. Usage: AnnDataR6$to_df(layer = NULL) Arguments: layer Key for layers Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ) ) ad$to_df() ad$to_df("unspliced") } Method transpose(): transpose Transpose whole object. Data matrix is transposed, observations and variables are interchanged. Ignores .raw. Usage: AnnDataR6$transpose() Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")) ) ad$transpose() } Method write_csvs(): Write annotation to .csv files. It is not possible to recover the full AnnData from these files. Use write_h5ad() for this. Usage: AnnDataR6$write_csvs(dirname, skip_data = TRUE, sep = ",") Arguments: dirname Name of the directory to which to export. skip_data Skip the data matrix X. sep Separator for the data anndata An AnnData() object Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$to_write_csvs("output") unlink("output", recursive = TRUE) } Method write_h5ad(): Write .h5ad-formatted hdf5 file. Generally, if you have sparse data that are stored as a dense matrix, you can dramatically improve performance and reduce disk space by converting to a csr_matrix: Usage: AnnDataR6$write_h5ad( filename, compression = NULL, compression_opts = NULL, as_dense = list() ) Arguments: filename Filename of data file. Defaults to backing file. compression See the h5py filter pipeline. Options are "gzip", "lzf" or NULL. compression_opts See the h5py filter pipeline. as_dense Sparse in AnnData object to write as dense. Currently only supports "X" and "raw/X". anndata An AnnData() object Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$write_h5ad("output.h5ad") file.remove("output.h5ad") } Method write_loom(): Write .loom-formatted hdf5 file. Usage: AnnDataR6$write_loom(filename, write_obsm_varm = FALSE) Arguments: filename The filename. write_obsm_varm Whether or not to also write the varm and obsm. anndata An AnnData() object Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$write_loom("output.loom") file.remove("output.loom") } Method print(): Print AnnData object Usage: AnnDataR6$print(...) Arguments: ... optional arguments to print method. Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$print() print(ad) } Method .set_py_object(): Set internal Python object Usage: AnnDataR6$.set_py_object(obj) Arguments: obj A python anndata object Method .get_py_object(): Get internal Python object Usage: AnnDataR6$.get_py_object() See Also read_h5ad() read_csv() read_excel() read_hdf() read_loom() read_mtx() read_text() read_umi_tools() write_h5ad() write_csvs() write_loom() Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) value <- matrix(c(1,2,3,4), nrow = 2) ad$X <- value ad$X ad$layers ad$layers["spliced"] ad$layers["test"] <- value ad$layers ad$to_df() ad$uns as.matrix(ad) as.matrix(ad, layer = "unspliced") dim(ad) rownames(ad) colnames(ad) ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$new` ## ------------------------------------------------ ## Not run: # use AnnData() instead of AnnDataR6$new() ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")) ) ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$obs_keys` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")) ) ad$obs_keys() ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$obs_names_make_unique` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(rep(1, 6), nrow = 3), obs = data.frame(field = c(1, 2, 3)) ) ad$obs_names <- c("a", "a", "b") ad$obs_names_make_unique() ad$obs_names ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$obsm_keys` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ) ) ad$obs_keys() ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$var_keys` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")) ) ad$var_keys() ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$var_names_make_unique` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(rep(1, 6), nrow = 2), var = data.frame(field = c(1, 2, 3)) ) ad$var_names <- c("a", "a", "b") ad$var_names_make_unique() ad$var_names ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$varm_keys` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ) ) ad$varm_keys() ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$uns_keys` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$chunk_X` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(runif(10000), nrow = 50) ) ad$chunk_X(select = 10L) # 10 random samples ad$chunk_X(select = 1:3) # first 3 samples ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$chunked_X` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(runif(10000), nrow = 50) ) ad$chunked_X(10) ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$copy` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2) ) ad$copy() ad$copy("file.h5ad") ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$rename_categories` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")) ) ad$rename_categories("group", c(a = "A", b = "B")) # ?? ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$strings_to_categoricals` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), ) ad$strings_to_categoricals() # ?? ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$to_df` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ) ) ad$to_df() ad$to_df("unspliced") ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$transpose` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")) ) ad$transpose() ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$write_csvs` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$to_write_csvs("output") unlink("output", recursive = TRUE) ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$write_h5ad` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$write_h5ad("output.h5ad") file.remove("output.h5ad") ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$write_loom` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$write_loom("output.loom") file.remove("output.loom") ## End(Not run) ## ------------------------------------------------ ## Method `AnnDataR6$print` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$print() print(ad) ## End(Not run) concat concat Description Concatenates AnnData objects along an axis. Usage concat( adatas, axis = 0L, join = "inner", merge = NULL, uns_merge = NULL, label = NULL, keys = NULL, index_unique = NULL, fill_value = NULL, pairwise = FALSE ) Arguments adatas The objects to be concatenated. If a Mapping is passed, keys are used for the keys argument and values are concatenated. axis Which axis to concatenate along. join How to align values when concatenating. If "outer", the union of the other axis is taken. If "inner", the intersection. See concatenation for more. merge How elements not aligned to the axis being concatenated along are selected. Currently implemented strategies include: * NULL: No elements are kept. * "same": Elements that are the same in each of the objects. * "unique": Ele- ments for which there is only one possible value. * "first": The first element seen at each from each position. * "only": Elements that show up in only one of the objects. uns_merge How the elements of .uns are selected. Uses the same set of strategies as the merge argument, except applied recursively. label Column in axis annotation (i.e. .obs or .var) to place batch information in. If it’s NULL, no column is added. keys Names for each object being added. These values are used for column values for label or appended to the index if index_unique is not NULL. Defaults to incrementing integer labels. index_unique Whether to make the index unique by using the keys. If provided, this is the delimeter between "orig_idxindex_uniquekey". When NULL, the original indices are kept. fill_value When join="outer", this is the value that will be used to fill the introduced indices. By default, sparse arrays are padded with zeros, while dense arrays and DataFrames are padded with missing values. pairwise Whether pairwise elements along the concatenated dimension should be in- cluded. This is FALSE by default, since the resulting arrays are often not mean- ingful. Details See the concatenation section in the docs for a more in-depth description. warning: This function is marked as experimental for the 0.7 release series, and will supercede the AnnData$concatenate() method in future releases. warning: If you use join='outer' this fills 0s for sparse data when variables are absent in a batch. Use this with care. Dense data is filled with NaN. Examples ## Not run: # Preparing example objects a <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2, byrow = TRUE), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list( a = 1, b = 2, c = list( c.a = 3, c.b = 4 ) ) ) b <- AnnData( X = matrix(c(4, 5, 6, 7, 8, 9), nrow = 2, byrow = TRUE), obs = data.frame(group = c("b", "c"), row.names = c("s3", "s4")), var = data.frame(type = c(1L, 2L, 3L), row.names = c("var1", "var2", "var3")), varm = list( ones = matrix(rep(1L, 15), nrow = 3), rand = matrix(rnorm(15), nrow = 3) ), uns = list( a = 1, b = 3, c = list( c.a = 3 ) ) ) c <- AnnData( X = matrix(c(10, 11, 12, 13), nrow = 2, byrow = TRUE), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(3L, 4L), row.names = c("var3", "var4")), uns = list( a = 1, b = 4, c = list( c.a = 3, c.b = 4, c.c = 5 ) ) ) # Concatenating along different axes concat(list(a, b))$to_df() concat(list(a, c), axis = 1L)$to_df() # Inner and outer joins inner <- concat(list(a, b)) inner inner$obs_names inner$var_names outer <- concat(list(a, b), join = "outer") outer outer$var_names outer$to_df() # Keeping track of source objects concat(list(a = a, b = b), label = "batch")$obs concat(list(a, b), label = "batch", keys = c("a", "b"))$obs concat(list(a = a, b = b), index_unique = "-")$obs # Combining values not aligned to axis of concatenation concat(list(a, b), merge = "same") concat(list(a, b), merge = "unique") concat(list(a, b), merge = "first") concat(list(a, b), merge = "only") # The same merge strategies can be used for elements in .uns concat(list(a, b, c), uns_merge = "same")$uns concat(list(a, b, c), uns_merge = "unique")$uns concat(list(a, b, c), uns_merge = "first")$uns concat(list(a, b, c), uns_merge = "only")$uns ## End(Not run) dimnames.AnnDataR6 AnnData Helpers Description AnnData Helpers Usage ## S3 method for class 'AnnDataR6' dimnames(x) ## S3 replacement method for class 'AnnDataR6' dimnames(x) <- value ## S3 method for class 'AnnDataR6' dim(x) ## S3 method for class 'AnnDataR6' as.data.frame(x, row.names = NULL, optional = FALSE, layer = NULL, ...) ## S3 method for class 'AnnDataR6' as.matrix(x, layer = NULL, ...) ## S3 method for class 'AnnDataR6' r_to_py(x, convert = FALSE) ## S3 method for class 'anndata._core.anndata.AnnData' py_to_r(x) ## S3 method for class 'AnnDataR6' x[oidx, vidx] ## S3 method for class 'AnnDataR6' t(x) ## S3 method for class 'anndata._core.sparse_dataset.SparseDataset' py_to_r(x) ## S3 method for class 'h5py._hl.dataset.Dataset' py_to_r(x) Arguments x An AnnData object. value a possible valie for dimnames(ad). The dimnames of a AnnData can be NULL (which is not stored) or a list of the same length as dim(ad). If a list, its com- ponents are either NULL or a character vector with positive length of the appro- priate dimension of ad. row.names Not used. optional Not used. layer An AnnData layer. If NULL, will use ad$X, otherwise ad$layers[layer]. ... Parameters passed to the underlying function. convert Not used. oidx Observation indices vidx Variable indices Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3, 4, 5), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L, 3L), row.names = c("var1", "var2", "var3")), layers = list( spliced = matrix(c(4, 5, 6, 7, 8, 9), nrow = 2), unspliced = matrix(c(8, 9, 10, 11, 12, 13), nrow = 2) ), dimnames.RawR6 29 obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 12), nrow = 3), rand = matrix(rnorm(6), nrow = 3), zeros = matrix(rep(0L, 12), nrow = 3) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) dimnames(ad) dim(ad) as.data.frame(ad) as.data.frame(ad, layer = "unspliced") as.matrix(ad) as.matrix(ad, layer = "unspliced") ad[2,,drop=FALSE] ad[,-1] ad[,c("var1", "var2")] ## End(Not run) dimnames.RawR6 Raw Helpers Description Raw Helpers Usage ## S3 method for class 'RawR6' dimnames(x) ## S3 method for class 'RawR6' dim(x) ## S3 method for class 'RawR6' as.matrix(x, ...) ## S3 method for class 'RawR6' r_to_py(x, convert = FALSE) ## S3 method for class 'anndata._core.raw.Raw' py_to_r(x) ## S3 method for class 'RawR6' x[...] Arguments x An AnnData object. ... Parameters passed to the underlying function. convert Not used. Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3, 4, 5), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L, 3L), row.names = c("var1", "var2", "var3")), layers = list( spliced = matrix(c(4, 5, 6, 7, 8, 9), nrow = 2), unspliced = matrix(c(8, 9, 10, 11, 12, 13), nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 12), nrow = 3), rand = matrix(rnorm(6), nrow = 3), zeros = matrix(rep(0L, 12), nrow = 3) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$raw <- ad dimnames(ad$raw) dim(ad$raw) as.matrix(ad$raw) ad$raw[2,,drop=FALSE] ad$raw[,-1] ad$raw[,c("var1", "var2")] ## End(Not run) install_anndata Install anndata Description Needs to be run after installing the anndata R package. Usage install_anndata(method = "auto", conda = "auto") Arguments method Installation method. By default, "auto" automatically finds a method that will work in the local environment. Change the default to force a specific installation method. Note that the "virtualenv" method is not available on Windows. conda The path to a conda executable. Use "auto" to allow reticulate to automati- cally find an appropriate conda binary. See Finding Conda and conda_binary() for more details. Examples ## Not run: reticulate::conda_install() install_anndata() ## End(Not run) Layers Create a Layers object Description Create a Layers object Usage Layers(parent, vals = NULL) Arguments parent An AnnData object. vals A named list of matrices with the same dimensions as parent. Active bindings parent Reference to parent AnnData view Methods Public methods: • LayersR6$new() • LayersR6$print() • LayersR6$get() • LayersR6$set() • LayersR6$del() • LayersR6$keys() • LayersR6$length() • LayersR6$.set_py_object() • LayersR6$.get_py_object() Method new(): Create a new Layers object Usage: LayersR6$new(obj) Arguments: obj A Python Layers object Method print(): Print Layers object Usage: LayersR6$print(...) Arguments: ... optional arguments to print method. Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ) ) print(ad$layers) } Method get(): Get a layer Usage: LayersR6$get(name) Arguments: name Name of the layer Method set(): Set a layer Usage: LayersR6$set(name, value) Arguments: name Name of the layer value A matrix Method del(): Delete a layer Usage: LayersR6$del(name) Arguments: name Name of the layer Method keys(): Get the names of the layers Usage: LayersR6$keys() Method length(): Get the number of layers Usage: LayersR6$length() Method .set_py_object(): Set internal Python object Usage: LayersR6$.set_py_object(obj) Arguments: obj A Python layers object Method .get_py_object(): Get internal Python object Usage: LayersR6$.get_py_object() Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ) ) ad$layers["spliced"] ad$layers["test"] <- matrix(c(1, 3, 5, 7), nrow = 2) length(ad$layers) names(ad$layers) ## End(Not run) ## ------------------------------------------------ ## Method `LayersR6$print` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ) ) print(ad$layers) ## End(Not run) names.LayersR6 Layers Helpers Description Layers Helpers Usage ## S3 method for class 'LayersR6' names(x) ## S3 method for class 'LayersR6' length(x) ## S3 method for class 'LayersR6' r_to_py(x, convert = FALSE) ## S3 method for class 'anndata._core.aligned_mapping.LayersBase' py_to_r(x) ## S3 method for class 'LayersR6' x[name] ## S3 replacement method for class 'LayersR6' x[name] <- value ## S3 method for class 'LayersR6' x[[name]] ## S3 replacement method for class 'LayersR6' x[[name]] <- value Arguments x An AnnData object. convert Not used. name Name of the layer. value Replacement value. Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3, 4, 5), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L, 3L), row.names = c("var1", "var2", "var3")), layers = list( spliced = matrix(c(4, 5, 6, 7, 8, 9), nrow = 2), unspliced = matrix(c(8, 9, 10, 11, 12, 13), nrow = 2) ) ) ad$layers["spliced"] ad$layers["test"] <- matrix(c(1, 3, 5, 7), nrow = 2) length(ad$layers) names(ad$layers) ## End(Not run) r-py-conversion Convert between Python and R objects Description Convert between Python and R objects Usage ## S3 replacement method for class 'collections.abc.MutableMapping' x[[name]] <- value ## S3 method for class 'collections.abc.Mapping' x[[name]] ## S3 replacement method for class 'collections.abc.MutableMapping' x[name] <- value ## S3 method for class 'collections.abc.Mapping' x[name] ## S3 method for class 'collections.abc.Mapping' names(x) ## S3 method for class 'collections.abc.Set' py_to_r(x) ## S3 method for class 'pandas.core.indexes.base.Index' py_to_r(x) ## S3 method for class 'collections.abc.KeysView' py_to_r(x) ## S3 method for class 'collections.abc.Mapping' py_to_r(x) Arguments x A Python object. name A name value A value Value An R object, as converted from the Python object. Raw Create a Raw object Description Create a Raw object Usage Raw(adata, X = NULL, var = NULL, varm = NULL) Arguments adata An AnnData object. X A #observations × #variables data matrix. var Key-indexed one-dimensional variables annotation of length #variables. varm Key-indexed multi-dimensional variables annotation of length #variables. Active bindings X Data matrix of shape n_obs × n_vars. n_obs Number of observations. obs_names Names of observations. n_vars Number of variables. var One-dimensional annotation of variables (data.frame). var_names Names of variables. varm Multi-dimensional annotation of variables (matrix). Stores for each key a two or higher-dimensional matrix with n_var rows. shape Shape of data matrix (n_obs, n_vars). Methods Public methods: • RawR6$new() • RawR6$copy() • RawR6$to_adata() • RawR6$print() • RawR6$.set_py_object() • RawR6$.get_py_object() Method new(): Create a new Raw object Usage: RawR6$new(obj) Arguments: obj A Python Raw object Method copy(): Full copy, optionally on disk. Usage: RawR6$copy() Arguments: filename Path to filename (default: NULL). Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2) ) ad$copy() ad$copy("file.h5ad") } Method to_adata(): Create a full AnnData object Usage: RawR6$to_adata() Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ) ) ad$raw <- ad ad$raw$to_adata() } Method print(): Print Raw object Usage: RawR6$print(...) Arguments: ... optional arguments to print method. Examples: \dontrun{ ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$raw <- ad library(reticulate) sc <- import("scanpy") sc$pp$normalize_per_cell(ad) ad[] ad$raw[] ad$print() print(ad) } Method .set_py_object(): Set internal Python object Usage: RawR6$.set_py_object(obj) Arguments: obj A Python Raw object Method .get_py_object(): Get internal Python object Usage: RawR6$.get_py_object() Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$raw <- ad library(reticulate) sc <- import("scanpy") sc$pp$normalize_per_cell(ad) ad[] ad$raw[] ## End(Not run) ## ------------------------------------------------ ## Method `RawR6$copy` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2) ) ad$copy() ad$copy("file.h5ad") ## End(Not run) ## ------------------------------------------------ ## Method `RawR6$to_adata` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ) ) ad$raw <- ad ad$raw$to_adata() ## End(Not run) ## ------------------------------------------------ ## Method `RawR6$print` ## ------------------------------------------------ ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), layers = list( spliced = matrix(c(4, 5, 6, 7), nrow = 2), unspliced = matrix(c(8, 9, 10, 11), nrow = 2) ), obsm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) ad$raw <- ad library(reticulate) sc <- import("scanpy") sc$pp$normalize_per_cell(ad) ad[] ad$raw[] ad$print() print(ad) ## End(Not run) read_csv read_csv Description Read .csv file. Usage read_csv( filename, delimiter = ",", first_column_names = NULL, dtype = "float32" ) Arguments filename Data file. delimiter Delimiter that separates data within text file. If NULL, will split at arbitrary num- ber of white spaces, which is different from enforcing splitting at single white space ' '. first_column_names Assume the first column stores row names. dtype Numpy data type. Details Same as read_text() but with default delimiter ','. Examples ## Not run: ad <- read_csv("matrix.csv") ## End(Not run) read_excel read_excel Description Read .xlsx (Excel) file. Usage read_excel(filename, sheet, dtype = "float32") Arguments filename File name to read from. sheet Name of sheet in Excel file. dtype Numpy data type. Details Assumes that the first columns stores the row names and the first row the column names. Examples ## Not run: ad <- read_excel("spreadsheet.xls") ## End(Not run) read_h5ad read_h5ad Description Read .h5ad-formatted hdf5 file. Usage read_h5ad(filename, backed = NULL) Arguments filename File name of data file. backed If 'r', load ~anndata.AnnData in backed mode instead of fully loading it into memory (memory mode). If you want to modify backed attributes of the Ann- Data object, you need to choose 'r+'. Examples ## Not run: ad <- read_h5ad("example_formats/pbmc_1k_protein_v3_processed.h5ad") ## End(Not run) read_hdf read_hdf Description Read .h5 (hdf5) file. Usage read_hdf(filename, key) Arguments filename Filename of data file. key Name of dataset in the file. Details Note: Also looks for fields row_names and col_names. Examples ## Not run: ad <- read_hdf("file.h5") ## End(Not run) read_loom read_loom Description Read .loom-formatted hdf5 file. Usage read_loom( filename, sparse = TRUE, cleanup = FALSE, X_name = "spliced", obs_names = "CellID", obsm_names = NULL, var_names = "Gene", varm_names = NULL, dtype = "float32", ... ) Arguments filename The filename. sparse Whether to read the data matrix as sparse. cleanup Whether to collapse all obs/var fields that only store one unique value into .uns['loom-.']. X_name Loompy key with which the data matrix AnnData.X is initialized. obs_names Loompy key where the observation/cell names are stored. obsm_names Loompy keys which will be constructed into observation matrices var_names Loompy key where the variable/gene names are stored. varm_names Loompy keys which will be constructed into variable matrices dtype Numpy data type. ... Arguments to loompy.connect Details This reads the whole file into memory. Beware that you have to explicitly state when you want to read the file as sparse data. read_mtx 45 Examples ## Not run: ad <- read_loom("dataset.loom") ## End(Not run) read_mtx read_mtx Description Read .mtx file. Usage read_mtx(filename, dtype = "float32") Arguments filename The filename. dtype Numpy data type. Examples ## Not run: ad <- read_mtx("matrix.mtx") ## End(Not run) read_text read_text Description Read .txt, .tab, .data (text) file. Usage read_text( filename, delimiter = NULL, first_column_names = NULL, dtype = "float32" ) Arguments filename Data file, filename or stream. delimiter Delimiter that separates data within text file. If NULL, will split at arbitrary num- ber of white spaces, which is different from enforcing splitting at single white space ' '. first_column_names Assume the first column stores row names. dtype Numpy data type. Details Same as read_csv() but with default delimiter NULL. Examples ## Not run: ad <- read_text("matrix.tab") ## End(Not run) read_umi_tools read_umi_tools Description Read a gzipped condensed count matrix from umi_tools. Usage read_umi_tools(filename, dtype = "float32") Arguments filename File name to read from. dtype Numpy data type. Examples ## Not run: ad <- read_umi_tools("...") ## End(Not run) write_csvs Write annotation to .csv files. Description It is not possible to recover the full AnnData from these files. Use write_h5ad() for this. Usage write_csvs(anndata, dirname, skip_data = TRUE, sep = ",") Arguments anndata An AnnData() object dirname Name of the directory to which to export. skip_data Skip the data matrix X. sep Separator for the data Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2, byrow = TRUE), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) write_csvs(ad, "output") unlink("output", recursive = TRUE) ## End(Not run) write_h5ad Write .h5ad-formatted hdf5 file. Description Generally, if you have sparse data that are stored as a dense matrix, you can dramatically improve performance and reduce disk space by converting to a csr_matrix: Usage write_h5ad( anndata, filename, compression = NULL, compression_opts = NULL, as_dense = list() ) Arguments anndata An AnnData() object filename Filename of data file. Defaults to backing file. compression See the h5py filter pipeline. Options are "gzip", "lzf" or NULL. compression_opts See the h5py filter pipeline. as_dense Sparse in AnnData object to write as dense. Currently only supports "X" and "raw/X". Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2, byrow = TRUE), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) write_h5ad(ad, "output.h5ad") file.remove("output.h5ad") ## End(Not run) write_loom Write .loom-formatted hdf5 file. Description Write .loom-formatted hdf5 file. Usage write_loom(anndata, filename, write_obsm_varm = FALSE) Arguments anndata An AnnData() object filename The filename. write_obsm_varm Whether or not to also write the varm and obsm. Examples ## Not run: ad <- AnnData( X = matrix(c(0, 1, 2, 3), nrow = 2, byrow = TRUE), obs = data.frame(group = c("a", "b"), row.names = c("s1", "s2")), var = data.frame(type = c(1L, 2L), row.names = c("var1", "var2")), varm = list( ones = matrix(rep(1L, 10), nrow = 2), rand = matrix(rnorm(6), nrow = 2), zeros = matrix(rep(0L, 10), nrow = 2) ), uns = list(a = 1, b = 2, c = list(c.a = 3, c.b = 4)) ) write_loom(ad, "output.loom") file.remove("output.loom") ## End(Not run)
lillinput
rust
Rust
Crate lillinput === Library for connecting libinput gestures to i3 and others. `lillinput` is a small for utility for connecting `libinput` gestures to: * commands for the `i3` tiling window manager `IPC` interface * shell commands This crate provides the library. See also the [`lillinput-cli`] crate for the commandline interface. Modules --- actionsComponents for representing actions.controllersComponents for mapping `ActionEvent`s to `Action`s.eventsComponents for capturing and handling events. Crate lillinput === Library for connecting libinput gestures to i3 and others. `lillinput` is a small for utility for connecting `libinput` gestures to: * commands for the `i3` tiling window manager `IPC` interface * shell commands This crate provides the library. See also the [`lillinput-cli`] crate for the commandline interface. Modules --- actionsComponents for representing actions.controllersComponents for mapping `ActionEvent`s to `Action`s.eventsComponents for capturing and handling events. Module lillinput::actions === Components for representing actions. Re-exports --- `pub use crate::actions::commandaction::CommandAction;``pub use crate::actions::errors::ActionError;``pub use crate::actions::i3action::I3Action;``pub use crate::actions::i3action::SharedConnection;`Modules --- commandactionAction for executing commands.errorsErrors related to `actions`.i3actionAction for interacting with `i3`.Enums --- ActionTypePossible choices for action types.Traits --- ActionHandler for a single action triggered by an event. Module lillinput::controllers === Components for mapping `ActionEvent`s to `Action`s. Re-exports --- `pub use crate::controllers::defaultcontroller::DefaultController;``pub use crate::controllers::errors::ControllerError;`Modules --- defaultcontrollerDefault `Controller` for actions.errorsErrors related to `controllers`.Traits --- ControllerController that connects events and actions. Enum lillinput::events::ActionEvent === ``` pub enum ActionEvent { ThreeFingerSwipeLeft, ThreeFingerSwipeLeftUp, ThreeFingerSwipeUp, ThreeFingerSwipeRightUp, ThreeFingerSwipeRight, ThreeFingerSwipeRightDown, ThreeFingerSwipeDown, ThreeFingerSwipeLeftDown, FourFingerSwipeLeft, FourFingerSwipeLeftUp, FourFingerSwipeUp, FourFingerSwipeRightUp, FourFingerSwipeRight, FourFingerSwipeRightDown, FourFingerSwipeDown, FourFingerSwipeLeftDown, } ``` High-level application events that can trigger an action. Variants --- ### `ThreeFingerSwipeLeft` Three-finger swipe to left. ### `ThreeFingerSwipeLeftUp` Three-finger swipe to left-up. ### `ThreeFingerSwipeUp` Three-finger swipe to up. ### `ThreeFingerSwipeRightUp` Three-finger swipe to right-up. ### `ThreeFingerSwipeRight` Three-finger swipe to right. ### `ThreeFingerSwipeRightDown` Three-finger swipe to right-down. ### `ThreeFingerSwipeDown` Three-finger swipe to down. ### `ThreeFingerSwipeLeftDown` Three-finger swipe to left-down. ### `FourFingerSwipeLeft` Four-finger swipe to left. ### `FourFingerSwipeLeftUp` Four-finger swipe to left-up. ### `FourFingerSwipeUp` Four-finger swipe to up. ### `FourFingerSwipeRightUp` Four-finger swipe to right-up. ### `FourFingerSwipeRight` Four-finger swipe to right. ### `FourFingerSwipeRightDown` Four-finger swipe to right-down. ### `FourFingerSwipeDown` Four-finger swipe to down. ### `FourFingerSwipeLeftDown` Four-finger swipe to left-down. Trait Implementations --- ### impl Clone for ActionEvent #### fn clone(&self) -> ActionEvent Returns a copy of the value. Read more1.0.0 · source#### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFormats the value using the given formatter. #### type Err = ParseError The associated error which can be returned from parsing.#### fn from_str(s: &str) -> Result<ActionEvent, <Self as FromStr>::ErrParses a string `s` to return a value of this type. #### fn hash<__H: Hasher>(&self, state: &mut__H) Feeds this value into the given `Hasher`. Read more1.3.0 · source#### fn hash_slice<H>(data: &[Self], state: &mutH)where    H: Hasher,    Self: Sized, Feeds a slice of this type into the given `Hasher`. #### type Iterator = ActionEventIter #### fn iter() -> ActionEventIterNotable traits for ActionEventIter`impl Iterator for ActionEventIter type Item = ActionEvent;` ### impl PartialEq<ActionEvent> for ActionEvent #### fn eq(&self, other: &ActionEvent) -> bool This method tests for `self` and `other` values to be equal, and is used by `==`. Read more1.0.0 · source#### fn ne(&self, other: &Rhs) -> bool This method tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. #### type Error = ParseError The type returned in the event of a conversion error.#### fn try_from(s: &str) -> Result<ActionEvent, <Self as TryFrom<&str>>::ErrorPerforms the conversion.### impl VariantNames for ActionEvent #### const VARIANTS: &'static [&'static str] = _ Names of the variants of this enum### impl Copy for ActionEvent ### impl Eq for ActionEvent ### impl StructuralEq for ActionEvent ### impl StructuralPartialEq for ActionEvent Auto Trait Implementations --- ### impl RefUnwindSafe for ActionEvent ### impl Send for ActionEvent ### impl Sync for ActionEvent ### impl Unpin for ActionEvent ### impl UnwindSafe for ActionEvent Blanket Implementations --- ### impl<T> Any for Twhere    T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. const: unstable · source#### fn borrow(&self) -> &T Immutably borrows from an owned value. const: unstable · source#### fn borrow_mut(&mut self) -> &mutT Mutably borrows from an owned value. const: unstable · source#### fn from(t: T) -> T Returns the argument unchanged. ### impl<T, U> Into<U> for Twhere    U: From<T>, const: unstable · source#### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From<T> for U` chooses to do. ### impl<T> ToOwned for Twhere    T: Clone, #### type Owned = T The resulting type after obtaining ownership.#### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Uses borrowed data to replace owned data, usually by cloning. #### default fn to_string(&self) -> String Converts the given value to a `String`. #### type Error = Infallible The type returned in the event of a conversion error.const: unstable · source#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::ErrorPerforms the conversion.### impl<T, U> TryInto<U> for Twhere    U: TryFrom<T>, #### type Error = <U as TryFrom<T>>::Error The type returned in the event of a conversion error.const: unstable · source#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::ErrorPerforms the conversion. Trait lillinput::actions::Action === ``` pub trait Action: Debug { fn execute_command(&mut self) -> Result<(), ActionError>; fn fmt_command(&self, f: &mut Formatter<'_>) -> Result; } ``` Handler for a single action triggered by an event. Required Methods --- #### fn execute_command(&mut self) -> Result<(), ActionErrorExecute the command for this action. ##### Errors Returns `Err` if the execution of the command was not successful. #### fn fmt_command(&self, f: &mut Formatter<'_>) -> Result Format the contents of the action as a `String`. ##### Errors Returns `Err` if the action cannot be formatted as a `String`. Trait Implementations --- ### impl Display for dyn Action #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. Read moreImplementors --- ### impl Action for CommandAction ### impl Action for I3Action Module lillinput::events === Components for capturing and handling events. Re-exports --- `pub use crate::events::defaultprocessor::DefaultProcessor;``pub use crate::events::errors::LibinputError;``pub use crate::events::errors::ProcessorError;`Modules --- defaultprocessorDefault `Processor` for events.errorsErrors related to `events`.libinputComponents for interacting with `libinput`.Structs --- ActionEventIterAn iterator over the variants of SelfEnums --- ActionEventHigh-level application events that can trigger an action.AxisAxis of a swipe action.FingerCountPossible choices for finger count.Traits --- ProcessorEvents processor, converting `libinput` events into `ActionEvent`s.