repo_name stringlengths 2 55 | dataset stringclasses 1 value | owner stringlengths 3 31 | lang stringclasses 10 values | func_name stringlengths 1 104 | code stringlengths 20 96.7k | docstring stringlengths 1 4.92k | url stringlengths 94 241 | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
fe | github_2023 | n9e | typescript | Positions.confirmHeight | confirmHeight(_i: number, heightGetter: THeightGetter) {
let i = _i;
if (i > this.lastI) {
this.calcHeights(i, heightGetter);
return;
}
const h = heightGetter(i);
if (h === this.heights[i]) {
return;
}
const chg = h - this.heights[i];
this.heights[i] = h;
// shift the y positions by `chg` for all known y positions
while (++i <= this.lastI) {
this.ys[i] += chg;
}
if (this.ys[this.lastI + 1] != null) {
this.ys[this.lastI + 1] += chg;
}
} | /**
* Get the latest height for index `_i`. If it's in new terretory
* (_i > lastI), find the heights (and y-values) leading up to it. If it's in
* known territory (_i <= lastI) and the height is different than what is
* known, recalculate subsequent y values, but don't confirm the heights of
* those items, just update based on the difference.
*/ | https://github.com/n9e/fe/blob/a99fb8353f00bdf6e79faabb1950e3b1f94fa700/src/pages/traceCpt/Detail/Timeline/ListView/Positions.tsx#L112-L131 | a99fb8353f00bdf6e79faabb1950e3b1f94fa700 |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | TransformedTargetRegressor.transformer_ | get transformer_(): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This TransformedTargetRegressor instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'TransformedTargetRegressor must call init() before accessing transformer_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_TransformedTargetRegressor_transformer_ = bridgeTransformedTargetRegressor[${this.id}].transformer_`
// convert the result from python to node.js
return this
._py`attr_TransformedTargetRegressor_transformer_.tolist() if hasattr(attr_TransformedTargetRegressor_transformer_, 'tolist') else attr_TransformedTargetRegressor_transformer_`
})()
} | /**
Transformer used in [`fit`](https://scikit-learn.org/stable/modules/generated/#sklearn.compose.TransformedTargetRegressor.fit "sklearn.compose.TransformedTargetRegressor.fit") and [`predict`](https://scikit-learn.org/stable/modules/generated/#sklearn.compose.TransformedTargetRegressor.predict "sklearn.compose.TransformedTargetRegressor.predict").
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/compose/TransformedTargetRegressor.ts#L366-L388 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | EllipticEnvelope.mahalanobis | async mahalanobis(opts: {
/**
The observations, the Mahalanobis distances of the which we compute. Observations are assumed to be drawn from the same distribution than the data used in fit.
*/
X?: ArrayLike[]
}): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This EllipticEnvelope instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error('EllipticEnvelope must call init() before mahalanobis()')
}
// set up method params
await this._py
.ex`pms_EllipticEnvelope_mahalanobis = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None}
pms_EllipticEnvelope_mahalanobis = {k: v for k, v in pms_EllipticEnvelope_mahalanobis.items() if v is not None}`
// invoke method
await this._py
.ex`res_EllipticEnvelope_mahalanobis = bridgeEllipticEnvelope[${this.id}].mahalanobis(**pms_EllipticEnvelope_mahalanobis)`
// convert the result from python to node.js
return this
._py`res_EllipticEnvelope_mahalanobis.tolist() if hasattr(res_EllipticEnvelope_mahalanobis, 'tolist') else res_EllipticEnvelope_mahalanobis`
} | /**
Compute the squared Mahalanobis distances of given observations.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/covariance/EllipticEnvelope.ts#L418-L447 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | GraphicalLassoCV.score | async score(opts: {
/**
Test data of which we compute the likelihood, where `n_samples` is the number of samples and `n_features` is the number of features. `X_test` is assumed to be drawn from the same distribution than the data used in fit (including centering).
*/
X_test?: ArrayLike[]
/**
Not used, present for API consistency by convention.
*/
y?: any
}): Promise<number> {
if (this._isDisposed) {
throw new Error(
'This GraphicalLassoCV instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error('GraphicalLassoCV must call init() before score()')
}
// set up method params
await this._py
.ex`pms_GraphicalLassoCV_score = {'X_test': np.array(${opts['X_test'] ?? undefined}) if ${opts['X_test'] !== undefined} else None, 'y': ${opts['y'] ?? undefined}}
pms_GraphicalLassoCV_score = {k: v for k, v in pms_GraphicalLassoCV_score.items() if v is not None}`
// invoke method
await this._py
.ex`res_GraphicalLassoCV_score = bridgeGraphicalLassoCV[${this.id}].score(**pms_GraphicalLassoCV_score)`
// convert the result from python to node.js
return this
._py`res_GraphicalLassoCV_score.tolist() if hasattr(res_GraphicalLassoCV_score, 'tolist') else res_GraphicalLassoCV_score`
} | /**
Compute the log-likelihood of `X_test` under the estimated Gaussian model.
The Gaussian model is defined by its mean and covariance matrix which are represented respectively by `self.location_` and `self.covariance_`.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/covariance/GraphicalLassoCV.ts#L381-L415 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | MinCovDet.get_precision | async get_precision(opts: {
/**
The precision matrix associated to the current covariance object.
*/
precision_?: ArrayLike[]
}): Promise<any> {
if (this._isDisposed) {
throw new Error('This MinCovDet instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('MinCovDet must call init() before get_precision()')
}
// set up method params
await this._py
.ex`pms_MinCovDet_get_precision = {'precision_': np.array(${opts['precision_'] ?? undefined}) if ${opts['precision_'] !== undefined} else None}
pms_MinCovDet_get_precision = {k: v for k, v in pms_MinCovDet_get_precision.items() if v is not None}`
// invoke method
await this._py
.ex`res_MinCovDet_get_precision = bridgeMinCovDet[${this.id}].get_precision(**pms_MinCovDet_get_precision)`
// convert the result from python to node.js
return this
._py`res_MinCovDet_get_precision.tolist() if hasattr(res_MinCovDet_get_precision, 'tolist') else res_MinCovDet_get_precision`
} | /**
Getter for the precision matrix.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/covariance/MinCovDet.ts#L282-L309 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | ShrunkCovariance.location_ | get location_(): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This ShrunkCovariance instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'ShrunkCovariance must call init() before accessing location_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_ShrunkCovariance_location_ = bridgeShrunkCovariance[${this.id}].location_`
// convert the result from python to node.js
return this
._py`attr_ShrunkCovariance_location_.tolist() if hasattr(attr_ShrunkCovariance_location_, 'tolist') else attr_ShrunkCovariance_location_`
})()
} | /**
Estimated location, i.e. the estimated mean.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/covariance/ShrunkCovariance.ts#L430-L452 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | IncrementalPCA.n_components_ | get n_components_(): Promise<number> {
if (this._isDisposed) {
throw new Error('This IncrementalPCA instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error(
'IncrementalPCA must call init() before accessing n_components_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_IncrementalPCA_n_components_ = bridgeIncrementalPCA[${this.id}].n_components_`
// convert the result from python to node.js
return this
._py`attr_IncrementalPCA_n_components_.tolist() if hasattr(attr_IncrementalPCA_n_components_, 'tolist') else attr_IncrementalPCA_n_components_`
})()
} | /**
The estimated number of components. Relevant when `n_components=None`.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/decomposition/IncrementalPCA.ts#L711-L731 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | DummyClassifier.classes_ | get classes_(): Promise<NDArray> {
if (this._isDisposed) {
throw new Error('This DummyClassifier instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error(
'DummyClassifier must call init() before accessing classes_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_DummyClassifier_classes_ = bridgeDummyClassifier[${this.id}].classes_`
// convert the result from python to node.js
return this
._py`attr_DummyClassifier_classes_.tolist() if hasattr(attr_DummyClassifier_classes_, 'tolist') else attr_DummyClassifier_classes_`
})()
} | /**
Unique class labels observed in `y`. For multi-output classification problems, this attribute is a list of arrays as each output has an independent set of possible classes.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/dummy/DummyClassifier.ts#L418-L438 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | SequentialFeatureSelector.transform | async transform(opts: {
/**
The input samples.
*/
X?: any
}): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This SequentialFeatureSelector instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'SequentialFeatureSelector must call init() before transform()'
)
}
// set up method params
await this._py
.ex`pms_SequentialFeatureSelector_transform = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None}
pms_SequentialFeatureSelector_transform = {k: v for k, v in pms_SequentialFeatureSelector_transform.items() if v is not None}`
// invoke method
await this._py
.ex`res_SequentialFeatureSelector_transform = bridgeSequentialFeatureSelector[${this.id}].transform(**pms_SequentialFeatureSelector_transform)`
// convert the result from python to node.js
return this
._py`res_SequentialFeatureSelector_transform.tolist() if hasattr(res_SequentialFeatureSelector_transform, 'tolist') else res_SequentialFeatureSelector_transform`
} | /**
Reduce X to the selected features.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/feature_selection/SequentialFeatureSelector.ts#L417-L448 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | PartialDependenceDisplay.bars_ | get bars_(): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This PartialDependenceDisplay instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'PartialDependenceDisplay must call init() before accessing bars_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_PartialDependenceDisplay_bars_ = bridgePartialDependenceDisplay[${this.id}].bars_`
// convert the result from python to node.js
return this
._py`attr_PartialDependenceDisplay_bars_.tolist() if hasattr(attr_PartialDependenceDisplay_bars_, 'tolist') else attr_PartialDependenceDisplay_bars_`
})()
} | /**
If `ax` is an axes or `undefined`, `bars_\[i, j\]` is the partial dependence bar plot on the i-th row and j-th column (for a categorical feature). If `ax` is a list of axes, `bars_\[i\]` is the partial dependence bar plot corresponding to the i-th item in `ax`. Elements that are `undefined` correspond to a nonexisting axes or an axes that does not include a bar plot.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/inspection/PartialDependenceDisplay.ts#L571-L593 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | Nystroem.fit_transform | async fit_transform(opts: {
/**
Input samples.
*/
X?: ArrayLike[]
/**
Target values (`undefined` for unsupervised transformations).
*/
y?: ArrayLike
/**
Additional fit parameters.
*/
fit_params?: any
}): Promise<any[]> {
if (this._isDisposed) {
throw new Error('This Nystroem instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('Nystroem must call init() before fit_transform()')
}
// set up method params
await this._py
.ex`pms_Nystroem_fit_transform = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None, 'y': np.array(${opts['y'] ?? undefined}) if ${opts['y'] !== undefined} else None, 'fit_params': ${opts['fit_params'] ?? undefined}}
pms_Nystroem_fit_transform = {k: v for k, v in pms_Nystroem_fit_transform.items() if v is not None}`
// invoke method
await this._py
.ex`res_Nystroem_fit_transform = bridgeNystroem[${this.id}].fit_transform(**pms_Nystroem_fit_transform)`
// convert the result from python to node.js
return this
._py`res_Nystroem_fit_transform.tolist() if hasattr(res_Nystroem_fit_transform, 'tolist') else res_Nystroem_fit_transform`
} | /**
Fit to data, then transform it.
Fits transformer to `X` and `y` with optional parameters `fit_params` and returns a transformed version of `X`.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/kernel_approximation/Nystroem.ts#L185-L222 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | ElasticNet.set_score_request | async set_score_request(opts: {
/**
Metadata routing for `sample_weight` parameter in `score`.
*/
sample_weight?: string | boolean
}): Promise<any> {
if (this._isDisposed) {
throw new Error('This ElasticNet instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('ElasticNet must call init() before set_score_request()')
}
// set up method params
await this._py
.ex`pms_ElasticNet_set_score_request = {'sample_weight': ${opts['sample_weight'] ?? undefined}}
pms_ElasticNet_set_score_request = {k: v for k, v in pms_ElasticNet_set_score_request.items() if v is not None}`
// invoke method
await this._py
.ex`res_ElasticNet_set_score_request = bridgeElasticNet[${this.id}].set_score_request(**pms_ElasticNet_set_score_request)`
// convert the result from python to node.js
return this
._py`res_ElasticNet_set_score_request.tolist() if hasattr(res_ElasticNet_set_score_request, 'tolist') else res_ElasticNet_set_score_request`
} | /**
Request metadata passed to the `score` method.
Note that this method is only relevant if `enable_metadata_routing=True` (see [`sklearn.set_config`](https://scikit-learn.org/stable/modules/generated/sklearn.set_config.html#sklearn.set_config "sklearn.set_config")). Please see [User Guide](https://scikit-learn.org/stable/modules/generated/../../metadata_routing.html#metadata-routing) on how the routing mechanism works.
The options for each parameter are:
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/linear_model/ElasticNet.ts#L503-L530 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | LarsCV.alpha_ | get alpha_(): Promise<number> {
if (this._isDisposed) {
throw new Error('This LarsCV instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('LarsCV must call init() before accessing alpha_')
}
return (async () => {
// invoke accessor
await this._py.ex`attr_LarsCV_alpha_ = bridgeLarsCV[${this.id}].alpha_`
// convert the result from python to node.js
return this
._py`attr_LarsCV_alpha_.tolist() if hasattr(attr_LarsCV_alpha_, 'tolist') else attr_LarsCV_alpha_`
})()
} | /**
the estimated regularization parameter alpha
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/linear_model/LarsCV.ts#L468-L485 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | Lasso.fit | async fit(opts: {
/**
Data.
Note that large sparse matrices and arrays requiring `int64` indices are not accepted.
*/
X?: SparseMatrix
/**
Target. Will be cast to X’s dtype if necessary.
*/
y?: NDArray
/**
Sample weights. Internally, the `sample_weight` vector will be rescaled to sum to `n_samples`.
*/
sample_weight?: number | ArrayLike
/**
Allow to bypass several input checking. Don’t use this parameter unless you know what you do.
@defaultValue `true`
*/
check_input?: boolean
}): Promise<any> {
if (this._isDisposed) {
throw new Error('This Lasso instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('Lasso must call init() before fit()')
}
// set up method params
await this._py
.ex`pms_Lasso_fit = {'X': ${opts['X'] ?? undefined}, 'y': np.array(${opts['y'] ?? undefined}) if ${opts['y'] !== undefined} else None, 'sample_weight': np.array(${opts['sample_weight'] ?? undefined}) if ${opts['sample_weight'] !== undefined} else None, 'check_input': ${opts['check_input'] ?? undefined}}
pms_Lasso_fit = {k: v for k, v in pms_Lasso_fit.items() if v is not None}`
// invoke method
await this._py
.ex`res_Lasso_fit = bridgeLasso[${this.id}].fit(**pms_Lasso_fit)`
// convert the result from python to node.js
return this
._py`res_Lasso_fit.tolist() if hasattr(res_Lasso_fit, 'tolist') else res_Lasso_fit`
} | /**
Fit model with coordinate descent.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/linear_model/Lasso.ts#L166-L212 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | LinearRegression.get_metadata_routing | async get_metadata_routing(opts: {
/**
A [`MetadataRequest`](https://scikit-learn.org/stable/modules/generated/sklearn.utils.metadata_routing.MetadataRequest.html#sklearn.utils.metadata_routing.MetadataRequest "sklearn.utils.metadata_routing.MetadataRequest") encapsulating routing information.
*/
routing?: any
}): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This LinearRegression instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'LinearRegression must call init() before get_metadata_routing()'
)
}
// set up method params
await this._py
.ex`pms_LinearRegression_get_metadata_routing = {'routing': ${opts['routing'] ?? undefined}}
pms_LinearRegression_get_metadata_routing = {k: v for k, v in pms_LinearRegression_get_metadata_routing.items() if v is not None}`
// invoke method
await this._py
.ex`res_LinearRegression_get_metadata_routing = bridgeLinearRegression[${this.id}].get_metadata_routing(**pms_LinearRegression_get_metadata_routing)`
// convert the result from python to node.js
return this
._py`res_LinearRegression_get_metadata_routing.tolist() if hasattr(res_LinearRegression_get_metadata_routing, 'tolist') else res_LinearRegression_get_metadata_routing`
} | /**
Get metadata routing of this object.
Please check [User Guide](https://scikit-learn.org/stable/modules/generated/../../metadata_routing.html#metadata-routing) on how the routing mechanism works.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/linear_model/LinearRegression.ts#L171-L202 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | LogisticRegression.predict | async predict(opts: {
/**
The data matrix for which we want to get the predictions.
*/
X?: ArrayLike | SparseMatrix[]
}): Promise<NDArray> {
if (this._isDisposed) {
throw new Error(
'This LogisticRegression instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error('LogisticRegression must call init() before predict()')
}
// set up method params
await this._py
.ex`pms_LogisticRegression_predict = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None}
pms_LogisticRegression_predict = {k: v for k, v in pms_LogisticRegression_predict.items() if v is not None}`
// invoke method
await this._py
.ex`res_LogisticRegression_predict = bridgeLogisticRegression[${this.id}].predict(**pms_LogisticRegression_predict)`
// convert the result from python to node.js
return this
._py`res_LogisticRegression_predict.tolist() if hasattr(res_LogisticRegression_predict, 'tolist') else res_LogisticRegression_predict`
} | /**
Predict class labels for samples in X.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/linear_model/LogisticRegression.ts#L366-L395 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | LocallyLinearEmbedding.set_output | async set_output(opts: {
/**
Configure output of `transform` and `fit_transform`.
*/
transform?: 'default' | 'pandas' | 'polars'
}): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This LocallyLinearEmbedding instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'LocallyLinearEmbedding must call init() before set_output()'
)
}
// set up method params
await this._py
.ex`pms_LocallyLinearEmbedding_set_output = {'transform': ${opts['transform'] ?? undefined}}
pms_LocallyLinearEmbedding_set_output = {k: v for k, v in pms_LocallyLinearEmbedding_set_output.items() if v is not None}`
// invoke method
await this._py
.ex`res_LocallyLinearEmbedding_set_output = bridgeLocallyLinearEmbedding[${this.id}].set_output(**pms_LocallyLinearEmbedding_set_output)`
// convert the result from python to node.js
return this
._py`res_LocallyLinearEmbedding_set_output.tolist() if hasattr(res_LocallyLinearEmbedding_set_output, 'tolist') else res_LocallyLinearEmbedding_set_output`
} | /**
Set output container.
See [Introducing the set_output API](https://scikit-learn.org/stable/modules/generated/../../auto_examples/miscellaneous/plot_set_output.html#sphx-glr-auto-examples-miscellaneous-plot-set-output-py) for an example on how to use the API.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/manifold/LocallyLinearEmbedding.ts#L339-L370 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | TSNE.learning_rate_ | get learning_rate_(): Promise<number> {
if (this._isDisposed) {
throw new Error('This TSNE instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('TSNE must call init() before accessing learning_rate_')
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_TSNE_learning_rate_ = bridgeTSNE[${this.id}].learning_rate_`
// convert the result from python to node.js
return this
._py`attr_TSNE_learning_rate_.tolist() if hasattr(attr_TSNE_learning_rate_, 'tolist') else attr_TSNE_learning_rate_`
})()
} | /**
Effective learning rate.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/manifold/TSNE.ts#L473-L491 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | ConfusionMatrixDisplay.dispose | async dispose() {
if (this._isDisposed) {
return
}
if (!this._isInitialized) {
return
}
await this._py.ex`del bridgeConfusionMatrixDisplay[${this.id}]`
this._isDisposed = true
} | /**
Disposes of the underlying Python resources.
Once `dispose()` is called, the instance is no longer usable.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/metrics/ConfusionMatrixDisplay.ts#L96-L108 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | LearningCurveDisplay.ax_ | get ax_(): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This LearningCurveDisplay instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'LearningCurveDisplay must call init() before accessing ax_'
)
}
return (async () => {
// invoke accessor
await this._py
.ex`attr_LearningCurveDisplay_ax_ = bridgeLearningCurveDisplay[${this.id}].ax_`
// convert the result from python to node.js
return this
._py`attr_LearningCurveDisplay_ax_.tolist() if hasattr(attr_LearningCurveDisplay_ax_, 'tolist') else attr_LearningCurveDisplay_ax_`
})()
} | /**
Axes with the learning curve.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/model_selection/LearningCurveDisplay.ts#L360-L382 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | RobustScaler.fit | async fit(opts: {
/**
The data used to compute the median and quantiles used for later scaling along the features axis.
*/
X?: ArrayLike | SparseMatrix[]
/**
Not used, present here for API consistency by convention.
*/
y?: any
}): Promise<any> {
if (this._isDisposed) {
throw new Error('This RobustScaler instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('RobustScaler must call init() before fit()')
}
// set up method params
await this._py
.ex`pms_RobustScaler_fit = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None, 'y': ${opts['y'] ?? undefined}}
pms_RobustScaler_fit = {k: v for k, v in pms_RobustScaler_fit.items() if v is not None}`
// invoke method
await this._py
.ex`res_RobustScaler_fit = bridgeRobustScaler[${this.id}].fit(**pms_RobustScaler_fit)`
// convert the result from python to node.js
return this
._py`res_RobustScaler_fit.tolist() if hasattr(res_RobustScaler_fit, 'tolist') else res_RobustScaler_fit`
} | /**
Compute the median and quantiles to be used for scaling.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/preprocessing/RobustScaler.ts#L134-L166 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | SelfTrainingClassifier.decision_function | async decision_function(opts: {
/**
Array representing the data.
*/
X?: ArrayLike | SparseMatrix[]
}): Promise<NDArray[]> {
if (this._isDisposed) {
throw new Error(
'This SelfTrainingClassifier instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'SelfTrainingClassifier must call init() before decision_function()'
)
}
// set up method params
await this._py
.ex`pms_SelfTrainingClassifier_decision_function = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None}
pms_SelfTrainingClassifier_decision_function = {k: v for k, v in pms_SelfTrainingClassifier_decision_function.items() if v is not None}`
// invoke method
await this._py
.ex`res_SelfTrainingClassifier_decision_function = bridgeSelfTrainingClassifier[${this.id}].decision_function(**pms_SelfTrainingClassifier_decision_function)`
// convert the result from python to node.js
return this
._py`res_SelfTrainingClassifier_decision_function.tolist() if hasattr(res_SelfTrainingClassifier_decision_function, 'tolist') else res_SelfTrainingClassifier_decision_function`
} | /**
Call decision function of the `base_estimator`.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/semi_supervised/SelfTrainingClassifier.ts#L145-L176 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | LinearSVC.sparsify | async sparsify(opts: {}): Promise<any> {
if (this._isDisposed) {
throw new Error('This LinearSVC instance has already been disposed')
}
if (!this._isInitialized) {
throw new Error('LinearSVC must call init() before sparsify()')
}
// set up method params
await this._py.ex`pms_LinearSVC_sparsify = {}
pms_LinearSVC_sparsify = {k: v for k, v in pms_LinearSVC_sparsify.items() if v is not None}`
// invoke method
await this._py
.ex`res_LinearSVC_sparsify = bridgeLinearSVC[${this.id}].sparsify(**pms_LinearSVC_sparsify)`
// convert the result from python to node.js
return this
._py`res_LinearSVC_sparsify.tolist() if hasattr(res_LinearSVC_sparsify, 'tolist') else res_LinearSVC_sparsify`
} | /**
Convert coefficient matrix to sparse format.
Converts the `coef_` member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation.
The `intercept_` member is not converted.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/svm/LinearSVC.ts#L474-L495 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | ExtraTreeClassifier.decision_path | async decision_path(opts: {
/**
The input samples. Internally, it will be converted to `dtype=np.float32` and if a sparse matrix is provided to a sparse `csr_matrix`.
*/
X?: ArrayLike | SparseMatrix[]
/**
Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.
@defaultValue `true`
*/
check_input?: boolean
}): Promise<SparseMatrix[]> {
if (this._isDisposed) {
throw new Error(
'This ExtraTreeClassifier instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error(
'ExtraTreeClassifier must call init() before decision_path()'
)
}
// set up method params
await this._py
.ex`pms_ExtraTreeClassifier_decision_path = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None, 'check_input': ${opts['check_input'] ?? undefined}}
pms_ExtraTreeClassifier_decision_path = {k: v for k, v in pms_ExtraTreeClassifier_decision_path.items() if v is not None}`
// invoke method
await this._py
.ex`res_ExtraTreeClassifier_decision_path = bridgeExtraTreeClassifier[${this.id}].decision_path(**pms_ExtraTreeClassifier_decision_path)`
// convert the result from python to node.js
return this
._py`res_ExtraTreeClassifier_decision_path.tolist() if hasattr(res_ExtraTreeClassifier_decision_path, 'tolist') else res_ExtraTreeClassifier_decision_path`
} | /**
Return the decision path in the tree.
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/tree/ExtraTreeClassifier.ts#L285-L323 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
scikit-learn-ts | github_2023 | transitive-bullshit | typescript | ExtraTreeRegressor.fit | async fit(opts: {
/**
The training input samples. Internally, it will be converted to `dtype=np.float32` and if a sparse matrix is provided to a sparse `csc_matrix`.
*/
X?: ArrayLike | SparseMatrix[]
/**
The target values (real numbers). Use `dtype=np.float64` and `order='C'` for maximum efficiency.
*/
y?: ArrayLike
/**
Sample weights. If `undefined`, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node.
*/
sample_weight?: ArrayLike
/**
Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.
@defaultValue `true`
*/
check_input?: boolean
}): Promise<any> {
if (this._isDisposed) {
throw new Error(
'This ExtraTreeRegressor instance has already been disposed'
)
}
if (!this._isInitialized) {
throw new Error('ExtraTreeRegressor must call init() before fit()')
}
// set up method params
await this._py
.ex`pms_ExtraTreeRegressor_fit = {'X': np.array(${opts['X'] ?? undefined}) if ${opts['X'] !== undefined} else None, 'y': np.array(${opts['y'] ?? undefined}) if ${opts['y'] !== undefined} else None, 'sample_weight': np.array(${opts['sample_weight'] ?? undefined}) if ${opts['sample_weight'] !== undefined} else None, 'check_input': ${opts['check_input'] ?? undefined}}
pms_ExtraTreeRegressor_fit = {k: v for k, v in pms_ExtraTreeRegressor_fit.items() if v is not None}`
// invoke method
await this._py
.ex`res_ExtraTreeRegressor_fit = bridgeExtraTreeRegressor[${this.id}].fit(**pms_ExtraTreeRegressor_fit)`
// convert the result from python to node.js
return this
._py`res_ExtraTreeRegressor_fit.tolist() if hasattr(res_ExtraTreeRegressor_fit, 'tolist') else res_ExtraTreeRegressor_fit`
} | /**
Build a decision tree regressor from the training set (X, y).
*/ | https://github.com/transitive-bullshit/scikit-learn-ts/blob/a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc/packages/sklearn/src/generated/tree/ExtraTreeRegressor.ts#L315-L361 | a7d01fc04d3f5fe124098d13dc6efc5f2e256bbc |
web5-js | github_2023 | decentralized-identity | typescript | DidResolverCacheMemory.set | public async set(didUri: string, resolutionResult: DidResolutionResult): Promise<void> {
this.cache.set(didUri, resolutionResult);
} | /**
* Stores a DID resolution result in the cache with a TTL.
*
* @param didUri - The DID string used as the key for storing the result.
* @param resolutionResult - The DID resolution result to be cached.
* @returns A promise that resolves when the operation is complete.
*/ | https://github.com/decentralized-identity/web5-js/blob/707bc224243aceeefd62f0e8592735315d580ec2/packages/agent/src/prototyping/dids/resolver-cache-memory.ts#L51-L53 | 707bc224243aceeefd62f0e8592735315d580ec2 |
web5-js | github_2023 | decentralized-identity | typescript | Record.contextId | get contextId() { return this.deleted ? this._initialWrite.contextId : this._contextId; } | /** Record's context ID. If the record is deleted, the context Id comes from the initial write */ | https://github.com/decentralized-identity/web5-js/blob/707bc224243aceeefd62f0e8592735315d580ec2/packages/api/src/record.ts#L281-L281 | 707bc224243aceeefd62f0e8592735315d580ec2 |
web5-js | github_2023 | decentralized-identity | typescript | Stream.consumeToArrayBuffer | public static async consumeToArrayBuffer({ readableStream }: { readableStream: ReadableStream}): Promise<ArrayBuffer> {
const iterableStream = Stream.asAsyncIterator(readableStream);
const arrayBuffer = await Convert.asyncIterable(iterableStream).toArrayBufferAsync();
return arrayBuffer;
} | /**
* Consumes a `ReadableStream` and returns its contents as an `ArrayBuffer`.
*
* This method reads all data from a `ReadableStream`, collects it, and converts it into an
* `ArrayBuffer`.
*
* @example
* ```ts
* const readableStream = new ReadableStream({ ... });
* const arrayBuffer = await Stream.consumeToArrayBuffer({ readableStream });
* ```
*
* @param readableStream - The Web `ReadableStream` whose data will be consumed.
* @returns A Promise that resolves to an `ArrayBuffer` containing all the data from the stream.
*/ | https://github.com/decentralized-identity/web5-js/blob/707bc224243aceeefd62f0e8592735315d580ec2/packages/common/src/stream.ts#L55-L60 | 707bc224243aceeefd62f0e8592735315d580ec2 |
web5-js | github_2023 | decentralized-identity | typescript | Secp256k1.decompressPublicKey | public static async decompressPublicKey({ publicKeyBytes }: {
publicKeyBytes: Uint8Array;
}): Promise<Uint8Array> {
// Decode Weierstrass points from the public key byte array.
const point = secp256k1.ProjectivePoint.fromHex(publicKeyBytes);
// Return the uncompressed form of the public key.
return point.toRawBytes(false);
} | /**
* Converts a public key to its uncompressed form.
*
* @remarks
* This method takes a compressed public key represented as a byte array and decompresses it.
* Public key decompression involves reconstructing the y-coordinate from the x-coordinate,
* resulting in the full public key. This method is used when the uncompressed key format is
* required for certain cryptographic operations or interoperability.
*
* @example
* ```ts
* const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes
* const decompressedPublicKey = await Secp256k1.decompressPublicKey({
* publicKeyBytes: compressedPublicKeyBytes
* });
* ```
*
* @param params - The parameters for the public key decompression.
* @param params.publicKeyBytes - The public key as a Uint8Array.
*
* @returns A Promise that resolves to the uncompressed public key as a Uint8Array.
*/ | https://github.com/decentralized-identity/web5-js/blob/707bc224243aceeefd62f0e8592735315d580ec2/packages/crypto/src/primitives/secp256k1.ts#L385-L393 | 707bc224243aceeefd62f0e8592735315d580ec2 |
web5-js | github_2023 | decentralized-identity | typescript | Sha256.digest | public static async digest({ data }: {
data: Uint8Array;
}): Promise<Uint8Array> {
const hash = sha256(data);
return hash;
} | /**
* Generates a SHA-256 hash digest for the given data.
*
* @remarks
* This method produces a hash digest using the SHA-256 algorithm. The resultant digest
* is deterministic, meaning the same data will always produce the same hash, but
* is computationally infeasible to regenerate the original data from the hash.
*
* @example
* ```ts
* const data = new Uint8Array([...]);
* const hash = await Sha256.digest({ data });
* ```
*
* @param params - The parameters for the hashing operation.
* @param params.data - The data to hash, represented as a Uint8Array.
*
* @returns A Promise that resolves to the SHA-256 hash digest of the provided data as a Uint8Array.
*/ | https://github.com/decentralized-identity/web5-js/blob/707bc224243aceeefd62f0e8592735315d580ec2/packages/crypto/src/primitives/sha256.ts#L40-L46 | 707bc224243aceeefd62f0e8592735315d580ec2 |
web5-js | github_2023 | decentralized-identity | typescript | DidWeb.resolve | public static async resolve(didUri: string, _options?: DidResolutionOptions): Promise<DidResolutionResult> {
// Attempt to parse the DID URI.
const parsedDid = Did.parse(didUri);
// If parsing failed, the DID is invalid.
if (!parsedDid) {
return {
...EMPTY_DID_RESOLUTION_RESULT,
didResolutionMetadata: { error: 'invalidDid' }
};
}
// If the DID method is not "web", return an error.
if (parsedDid.method !== DidWeb.methodName) {
return {
...EMPTY_DID_RESOLUTION_RESULT,
didResolutionMetadata: { error: 'methodNotSupported' }
};
}
// Replace ":" with "/" in the identifier and prepend "https://" to obtain the fully qualified
// domain name and optional path.
let baseUrl = `https://${parsedDid.id.replace(/:/g, '/')}`;
// If the domain contains a percent encoded port value, decode the colon.
baseUrl = decodeURIComponent(baseUrl);
// Append the expected location of the DID document depending on whether a path was specified.
const didDocumentUrl = parsedDid.id.includes(':') ?
`${baseUrl}/did.json` :
`${baseUrl}/.well-known/did.json`;
try {
// Perform an HTTP GET request to obtain the DID document.
const response = await fetch(didDocumentUrl);
// If the response status code is not 200, return an error.
if (!response.ok) throw new Error('HTTP error status code returned');
// Parse the DID document.
const didDocument = await response.json() as DidDocument;
return {
...EMPTY_DID_RESOLUTION_RESULT,
didDocument,
};
} catch (error: any) {
// If the DID document could not be retrieved, return an error.
return {
...EMPTY_DID_RESOLUTION_RESULT,
didResolutionMetadata: { error: 'notFound' }
};
}
} | /**
* Resolves a `did:web` identifier to a DID Document.
*
* @param didUri - The DID to be resolved.
* @param _options - Optional parameters for resolving the DID. Unused by this DID method.
* @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of the resolution.
*/ | https://github.com/decentralized-identity/web5-js/blob/707bc224243aceeefd62f0e8592735315d580ec2/packages/dids/src/methods/did-web.ts#L41-L95 | 707bc224243aceeefd62f0e8592735315d580ec2 |
aibpm.ui.plus | github_2023 | leooneone | typescript | ViewApi.softDelete | softDelete = (
query?: {
/** @format int64 */
id?: number
},
params: RequestParams = {}
) =>
this.request<AxiosResponse, any>({
path: `/api/admin/view/soft-delete`,
method: 'DELETE',
query: query,
secure: true,
...params,
}) | /**
* No description
*
* @tags view
* @name SoftDelete
* @summary 删除
* @request DELETE:/api/admin/view/soft-delete
* @secure
*/ | https://github.com/leooneone/aibpm.ui.plus/blob/f6d6d8c37e19c734cbf0c7c98d80c39f5a56900a/src/api/admin/View.ts#L158-L171 | f6d6d8c37e19c734cbf0c7c98d80c39f5a56900a |
aibpm.ui.plus | github_2023 | leooneone | typescript | svgFind | function svgFind(e: any) {
const arr = []
const dirents = readdirSync(e, { withFileTypes: true })
for (const dirent of dirents) {
if (dirent.isDirectory()) arr.push(...svgFind(e + dirent.name + '/'))
else {
const svg = readFileSync(e + dirent.name)
.toString()
.replace(clearReturn, '')
.replace(svgTitle, ($1: any, $2: any) => {
let width = 0,
height = 0,
content = $2.replace(clearHeightWidth, (s1: any, s2: any, s3: any) => {
if (s2 === 'width') width = s3
else if (s2 === 'height') height = s3
return ''
})
if (!hasViewBox.test($2)) content += `viewBox="0 0 ${width} ${height}"`
return `<symbol id="${idPerfix}-${dirent.name.replace('.svg', '')}" ${content}>`
}).replace('</svg>', '</symbol>')
arr.push(svg)
}
}
return arr
} | // 查找svg文件 | https://github.com/leooneone/aibpm.ui.plus/blob/f6d6d8c37e19c734cbf0c7c98d80c39f5a56900a/src/icons/index.ts#L10-L34 | f6d6d8c37e19c734cbf0c7c98d80c39f5a56900a |
sensitive-data-protection-on-aws | github_2023 | awslabs | typescript | getTablesByDatabase | const getTablesByDatabase = async (params: any) => {
const result = await apiRequest(
'get',
'catalog/get-tables-by-database',
params
);
return result;
}; | // 获取catalog弹窗 Folders/Tables列表 | https://github.com/awslabs/sensitive-data-protection-on-aws/blob/03c90b9e2d464d014fa2b3d3c955af136f0aa3fd/source/portal/src/apis/data-catalog/api.ts#L4-L11 | 03c90b9e2d464d014fa2b3d3c955af136f0aa3fd |
TeyvatGuide | github_2023 | BTMuli | typescript | getPostCollect | async function getPostCollect(
postId: string,
): Promise<TGApp.Sqlite.UserCollection.UFMap[] | boolean> {
const db = await TGSqlite.getDB();
const sql = "SELECT * FROM UFMap WHERE postId = ?";
const res: TGApp.Sqlite.UserCollection.UFMap[] = await db.select(sql, [postId]);
if (res.length > 0) return res;
const unclassifiedSql = "SELECT * FROM UFPost WHERE id = ?";
const unclassifiedRes: TGApp.Sqlite.UserCollection.UFPost[] = await db.select(unclassifiedSql, [
postId,
]);
return unclassifiedRes.length > 0;
} | /**
* @description 获取单个帖子的收藏信息
* @since Beta v0.4.5
* @param {string} postId 文章 id
* @return {Promise<TGApp.Sqlite.UserCollection.UFMap[]|boolean>} 返回收藏信息
*/ | https://github.com/BTMuli/TeyvatGuide/blob/25f95d9f90b37f8b7f1d77ae7494c740b1e820b7/src/plugins/Sqlite/modules/userCollect.ts#L15-L27 | 25f95d9f90b37f8b7f1d77ae7494c740b1e820b7 |
NextChat | github_2023 | ChatGPTNextWeb | typescript | animateResponseText | function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
if (responseText?.length === 0) {
options.onError?.(new Error("empty response from server"));
}
return;
}
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
const fetchText = remainText.slice(0, fetchCount);
responseText += fetchText;
remainText = remainText.slice(fetchCount);
options.onUpdate?.(responseText, fetchText);
}
requestAnimationFrame(animateResponseText);
} | // animate response to make it looks smooth | https://github.com/ChatGPTNextWeb/NextChat/blob/a029b4330b89f8f2d1258e46fa68ba87c998a745/app/client/platforms/alibaba.ts#L149-L168 | a029b4330b89f8f2d1258e46fa68ba87c998a745 |
NextChat | github_2023 | ChatGPTNextWeb | typescript | updateMcpConfig | async function updateMcpConfig(config: McpConfigData): Promise<void> {
try {
// 确保目录存在
await fs.mkdir(path.dirname(CONFIG_PATH), { recursive: true });
await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2));
} catch (error) {
throw error;
}
} | // 更新 MCP 配置文件 | https://github.com/ChatGPTNextWeb/NextChat/blob/a029b4330b89f8f2d1258e46fa68ba87c998a745/app/mcp/actions.ts#L366-L374 | a029b4330b89f8f2d1258e46fa68ba87c998a745 |
chatGPT | github_2023 | zuoFeng59556 | typescript | createSign | function createSign(apiUrl: string, timestamp: number, nonceStr: string) {
const method = 'GET'
const signStr = `${method}\n${apiUrl}\n${timestamp}\n${nonceStr}\n\n`
const cert = WechatPaySpec.privateKey
const sign = crypto.createSign('RSA-SHA256')
sign.update(signStr)
return sign.sign(cert, 'base64')
} | /**
* Sign a wechat query request
*/ | https://github.com/zuoFeng59556/chatGPT/blob/8db2578bd0471aa3c424a290b6490d6f042bc90a/cloudFunction/wechat-order-query.ts#L66-L73 | 8db2578bd0471aa3c424a290b6490d6f042bc90a |
orillusion | github_2023 | Orillusion | typescript | Graphic3D.drawCameraFrustum | public drawCameraFrustum(camera: Camera3D, color: Color = Color.COLOR_WHITE) {
if (camera.type == CameraType.perspective) {
let y = Math.tan(camera.fov / 2 * DEGREES_TO_RADIANS);
let x = y * camera.aspect;
let worldMatrix = camera.transform._worldMatrix;
let f0 = worldMatrix.transformVector(new Vector3(-x, -y, 1));
let f1 = worldMatrix.transformVector(new Vector3(-x, y, 1));
let f2 = worldMatrix.transformVector(new Vector3(x, -y, 1));
let f3 = worldMatrix.transformVector(new Vector3(x, y, 1));
let far = camera.far;
let near = camera.near;
let pos = camera.transform.worldPosition;
let farLB = new Vector3().copyFrom(f0).multiplyScalar(far).add(pos);
let farLT = new Vector3().copyFrom(f1).multiplyScalar(far).add(pos);
let farRB = new Vector3().copyFrom(f2).multiplyScalar(far).add(pos);
let farRT = new Vector3().copyFrom(f3).multiplyScalar(far).add(pos);
let nearLB = new Vector3().copyFrom(f0).multiplyScalar(near).add(pos);
let nearLT = new Vector3().copyFrom(f1).multiplyScalar(near).add(pos);
let nearRB = new Vector3().copyFrom(f2).multiplyScalar(near).add(pos);
let nearRT = new Vector3().copyFrom(f3).multiplyScalar(near).add(pos);
let custom = this.createCustomShape(`CameraFrustum_${camera.object3D.instanceID}`);
custom.buildLines([nearLT, farLT], color);
custom.buildLines([nearLB, farLB], color);
custom.buildLines([nearRT, farRT], color);
custom.buildLines([nearRB, farRB], color);
custom.buildLines([farLT, farRT, farRB, farLB, farLT], color);
custom.buildLines([nearLT, nearRT, nearRB, nearLB, nearLT], color);
} else if (camera.type == CameraType.ortho) {
camera.viewPort;
camera.viewPort.height;
let worldMatrix = camera.transform.worldMatrix;
let farLT = worldMatrix.transformVector(new Vector3(camera.viewPort.width * -0.5, camera.viewPort.height * 0.5, camera.far));
let farLB = worldMatrix.transformVector(new Vector3(camera.viewPort.width * -0.5, camera.viewPort.height * -0.5, camera.far));
let farRT = worldMatrix.transformVector(new Vector3(camera.viewPort.width * 0.5, camera.viewPort.height * 0.5, camera.far));
let farRB = worldMatrix.transformVector(new Vector3(camera.viewPort.width * 0.5, camera.viewPort.height * -0.5, camera.far));
let nearLT = worldMatrix.transformVector(new Vector3(camera.viewPort.width * -0.5, camera.viewPort.height * 0.5, camera.near));
let nearLB = worldMatrix.transformVector(new Vector3(camera.viewPort.width * -0.5, camera.viewPort.height * -0.5, camera.near));
let nearRT = worldMatrix.transformVector(new Vector3(camera.viewPort.width * 0.5, camera.viewPort.height * 0.5, camera.near));
let nearRB = worldMatrix.transformVector(new Vector3(camera.viewPort.width * 0.5, camera.viewPort.height * -0.5, camera.near));
let custom = this.createCustomShape(`CameraFrustum_${camera.object3D.instanceID}`);
custom.buildLines([nearLT, farLT], color);
custom.buildLines([nearLB, farLB], color);
custom.buildLines([nearRT, farRT], color);
custom.buildLines([nearRB, farRB], color);
custom.buildLines([farLT, farRT, farRB, farLB, farLT], color);
custom.buildLines([nearLT, nearRT, nearRB, nearLB, nearLT], color);
}
} | /**
* Draw the camera cone
* @param camera The camera to display the cone
* @param color The color of the camera cone
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/packages/graphic/renderer/Graphic3DRender.ts#L358-L412 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Generic6DofSpringConstraint.enableSpring | public enableSpring(index: number, onOff: boolean): void {
if (this._constraint) {
this._constraint.enableSpring(index, onOff);
} else {
this._springParams.push({ index, onOff });
}
} | /**
* 启用或禁用弹簧功能。
* @param index 弹簧的索引
* @param onOff 是否启用
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/packages/physics/constraint/Generic6DofSpringConstraint.ts#L70-L76 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | PhysicsDragger.enable | public set enable(value: boolean) {
if (this._enable === value) return;
this._enable = value;
value ? this.registerEvents() : this.unregisterEvents();
} | /**
* 是否启用拖拽功能
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/packages/physics/utils/PhysicsDragger.ts#L29-L33 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | CameraControllerBase.target | public set target(val: Object3D | null) {
if (this._target == val) return;
this._target = val;
} | /**
*
* Set the control object3D
* @param val Object3D
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/components/controller/CameraControllerBase.ts#L41-L44 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | LightBase.lightColor | public get lightColor(): Color {
return this.lightData.lightColor;
} | /**
* Get light source color
* @return Color
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/components/lights/LightBase.ts#L183-L185 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | SpotLight.radius | public get radius(): number {
return this.lightData.radius as number;
} | /**
*
* Get the radius of the light source
* @return number
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/components/lights/SpotLight.ts#L71-L73 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Object3D.notifyChange | public notifyChange(): void {
this.transform.notifyChange();
} | /**
* Notify transformation attribute updates
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/core/entities/Object3D.ts#L328-L330 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Object3D.rotationY | public set rotationY(value: number) {
this.transform.rotationY = value;
} | /**
*
* Set the y rotation relative to the local coordinates of the parent container.
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/core/entities/Object3D.ts#L460-L462 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | RenderShaderPass.topology | public get topology(): GPUPrimitiveTopology {
return this.shaderState.topology;
} | /**
* Primitive topology
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/gfx/graphics/webGpu/shader/RenderShaderPass.ts#L214-L216 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | RendererJob.pause | public pause() {
this.pauseRender = true;
} | /**
* pause render task
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/gfx/renderJob/jobs/RendererJob.ts#L159-L161 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | UnLitTexArrayMaterial.baseColor | public get baseColor() {
return this.shader.getUniformColor("baseColor");
} | /**
* get base color (tint color)
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/materials/UnLitTexArrayMaterial.ts#L43-L45 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Matrix3.prepend | public prepend(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix3 {
let tx1 = this.tx;
if (a != 1 || b != 0 || c != 0 || d != 1) {
let a1 = this.a;
let c1 = this.c;
this.a = a1 * a + this.b * c;
this.b = a1 * b + this.b * d;
this.c = c1 * a + this.d * c;
this.d = c1 * b + this.d * d;
}
this.tx = tx1 * a + this.ty * c + tx;
this.ty = tx1 * b + this.ty * d + ty;
return this;
} | /**
* get a front matrix by multiplication
* @param a Multiply by a
* @param b Multiply by b
* @param c Multiply by c
* @param d Multiply by d
* @param tx Multiply by tx
* @param ty Multiply by ty
* @returns prematrix
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/math/Matrix3.ts#L287-L300 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Matrix4.decompose | public decompose(orientationStyle: string = 'eulerAngles', target?: Vector3[]): Vector3[] {
let q: Quaternion = Quaternion.CALCULATION_QUATERNION;
let vec: Vector3[] = target ? target : Matrix4._prs;
this.copyRawDataTo(Matrix4.decomposeRawData);
let mr = Matrix4.decomposeRawData;
let pos: Vector3 = vec[0];
pos.x = mr[12];
pos.y = mr[13];
pos.z = mr[14];
mr[12] = 0;
mr[13] = 0;
mr[14] = 0;
let scale: Vector3 = vec[2];
scale.x = Math.sqrt(mr[0] * mr[0] + mr[1] * mr[1] + mr[2] * mr[2]);
scale.y = Math.sqrt(mr[4] * mr[4] + mr[5] * mr[5] + mr[6] * mr[6]);
scale.z = Math.sqrt(mr[8] * mr[8] + mr[9] * mr[9] + mr[10] * mr[10]);
if (mr[0] * (mr[5] * mr[10] - mr[6] * mr[9])
- mr[1] * (mr[4] * mr[10] - mr[6] * mr[8])
+ mr[2] * (mr[4] * mr[9] - mr[5] * mr[8]) < 0) {
scale.z = -scale.z;
}
mr[0] /= scale.x;
mr[1] /= scale.x;
mr[2] /= scale.x;
mr[4] /= scale.y;
mr[5] /= scale.y;
mr[6] /= scale.y;
mr[8] /= scale.z;
mr[9] /= scale.z;
mr[10] /= scale.z;
let rot = vec[1];
let tr: number;
switch (orientationStyle) {
case Orientation3D.AXIS_ANGLE:
rot.w = Math.acos((mr[0] + mr[5] + mr[10] - 1) / 2);
let len: number = Math.sqrt((mr[6] - mr[9]) * (mr[6] - mr[9]) + (mr[8] - mr[2]) * (mr[8] - mr[2]) + (mr[1] - mr[4]) * (mr[1] - mr[4]));
rot.x = (mr[6] - mr[9]) / len;
rot.y = (mr[8] - mr[2]) / len;
rot.z = (mr[1] - mr[4]) / len;
break;
case Orientation3D.QUATERNION:
tr = mr[0] + mr[5] + mr[10];
if (tr > 0) {
rot.w = Math.sqrt(1 + tr) / 2;
rot.x = (mr[6] - mr[9]) / (4 * rot.w);
rot.y = (mr[8] - mr[2]) / (4 * rot.w);
rot.z = (mr[1] - mr[4]) / (4 * rot.w);
} else if (mr[0] > mr[5] && mr[0] > mr[10]) {
rot.x = Math.sqrt(1 + mr[0] - mr[5] - mr[10]) / 2;
rot.w = (mr[6] - mr[9]) / (4 * rot.x);
rot.y = (mr[1] + mr[4]) / (4 * rot.x);
rot.z = (mr[8] + mr[2]) / (4 * rot.x);
} else if (mr[5] > mr[10]) {
rot.y = Math.sqrt(1 + mr[5] - mr[0] - mr[10]) / 2;
rot.x = (mr[1] + mr[4]) / (4 * rot.y);
rot.w = (mr[8] - mr[2]) / (4 * rot.y);
rot.z = (mr[6] + mr[9]) / (4 * rot.y);
} else {
rot.z = Math.sqrt(1 + mr[10] - mr[0] - mr[5]) / 2;
rot.x = (mr[8] + mr[2]) / (4 * rot.z);
rot.y = (mr[6] + mr[9]) / (4 * rot.z);
rot.w = (mr[1] - mr[4]) / (4 * rot.z);
}
break;
case Orientation3D.EULER_ANGLES:
tr = mr[0] + mr[5] + mr[10];
if (tr > 0) {
q.w = Math.sqrt(1 + tr) / 2;
q.x = (mr[6] - mr[9]) / (4 * q.w);
q.y = (mr[8] - mr[2]) / (4 * q.w);
q.z = (mr[1] - mr[4]) / (4 * q.w);
} else if (mr[0] > mr[5] && mr[0] > mr[10]) {
q.x = Math.sqrt(1 + mr[0] - mr[5] - mr[10]) / 2;
q.w = (mr[6] - mr[9]) / (4 * q.x);
q.y = (mr[1] + mr[4]) / (4 * q.x);
q.z = (mr[8] + mr[2]) / (4 * q.x);
} else if (mr[5] > mr[10]) {
rot.y = Math.sqrt(1 + mr[5] - mr[0] - mr[10]) / 2;
q.x = (mr[1] + mr[4]) / (4 * q.y);
q.w = (mr[8] - mr[2]) / (4 * q.y);
q.z = (mr[6] + mr[9]) / (4 * q.y);
} else {
q.z = Math.sqrt(1 + mr[10] - mr[0] - mr[5]) / 2;
q.x = (mr[8] + mr[2]) / (4 * q.z);
q.y = (mr[6] + mr[9]) / (4 * q.z);
q.w = (mr[1] - mr[4]) / (4 * q.z);
}
q.getEulerAngles(rot);
break;
}
vec[0] = pos;
vec[1] = rot;
vec[2] = scale;
return vec;
} | /**
* Decompose the current matrix
* @param orientationStyle The default decomposition type is Orientation3D.EULER_ANGLES
* @see Orientation3D.AXIS_ANGLE
* @see Orientation3D.EULER_ANGLES
* @see Orientation3D.QUATERNION
* @returns Vector3[3] pos rot scale
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/math/Matrix4.ts#L1437-L1553 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Matrix4.makeBasis | public makeBasis(xAxis: Vector3, yAxis: Vector3, zAxis: Vector3) {
this.setElements(
xAxis.x, yAxis.x, zAxis.x, 0,
xAxis.y, yAxis.y, zAxis.y, 0,
xAxis.z, yAxis.z, zAxis.z, 0,
0, 0, 0, 1
);
return this;
} | /**
* Generate the matrix according to the three axes
* @param xAxis
* @param yAxis
* @param zAxis
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/math/Matrix4.ts#L2066-L2074 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Quaternion.identity | public static identity() {
return Quaternion._zero;
} | /**
* Identity quaternion
* @returns
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/math/Quaternion.ts#L52-L54 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | Ray.sqrDistToPoint | public sqrDistToPoint(P: Vector3): number {
let v = this._dir;
let w = P.subtract(this.origin);
let c1 = dot(w, v);
let c2 = dot(v, v);
let b = c1 / c2;
let Pb = this.getPoint(b);
return sqrMagnitude(P.subtract(Pb));
} | /**
* Calculate the distance from a point
* @param P Specify Point
* @returns result
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/math/Ray.ts#L179-L189 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
orillusion | github_2023 | Orillusion | typescript | TextureCubeFaceData.generateMipmap | private generateMipmap(texture: Texture) {
let mipmap: number = 1;
while (mipmap < this._texture.mipmapCount) {
this.generateMipmapAtLevel(mipmap, texture);
mipmap++;
}
} | /**
* @private generateMipmap
* @param texture texture reference
*/ | https://github.com/Orillusion/orillusion/blob/8887427f0a2e426a1cc75ef022c8649bcdd785b0/src/textures/TextureCubeFaceData.ts#L68-L74 | 8887427f0a2e426a1cc75ef022c8649bcdd785b0 |
ndk | github_2023 | nostr-dev-kit | typescript | NDKCacheAdapterDexie.byTags | private byTags(filter: NDKFilter, subscription: NDKSubscription): boolean {
const tagFilters = Object.entries(filter)
.filter(([filter]) => filter.startsWith("#") && filter.length === 2)
.map(([filter, values]) => [filter[1], values]);
if (tagFilters.length === 0) return false;
// Go through all the tags (#e, #p, etc)
for (const [tag, values] of tagFilters) {
// Go throgh each value in the filter
for (const value of values as string[]) {
const tagValue = tag + value;
// Get all events with this tag
const eventIds = this.eventTags.getSet(tagValue);
if (!eventIds) continue;
// Go through each event that came back
eventIds.forEach((id) => {
const event = this.events.get(id);
if (!event) return;
if (!filter.kinds || filter.kinds.includes(event.kind!)) {
foundEvent(subscription, event, event.relay, filter);
}
});
}
}
return true;
} | /**
* Searches by tags and optionally filters by tags
*/ | https://github.com/nostr-dev-kit/ndk/blob/fdbe6e5934c431318f1f210fa9f797f40b53326c/ndk-cache-dexie/src/index.ts#L497-L526 | fdbe6e5934c431318f1f210fa9f797f40b53326c |
ndk | github_2023 | nostr-dev-kit | typescript | NDKCashuToken.cleanProof | private cleanProof(proof: Proof): Proof {
return {
id: proof.id,
amount: proof.amount,
C: proof.C,
secret: proof.secret
};
} | /**
* Returns a minimal proof object with only essential properties
*/ | https://github.com/nostr-dev-kit/ndk/blob/fdbe6e5934c431318f1f210fa9f797f40b53326c/ndk-wallet/src/wallets/cashu/token.ts#L88-L95 | fdbe6e5934c431318f1f210fa9f797f40b53326c |
chunyu-cms | github_2023 | yinMrsir | typescript | LevelService.findAll | findAll() {
return this.levelRepository.find();
} | /* 不分页查询所有家长引导 */ | https://github.com/yinMrsir/chunyu-cms/blob/7177fcbb75b941cbf7556e391c05b37e992c1476/Nest-server/src/modules/basic/level/level.service.ts#L40-L42 | 7177fcbb75b941cbf7556e391c05b37e992c1476 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | SolidityParser.ruleNames | public get ruleNames(): string[] { return SolidityParser.ruleNames; } | // @Override | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/prettier-plugin-solidity/node_modules/@solidity-parser/parser/src/antlr/SolidityParser.ts#L349-L349 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | SolidityParser.customErrorDefinition | public customErrorDefinition(): CustomErrorDefinitionContext {
let _localctx: CustomErrorDefinitionContext = new CustomErrorDefinitionContext(this._ctx, this.state);
this.enterRule(_localctx, 30, SolidityParser.RULE_customErrorDefinition);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 364;
this.match(SolidityParser.T__24);
this.state = 365;
this.identifier();
this.state = 366;
this.parameterList();
this.state = 367;
this.match(SolidityParser.T__1);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
} | // @RuleVersion(0) | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/prettier-plugin-solidity/node_modules/@solidity-parser/parser/src/antlr/SolidityParser.ts#L1288-L1317 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | SolidityParser.assemblyFunctionDefinition | public assemblyFunctionDefinition(): AssemblyFunctionDefinitionContext {
let _localctx: AssemblyFunctionDefinitionContext = new AssemblyFunctionDefinitionContext(this._ctx, this.state);
this.enterRule(_localctx, 176, SolidityParser.RULE_assemblyFunctionDefinition);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 1061;
this.match(SolidityParser.T__29);
this.state = 1062;
this.identifier();
this.state = 1063;
this.match(SolidityParser.T__22);
this.state = 1065;
this._errHandler.sync(this);
_la = this._input.LA(1);
if (_la === SolidityParser.T__13 || _la === SolidityParser.T__24 || ((((_la - 36)) & ~0x1F) === 0 && ((1 << (_la - 36)) & ((1 << (SolidityParser.T__35 - 36)) | (1 << (SolidityParser.T__41 - 36)) | (1 << (SolidityParser.T__53 - 36)))) !== 0) || ((((_la - 95)) & ~0x1F) === 0 && ((1 << (_la - 95)) & ((1 << (SolidityParser.T__94 - 95)) | (1 << (SolidityParser.LeaveKeyword - 95)) | (1 << (SolidityParser.PayableKeyword - 95)) | (1 << (SolidityParser.ConstructorKeyword - 95)))) !== 0) || _la === SolidityParser.ReceiveKeyword || _la === SolidityParser.Identifier) {
{
this.state = 1064;
this.assemblyIdentifierList();
}
}
this.state = 1067;
this.match(SolidityParser.T__23);
this.state = 1069;
this._errHandler.sync(this);
_la = this._input.LA(1);
if (_la === SolidityParser.T__93) {
{
this.state = 1068;
this.assemblyFunctionReturns();
}
}
this.state = 1071;
this.assemblyBlock();
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
} | // @RuleVersion(0) | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/prettier-plugin-solidity/node_modules/@solidity-parser/parser/src/antlr/SolidityParser.ts#L5546-L5598 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | IdentifierListContext.accept | public accept<Result>(visitor: SolidityVisitor<Result>): Result {
if (visitor.visitIdentifierList) {
return visitor.visitIdentifierList(this);
} else {
return visitor.visitChildren(this);
}
} | // @Override | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/prettier-plugin-solidity/node_modules/@solidity-parser/parser/src/antlr/SolidityParser.ts#L9586-L9592 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | InlineAssemblyStatementContext.enterRule | public enterRule(listener: SolidityListener): void {
if (listener.enterInlineAssemblyStatement) {
listener.enterInlineAssemblyStatement(this);
}
} | // @Override | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/@solidity-parser/parser/src/antlr/SolidityParser.ts#L9110-L9114 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | AssemblyCaseContext.accept | public accept<Result>(visitor: SolidityVisitor<Result>): Result {
if (visitor.visitAssemblyCase) {
return visitor.visitAssemblyCase(this);
} else {
return visitor.visitChildren(this);
}
} | // @Override | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/@solidity-parser/parser/src/antlr/SolidityParser.ts#L10330-L10336 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | Address.isZero | isZero(): boolean {
return this.equals(Address.zero())
} | /**
* Is address zero.
*/ | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/ethereumjs-util/src/address.ts#L88-L90 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | HardhatModule._hardhatSetPrevRandaoParams | private _hardhatSetPrevRandaoParams(params: any[]): [Buffer] {
// using rpcHash because it's also 32 bytes long
return validateParams(params, rpcHash);
} | // hardhat_setPrevRandao | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/hardhat/src/internal/hardhat-network/provider/modules/hardhat.ts#L411-L414 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | B2B_G | function B2B_G(
v: Uint32Array,
mw: Uint32Array,
a: number,
b: number,
c: number,
d: number,
ix: number,
iy: number
) {
const x0 = mw[ix]
const x1 = mw[ix + 1]
const y0 = mw[iy]
const y1 = mw[iy + 1]
ADD64AA(v, a, b) // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s
ADD64AC(v, a, x0, x1) // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits
// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits
let xor0 = v[d] ^ v[a]
let xor1 = v[d + 1] ^ v[a + 1]
v[d] = xor1
v[d + 1] = xor0
ADD64AA(v, c, d)
// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits
xor0 = v[b] ^ v[c]
xor1 = v[b + 1] ^ v[c + 1]
v[b] = (xor0 >>> 24) ^ (xor1 << 8)
v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8)
ADD64AA(v, a, b)
ADD64AC(v, a, y0, y1)
// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits
xor0 = v[d] ^ v[a]
xor1 = v[d + 1] ^ v[a + 1]
v[d] = (xor0 >>> 16) ^ (xor1 << 16)
v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16)
ADD64AA(v, c, d)
// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits
xor0 = v[b] ^ v[c]
xor1 = v[b + 1] ^ v[c + 1]
v[b] = (xor1 >>> 31) ^ (xor0 << 1)
v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1)
} | // G Mixing function | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/@nomicfoundation/ethereumjs-evm/src/precompiles/09-blake2f.ts#L48-L96 | 8179e08cac72072bd260796633fec41fdfd5b441 |
FreshCryptoLib | github_2023 | rdubois-crypto | typescript | safeSlice | function safeSlice(input: Uint8Array, start: number, end: number) {
if (end > input.length) {
throw new Error('invalid RLP (safeSlice): end slice of Uint8Array out-of-bounds')
}
return input.slice(start, end)
} | /**
* Slices a Uint8Array, throws if the slice goes out-of-bounds of the Uint8Array.
* E.g. `safeSlice(hexToBytes('aa'), 1, 2)` will throw.
* @param input
* @param start
* @param end
*/ | https://github.com/rdubois-crypto/FreshCryptoLib/blob/8179e08cac72072bd260796633fec41fdfd5b441/solidity/tests/hardhat/node_modules/@nomicfoundation/ethereumjs-tx/node_modules/@nomicfoundation/ethereumjs-rlp/src/index.ts#L40-L45 | 8179e08cac72072bd260796633fec41fdfd5b441 |
MallChatWeb | github_2023 | Evansy | typescript | updateMarkCount | const updateMarkCount = (markList: MarkItemType[]) => {
markList.forEach((mark: MarkItemType) => {
const { msgId, markType, markCount } = mark
const msgItem = currentMessageMap.value?.get(msgId)
if (msgItem) {
if (markType === MarkEnum.LIKE) {
msgItem.message.messageMark.likeCount = markCount
} else if (markType === MarkEnum.DISLIKE) {
msgItem.message.messageMark.dislikeCount = markCount
}
}
})
} | // 更新点赞、举报数 | https://github.com/Evansy/MallChatWeb/blob/aab69ea2f97aa0b94a3fcbff06995c16c2a8bf5c/src/stores/chat.ts#L375-L388 | aab69ea2f97aa0b94a3fcbff06995c16c2a8bf5c |
chatgpt-plus | github_2023 | zhpd | typescript | ChatgptService.getBill | async getBill(): Promise<OutputOptions> {
// throw new Error('Method not implemented.');
return output({ code: 0, data: null });
} | /**
* get account bill token
*/ | https://github.com/zhpd/chatgpt-plus/blob/6b076be24ec297e18daac0740d5a9ab82f6e60ed/service/src/modules/chatgpt/chatgpt.service.ts#L147-L150 | 6b076be24ec297e18daac0740d5a9ab82f6e60ed |
billd-live-server | github_2023 | galaxy-s10 | typescript | csrf | const csrf = async () => {
/**
* 1,验证referer
* 2,验证origin
*/
}; | // import { ParameterizedContext } from 'koa'; | https://github.com/galaxy-s10/billd-live-server/blob/5676de99286a75a3e817fed1a6434932b8bbf7d4/src/middleware/csrf.middleware.ts#L6-L11 | 5676de99286a75a3e817fed1a6434932b8bbf7d4 |
lilac | github_2023 | databricks | typescript | ConceptsService.getConceptModels | public static getConceptModels(
namespace: string,
conceptName: string,
): CancelablePromise<Array<ConceptModelInfo>> {
return __request(OpenAPI, {
method: 'GET',
url: '/api/v1/concepts/{namespace}/{concept_name}/model',
path: {
'namespace': namespace,
'concept_name': conceptName,
},
errors: {
422: `Validation Error`,
},
});
} | /**
* Get Concept Models
* Get a concept model from a database.
* @param namespace
* @param conceptName
* @returns ConceptModelInfo Successful Response
* @throws ApiError
*/ | https://github.com/databricks/lilac/blob/b7d92b775fe5dc813283ab3ef9e62007f728c3b9/web/lib/fastapi_client/services/ConceptsService.ts#L204-L219 | b7d92b775fe5dc813283ab3ef9e62007f728c3b9 |
likec4 | github_2023 | likec4 | typescript | LikeC4ViewModel.node | public node(node: M['NodeOrId']): NodeModel<M, V> {
const nodeId = getId(node)
return nonNullable(this.#nodes.get(nodeId), `Node ${nodeId} not found in view ${this.$view.id}`)
} | /**
* Get node by id.
* @throws Error if node is not found.
*/ | https://github.com/likec4/likec4/blob/f420421cb95b7fb5d40f6556e138394b2a7a5ad1/packages/core/src/model/view/LikeC4ViewModel.ts#L130-L133 | f420421cb95b7fb5d40f6556e138394b2a7a5ad1 |
likec4 | github_2023 | likec4 | typescript | printEdge | const printEdge = (edge: ComputedEdge): CompositeGeneratorNode => {
return new CompositeGeneratorNode().append(
names.get(edge.source),
' -.',
edge.label ? ' "' + edge.label.replaceAll('\n', '\\n') + '" .-' : '-',
'> ',
names.get(edge.target)
)
} | // return `${names.get(edge.source)} -> ${names.get(edge.target)}${edge.label ? ': ' + edge.label : ''}` | https://github.com/likec4/likec4/blob/f420421cb95b7fb5d40f6556e138394b2a7a5ad1/packages/generators/src/mmd/generate-mmd.ts#L66-L74 | f420421cb95b7fb5d40f6556e138394b2a7a5ad1 |
likec4 | github_2023 | likec4 | typescript | LikeC4ScopeProvider.uniqueDescedants | private uniqueDescedants(of: () => ast.Element | undefined): Stream<AstNodeDescription> {
return new StreamImpl(
() => {
const element = of()
const fqn = element && this.fqnIndex.getFqn(element)
if (fqn) {
return this.fqnIndex.uniqueDescedants(fqn).iterator()
}
return null
},
iterator => {
if (iterator) {
return iterator.next()
}
return DONE_RESULT
},
)
} | // we need lazy resolving here | https://github.com/likec4/likec4/blob/f420421cb95b7fb5d40f6556e138394b2a7a5ad1/packages/language-server/src/references/scope-provider.ts#L42-L59 | f420421cb95b7fb5d40f6556e138394b2a7a5ad1 |
babylon-mmd | github_2023 | noname0310 | typescript | MmdWasmRuntime.camera | public get camera(): Nullable<MmdCamera> {
return this._camera;
} | /**
* MMD camera
*/ | https://github.com/noname0310/babylon-mmd/blob/b93b7f2dcf3fa3d72eecbb228d1c759b3d678357/src/Runtime/Optimized/mmdWasmRuntime.ts#L1107-L1109 | b93b7f2dcf3fa3d72eecbb228d1c759b3d678357 |
babylon-mmd | github_2023 | noname0310 | typescript | MmdWasmRuntimeModelAnimation.Create | public static Create(animation: MmdWasmAnimation, model: MmdWasmModel, onDispose: () => void, retargetingMap?: { [key: string]: string }, logger?: ILogger): MmdWasmRuntimeModelAnimation {
const wasmInstance = animation._poolWrapper.instance;
const animationPool = animation._poolWrapper.pool;
const skeleton = model.skeleton;
const bones = skeleton.bones;
const boneIndexMap = new Map<string, number>();
if (retargetingMap === undefined) {
for (let i = 0; i < bones.length; ++i) {
boneIndexMap.set(bones[i].name, i);
}
} else {
for (let i = 0; i < bones.length; ++i) {
boneIndexMap.set(retargetingMap[bones[i].name] ?? bones[i].name, i);
}
}
const boneBindIndexMapPtr = animationPool.createBoneBindIndexMap(animation.ptr);
const boneBindIndexMap = wasmInstance.createTypedArray(Int32Array, boneBindIndexMapPtr, animation.boneTracks.length);
{
const boneTracks = animation.boneTracks;
const boneBindIndexMapArray = boneBindIndexMap.array;
for (let i = 0; i < boneTracks.length; ++i) {
const boneTrack = boneTracks[i];
const boneIndex = boneIndexMap.get(boneTrack.name);
if (boneIndex === undefined) {
logger?.warn(`Binding failed: bone ${boneTrack.name} not found`);
boneBindIndexMapArray[i] = -1;
} else {
boneBindIndexMapArray[i] = boneIndex;
}
}
}
const movableBoneBindIndexMapPtr = animationPool.createMovableBoneBindIndexMap(animation.ptr);
const movableBoneBindIndexMap = wasmInstance.createTypedArray(Int32Array, movableBoneBindIndexMapPtr, animation.movableBoneTracks.length);
{
const movableBoneBindIndexMapArray = movableBoneBindIndexMap.array;
const movableBoneTracks = animation.movableBoneTracks;
for (let i = 0; i < movableBoneTracks.length; ++i) {
const movableBoneTrack = movableBoneTracks[i];
const boneIndex = boneIndexMap.get(movableBoneTrack.name);
if (boneIndex === undefined) {
logger?.warn(`Binding failed: bone ${movableBoneTrack.name} not found`);
movableBoneBindIndexMapArray[i] = -1;
} else {
movableBoneBindIndexMapArray[i] = boneIndex;
}
}
}
const morphBindIndexMap: Nullable<MorphIndices>[] = new Array(animation.morphTracks.length);
const morphController = model.morph;
const morphTracks = animation.morphTracks;
for (let i = 0; i < morphTracks.length; ++i) {
const morphTrack = morphTracks[i];
const mappedName = retargetingMap?.[morphTrack.name] ?? morphTrack.name;
const morphIndices = morphController.getMorphIndices(mappedName);
if (morphIndices === undefined) {
logger?.warn(`Binding failed: morph ${mappedName} not found`);
morphBindIndexMap[i] = null;
} else {
morphBindIndexMap[i] = morphIndices;
}
}
const morphLengthBufferPtr = animationPool.allocateLengthsBuffer(morphTracks.length);
const morphLengthBuffer = wasmInstance.createTypedArray(Uint32Array, morphLengthBufferPtr, morphTracks.length);
{
const morphLengthBufferArray = morphLengthBuffer.array;
const wasmMorphIndexMap = morphController.wasmMorphIndexMap;
for (let i = 0; i < morphTracks.length; ++i) {
let indicesCount = 0;
const morphIndices = morphBindIndexMap[i];
if (morphIndices !== null) {
for (let j = 0; j < morphIndices.length; ++j) {
const remappedIndex = wasmMorphIndexMap[morphIndices[j]];
if (remappedIndex !== undefined && remappedIndex !== -1) indicesCount += 1;
}
}
morphLengthBufferArray[i] = indicesCount;
}
}
const morphBindIndexMapPtr = animationPool.createMorphBindIndexMap(animation.ptr, morphLengthBufferPtr);
{
const wasmMorphIndexMap = morphController.wasmMorphIndexMap;
for (let i = 0; i < morphTracks.length; ++i) {
const nthMorphIndicesPtr = animationPool.getNthMorphBindIndexMap(morphBindIndexMapPtr, i);
const nthMorphIndices = wasmInstance.createTypedArray(Int32Array, nthMorphIndicesPtr, morphLengthBuffer.array[i]).array;
let indicesCount = 0;
const morphIndices = morphBindIndexMap[i];
if (morphIndices !== null) {
for (let j = 0; j < morphIndices.length; ++j) {
const remappedIndex = wasmMorphIndexMap[morphIndices[j]];
if (remappedIndex !== undefined && remappedIndex !== -1) {
nthMorphIndices[indicesCount] = remappedIndex;
indicesCount += 1;
}
}
}
}
}
animationPool.deallocateLengthsBuffer(morphLengthBufferPtr, morphTracks.length);
const ikSolverBindIndexMapPtr = animationPool.createIkSolverBindIndexMap(animation.ptr);
const ikSolverBindIndexMap = wasmInstance.createTypedArray(Int32Array, ikSolverBindIndexMapPtr, animation.propertyTrack.ikBoneNames.length);
{
const ikSolverBindIndexMapArray = ikSolverBindIndexMap.array;
const runtimeBones = model.runtimeBones;
const propertyTrackIkBoneNames = animation.propertyTrack.ikBoneNames;
for (let i = 0; i < propertyTrackIkBoneNames.length; ++i) {
const ikBoneName = propertyTrackIkBoneNames[i];
const ikBoneIndex = boneIndexMap.get(ikBoneName);
if (ikBoneIndex === undefined) {
logger?.warn(`Binding failed: IK bone ${ikBoneName} not found`);
ikSolverBindIndexMapArray[i] = -1;
} else {
const ikSolverIndex = runtimeBones[ikBoneIndex].ikSolverIndex;
if (ikSolverIndex === -1) {
logger?.warn(`Binding failed: IK solver for bone ${ikBoneName} not found`);
ikSolverBindIndexMapArray[i] = -1;
} else {
ikSolverBindIndexMapArray[i] = ikSolverIndex;
}
}
}
}
const runtimeAnimationPtr = animationPool.createRuntimeAnimation(
animation.ptr,
boneBindIndexMapPtr,
movableBoneBindIndexMapPtr,
morphBindIndexMapPtr,
ikSolverBindIndexMapPtr
);
return new MmdWasmRuntimeModelAnimation(
runtimeAnimationPtr,
model.ptr,
animation,
boneBindIndexMap,
movableBoneBindIndexMap,
morphController,
morphBindIndexMap,
model.mesh.metadata.meshes,
ikSolverBindIndexMap,
model.mesh.metadata.materials,
onDispose
);
} | /**
* @internal
* Bind animation to model and prepare material for morph animation
* @param animation Animation to bind
* @param model Bind target
* @param onDispose Callback when this instance is disposed
* @param retargetingMap Animation bone name to model bone name map
* @param logger Logger
* @return MmdRuntimeModelAnimation instance
*/ | https://github.com/noname0310/babylon-mmd/blob/b93b7f2dcf3fa3d72eecbb228d1c759b3d678357/src/Runtime/Optimized/Animation/mmdWasmRuntimeModelAnimation.ts#L236-L387 | b93b7f2dcf3fa3d72eecbb228d1c759b3d678357 |
twake-drive | github_2023 | linagora | typescript | AuthService.verifyToken | verifyToken(token: string): JWTObject {
return jwt.verify(token, this.configuration.secret) as JWTObject;
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/linagora/twake-drive/blob/fdc3630d21e0a5ce28b0be5cc8191cd0d3e1923b/tdrive/backend/node/src/core/platform/services/auth/service.ts#L23-L25 | fdc3630d21e0a5ce28b0be5cc8191cd0d3e1923b |
twake-drive | github_2023 | linagora | typescript | entriesApi | function entriesApi(
items: DataTransferItemList,
cb: (files?: File[], paths?: string[]) => void,
) {
const fd: any[] = [],
files: any[] = [],
rootPromises: any[] = [];
function readEntries(entry: any, reader: any, oldEntries: any, cb: any) {
const dirReader = reader || entry.createReader();
dirReader.readEntries(function (entries: any) {
const newEntries = oldEntries ? oldEntries.concat(entries) : entries;
if (entries.length) {
setTimeout(readEntries.bind(null, entry, dirReader, newEntries, cb), 0);
} else {
cb(newEntries);
}
});
}
function readDirectory(entry: any, path: null | string, resolve: (v: any) => void) {
if (!path) path = entry.name;
readEntries(entry, 0, 0, function (entries: any[]) {
const promises: Promise<any>[] = [];
entries.forEach(function (entry: any) {
promises.push(
new Promise(function (resolve) {
if (entry.isFile) {
entry.file(function (file: File) {
const p = path + '/' + file.name;
fd.push(file);
files.push(p);
if (files.length > 1000000) {
return false;
}
resolve(true);
}, resolve.bind(null, true));
} else readDirectory(entry, path + '/' + entry.name, resolve);
}),
);
});
Promise.all(promises).then(resolve.bind(null, true));
});
}
let timeBegin = Date.now();
[].slice.call(items).forEach(function (entry: any) {
entry = entry.webkitGetAsEntry();
if (entry) {
rootPromises.push(
new Promise(function (resolve) {
if (entry.isFile) {
entry.file(function (file: File) {
fd.push(file);
files.push(file.name);
if (files.length > 1000000) {
return false;
}
resolve(true);
}, resolve.bind(null, true));
} else if (entry.isDirectory) {
const timeToRead = Date.now();
readDirectory(entry, null, resolve);
}
}),
);
}
});
if (files.length > 1000000) {
return false;
}
timeBegin = Date.now();
Promise.all(rootPromises).then(cb.bind(null, fd, files));
} | // old drag and drop API implemented in Chrome 11+ | https://github.com/linagora/twake-drive/blob/fdc3630d21e0a5ce28b0be5cc8191cd0d3e1923b/tdrive/frontend/src/app/components/uploads/file-tree-utils.ts#L80-L155 | fdc3630d21e0a5ce28b0be5cc8191cd0d3e1923b |
happyx | github_2023 | HapticX | typescript | Server.mount | public mount(path: string, other: Server) {
hpx.hpxServerMount(this.serverId, path, other.serverId);
} | /**
* Defines a WebSocket route on the server.
* @param {string} path - The route path.
* @param {(wsClient: WebSocketClient) => any} callback -
* The callback function to handle WebSocket connections.
*
* @example
* asdasdasdasdasdsa;
*
*/ | https://github.com/HapticX/happyx/blob/20072a2b0d0c33cba350be66ff9c690871184444/bindings/node/src/index.ts#L372-L374 | 20072a2b0d0c33cba350be66ff9c690871184444 |
qdrant-js | github_2023 | qdrant | typescript | QdrantClient.updateVectors | async updateVectors(
collection_name: string,
{
wait = true,
ordering,
points,
shard_key,
}: {wait?: boolean; ordering?: SchemaFor<'WriteOrdering'>} & SchemaFor<'UpdateVectors'>,
) {
const response = await this._openApiClient.points.updateVectors({
collection_name,
wait,
ordering,
points,
shard_key,
});
return maybe(response.data.result).orThrow('Update vectors returned empty');
} | /**
* Update vectors
* @param collection_name
* @param {object} args
* - wait: Await for the results to be processed.
* - If `true`, result will be returned only when all changes are applied
* - If `false`, result will be returned immediately after the confirmation of receiving.
* - Default: `true`
* - ordering: Define strategy for ordering of the points. Possible values:
* - 'weak' - write operations may be reordered, works faster, default
* - 'medium' - write operations go through dynamically selected leader,
* may be inconsistent for a short period of time in case of leader change
* - 'strong' - Write operations go through the permanent leader,
* consistent, but may be unavailable if leader is down
* - points: Points with named vectors
* - shard_key: Specify in which shards to look for the points, if not specified - look in all shards
* @returns Operation result
*/ | https://github.com/qdrant/qdrant-js/blob/1c43b2db971367ece3788c4b6c368a1604b29530/packages/js-client-rest/src/qdrant-client.ts#L555-L572 | 1c43b2db971367ece3788c4b6c368a1604b29530 |
MKFramework | github_2023 | 1226085293 | typescript | main_main_item.init | init(init_?: typeof this.init_data): void {
// 不存在多语言则删除组件
if (!mk.language_manage.label_data_tab[cc.js.getClassName(main_main)]?.[this.init_data.label_s]) {
this.nodes.label.getComponent(mk.language.label)?.destroy();
}
Object.assign(this.data, this.init_data);
} | /* ------------------------------- 生命周期 ------------------------------- */ | https://github.com/1226085293/MKFramework/blob/33ed975103f1e7c74200cb658818eea945fd678f/assets/main/module/main/item/main_main_item.ts#L24-L31 | 33ed975103f1e7c74200cb658818eea945fd678f |
MKFramework | github_2023 | 1226085293 | typescript | mk_storage.clear | clear(): void {
for (const k_s in this._cache) {
this._cache[k_s] = undefined!;
}
if (!this._init_config.name_s) {
return;
}
Object.keys(this._init_config.data).forEach((v_s) => {
const key_s = `${this._init_config.name_s}-${String(v_s)}`;
this._write_pipeline.add(() => {
cc.sys.localStorage.removeItem(key_s);
});
});
} | /** 清空当前存储器数据 */ | https://github.com/1226085293/MKFramework/blob/33ed975103f1e7c74200cb658818eea945fd678f/extensions/MKFramework/assets/mk-framework/@framework/mk_storage.ts#L136-L152 | 33ed975103f1e7c74200cb658818eea945fd678f |
MKFramework | github_2023 | 1226085293 | typescript | mk_asset.release | release(asset_: cc.Asset | cc.Asset[]): void {
const asset_as: cc.Asset[] = Array.isArray(asset_) ? asset_ : [asset_];
asset_as.forEach((v) => {
if (!v.isValid) {
return;
}
// 释放动态图集中的资源
if (cc.dynamicAtlasManager?.enabled) {
if (v instanceof cc.SpriteFrame) {
cc.dynamicAtlasManager.deleteAtlasSpriteFrame(v);
} else if (v instanceof cc.Texture2D) {
cc.dynamicAtlasManager.deleteAtlasTexture(v);
}
}
// 更新引用计数
for (let k_n = 0; k_n < v.refCount; k_n++) {
v.decRef(false);
}
// 释放资源,禁止自动释放,否则会出现释放后立即加载当前资源导致加载返回资源是已释放后的
cc.assetManager.releaseAsset(v);
// 更新资源管理表
this._asset_manage_map.delete(v.nativeUrl || v._uuid);
this._log.debug("释放资源", v.name, v.nativeUrl, v._uuid);
});
} | /**
* 释放资源
* @param asset_ 释放的资源
*/ | https://github.com/1226085293/MKFramework/blob/33ed975103f1e7c74200cb658818eea945fd678f/extensions/MKFramework/assets/mk-framework/@framework/resources/mk_asset.ts#L460-L489 | 33ed975103f1e7c74200cb658818eea945fd678f |
obsidian-auto-timelines | github_2023 | April-Gras | typescript | getTagToFindSuggestion | function getTagToFindSuggestion(
app: App,
settings: AutoTimelineSettings,
query: string
): string[] {
const unfilteredRestults = app.vault
.getMarkdownFiles()
.reduce<string[]>((accumulator, file) => {
const cachedMetadata = app.metadataCache.getFileCache(file);
if (!cachedMetadata || !cachedMetadata.frontmatter)
return accumulator;
accumulator.push(
...getTagsFromMetadataOrTagObject(
settings,
cachedMetadata.frontmatter,
cachedMetadata.tags
)
);
return accumulator;
}, []);
const allQueries = query.split(settings.markdownBlockTagsToFindSeparator);
const currentQuery = allQueries[allQueries.length - 1];
const allreadyUsedQueries = allQueries.slice(0, -1);
return filterAndSortSuggestionResults(
unfilteredRestults,
currentQuery,
allreadyUsedQueries
);
} | /**
* Given a query get all the `TagToFind` typed suggestions.
* This will go trough every cached file and retrieve all timeline metadata + tags.
*
* @param app - The obsidian app object.
* @param settings - The plugin settings.
* @param query - The query that the user just typed.
* @returns the suggestions set.
*/ | https://github.com/April-Gras/obsidian-auto-timelines/blob/efb47f419c90db6a65e865c440958ace84680aa0/src/suggester.ts#L272-L303 | efb47f419c90db6a65e865c440958ace84680aa0 |
Flowise | github_2023 | FlowiseAI | typescript | ChatflowTool._call | protected async _call(
arg: z.infer<typeof this.schema>,
_?: CallbackManagerForToolRun,
flowConfig?: { sessionId?: string; chatId?: string; input?: string }
): Promise<string> {
const inputQuestion = this.input || arg.input
const body = {
question: inputQuestion,
chatId: this.startNewSession ? uuidv4() : flowConfig?.chatId,
overrideConfig: {
sessionId: this.startNewSession ? uuidv4() : flowConfig?.sessionId,
...(this.overrideConfig ?? {}),
...(arg.overrideConfig ?? {})
}
}
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...this.headers
},
body: JSON.stringify(body)
}
let sandbox = {
$callOptions: options,
$callBody: body,
util: undefined,
Symbol: undefined,
child_process: undefined,
fs: undefined,
process: undefined
}
const code = `
const fetch = require('node-fetch');
const url = "${this.baseURL}/api/v1/prediction/${this.chatflowid}";
const body = $callBody;
const options = $callOptions;
try {
const response = await fetch(url, options);
const resp = await response.json();
return resp.text;
} catch (error) {
console.error(error);
return '';
}
`
const builtinDeps = process.env.TOOL_FUNCTION_BUILTIN_DEP
? defaultAllowBuiltInDep.concat(process.env.TOOL_FUNCTION_BUILTIN_DEP.split(','))
: defaultAllowBuiltInDep
const externalDeps = process.env.TOOL_FUNCTION_EXTERNAL_DEP ? process.env.TOOL_FUNCTION_EXTERNAL_DEP.split(',') : []
const deps = availableDependencies.concat(externalDeps)
const vmOptions = {
console: 'inherit',
sandbox,
require: {
external: { modules: deps },
builtin: builtinDeps
},
eval: false,
wasm: false,
timeout: 10000
} as any
const vm = new NodeVM(vmOptions)
const response = await vm.run(`module.exports = async function() {${code}}()`, __dirname)
return response
} | // @ts-ignore | https://github.com/FlowiseAI/Flowise/blob/c0a74782d8f1dbe118d2ed3aa40dd292d25d9119/packages/components/nodes/tools/ChatflowTool/ChatflowTool.ts#L295-L370 | c0a74782d8f1dbe118d2ed3aa40dd292d25d9119 |
Langchain-Chatchat | github_2023 | chatchat-space | typescript | currentAgentMeta | const currentAgentMeta = (s: SessionStore): MetaData => {
const isInbox = sessionSelectors.isInboxSession(s);
const defaultMeta = {
avatar: isInbox ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR,
backgroundColor: DEFAULT_BACKGROUND_COLOR,
description: isInbox
? t('inbox.desc', { ns: 'chat' })
: currentAgentSystemRole(s) || t('noDescription'),
title: isInbox ? t('inbox.title', { ns: 'chat' }) : t('defaultSession'),
};
const session = sessionSelectors.currentSession(s);
return merge(defaultMeta, session?.meta);
}; | // ========== Meta ============== // | https://github.com/chatchat-space/Langchain-Chatchat/blob/40994eb6c3c8aeb9af4d52123abfb471a3f27b9c/frontend/src/store/session/slices/agent/selectors.ts#L79-L94 | 40994eb6c3c8aeb9af4d52123abfb471a3f27b9c |
playwright-bdd | github_2023 | vitalets | typescript | TestCaseRun.fillExecutedBddStep | private fillExecutedBddStep(bddStep: BddStepData, possiblePwSteps: pw.TestStep[]) {
const pwStep = this.findPlaywrightStep(possiblePwSteps, bddStep);
if (pwStep?.error) {
this.registerErrorStep(pwStep, pwStep.error);
}
if (this.isTimeouted() && pwStep && isUnknownDuration(pwStep)) {
this.registerTimeoutedStep(pwStep);
}
if (pwStep?.parent && bddStep.isBg) {
this.bgRoots.add(pwStep.parent);
}
if (pwStep) {
this.attachmentMapper.populateStepAttachments(pwStep);
}
return { bddStep, pwStep };
} | // eslint-disable-next-line visual/complexity | https://github.com/vitalets/playwright-bdd/blob/fc78801c6c525543fb3f26d2261567da32c3e808/src/reporter/cucumber/messagesBuilder/TestCaseRun.ts#L109-L125 | fc78801c6c525543fb3f26d2261567da32c3e808 |
ComfyBox | github_2023 | space-nuko | typescript | ComfyApp.graphToPrompt | graphToPrompt(workflow: ComfyBoxWorkflow, tag: string | null = null): SerializedPrompt {
return this.promptSerializer.serialize(workflow.graph, tag)
} | /**
* Converts the current graph workflow for sending to the API
* @returns The workflow and node links
*/ | https://github.com/space-nuko/ComfyBox/blob/abd31401f0e159af84040453866d308e519ca819/src/lib/components/ComfyApp.ts#L1016-L1018 | abd31401f0e159af84040453866d308e519ca819 |
ComfyBox | github_2023 | space-nuko | typescript | insertTemplate | function insertTemplate(template: SerializedComfyBoxTemplate, graph: LGraph, templateNodeIDToNode: Record<NodeID, LGraphNode>, container: ContainerLayout, childIndex: number): IDragItem {
const idMapping: Record<DragItemID, DragItemID> = {};
const getDragItemID = (id: DragItemID): DragItemID => {
idMapping[id] ||= uuidv4();
return idMapping[id];
}
// Ensure all IDs are unique, and rewrite node IDs in widgets to point
// to newly created nodes
for (const [id, entry] of Object.entries(template.layout.allItems)) {
const newId = getDragItemID(id);
template.layout.allItems[newId] = entry;
entry.dragItem.id = newId;
if (entry.parent)
entry.parent = getDragItemID(entry.parent)
entry.children = entry.children.map(getDragItemID);
if (entry.dragItem.type === "widget") {
entry.dragItem.nodeId = templateNodeIDToNode[entry.dragItem.nodeId].id;
}
}
if (template.layout.root) {
template.layout.root = getDragItemID(template.layout.root)
// make sure the new root doesn't have a parent since that parent
// was detached from the serialized layout and won't be found in
// template.layout.allItems
template.layout.allItems[template.layout.root].parent = null;
}
const raw = deserializeRaw(template.layout, graph);
// merge the template's detached layout tree into this layout
store.update(s => {
s.allItems = { ...s.allItems, ...raw.allItems }
s.allItemsByNode = { ...s.allItemsByNode, ...raw.allItemsByNode }
return s;
})
moveItem(raw.root, container, childIndex);
return raw.root
} | /*
* NOTE: Modifies the template in-place, be sure you cloned it beforehand!
*/ | https://github.com/space-nuko/ComfyBox/blob/abd31401f0e159af84040453866d308e519ca819/src/lib/stores/layoutStates.ts#L1094-L1139 | abd31401f0e159af84040453866d308e519ca819 |
MATLAB-extension-for-vscode | github_2023 | mathworks | typescript | ExecutionCommandProvider.handleChangeDirectory | async handleChangeDirectory (uri: vscode.Uri): Promise<void> {
this._telemetryLogger.logEvent({
eventKey: 'ML_VS_CODE_ACTIONS',
data: {
action_type: 'changeDirectory',
result: ''
}
});
await this._terminalService.openTerminalOrBringToFront();
try {
await this._mvm.getReadyPromise();
} catch (e) {
return;
}
void this._mvm.feval('cd', 0, [uri.fsPath]);
} | /**
* Implements the MATLAB change directory action
* @param uri The file path that MATLAB should "cd" to
* @returns
*/ | https://github.com/mathworks/MATLAB-extension-for-vscode/blob/1cdb3395a62bff2bb8e08229ca19c4d6f5750d9c/src/commandwindow/ExecutionCommandProvider.ts#L282-L300 | 1cdb3395a62bff2bb8e08229ca19c4d6f5750d9c |
chatluna | github_2023 | ChatLunaLab | typescript | _convertAgentStepToMessages | function _convertAgentStepToMessages(
action: AgentAction | FunctionsAgentAction | ToolsAgentAction,
observation: string
) {
if (isToolsAgentAction(action) && action.toolCallId !== undefined) {
const log = action.messageLog as BaseMessage[]
if (observation.length < 1) {
observation = `The tool ${action.tool} returned no output.`
}
return log.concat(
new ToolMessage({
content: observation,
name: action.tool,
tool_call_id: action.toolCallId
})
)
} else if (
isFunctionsAgentAction(action) &&
action.messageLog !== undefined
) {
return action.messageLog?.concat(
new FunctionMessage(observation, action.tool)
)
} else {
return [new AIMessage(action.log)]
}
} | // eslint-disable-next-line @typescript-eslint/naming-convention | https://github.com/ChatLunaLab/chatluna/blob/a52137997f69d9a76e766f20c2b4daf1484e7452/packages/core/src/llm-core/agent/openai/index.ts#L43-L69 | a52137997f69d9a76e766f20c2b4daf1484e7452 |
tour-of-wgsl | github_2023 | google | typescript | NoopVizualizationBuilder.configure | async configure() {
const adapter = await navigator.gpu.requestAdapter();
if (adapter === null) {
throw new VisualizerError('Unable to request webgpu adapter');
}
this.device = await adapter.requestDevice();
if (this.device === null) {
throw new VisualizerError('Unable to get WebGPU device');
}
} | /**
* @inheritDoc VisualizationBuilder.configure
*/ | https://github.com/google/tour-of-wgsl/blob/cffb757ef2f0c4554d6fa7c061337ecf7c17190b/assets/ts/noop_visualizer.ts#L27-L37 | cffb757ef2f0c4554d6fa7c061337ecf7c17190b |
java_map_download | github_2023 | kurimuson | typescript | GeoUtil.getNorthByPointAB | public static getNorthByPointAB(point_a: Point, point_b: Point): number {
let point_c = new Point(point_a.lng, point_b.lat);
let ab = this.getDistance(point_a, point_b);
let bc = this.getDistance(point_b, point_c);
// 0
if (point_a.lng == point_b.lng && point_a.lat == point_b.lat) {
return 0;
}
// 0 <= n <= 90
if (point_a.lng <= point_b.lng && point_a.lat <= point_b.lat) {
if (bc < ab) {
let BAC = Math.asin(bc / ab);
return this.radToDeg(BAC);
} else {
return 90;
}
}
// 90 < n <= 180
if (point_a.lng <= point_b.lng && point_a.lat > point_b.lat) {
if (bc < ab) {
let BAC = Math.asin(bc / ab);
return 180 - this.radToDeg(BAC);
} else {
return 90;
}
}
// 180 < n <= 270
if (point_a.lng >= point_b.lng && point_a.lat >= point_b.lat) {
if (bc < ab) {
let BAC = Math.asin(bc / ab);
return 180 + this.radToDeg(BAC);
} else {
return 270;
}
}
// 270 < n <= 360
if (point_a.lng >= point_b.lng && point_a.lat < point_b.lat) {
if (bc < ab) {
let BAC = Math.asin(bc / ab);
return 360 - this.radToDeg(BAC);
} else {
return 270;
}
}
return 0;
} | /** 根据一点的经纬度求另一点与其相对的北向夹角 */ | https://github.com/kurimuson/java_map_download/blob/743dfa5b699efc44efa85004f73bd6fe7fca13ef/Web/src/app/map/geo-util.ts#L475-L520 | 743dfa5b699efc44efa85004f73bd6fe7fca13ef |
web-llm | github_2023 | mlc-ai | typescript | ChatUI.asyncGenerate | private async asyncGenerate() {
await this.asyncInitChat();
this.requestInProgress = true;
const prompt = this.uiChatInput.value;
if (prompt == "") {
this.requestInProgress = false;
return;
}
this.appendMessage("right", prompt);
this.uiChatInput.value = "";
this.uiChatInput.setAttribute("placeholder", "Generating...");
this.appendMessage("left", "");
this.chatHistory.push({ role: "user", content: prompt });
try {
let curMessage = "";
let usage: webllm.CompletionUsage | undefined = undefined;
const completion = await this.engine.chat.completions.create({
stream: true,
messages: this.chatHistory,
stream_options: { include_usage: true },
});
// TODO(Charlie): Processing of � requires changes
for await (const chunk of completion) {
const curDelta = chunk.choices[0]?.delta.content;
if (curDelta) {
curMessage += curDelta;
}
this.updateLastMessage("left", curMessage);
if (chunk.usage) {
usage = chunk.usage;
}
}
if (usage) {
this.uiChatInfoLabel.innerHTML =
`prompt_tokens: ${usage.prompt_tokens}, ` +
`completion_tokens: ${usage.completion_tokens}, ` +
`prefill: ${usage.extra.prefill_tokens_per_s.toFixed(4)} tokens/sec, ` +
`decoding: ${usage.extra.decode_tokens_per_s.toFixed(4)} tokens/sec`;
}
const finalMessage = await this.engine.getMessage();
this.updateLastMessage("left", finalMessage); // TODO: Remove this after � issue is fixed
this.chatHistory.push({ role: "assistant", content: finalMessage });
} catch (err) {
this.appendMessage("error", "Generate error, " + err.toString());
console.log(err.stack);
await this.unloadChat();
}
this.uiChatInput.setAttribute("placeholder", "Enter your message...");
this.requestInProgress = false;
} | /**
* Run generate
*/ | https://github.com/mlc-ai/web-llm/blob/632d34725629b480b5b2772379ef5c150b1286f0/examples/simple-chat-upload/src/simple_chat.ts#L263-L315 | 632d34725629b480b5b2772379ef5c150b1286f0 |
effect-http | github_2023 | sukovanej | typescript | resolveConstrainedBigint | const resolveConstrainedBigint = (
number: bigint,
constraint: TypeConstraint<bigint>
) => {
const min = constraint.min && constraint.min + BigInt(constraint.minExclusive ? 1 : 0)
const max = constraint.max && constraint.max - BigInt(constraint.maxExclusive ? 1 : 0)
let result: number | bigint = number
if (min && number < min) {
result = min
}
if (max && number > max) {
result = max
}
return result
} | /** @internal */ | https://github.com/sukovanej/effect-http/blob/598af7145b6b72a49adb68f86411f9f3053a114b/packages/effect-http/src/internal/example-compiler.ts#L299-L316 | 598af7145b6b72a49adb68f86411f9f3053a114b |
effect-http | github_2023 | sukovanej | typescript | createParameters | const createParameters = (
type: "query" | "header" | "path",
schema: Schema.Schema<any, any, any>,
componentSchemaCallback: ComponentSchemaCallback
): Array<OpenApiTypes.OpenAPISpecParameter> => {
return getPropertySignatures(type, schema.ast).map((ps) => {
if (typeof ps.name !== "string") {
throw new Error(`${type} parameter struct fields must be strings`)
}
const ast = (ps.type._tag === "Union" && ps.type.types.some(AST.isUndefinedKeyword)) ?
AST.Union.make(
ps.type.types.filter((ast) => !AST.isUndefinedKeyword(ast)),
ps.type.annotations
) :
ps.type
const schema = Schema.make<unknown, unknown, never>(ast)
const parameter: OpenApiTypes.OpenAPISpecParameter = {
name: ps.name,
in: type,
schema: makeSchema(schema, componentSchemaCallback)
}
if (!ps.isOptional) {
parameter["required"] = true
}
const description = AST.getDescriptionAnnotation(schema.ast)
if (Option.isSome(description)) {
parameter["description"] = description.value
}
return parameter
})
} | /** @internal */ | https://github.com/sukovanej/effect-http/blob/598af7145b6b72a49adb68f86411f9f3053a114b/packages/effect-http/src/internal/open-api.ts#L285-L321 | 598af7145b6b72a49adb68f86411f9f3053a114b |
hume-api-examples | github_2023 | HumeAI | typescript | stopAudio | function stopAudio(): void {
// stop the audio playback
currentAudio?.pause();
currentAudio = null;
// update audio playback state
isPlaying = false;
// clear the audioQueue
audioQueue.length = 0;
} | /**
* stops audio playback, clears audio playback queue, and updates audio playback state
*/ | https://github.com/HumeAI/hume-api-examples/blob/2c4be65c2bc56604cfedb0d129856a038e415f17/evi-typescript-function-calling/src/main.ts#L209-L219 | 2c4be65c2bc56604cfedb0d129856a038e415f17 |
yudao-ui-admin-vben | github_2023 | yudaocode | typescript | MD5Hashing.getInstance | public static getInstance(): MD5Hashing {
if (!MD5Hashing.instance)
MD5Hashing.instance = new MD5Hashing()
return MD5Hashing.instance
} | // 获取单例实例 | https://github.com/yudaocode/yudao-ui-admin-vben/blob/5e00382e0af48d8dc8da33de6902b1289311c28d/src/utils/cipher.ts#L85-L90 | 5e00382e0af48d8dc8da33de6902b1289311c28d |
harmonix | github_2023 | awslabs | typescript | getEnvProviderSsmParams | const getEnvProviderSsmParams = async ()
: Promise<{ [key: string]: string; }> => {
const params = (await Promise.all(
paramKeys.map(async (paramKey): Promise<{ [key: string]: string; }> => {
const val = await getPlatformAccountSSMParameterValue(paramKey, region, ctx.logger);
return {
[paramKey]: val
};
})
)).reduce((acc, paramKeyValMap) => {
const typedAcc: { [key: string]: string; } = acc;
const key = Object.keys(paramKeyValMap)[0];
return {
...typedAcc, [key]: paramKeyValMap[key]
};
}, {});
return params;
}; | // Get a key/value map of SSM parameters | https://github.com/awslabs/harmonix/blob/fd3d3e2c41f68775e69259d70f2e8e500f885234/backstage-plugins/plugins/scaffolder-backend-module-aws-apps/src/actions/get-platform-parameters/get-platform-parameters.ts#L102-L121 | fd3d3e2c41f68775e69259d70f2e8e500f885234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.