type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
TypeAliasDeclaration
|
export type DashboardTemplateIncluded =
| CellIncluded
| ViewIncluded
| LabelIncluded
| VariableIncluded
|
EmOne/influxdb
|
ui/src/types/templates.ts
|
TypeScript
|
TypeAliasDeclaration
|
export type VariableTemplateIncluded = LabelIncluded | VariableIncluded
|
EmOne/influxdb
|
ui/src/types/templates.ts
|
TypeScript
|
TypeAliasDeclaration
|
export type Template = TaskTemplate | DashboardTemplate | VariableTemplate
|
EmOne/influxdb
|
ui/src/types/templates.ts
|
TypeScript
|
FunctionDeclaration
|
export async function npmSetupMainAction() {
const nodeModulesCache: Cache = await getNodeModulesCache();
const npmModulesCache: Cache = await getNpmCache();
const cypressCache: Cache = await getCypressCache();
const nxCache: Cache = await getNxCache();
if (await restoreCacheAction(nodeModulesCache)) {
if ((await isCypressRequired()) && !(await restoreCacheAction(cypressCache))) {
await installCypress();
}
} else {
await restoreCacheAction(npmModulesCache);
await installDependencies();
await saveCacheAction(nodeModulesCache);
await saveCacheAction(npmModulesCache);
if (await isCypressRequired()) {
await saveCacheAction(cypressCache);
}
}
if (ixNxCached()) {
await restoreCacheAction(nxCache);
}
}
|
ng-easy/npm-setup
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
() => {
info('');
info('npm dependencies restored successfully');
}
|
ng-easy/npm-setup
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
(err) => {
error(err);
setFailed(err.message);
}
|
ng-easy/npm-setup
|
src/main.ts
|
TypeScript
|
ClassDeclaration
|
@Component({
selector: 'cmp-211',
template: '<strong>211</strong> ',
})
export class Cmp211Component {
add211(x: number) {
return x + 211;
}
}
|
thelgevold/remote-builder
|
angular-demo/src/airplane/team2/mod1/cmp1/cmp.ts
|
TypeScript
|
MethodDeclaration
|
add211(x: number) {
return x + 211;
}
|
thelgevold/remote-builder
|
angular-demo/src/airplane/team2/mod1/cmp1/cmp.ts
|
TypeScript
|
ArrowFunction
|
() => {
it('should render', () => {
const wrapper = mount(Header, {
global: {
plugins: [i18n, pinia],
},
})
expect(wrapper.html()).toMatchSnapshot()
})
}
|
matheusgomes062/mgodev
|
test/component.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
const wrapper = mount(Header, {
global: {
plugins: [i18n, pinia],
},
})
expect(wrapper.html()).toMatchSnapshot()
}
|
matheusgomes062/mgodev
|
test/component.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
it('should render', () => {
const wrapper = mount(Navbar, {
global: {
plugins: [i18n, pinia],
},
})
expect(wrapper.html()).toMatchSnapshot()
})
it('should change dark theme icon when clicked', async() => {
const wrapper = mount(Navbar, {
global: {
plugins: [i18n, pinia],
},
})
await wrapper.get('[data-test="nav_theme"]').trigger('click')
expect(wrapper.html()).toContain('data-test="sun"')
})
}
|
matheusgomes062/mgodev
|
test/component.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
const wrapper = mount(Navbar, {
global: {
plugins: [i18n, pinia],
},
})
expect(wrapper.html()).toMatchSnapshot()
}
|
matheusgomes062/mgodev
|
test/component.test.ts
|
TypeScript
|
ArrowFunction
|
async() => {
const wrapper = mount(Navbar, {
global: {
plugins: [i18n, pinia],
},
})
await wrapper.get('[data-test="nav_theme"]').trigger('click')
expect(wrapper.html()).toContain('data-test="sun"')
}
|
matheusgomes062/mgodev
|
test/component.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
it('should render', () => {
const wrapper = mount(About, {
global: {
plugins: [i18n],
},
})
expect(wrapper.html()).toMatchSnapshot()
})
}
|
matheusgomes062/mgodev
|
test/component.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
const wrapper = mount(About, {
global: {
plugins: [i18n],
},
})
expect(wrapper.html()).toMatchSnapshot()
}
|
matheusgomes062/mgodev
|
test/component.test.ts
|
TypeScript
|
FunctionDeclaration
|
export function updateDeltaTs(post2019values?: number[], lastKnownLeapSecond?: YMDDate): void {
if (!post2019values)
post2019values = [69.36, 69.36];
historicDeltaT = clone(baseHistoricDeltaT);
historicDeltaT.push(...post2019values);
calibration = 0;
lastTableYear = -1;
// const now = new DateTime().wallTime; // max(new DateTime(), new DateTime(Timezone.getDateAfterLastKnownLeapSecond(), 'UTC')).wallTime;
let lastDay = Date.now() / DAY_MSEC;
if (lastKnownLeapSecond)
lastDay = max(lastDay, getDayNumber_SGC(lastKnownLeapSecond));
const lastYMD = getDateFromDayNumber_SGC(lastDay);
postKnownLeapSeconds = getDayNumber_SGC({ y: lastYMD.y + 1, m: lastYMD.m < 7 ? 1 : 7, d: 1 }) + UNIX_TIME_ZERO_AS_JULIAN_DAY;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function getDeltaTAtJulianDate(timeJDE: number): number {
const year = (timeJDE - JD_J2000) / 365.25 + 2000.0;
// Do a three-point interpolation from either the table or the computed values.
const tableMidYear = floor(year);
const dt1 = deltaTAtStartOfYear(tableMidYear - 1);
const dt2 = deltaTAtStartOfYear(tableMidYear);
const dt3 = deltaTAtStartOfYear(tableMidYear + 1);
const a = dt2 - dt1;
const b = dt3 - dt2;
const c = b - a;
const n = year - tableMidYear;
return dt2 + n * (a + b + n * c) / 2.0;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function getDeltaTAtTaiMillis(millis: number): number {
return getDeltaTAtJulianDate(millis / DAY_MSEC + UNIX_TIME_ZERO_AS_JULIAN_DAY);
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function utToTdt(timeJDU: number): number {
let timeJDE = timeJDU;
for (let i = 0; i < 5; ++i)
timeJDE = timeJDU + getDeltaTAtJulianDate(timeJDE) / DAY_SEC;
return timeJDE;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function utToTai(timeJDU: number, asUtc = false): number {
let utcMillis: number;
let deltaTai: number;
if (asUtc && preKnownLeapSeconds - 365 <= timeJDU && timeJDU <= postKnownLeapSeconds + 365) {
utcMillis = round((timeJDU - UNIX_TIME_ZERO_AS_JULIAN_DAY) * DAY_MSEC);
deltaTai = Timezone.findDeltaTaiFromUtc(utcMillis)?.deltaTai ?? 0;
}
if (asUtc && preKnownLeapSeconds <= timeJDU && timeJDU <= postKnownLeapSeconds)
return timeJDU + deltaTai / DAY_SEC;
const tai = utToTdt(timeJDU) - DELTA_TDT_DAYS;
if (!asUtc || timeJDU < preKnownLeapSeconds - 365 || timeJDU > postKnownLeapSeconds + 365)
return tai;
const weight = (timeJDU <= preKnownLeapSeconds ? preKnownLeapSeconds - timeJDU : timeJDU - postKnownLeapSeconds);
return ((timeJDU + deltaTai / DAY_SEC) * (365 - weight) + tai * weight) / 365;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function utToTaiMillis(millis: number, asUtc = false): number {
return round((utToTai(millis / DAY_MSEC + UNIX_TIME_ZERO_AS_JULIAN_DAY, asUtc) -
UNIX_TIME_ZERO_AS_JULIAN_DAY) * DAY_MSEC);
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function tdtToUt(timeJDE: number): number {
return timeJDE - getDeltaTAtJulianDate(timeJDE) / DAY_SEC;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function tdtDaysToTaiMillis(timeJDE: number): number {
return (timeJDE - UNIX_TIME_ZERO_AS_JULIAN_DAY) * DAY_MSEC - DELTA_TDT_MSEC;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function taiDaysToUt(timeJDE: number): number {
return tdtToUt(timeJDE + DELTA_TDT_DAYS);
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function taiMillisToTdt(millis: number): number {
return (millis + DELTA_TDT_MSEC) / DAY_MSEC + UNIX_TIME_ZERO_AS_JULIAN_DAY;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
export function taiToUtMillis(millis: number, forUtc = false): number {
const tdt = millis / DAY_MSEC + UNIX_TIME_ZERO_AS_JULIAN_DAY + DELTA_TDT_DAYS;
const timeJDU = tdtToUt(tdt);
const jduMillis = (timeJDU - UNIX_TIME_ZERO_AS_JULIAN_DAY) * DAY_MSEC;
if (!forUtc || timeJDU < preKnownLeapSeconds - 365 || timeJDU > postKnownLeapSeconds + 365)
return round(jduMillis);
const deltaTai = Timezone.findDeltaTaiFromTai(millis)?.deltaTai ?? 0;
const utMillis = millis - deltaTai * 1000;
if (preKnownLeapSeconds <= timeJDU && timeJDU <= postKnownLeapSeconds)
return utMillis;
const weight = (timeJDU <= preKnownLeapSeconds ? preKnownLeapSeconds - timeJDU : timeJDU - postKnownLeapSeconds);
return round((utMillis * (365 - weight) + jduMillis * weight) / 365);
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
function deltaTAtStartOfYear(year: number): number {
// Make the post-table approximations line up with the last tabular delta T.
if (lastTableYear < 0) {
lastTableYear = historicDeltaT.length + 1578; // Temporarily 1 less than it should be
calibration = historicDeltaT[historicDeltaT.length - 1] - deltaTAtStartOfYear(lastTableYear + 1);
++lastTableYear;
}
// Polynomial expressions from http://eclipsewise.com/help/deltatpoly2014.html
let t, u;
if (year < -500) {
u = (year - 1820) / 100;
return -20 + 32 * u ** 2;
}
else if (year < 500) {
u = year / 100.0;
return 10583.6 - 1014.41 * u + 33.78311 * u ** 2 - 5.952053 * u ** 3
- 0.1798452 * u ** 4 + 0.022174192 * u ** 5 + 0.0090316521 * u ** 6;
}
else if (year <= 1580) {
u = (year - 1000.0) / 100.0;
return 1574.2 - 556.01 * u + 71.23472 * u ** 2 + 0.319781 * u ** 3
- 0.8503463 * u ** 4 - 0.005050998 * u ** 5 + 0.0083572073 * u ** 6;
}
else if (year <= lastTableYear)
return historicDeltaT[year - 1580];
else if (year < 3000) {
t = year - 2015;
return calibration + 67.69 + 0.3645 * t + 0.0039755 * t ** 2;
}
u = (year - 1820.0) / 100.0;
// Changed -20 in original expression to -171.82, so result matches above formula at year 3000
return calibration - 171.82 + 32 * u ** 2;
}
|
kshetline/tubular_time
|
src/ut-converter.ts
|
TypeScript
|
FunctionDeclaration
|
/**
* @param {any} pubKeyCred
* @param {Function} encode
* @returns any
*/
export function publicKeyCredentialToJSON(pubKeyCred: any, encode: Function): any {
if (pubKeyCred instanceof Array) {
let arr = [];
for (let i of pubKeyCred)
arr.push(publicKeyCredentialToJSON(i, encode));
return arr;
}
if (pubKeyCred instanceof ArrayBuffer) {
return encode(pubKeyCred);
}
if (pubKeyCred instanceof Object) {
let obj: any = {};
for (let key in pubKeyCred) {
obj[key] = publicKeyCredentialToJSON(pubKeyCred[key], encode);
}
return obj;
}
}
|
namaggarwal/circle-ci-tests
|
src/webauth-helpers.ts
|
TypeScript
|
FunctionDeclaration
|
/**
* @param {SerialPublicKeyCredentialRequestOptions} credentials
* @param {Function} decode
* @returns PublicKeyCredentialRequestOptions
*/
export function preFormatCreateCredentialRequest(credentials: SerialPublicKeyCredentialRequestOptions, decode: Function): PublicKeyCredentialRequestOptions {
const createCredentialRequest: PublicKeyCredentialRequestOptions = {
...credentials,
challenge: decode(credentials.challenge),
user: {
...credentials.user,
id: decode(credentials.user.id),
},
};
return createCredentialRequest
}
|
namaggarwal/circle-ci-tests
|
src/webauth-helpers.ts
|
TypeScript
|
InterfaceDeclaration
|
interface SerialPublicKeyCredentialUserEntity {
readonly id: string
[propName: string]: any;
}
|
namaggarwal/circle-ci-tests
|
src/webauth-helpers.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface SerialPublicKeyCredentialRequestOptions {
readonly challenge: string
readonly user: SerialPublicKeyCredentialUserEntity
[propName: string]: any;
}
|
namaggarwal/circle-ci-tests
|
src/webauth-helpers.ts
|
TypeScript
|
InterfaceDeclaration
|
interface PublicKeyCredentialUserEntity {
id: ArrayBuffer
[propName: string]: any;
}
|
namaggarwal/circle-ci-tests
|
src/webauth-helpers.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface PublicKeyCredentialRequestOptions {
challenge: ArrayBuffer
user: PublicKeyCredentialUserEntity
[propName: string]: any;
}
|
namaggarwal/circle-ci-tests
|
src/webauth-helpers.ts
|
TypeScript
|
ClassDeclaration
|
@Component({
selector: 'app-form-error-handler',
templateUrl: './form-error-handler.component.html',
styleUrls: ['./form-error-handler.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormErrorHandlerComponent implements OnInit {
@Input() errors: {};
constructor() {}
ngOnInit() {}
/**
* Return an error message accordingly.
*/
get errorMessage(): string {
const errorKey = Object.keys(this.errors)[0];
const error = this.errors[errorKey];
switch (errorKey) {
case 'required':
case 'whitespaces':
return 'Input is required';
case 'maxlength':
return `Up to ${error.requiredLength} characters allowed`;
case 'numeric':
return 'Only numebrs are allowed';
default:
return 'Input is invalid';
}
}
}
|
OriyanJ/crudella
|
src/app/form-error-handler/form-error-handler.component.ts
|
TypeScript
|
ArrowFunction
|
() => {
let connections: Connection[];
before(async () => connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
schemaCreate: true,
dropSchema: true,
}));
beforeEach(() => reloadTestingDatabases(connections));
after(() => closeTestingConnections(connections));
it("entityManager should allow you to save unrelated entities with one persist call", () => Promise.all(connections.map(async connection => {
const car = new Car();
car.name = "Ferrari";
const fruit = new Fruit();
fruit.name = "Banana";
const [savedCar, savedFruit] = await connection.manager.save([car, fruit]);
expect(savedFruit).to.have.property("name", "Banana");
expect(savedFruit).to.be.instanceof(Fruit);
expect(savedCar).to.have.property("name", "Ferrari");
expect(savedCar).to.be.instanceof(Car);
const cars = await connection.manager.find(Car);
// before the changes in this PR, all the tests before this one actually passed
expect(cars).to.length(1);
expect(cars[0]).to.have.property("name", "Ferrari");
const fruits = await connection.manager.find(Fruit);
expect(fruits).to.length(1);
expect(fruits[0]).to.have.property("name", "Banana");
})));
it("entityManager should allow you to delete unrelated entities with one remove call", () => Promise.all(connections.map(async connection => {
const fruit = new Fruit();
fruit.name = "Banana";
const fruit2 = new Fruit();
fruit2.name = "Apple";
const [savedFruit] = await connection.manager.save([fruit, fruit2]);
const car = new Car();
car.name = "Ferrari";
const savedCar = await connection.manager.save(car);
await connection.manager.remove([savedCar, savedFruit]);
const cars = await connection.manager.find(Car);
expect(cars).to.length(0);
const fruits = await connection.manager.find(Fruit);
expect(fruits).to.length(1);
expect(fruits[0]).to.have.property("name", "Apple");
})));
}
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
async () => connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
schemaCreate: true,
dropSchema: true,
})
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
() => reloadTestingDatabases(connections)
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
() => closeTestingConnections(connections)
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
() => Promise.all(connections.map(async connection => {
const car = new Car();
car.name = "Ferrari";
const fruit = new Fruit();
fruit.name = "Banana";
const [savedCar, savedFruit] = await connection.manager.save([car, fruit]);
expect(savedFruit).to.have.property("name", "Banana");
expect(savedFruit).to.be.instanceof(Fruit);
expect(savedCar).to.have.property("name", "Ferrari");
expect(savedCar).to.be.instanceof(Car);
const cars = await connection.manager.find(Car);
// before the changes in this PR, all the tests before this one actually passed
expect(cars).to.length(1);
expect(cars[0]).to.have.property("name", "Ferrari");
const fruits = await connection.manager.find(Fruit);
expect(fruits).to.length(1);
expect(fruits[0]).to.have.property("name", "Banana");
}))
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
async connection => {
const car = new Car();
car.name = "Ferrari";
const fruit = new Fruit();
fruit.name = "Banana";
const [savedCar, savedFruit] = await connection.manager.save([car, fruit]);
expect(savedFruit).to.have.property("name", "Banana");
expect(savedFruit).to.be.instanceof(Fruit);
expect(savedCar).to.have.property("name", "Ferrari");
expect(savedCar).to.be.instanceof(Car);
const cars = await connection.manager.find(Car);
// before the changes in this PR, all the tests before this one actually passed
expect(cars).to.length(1);
expect(cars[0]).to.have.property("name", "Ferrari");
const fruits = await connection.manager.find(Fruit);
expect(fruits).to.length(1);
expect(fruits[0]).to.have.property("name", "Banana");
}
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
() => Promise.all(connections.map(async connection => {
const fruit = new Fruit();
fruit.name = "Banana";
const fruit2 = new Fruit();
fruit2.name = "Apple";
const [savedFruit] = await connection.manager.save([fruit, fruit2]);
const car = new Car();
car.name = "Ferrari";
const savedCar = await connection.manager.save(car);
await connection.manager.remove([savedCar, savedFruit]);
const cars = await connection.manager.find(Car);
expect(cars).to.length(0);
const fruits = await connection.manager.find(Fruit);
expect(fruits).to.length(1);
expect(fruits[0]).to.have.property("name", "Apple");
}))
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
async connection => {
const fruit = new Fruit();
fruit.name = "Banana";
const fruit2 = new Fruit();
fruit2.name = "Apple";
const [savedFruit] = await connection.manager.save([fruit, fruit2]);
const car = new Car();
car.name = "Ferrari";
const savedCar = await connection.manager.save(car);
await connection.manager.remove([savedCar, savedFruit]);
const cars = await connection.manager.find(Car);
expect(cars).to.length(0);
const fruits = await connection.manager.find(Fruit);
expect(fruits).to.length(1);
expect(fruits[0]).to.have.property("name", "Apple");
}
|
Akshay-Gupta/typeorm
|
test/github-issues/363/issue-363.ts
|
TypeScript
|
ArrowFunction
|
(
assetNamespace: string,
): assetNamespace is CAIP22AssetNamespace => assetNamespace === 'erc721'
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
ArrowFunction
|
(
assetReference: string,
): assetReference is CAIP22AssetReference => utils.isAddress(assetReference)
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
ArrowFunction
|
(tokenId: any): tokenId is CAIP22TokenID =>
ethers.BigNumber.isBigNumber(tokenId)
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
ArrowFunction
|
(assetId: any): assetId is CAIP22AssetID => !!assetId.tokenId
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface CAIP22AssetType extends CAIP19AssetType {
chainId: CAIP3ChainId;
assetNamespace: CAIP22AssetNamespace;
assetReference: CAIP22AssetReference;
}
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface CAIP22AssetID extends CAIP22AssetType {
tokenId: CAIP22TokenID;
}
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
TypeAliasDeclaration
|
// https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-22.md#erc721-asset-namespace
export type CAIP22AssetNamespace = 'erc721';
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
TypeAliasDeclaration
|
// https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-22.md#asset-reference-definition
export type CAIP22AssetReference = string;
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
TypeAliasDeclaration
|
// https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-22.md#token-id-definition
export type CAIP22TokenID = BigNumber;
|
XLNT/caip
|
src/CAIP22.ts
|
TypeScript
|
ClassDeclaration
|
/**
* A database of regional information.
*/
export class Fact {
/**
* @returns the list of names of AWS regions for which there is at least one registered fact. This
* may not be an exhaustive list of all available AWS regions.
*/
public static get regions(): string[] {
return Object.keys(this.database);
}
/**
* Retrieves a fact from this Fact database.
*
* @param region the name of the region (e.g: `us-east-1`)
* @param name the name of the fact being looked up (see the `FactName` class for details)
*
* @returns the fact value if it is known, and `undefined` otherwise.
*/
public static find(region: string, name: string): string | undefined {
const regionFacts = this.database[region];
return regionFacts && regionFacts[name];
}
/**
* Retrieve a fact from the Fact database. (retrieval will fail if the specified region or
* fact name does not exist.)
*
* @param region the name of the region (e.g: `us-east-1`)
* @param name the name of the fact being looked up (see the `FactName` class for details)
*/
public static requireFact(region: string, name: string): string {
const foundFact = this.find(region, name);
if (!foundFact) {
throw new Error(`No fact ${name} could be found for region: ${region} and name: ${name}`);
}
return foundFact;
}
/**
* Registers a new fact in this Fact database.
*
* @param fact the new fact to be registered.
* @param allowReplacing whether new facts can replace existing facts or not.
*/
public static register(fact: IFact, allowReplacing = false): void {
const regionFacts = this.database[fact.region] || (this.database[fact.region] = {});
if (fact.name in regionFacts && regionFacts[fact.name] !== fact.value && !allowReplacing) {
throw new Error(`Region ${fact.region} already has a fact ${fact.name}, with value ${regionFacts[fact.name]}`);
}
if (fact.value !== undefined) {
regionFacts[fact.name] = fact.value;
}
}
/**
* Removes a fact from the database.
* @param region the region for which the fact is to be removed.
* @param name the name of the fact to remove.
* @param value the value that should be removed (removal will fail if the value is specified, but does not match the
* current stored value).
*/
public static unregister(region: string, name: string, value?: string): void {
const regionFacts = this.database[region] || {};
if (name in regionFacts && value && regionFacts[name] !== value) {
throw new Error(`Attempted to remove ${name} from ${region} with value ${value}, but the fact's value is ${regionFacts[name]}`);
}
delete regionFacts[name];
}
private static readonly database: { [region: string]: { [name: string]: string } } = {};
private constructor() {
throw new Error('Use the static methods of Fact instead!');
}
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
ClassDeclaration
|
/**
* All standardized fact names.
*/
export class FactName {
/**
* The name of the partition for a region (e.g: 'aws', 'aws-cn', ...)
*/
public static readonly PARTITION = 'partition';
/**
* The domain suffix for a region (e.g: 'amazonaws.com`)
*/
public static readonly DOMAIN_SUFFIX = 'domainSuffix';
/**
* Whether the AWS::CDK::Metadata CloudFormation Resource is available in-region or not. The value is a boolean
* modelled as `YES` or `NO`.
*/
public static readonly CDK_METADATA_RESOURCE_AVAILABLE = 'cdk:metadata-resource:available';
/**
* The endpoint used for hosting S3 static websites
*/
public static readonly S3_STATIC_WEBSITE_ENDPOINT = 's3-static-website:endpoint';
/**
* The endpoint used for aliasing S3 static websites in Route 53
*/
public static readonly S3_STATIC_WEBSITE_ZONE_53_HOSTED_ZONE_ID = 's3-static-website:route-53-hosted-zone-id';
/**
* The prefix for VPC Endpoint Service names,
* cn.com.amazonaws.vpce for China regions,
* com.amazonaws.vpce otherwise.
*/
public static readonly VPC_ENDPOINT_SERVICE_NAME_PREFIX = 'vpcEndpointServiceNamePrefix';
/**
* The account for ELBv2 in this region
*/
public static readonly ELBV2_ACCOUNT = 'elbv2Account';
/**
* The ID of the AWS account that owns the public ECR repository that contains the
* AWS Deep Learning Containers images in a given region.
*/
public static readonly DLC_REPOSITORY_ACCOUNT = 'dlcRepositoryAccount';
/**
* The name of the regional service principal for a given service.
*
* @param service the service name, either simple (e.g: `s3`, `codedeploy`) or qualified (e.g: `s3.amazonaws.com`).
* The `.amazonaws.com` and `.amazonaws.com.cn` domains are stripped from service names, so they are
* canonicalized in that respect.
*/
public static servicePrincipal(service: string) {
return `service-principal:${service.replace(/\.amazonaws\.com(\.cn)?$/, '')}`;
}
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
InterfaceDeclaration
|
/**
* A fact that can be registered about a particular region.
*/
export interface IFact {
/**
* The region for which this fact applies.
*/
readonly region: string;
/**
* The name of this fact. Standardized values are provided by the `Facts` class.
*/
readonly name: string;
/**
* The value of this fact.
*/
readonly value: string | undefined;
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Retrieves a fact from this Fact database.
*
* @param region the name of the region (e.g: `us-east-1`)
* @param name the name of the fact being looked up (see the `FactName` class for details)
*
* @returns the fact value if it is known, and `undefined` otherwise.
*/
public static find(region: string, name: string): string | undefined {
const regionFacts = this.database[region];
return regionFacts && regionFacts[name];
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Retrieve a fact from the Fact database. (retrieval will fail if the specified region or
* fact name does not exist.)
*
* @param region the name of the region (e.g: `us-east-1`)
* @param name the name of the fact being looked up (see the `FactName` class for details)
*/
public static requireFact(region: string, name: string): string {
const foundFact = this.find(region, name);
if (!foundFact) {
throw new Error(`No fact ${name} could be found for region: ${region} and name: ${name}`);
}
return foundFact;
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Registers a new fact in this Fact database.
*
* @param fact the new fact to be registered.
* @param allowReplacing whether new facts can replace existing facts or not.
*/
public static register(fact: IFact, allowReplacing = false): void {
const regionFacts = this.database[fact.region] || (this.database[fact.region] = {});
if (fact.name in regionFacts && regionFacts[fact.name] !== fact.value && !allowReplacing) {
throw new Error(`Region ${fact.region} already has a fact ${fact.name}, with value ${regionFacts[fact.name]}`);
}
if (fact.value !== undefined) {
regionFacts[fact.name] = fact.value;
}
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Removes a fact from the database.
* @param region the region for which the fact is to be removed.
* @param name the name of the fact to remove.
* @param value the value that should be removed (removal will fail if the value is specified, but does not match the
* current stored value).
*/
public static unregister(region: string, name: string, value?: string): void {
const regionFacts = this.database[region] || {};
if (name in regionFacts && value && regionFacts[name] !== value) {
throw new Error(`Attempted to remove ${name} from ${region} with value ${value}, but the fact's value is ${regionFacts[name]}`);
}
delete regionFacts[name];
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
MethodDeclaration
|
/**
* The name of the regional service principal for a given service.
*
* @param service the service name, either simple (e.g: `s3`, `codedeploy`) or qualified (e.g: `s3.amazonaws.com`).
* The `.amazonaws.com` and `.amazonaws.com.cn` domains are stripped from service names, so they are
* canonicalized in that respect.
*/
public static servicePrincipal(service: string) {
return `service-principal:${service.replace(/\.amazonaws\.com(\.cn)?$/, '')}`;
}
|
Albert-Gao/aws-cdk
|
packages/@aws-cdk/region-info/lib/fact.ts
|
TypeScript
|
FunctionDeclaration
|
function singleFire(fn: Function) {
let fired = false;
return function () {
if (fired) return;
fired = true;
fn.apply(null, arguments);
};
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
FunctionDeclaration
|
function setupTest(done: MochaDone) {
myExtension.transformers.push(new TestTransformerAsync());
myExtension.transformers.push(new TestTransformerSync());
//myExtension.activateAgain(); //Actually extension should be initiliazed at startup, so before coming to this line?!
const selections = new Array<vscode.Selection>();
selections.push(new vscode.Selection(new vscode.Position(0, 0), new vscode.Position(0, 2)));
selections.push(new vscode.Selection(new vscode.Position(0, 5), new vscode.Position(0, 11)));
vscode.workspace.openTextDocument(__dirname + "/../../test/sample_text").then((doc: vscode.TextDocument) => {
vscode.window.activeTextEditor.edit((editBuilder: vscode.TextEditorEdit) => {
editBuilder.insert(new vscode.Position(0, 0), doc.getText());
}).then(() => {
vscode.window.activeTextEditor.selections = selections;
done();
});
}, (err) => {
console.error(err);
done(new Error("Could not load sample text file!"));
});
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
suiteSetup(setupTest);
test("behaviour of text-transformer framework (async)", (done: MochaDone) => {
vscode.workspace.onDidChangeTextDocument(singleFire((change: vscode.TextDocumentChangeEvent) => { //We need singleFire here, otherwise this handler gets procesed when editor content changed during second testcase
const text = vscode.window.activeTextEditor.document.getText();
try { //Usually one wouldn"t need this construct - but it seems like the "thenables" catch the error before getting up higher in the stack
assert.equal(text, "HAllo, HIER bin ich!\n");
}
catch (err) {
return done(err);
}
done();
}));
vscode.commands.executeCommand("Test-Transformer-Async");
});
test("behaviour of text-transformer framework (sync)", (done: MochaDone) => {
vscode.workspace.onDidChangeTextDocument((change: vscode.TextDocumentChangeEvent) => {
const text = vscode.window.activeTextEditor.document.getText();
try { //Usually one wouldn"t need this construct - but it seems like the "thenables" catch the error before getting up higher in the stack
assert.equal(text, "hallo, hier bin ich!\n");
}
catch (err) {
return done(err);
}
done();
});
//Actually the next three lines are setup code...
const selections = new Array<vscode.Selection>();
selections.push(new vscode.Selection(new vscode.Position(0, 0), new vscode.Position(0, 2)));
selections.push(new vscode.Selection(new vscode.Position(0, 5), new vscode.Position(0, 11)));
vscode.window.activeTextEditor.selections = selections;
vscode.commands.executeCommand("Test-Transformer-Sync");
});
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
(done: MochaDone) => {
vscode.workspace.onDidChangeTextDocument(singleFire((change: vscode.TextDocumentChangeEvent) => { //We need singleFire here, otherwise this handler gets procesed when editor content changed during second testcase
const text = vscode.window.activeTextEditor.document.getText();
try { //Usually one wouldn"t need this construct - but it seems like the "thenables" catch the error before getting up higher in the stack
assert.equal(text, "HAllo, HIER bin ich!\n");
}
catch (err) {
return done(err);
}
done();
}));
vscode.commands.executeCommand("Test-Transformer-Async");
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
(change: vscode.TextDocumentChangeEvent) => { //We need singleFire here, otherwise this handler gets procesed when editor content changed during second testcase
const text = vscode.window.activeTextEditor.document.getText();
try { //Usually one wouldn"t need this construct - but it seems like the "thenables" catch the error before getting up higher in the stack
assert.equal(text, "HAllo, HIER bin ich!\n");
}
catch (err) {
return done(err);
}
done();
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
(done: MochaDone) => {
vscode.workspace.onDidChangeTextDocument((change: vscode.TextDocumentChangeEvent) => {
const text = vscode.window.activeTextEditor.document.getText();
try { //Usually one wouldn"t need this construct - but it seems like the "thenables" catch the error before getting up higher in the stack
assert.equal(text, "hallo, hier bin ich!\n");
}
catch (err) {
return done(err);
}
done();
});
//Actually the next three lines are setup code...
const selections = new Array<vscode.Selection>();
selections.push(new vscode.Selection(new vscode.Position(0, 0), new vscode.Position(0, 2)));
selections.push(new vscode.Selection(new vscode.Position(0, 5), new vscode.Position(0, 11)));
vscode.window.activeTextEditor.selections = selections;
vscode.commands.executeCommand("Test-Transformer-Sync");
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
(change: vscode.TextDocumentChangeEvent) => {
const text = vscode.window.activeTextEditor.document.getText();
try { //Usually one wouldn"t need this construct - but it seems like the "thenables" catch the error before getting up higher in the stack
assert.equal(text, "hallo, hier bin ich!\n");
}
catch (err) {
return done(err);
}
done();
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
(doc: vscode.TextDocument) => {
vscode.window.activeTextEditor.edit((editBuilder: vscode.TextEditorEdit) => {
editBuilder.insert(new vscode.Position(0, 0), doc.getText());
}).then(() => {
vscode.window.activeTextEditor.selections = selections;
done();
});
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
(editBuilder: vscode.TextEditorEdit) => {
editBuilder.insert(new vscode.Position(0, 0), doc.getText());
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
vscode.window.activeTextEditor.selections = selections;
done();
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
(err) => {
console.error(err);
done(new Error("Could not load sample text file!"));
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ClassDeclaration
|
class TestTransformerAsync extends Transformation {
getCommandName(): string {
return "Test-Transformer-Async";
}
transform(input: string, cb: (output: string) => void): void {
process.nextTick(cb.bind(null, input.toUpperCase()));
}
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ClassDeclaration
|
class TestTransformerSync extends Transformation {
getCommandName(): string {
return "Test-Transformer-Sync";
}
transform(input: string, cb: (output: string) => void): string {
return input.toLowerCase();
}
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
MethodDeclaration
|
getCommandName(): string {
return "Test-Transformer-Async";
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
MethodDeclaration
|
transform(input: string, cb: (output: string) => void): void {
process.nextTick(cb.bind(null, input.toUpperCase()));
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
MethodDeclaration
|
getCommandName(): string {
return "Test-Transformer-Sync";
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
MethodDeclaration
|
transform(input: string, cb: (output: string) => void): string {
return input.toLowerCase();
}
|
invocationtarget/vscode-case-convert
|
test/extension.test.ts
|
TypeScript
|
ArrowFunction
|
() => {
const errormsg = 'Error sample';
it('should return an error message with status', () => {
const axErr: AxiosError = {
config: { method: 'GET' },
name: 'AxiosError',
message: 'Error in Response',
response: {
data: null,
status: 400,
statusText: 'InternalError',
headers: null,
config: {}
}
};
expect(API.getErrorMsg(errormsg, axErr)).toEqual(`${errormsg}, Error: [ InternalError ]`);
});
it('should return an error message with data', () => {
const responseServerError = 'Internal Error';
const axErr: AxiosError = {
config: { method: 'GET' },
name: 'AxiosError',
message: 'Error in Response',
response: {
data: { error: responseServerError },
status: 400,
statusText: 'InternalError',
headers: null,
config: {}
}
};
expect(API.getErrorMsg(errormsg, axErr)).toEqual(`${errormsg}, Error: [ ${responseServerError} ]`);
});
it('should return specific error message for unauthorized', () => {
const axErr: AxiosError = {
config: { method: 'GET' },
name: 'AxiosError',
message: 'Error in Response',
response: {
data: null,
status: 401,
statusText: 'Unauthorized',
headers: null,
config: {}
}
};
expect(API.getErrorMsg(errormsg, axErr)).toEqual(
`${errormsg}, Error: [ Unauthorized ] Has your session expired? Try logging in again.`
);
});
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const axErr: AxiosError = {
config: { method: 'GET' },
name: 'AxiosError',
message: 'Error in Response',
response: {
data: null,
status: 400,
statusText: 'InternalError',
headers: null,
config: {}
}
};
expect(API.getErrorMsg(errormsg, axErr)).toEqual(`${errormsg}, Error: [ InternalError ]`);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const responseServerError = 'Internal Error';
const axErr: AxiosError = {
config: { method: 'GET' },
name: 'AxiosError',
message: 'Error in Response',
response: {
data: { error: responseServerError },
status: 400,
statusText: 'InternalError',
headers: null,
config: {}
}
};
expect(API.getErrorMsg(errormsg, axErr)).toEqual(`${errormsg}, Error: [ ${responseServerError} ]`);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const axErr: AxiosError = {
config: { method: 'GET' },
name: 'AxiosError',
message: 'Error in Response',
response: {
data: null,
status: 401,
statusText: 'Unauthorized',
headers: null,
config: {}
}
};
expect(API.getErrorMsg(errormsg, axErr)).toEqual(
`${errormsg}, Error: [ Unauthorized ] Has your session expired? Try logging in again.`
);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const evaluatePromise = (result: Promise<any>) => {
expect(result).toBeDefined();
expect(typeof result).toEqual('object');
expect(typeof result.then).toEqual('function');
expect(typeof result.catch).toEqual('function');
};
it('#login', () => {
const result = API.login({ username: 'admin', password: 'admin' });
evaluatePromise(result);
});
it('#getStatus', () => {
const result = API.getStatus();
evaluatePromise(result);
});
it('#getNamespaces', () => {
const result = API.getNamespaces();
evaluatePromise(result);
});
it('#getNamespaceMetrics', () => {
const result = API.getNamespaceMetrics('istio-system', {} as IstioMetricsOptions);
evaluatePromise(result);
});
it('#getServices', () => {
const result = API.getServices('istio-system');
evaluatePromise(result);
});
it('#getAppMetrics', () => {
const result = API.getAppMetrics('istio-system', 'book-info', {} as IstioMetricsOptions);
evaluatePromise(result);
});
it('#getServiceHealth', () => {
const result = API.getServiceHealth('istio-system', 'book-info', 60, true);
evaluatePromise(result);
});
it('#getGrafanaInfo', () => {
const result = API.getGrafanaInfo();
evaluatePromise(result);
});
it('#getJaegerInfo', () => {
const result = API.getJaegerInfo();
evaluatePromise(result);
});
it('#getGraphElements', () => {
const result = API.getGraphElements({ namespaces: 'istio-system' });
evaluatePromise(result);
});
it('#getServiceDetail', () => {
const result = API.getServiceDetail('istio-system', '', false);
evaluatePromise(result);
});
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
(result: Promise<any>) => {
expect(result).toBeDefined();
expect(typeof result).toEqual('object');
expect(typeof result.then).toEqual('function');
expect(typeof result.catch).toEqual('function');
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.login({ username: 'admin', password: 'admin' });
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getStatus();
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getNamespaces();
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getNamespaceMetrics('istio-system', {} as IstioMetricsOptions);
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getServices('istio-system');
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getAppMetrics('istio-system', 'book-info', {} as IstioMetricsOptions);
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getServiceHealth('istio-system', 'book-info', 60, true);
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getGrafanaInfo();
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getJaegerInfo();
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getGraphElements({ namespaces: 'istio-system' });
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
ArrowFunction
|
() => {
const result = API.getServiceDetail('istio-system', '', false);
evaluatePromise(result);
}
|
Buri/kiali-ui
|
src/services/__tests__/ApiMethods.test.tsx.ts
|
TypeScript
|
FunctionDeclaration
|
async function dbConnect() {
await mongoose
.connect(`${process.env.MONGODB_URI}`)
.then((res) => console.log("connection made"))
.catch((err) => console.log("error", err));
}
|
saurabhtopthon01/dev-shopping-cart
|
lib/dbConnect.tsx
|
TypeScript
|
ArrowFunction
|
(res) => console.log("connection made")
|
saurabhtopthon01/dev-shopping-cart
|
lib/dbConnect.tsx
|
TypeScript
|
ArrowFunction
|
(err) => console.log("error", err)
|
saurabhtopthon01/dev-shopping-cart
|
lib/dbConnect.tsx
|
TypeScript
|
InterfaceDeclaration
|
export interface BoilerSettings {
ControlType: string;
FuelType: string;
CycleRate: string;
OnOffHysteresis: number;
}
|
stringbean/drayton-wiser-client
|
src/api/responses/BoilerSettings.ts
|
TypeScript
|
ArrowFunction
|
(dispatch: Dispatch, zesp: IZespConnector) => {
const uiSettingsRef = useRef<UiSettings>({} as UiSettings);
const firmwareUpdateMinTimout = 1000 * 60 * 60 * 24;
// init
const connectAsync = (server: IServerInfo): Promise<void> => zesp
.connectAsync(server, (status) => dispatch(setConnectionStatus(status)), false)
// read devices list
const getDevices = (): Promise<void> => ServiceDevices.getDevicesListAsync(zesp)
.then(result => {
dispatch(setDevices(result.devices));
if (result.zespVersion) dispatch(setZespFirmwareInstalledVersion(result.zespVersion));
});
// read root info
const getRoot = (): Promise<void> => ServiceRoot
.getRootDataAsync(zesp)
.then(reports => {
dispatch(updateRootReports(reports))
console.debug("Root device reports updated");
});
// read ui settings
const readUiSettings = (): Promise<void> => useZespSettings(zesp)
.getCustomAsync<UiSettings>("zesp_ui")
.then(settings => {
const result = settings || UiDefaultSettings;
dispatch(setUiSettings(result))
uiSettingsRef.current = result;
})
// private firmware updates downloading
const _getFirmware = (): void => {
ServiceFirmware
.getFirmwareInfoAsync(zesp)
.then(firmwareInfo => {
dispatch(setZespFirmwareInstalledVersion(firmwareInfo.currentVersion));
dispatch(setZespFirmwareUpdate(firmwareInfo.updatesInformation));
uiSettingsRef.current = {...uiSettingsRef.current, ...{firmwareUpdate: firmwareInfo.updatesInformation, firmwareLastCheck: Date.now()}};
useZespSettings(zesp).setCustom("zesp_ui", uiSettingsRef.current);
dispatch(setUiSettings(uiSettingsRef.current));
console.debug("Firmware updates information loaded");
})
.catch(reason => {
console.warn("Cannot read Firmware update information");
console.warn(reason);
});
}
// read firmware updates
const readFirmwareUpdates = (): Promise<void> => {
const uiSettings = uiSettingsRef.current
if (!uiSettings) throw new Error("Read UI settings before firmware checking");
if (uiSettings.firmwareUpdate && uiSettings.firmwareLastCheck && (Date.now() - uiSettings.firmwareLastCheck) < firmwareUpdateMinTimout) {
dispatch(setZespFirmwareUpdate(uiSettings.firmwareUpdate));
console.debug("Firmware information read from settings");
return Promise.resolve();
}
// run firmware loading in background
_getFirmware();
return Promise.resolve();
}
// subscribe to report updates events
const subscribeReportUpdates = (): Promise<void> => {
const onReport = (ieee: string, reportKey: string, update: Partial<ZespReportInfo>) =>
dispatch(updateReport({ieee, reportKey, update}));
ServiceUpdates.subscribeToEvents(zesp, onReport);
return Promise.resolve();
}
const subscribeDevicesListUpdate = (): Promise<void> => {
const onUpdate = (devices: DeviceInfo[]): void => {
// devices.pop();
dispatch(updateDevices(devices));
console.debug("Devices list updated");
}
ServiceDevices.subscribeListUpdate(zesp, onUpdate);
return Promise.resolve();
}
return {
connectAsync,
getDevices,
getRoot,
readUiSettings,
readFirmwareUpdates,
subscribeReportUpdates,
subscribeDevicesListUpdate,
}
}
|
NickRimmer/zesp-ui
|
src/shared/agents/ZespAgent.hook.tsx
|
TypeScript
|
ArrowFunction
|
(server: IServerInfo): Promise<void> => zesp
.connectAsync(server, (status) => dispatch(setConnectionStatus(status)), false)
|
NickRimmer/zesp-ui
|
src/shared/agents/ZespAgent.hook.tsx
|
TypeScript
|
ArrowFunction
|
(status) => dispatch(setConnectionStatus(status))
|
NickRimmer/zesp-ui
|
src/shared/agents/ZespAgent.hook.tsx
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.