hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 3, "code_window": [ " PackageName: Visual Studio Code Server\n", " condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal'))\n", "\n", " - publish: $(agent.builddirectory)/vscode-server-darwin/_manifest\n", " displayName: Publish SBOM (server)\n", " artifact: vscode_server_darwin_$(VSCODE_ARCH)_sbom\n", " condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal'))" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " - publish: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)/_manifest\n" ], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "replace", "edit_start_line_idx": 362 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; const gulp = require('gulp'); const path = require('path'); const fs = require('fs'); const assert = require('assert'); const cp = require('child_process'); const _7z = require('7zip')['7z']; const util = require('./lib/util'); const task = require('./lib/task'); const pkg = require('../package.json'); const product = require('../product.json'); const vfs = require('vinyl-fs'); const rcedit = require('rcedit'); const mkdirp = require('mkdirp'); const repoPath = path.dirname(__dirname); const buildPath = (/** @type {string} */ arch) => path.join(path.dirname(repoPath), `VSCode-win32-${arch}`); const zipDir = (/** @type {string} */ arch) => path.join(repoPath, '.build', `win32-${arch}`, 'archive'); const zipPath = (/** @type {string} */ arch) => path.join(zipDir(arch), `VSCode-win32-${arch}.zip`); const setupDir = (/** @type {string} */ arch, /** @type {string} */ target) => path.join(repoPath, '.build', `win32-${arch}`, `${target}-setup`); const issPath = path.join(__dirname, 'win32', 'code.iss'); const innoSetupPath = path.join(path.dirname(path.dirname(require.resolve('innosetup'))), 'bin', 'ISCC.exe'); const signWin32Path = path.join(repoPath, 'build', 'azure-pipelines', 'common', 'sign-win32'); function packageInnoSetup(iss, options, cb) { options = options || {}; const definitions = options.definitions || {}; if (process.argv.some(arg => arg === '--debug-inno')) { definitions['Debug'] = 'true'; } if (process.argv.some(arg => arg === '--sign')) { definitions['Sign'] = 'true'; } const keys = Object.keys(definitions); keys.forEach(key => assert(typeof definitions[key] === 'string', `Missing value for '${key}' in Inno Setup package step`)); const defs = keys.map(key => `/d${key}=${definitions[key]}`); const args = [ iss, ...defs, `/sesrp=node ${signWin32Path} $f` ]; cp.spawn(innoSetupPath, args, { stdio: ['ignore', 'inherit', 'inherit'] }) .on('error', cb) .on('exit', code => { if (code === 0) { cb(null); } else { cb(new Error(`InnoSetup returned exit code: ${code}`)); } }); } /** * @param {string} arch * @param {string} target */ function buildWin32Setup(arch, target) { if (target !== 'system' && target !== 'user') { throw new Error('Invalid setup target'); } return cb => { const ia32AppId = target === 'system' ? product.win32AppId : product.win32UserAppId; const x64AppId = target === 'system' ? product.win32x64AppId : product.win32x64UserAppId; const arm64AppId = target === 'system' ? product.win32arm64AppId : product.win32arm64UserAppId; const sourcePath = buildPath(arch); const outputPath = setupDir(arch, target); mkdirp.sync(outputPath); const originalProductJsonPath = path.join(sourcePath, 'resources/app/product.json'); const productJsonPath = path.join(outputPath, 'product.json'); const productJson = JSON.parse(fs.readFileSync(originalProductJsonPath, 'utf8')); productJson['target'] = target; fs.writeFileSync(productJsonPath, JSON.stringify(productJson, undefined, '\t')); const definitions = { NameLong: product.nameLong, NameShort: product.nameShort, DirName: product.win32DirName, Version: pkg.version, RawVersion: pkg.version.replace(/-\w+$/, ''), NameVersion: product.win32NameVersion + (target === 'user' ? ' (User)' : ''), ExeBasename: product.nameShort, RegValueName: product.win32RegValueName, ShellNameShort: product.win32ShellNameShort, AppMutex: product.win32MutexName, Arch: arch, AppId: { 'ia32': ia32AppId, 'x64': x64AppId, 'arm64': arm64AppId }[arch], IncompatibleTargetAppId: { 'ia32': product.win32AppId, 'x64': product.win32x64AppId, 'arm64': product.win32arm64AppId }[arch], IncompatibleArchAppId: { 'ia32': x64AppId, 'x64': ia32AppId, 'arm64': ia32AppId }[arch], AppUserId: product.win32AppUserModelId, ArchitecturesAllowed: { 'ia32': '', 'x64': 'x64', 'arm64': 'arm64' }[arch], ArchitecturesInstallIn64BitMode: { 'ia32': '', 'x64': 'x64', 'arm64': 'arm64' }[arch], SourceDir: sourcePath, RepoDir: repoPath, OutputDir: outputPath, InstallTarget: target, ProductJsonPath: productJsonPath }; packageInnoSetup(issPath, { definitions }, cb); }; } /** * @param {string} arch * @param {string} target */ function defineWin32SetupTasks(arch, target) { const cleanTask = util.rimraf(setupDir(arch, target)); gulp.task(task.define(`vscode-win32-${arch}-${target}-setup`, task.series(cleanTask, buildWin32Setup(arch, target)))); } defineWin32SetupTasks('ia32', 'system'); defineWin32SetupTasks('x64', 'system'); defineWin32SetupTasks('arm64', 'system'); defineWin32SetupTasks('ia32', 'user'); defineWin32SetupTasks('x64', 'user'); defineWin32SetupTasks('arm64', 'user'); /** * @param {string} arch */ function archiveWin32Setup(arch) { return cb => { const args = ['a', '-tzip', zipPath(arch), '-x!CodeSignSummary*.md', '.', '-r']; cp.spawn(_7z, args, { stdio: 'inherit', cwd: buildPath(arch) }) .on('error', cb) .on('exit', () => cb(null)); }; } gulp.task(task.define('vscode-win32-ia32-archive', task.series(util.rimraf(zipDir('ia32')), archiveWin32Setup('ia32')))); gulp.task(task.define('vscode-win32-x64-archive', task.series(util.rimraf(zipDir('x64')), archiveWin32Setup('x64')))); gulp.task(task.define('vscode-win32-arm64-archive', task.series(util.rimraf(zipDir('arm64')), archiveWin32Setup('arm64')))); /** * @param {string} arch */ function copyInnoUpdater(arch) { return () => { return gulp.src('build/win32/{inno_updater.exe,vcruntime140.dll}', { base: 'build/win32' }) .pipe(vfs.dest(path.join(buildPath(arch), 'tools'))); }; } /** * @param {string} executablePath */ function updateIcon(executablePath) { return cb => { const icon = path.join(repoPath, 'resources', 'win32', 'code.ico'); rcedit(executablePath, { icon }, cb); }; } gulp.task(task.define('vscode-win32-ia32-inno-updater', task.series(copyInnoUpdater('ia32'), updateIcon(path.join(buildPath('ia32'), 'tools', 'inno_updater.exe'))))); gulp.task(task.define('vscode-win32-x64-inno-updater', task.series(copyInnoUpdater('x64'), updateIcon(path.join(buildPath('x64'), 'tools', 'inno_updater.exe'))))); gulp.task(task.define('vscode-win32-arm64-inno-updater', task.series(copyInnoUpdater('arm64'), updateIcon(path.join(buildPath('arm64'), 'tools', 'inno_updater.exe')))));
build/gulpfile.vscode.win32.js
0
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.00018501780868973583, 0.00017155845125671476, 0.0001651206985116005, 0.00017119053518399596, 0.000004414989234646782 ]
{ "id": 4, "code_window": [ "\t\t\t\t`Microsoft.PowerShell.Archive\\\\Expand-Archive -Path \"${vscodeArchivePath}\" -DestinationPath \"${tempDir}\"`\n", "\t\t\t]);\n", "\t\t} else {\n", "\t\t\tcp.spawnSync('unzip', [vscodeArchivePath, '-d', `${tempDir}`]);\n", "\t\t}\n", "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin'), extractDir);\n", "\t} else {\n", "\t\t// tar does not create extractDir by default\n", "\t\tif (!fs.existsSync(extractDir)) {\n", "\t\t\tfs.mkdirSync(extractDir);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin-x64'), extractDir);\n" ], "file_path": "extensions/vscode-test-resolver/src/download.ts", "type": "replace", "edit_start_line_idx": 88 }
# VS Code Smoke Test Make sure you are on **Node v12.x**. ### Quick Overview ```bash # Build extensions in the VS Code repo (if needed) yarn && yarn compile # Dev (Electron) yarn smoketest # Dev (Web - Must be run on distro) yarn smoketest --web --browser [chromium|webkit] # Build (Electron) yarn smoketest --build <path to latest version> example: yarn smoketest --build /Applications/Visual\ Studio\ Code\ -\ Insiders.app # Build (Web - read instructions below) yarn smoketest --build <path to server web build (ends in -web)> --web --browser [chromium|webkit] # Remote (Electron - Must be run on distro) yarn smoketest --build <path to latest version> --remote ``` \* This step is necessary only when running without `--build` and OSS doesn't already exist in the `.build/electron` directory. ### Running for a release (Endgame) You must always run the smoketest version that matches the release you are testing. So, if you want to run the smoketest for a release build (e.g. `release/1.22`), you need to check out that version of the smoke tests too: ```bash git fetch git checkout release/1.22 yarn && yarn compile yarn --cwd test/smoke ``` #### Web There is no support for testing an old version to a new one yet. Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-web` for macOS). The server web build is available from the builds page (see previous subsection). **macOS**: if you have downloaded the server with web bits, make sure to run the following command before unzipping it to avoid security issues on startup: ```bash xattr -d com.apple.quarantine <path to server with web folder zip> ``` **Note**: make sure to point to the server that includes the client bits! ### Debug - `--verbose` logs all the low level driver calls made to Code; - `-f PATTERN` (alias `-g PATTERN`) filters the tests to be run. You can also use pretty much any mocha argument; - `--headless` will run playwright in headless mode when `--web` is used. **Note**: you can enable verbose logging of playwright library by setting a `DEBUG` environment variable before running the tests (https://playwright.dev/docs/debug#verbose-api-logs) ### Develop ```bash cd test/smoke yarn watch ``` ## Troubleshooting ### Error: Could not get a unique tmp filename, max tries reached On Windows, check for the folder `C:\Users\<username>\AppData\Local\Temp\t`. If this folder exists, the `tmp` module can't run properly, resulting in the error above. In this case, delete the `t` folder. ## Pitfalls - Beware of workbench **state**. The tests within a single suite will share the same state. - Beware of **singletons**. This evil can, and will, manifest itself under the form of FS paths, TCP ports, IPC handles. Whenever writing a test, or setting up more smoke test architecture, make sure it can run simultaneously with any other tests and even itself. All test suites should be able to run many times in parallel. - Beware of **focus**. **Never** depend on DOM elements having focus using `.focused` classes or `:focus` pseudo-classes, since they will lose that state as soon as another window appears on top of the running VS Code window. A safe approach which avoids this problem is to use the `waitForActiveElement` API. Many tests use this whenever they need to wait for a specific element to _have focus_. - Beware of **timing**. You need to read from or write to the DOM... but is it the right time to do that? Can you 100% guarantee that `input` box will be visible at that point in time? Or are you just hoping that it will be so? Hope is your worst enemy in UI tests. Example: just because you triggered Quick Access with `F1`, it doesn't mean that it's open and you can just start typing; you must first wait for the input element to be in the DOM as well as be the current active element. - Beware of **waiting**. **Never** wait longer than a couple of seconds for anything, unless it's justified. Think of it as a human using Code. Would a human take 10 minutes to run through the Search viewlet smoke test? Then, the computer should even be faster. **Don't** use `setTimeout` just because. Think about what you should wait for in the DOM to be ready and wait for that instead.
test/smoke/README.md
1
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.00047860239283181727, 0.0002007699804380536, 0.00016016005247365683, 0.00016635826614219695, 0.00009829227201407775 ]
{ "id": 4, "code_window": [ "\t\t\t\t`Microsoft.PowerShell.Archive\\\\Expand-Archive -Path \"${vscodeArchivePath}\" -DestinationPath \"${tempDir}\"`\n", "\t\t\t]);\n", "\t\t} else {\n", "\t\t\tcp.spawnSync('unzip', [vscodeArchivePath, '-d', `${tempDir}`]);\n", "\t\t}\n", "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin'), extractDir);\n", "\t} else {\n", "\t\t// tar does not create extractDir by default\n", "\t\tif (!fs.existsSync(extractDir)) {\n", "\t\t\tfs.mkdirSync(extractDir);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin-x64'), extractDir);\n" ], "file_path": "extensions/vscode-test-resolver/src/download.ts", "type": "replace", "edit_start_line_idx": 88 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "title": "HTML contributions to package.json", "type": "object", "properties": { "contributes": { "type": "object", "properties": { "html.customData": { "type": "array", "markdownDescription": "A list of relative file paths pointing to JSON files following the [custom data format](https://github.com/microsoft/vscode-html-languageservice/blob/master/docs/customData.md).\n\nVS Code loads custom data on startup to enhance its HTML support for the custom HTML tags, attributes and attribute values you specify in the JSON files.\n\nThe file paths are relative to workspace and only workspace folder settings are considered.", "items": { "type": "string", "description": "Relative path to a HTML custom data file" } } } } } }
extensions/html-language-features/schemas/package.schema.json
0
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.00017171278886962682, 0.00016853045963216573, 0.00016583973774686456, 0.00016803891048766673, 0.0000024227274479926564 ]
{ "id": 4, "code_window": [ "\t\t\t\t`Microsoft.PowerShell.Archive\\\\Expand-Archive -Path \"${vscodeArchivePath}\" -DestinationPath \"${tempDir}\"`\n", "\t\t\t]);\n", "\t\t} else {\n", "\t\t\tcp.spawnSync('unzip', [vscodeArchivePath, '-d', `${tempDir}`]);\n", "\t\t}\n", "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin'), extractDir);\n", "\t} else {\n", "\t\t// tar does not create extractDir by default\n", "\t\tif (!fs.existsSync(extractDir)) {\n", "\t\t\tfs.mkdirSync(extractDir);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin-x64'), extractDir);\n" ], "file_path": "extensions/vscode-test-resolver/src/download.ts", "type": "replace", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { deepStrictEqual } from 'assert'; import { TestExtensionService, TestStorageService } from 'vs/workbench/test/common/workbenchTestServices'; import { EnvironmentVariableService } from 'vs/workbench/contrib/terminal/common/environmentVariableService'; import { EnvironmentVariableMutatorType, IEnvironmentVariableMutator } from 'vs/workbench/contrib/terminal/common/environmentVariable'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { Emitter } from 'vs/base/common/event'; import { IProcessEnvironment } from 'vs/base/common/platform'; class TestEnvironmentVariableService extends EnvironmentVariableService { persistCollections(): void { this._persistCollections(); } notifyCollectionUpdates(): void { this._notifyCollectionUpdates(); } } suite('EnvironmentVariable - EnvironmentVariableService', () => { let instantiationService: TestInstantiationService; let environmentVariableService: TestEnvironmentVariableService; let storageService: TestStorageService; let changeExtensionsEvent: Emitter<void>; setup(() => { changeExtensionsEvent = new Emitter<void>(); instantiationService = new TestInstantiationService(); instantiationService.stub(IExtensionService, TestExtensionService); storageService = new TestStorageService(); instantiationService.stub(IStorageService, storageService); instantiationService.stub(IExtensionService, TestExtensionService); instantiationService.stub(IExtensionService, 'onDidChangeExtensions', changeExtensionsEvent.event); instantiationService.stub(IExtensionService, 'getExtensions', [ { identifier: { value: 'ext1' } }, { identifier: { value: 'ext2' } }, { identifier: { value: 'ext3' } } ]); environmentVariableService = instantiationService.createInstance(TestEnvironmentVariableService); }); test('should persist collections to the storage service and be able to restore from them', () => { const collection = new Map<string, IEnvironmentVariableMutator>(); collection.set('A', { value: 'a', type: EnvironmentVariableMutatorType.Replace }); collection.set('B', { value: 'b', type: EnvironmentVariableMutatorType.Append }); collection.set('C', { value: 'c', type: EnvironmentVariableMutatorType.Prepend }); environmentVariableService.set('ext1', { map: collection, persistent: true }); deepStrictEqual([...environmentVariableService.mergedCollection.map.entries()], [ ['A', [{ extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Replace, value: 'a' }]], ['B', [{ extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Append, value: 'b' }]], ['C', [{ extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Prepend, value: 'c' }]] ]); // Persist with old service, create a new service with the same storage service to verify restore environmentVariableService.persistCollections(); const service2: TestEnvironmentVariableService = instantiationService.createInstance(TestEnvironmentVariableService); deepStrictEqual([...service2.mergedCollection.map.entries()], [ ['A', [{ extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Replace, value: 'a' }]], ['B', [{ extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Append, value: 'b' }]], ['C', [{ extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Prepend, value: 'c' }]] ]); }); suite('mergedCollection', () => { test('should overwrite any other variable with the first extension that replaces', () => { const collection1 = new Map<string, IEnvironmentVariableMutator>(); const collection2 = new Map<string, IEnvironmentVariableMutator>(); const collection3 = new Map<string, IEnvironmentVariableMutator>(); collection1.set('A', { value: 'a1', type: EnvironmentVariableMutatorType.Append }); collection1.set('B', { value: 'b1', type: EnvironmentVariableMutatorType.Replace }); collection2.set('A', { value: 'a2', type: EnvironmentVariableMutatorType.Replace }); collection2.set('B', { value: 'b2', type: EnvironmentVariableMutatorType.Append }); collection3.set('A', { value: 'a3', type: EnvironmentVariableMutatorType.Prepend }); collection3.set('B', { value: 'b3', type: EnvironmentVariableMutatorType.Replace }); environmentVariableService.set('ext1', { map: collection1, persistent: true }); environmentVariableService.set('ext2', { map: collection2, persistent: true }); environmentVariableService.set('ext3', { map: collection3, persistent: true }); deepStrictEqual([...environmentVariableService.mergedCollection.map.entries()], [ ['A', [ { extensionIdentifier: 'ext2', type: EnvironmentVariableMutatorType.Replace, value: 'a2' }, { extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Append, value: 'a1' } ]], ['B', [{ extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Replace, value: 'b1' }]] ]); }); test('should correctly apply the environment values from multiple extension contributions in the correct order', () => { const collection1 = new Map<string, IEnvironmentVariableMutator>(); const collection2 = new Map<string, IEnvironmentVariableMutator>(); const collection3 = new Map<string, IEnvironmentVariableMutator>(); collection1.set('A', { value: ':a1', type: EnvironmentVariableMutatorType.Append }); collection2.set('A', { value: 'a2:', type: EnvironmentVariableMutatorType.Prepend }); collection3.set('A', { value: 'a3', type: EnvironmentVariableMutatorType.Replace }); environmentVariableService.set('ext1', { map: collection1, persistent: true }); environmentVariableService.set('ext2', { map: collection2, persistent: true }); environmentVariableService.set('ext3', { map: collection3, persistent: true }); // The entries should be ordered in the order they are applied deepStrictEqual([...environmentVariableService.mergedCollection.map.entries()], [ ['A', [ { extensionIdentifier: 'ext3', type: EnvironmentVariableMutatorType.Replace, value: 'a3' }, { extensionIdentifier: 'ext2', type: EnvironmentVariableMutatorType.Prepend, value: 'a2:' }, { extensionIdentifier: 'ext1', type: EnvironmentVariableMutatorType.Append, value: ':a1' } ]] ]); // Verify the entries get applied to the environment as expected const env: IProcessEnvironment = { A: 'foo' }; environmentVariableService.mergedCollection.applyToProcessEnvironment(env); deepStrictEqual(env, { A: 'a2:a3:a1' }); }); }); });
src/vs/workbench/contrib/terminal/test/common/environmentVariableService.test.ts
0
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.00017757521709427238, 0.00017387059051543474, 0.00017015948833432049, 0.00017391028814017773, 0.000002073019913950702 ]
{ "id": 4, "code_window": [ "\t\t\t\t`Microsoft.PowerShell.Archive\\\\Expand-Archive -Path \"${vscodeArchivePath}\" -DestinationPath \"${tempDir}\"`\n", "\t\t\t]);\n", "\t\t} else {\n", "\t\t\tcp.spawnSync('unzip', [vscodeArchivePath, '-d', `${tempDir}`]);\n", "\t\t}\n", "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin'), extractDir);\n", "\t} else {\n", "\t\t// tar does not create extractDir by default\n", "\t\tif (!fs.existsSync(extractDir)) {\n", "\t\t\tfs.mkdirSync(extractDir);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tfs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin-x64'), extractDir);\n" ], "file_path": "extensions/vscode-test-resolver/src/download.ts", "type": "replace", "edit_start_line_idx": 88 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import 'mocha'; import * as vscode from 'vscode'; import MDDocumentSymbolProvider from '../features/documentSymbolProvider'; import MarkdownWorkspaceSymbolProvider, { WorkspaceMarkdownDocumentProvider } from '../features/workspaceSymbolProvider'; import { createNewMarkdownEngine } from './engine'; import { InMemoryDocument } from './inMemoryDocument'; const symbolProvider = new MDDocumentSymbolProvider(createNewMarkdownEngine()); suite('markdown.WorkspaceSymbolProvider', () => { test('Should not return anything for empty workspace', async () => { const provider = new MarkdownWorkspaceSymbolProvider(symbolProvider, new InMemoryWorkspaceMarkdownDocumentProvider([])); assert.deepStrictEqual(await provider.provideWorkspaceSymbols(''), []); }); test('Should return symbols from workspace with one markdown file', async () => { const testFileName = vscode.Uri.file('test.md'); const provider = new MarkdownWorkspaceSymbolProvider(symbolProvider, new InMemoryWorkspaceMarkdownDocumentProvider([ new InMemoryDocument(testFileName, `# header1\nabc\n## header2`) ])); const symbols = await provider.provideWorkspaceSymbols(''); assert.strictEqual(symbols.length, 2); assert.strictEqual(symbols[0].name, '# header1'); assert.strictEqual(symbols[1].name, '## header2'); }); test('Should return all content basic workspace', async () => { const fileNameCount = 10; const files: vscode.TextDocument[] = []; for (let i = 0; i < fileNameCount; ++i) { const testFileName = vscode.Uri.file(`test${i}.md`); files.push(new InMemoryDocument(testFileName, `# common\nabc\n## header${i}`)); } const provider = new MarkdownWorkspaceSymbolProvider(symbolProvider, new InMemoryWorkspaceMarkdownDocumentProvider(files)); const symbols = await provider.provideWorkspaceSymbols(''); assert.strictEqual(symbols.length, fileNameCount * 2); }); test('Should update results when markdown file changes symbols', async () => { const testFileName = vscode.Uri.file('test.md'); const workspaceFileProvider = new InMemoryWorkspaceMarkdownDocumentProvider([ new InMemoryDocument(testFileName, `# header1`, 1 /* version */) ]); const provider = new MarkdownWorkspaceSymbolProvider(symbolProvider, workspaceFileProvider); assert.strictEqual((await provider.provideWorkspaceSymbols('')).length, 1); // Update file workspaceFileProvider.updateDocument(new InMemoryDocument(testFileName, `# new header\nabc\n## header2`, 2 /* version */)); const newSymbols = await provider.provideWorkspaceSymbols(''); assert.strictEqual(newSymbols.length, 2); assert.strictEqual(newSymbols[0].name, '# new header'); assert.strictEqual(newSymbols[1].name, '## header2'); }); test('Should remove results when file is deleted', async () => { const testFileName = vscode.Uri.file('test.md'); const workspaceFileProvider = new InMemoryWorkspaceMarkdownDocumentProvider([ new InMemoryDocument(testFileName, `# header1`) ]); const provider = new MarkdownWorkspaceSymbolProvider(symbolProvider, workspaceFileProvider); assert.strictEqual((await provider.provideWorkspaceSymbols('')).length, 1); // delete file workspaceFileProvider.deleteDocument(testFileName); const newSymbols = await provider.provideWorkspaceSymbols(''); assert.strictEqual(newSymbols.length, 0); }); test('Should update results when markdown file is created', async () => { const testFileName = vscode.Uri.file('test.md'); const workspaceFileProvider = new InMemoryWorkspaceMarkdownDocumentProvider([ new InMemoryDocument(testFileName, `# header1`) ]); const provider = new MarkdownWorkspaceSymbolProvider(symbolProvider, workspaceFileProvider); assert.strictEqual((await provider.provideWorkspaceSymbols('')).length, 1); // Creat file workspaceFileProvider.createDocument(new InMemoryDocument(vscode.Uri.file('test2.md'), `# new header\nabc\n## header2`)); const newSymbols = await provider.provideWorkspaceSymbols(''); assert.strictEqual(newSymbols.length, 3); }); }); class InMemoryWorkspaceMarkdownDocumentProvider implements WorkspaceMarkdownDocumentProvider { private readonly _documents = new Map<string, vscode.TextDocument>(); constructor(documents: vscode.TextDocument[]) { for (const doc of documents) { this._documents.set(doc.fileName, doc); } } async getAllMarkdownDocuments() { return Array.from(this._documents.values()); } private readonly _onDidChangeMarkdownDocumentEmitter = new vscode.EventEmitter<vscode.TextDocument>(); public onDidChangeMarkdownDocument = this._onDidChangeMarkdownDocumentEmitter.event; private readonly _onDidCreateMarkdownDocumentEmitter = new vscode.EventEmitter<vscode.TextDocument>(); public onDidCreateMarkdownDocument = this._onDidCreateMarkdownDocumentEmitter.event; private readonly _onDidDeleteMarkdownDocumentEmitter = new vscode.EventEmitter<vscode.Uri>(); public onDidDeleteMarkdownDocument = this._onDidDeleteMarkdownDocumentEmitter.event; public updateDocument(document: vscode.TextDocument) { this._documents.set(document.fileName, document); this._onDidChangeMarkdownDocumentEmitter.fire(document); } public createDocument(document: vscode.TextDocument) { assert.ok(!this._documents.has(document.uri.fsPath)); this._documents.set(document.uri.fsPath, document); this._onDidCreateMarkdownDocumentEmitter.fire(document); } public deleteDocument(resource: vscode.Uri) { this._documents.delete(resource.fsPath); this._onDidDeleteMarkdownDocumentEmitter.fire(resource); } }
extensions/markdown-language-features/src/test/workspaceSymbolProvider.test.ts
0
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.00017685908824205399, 0.0001715072285151109, 0.0001642186543904245, 0.000172394749824889, 0.000003317455366413924 ]
{ "id": 5, "code_window": [ "#### Web\n", "\n", "There is no support for testing an old version to a new one yet.\n", "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-web` for macOS). The server web build is available from the builds page (see previous subsection).\n", "\n", "**macOS**: if you have downloaded the server with web bits, make sure to run the following command before unzipping it to avoid security issues on startup:\n", "\n", "```bash\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-x64-web` for macOS). The server web build is available from the builds page (see previous subsection).\n" ], "file_path": "test/smoke/README.md", "type": "replace", "edit_start_line_idx": 43 }
steps: - task: NodeTool@0 inputs: versionSpec: "16.x" - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode SecretsFilter: "github-distro-mixin-password,macos-developer-certificate,macos-developer-certificate-key" - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'universal')) - script: | set -e tar -xzf $(Build.ArtifactStagingDirectory)/compilation.tar.gz displayName: Extract compilation output condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'universal')) # Set up the credentials to retrieve distro repo and setup git persona # to create a merge commit for when we merge distro into oss - script: | set -e cat << EOF > ~/.netrc machine github.com login vscode password $(github-distro-mixin-password) EOF git config user.email "[email protected]" git config user.name "VSCode" displayName: Prepare tooling - script: | set -e git pull --no-rebase https://github.com/$(VSCODE_MIXIN_REPO).git $(node -p "require('./package.json').distro") displayName: Merge distro - script: | mkdir -p .build node build/azure-pipelines/common/computeNodeModulesCacheKey.js $VSCODE_ARCH $ENABLE_TERRAPIN > .build/yarnlockhash displayName: Prepare yarn cache flags - task: Cache@2 inputs: key: "nodeModules | $(Agent.OS) | .build/yarnlockhash" path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - script: | set -e tar -xzf .build/node_modules_cache/cache.tgz condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - script: | set -e npm install -g node-gyp@latest node-gyp --version displayName: Update node-gyp condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - script: | set -e npx https://aka.ms/enablesecurefeed standAlone timeoutInMinutes: 5 retryCountOnTaskFailure: 3 condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), eq(variables['ENABLE_TERRAPIN'], 'true')) displayName: Switch to Terrapin packages - script: | set -e export npm_config_arch=$(VSCODE_ARCH) export npm_config_node_gyp=$(which node-gyp) for i in {1..3}; do # try 3 times, for Terrapin yarn --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done env: ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - script: | set -e node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt mkdir -p .build/node_modules_cache tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive # This script brings in the right resources (images, icons, etc) based on the quality (insiders, stable, exploration) - script: | set -e node build/azure-pipelines/mixin displayName: Mix in quality - script: | set -e VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" \ yarn gulp vscode-darwin-$(VSCODE_ARCH)-min-ci displayName: Build client condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'universal')) - script: | set -e node build/azure-pipelines/mixin --server displayName: Mix in server quality - script: | set -e VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" \ yarn gulp vscode-reh-darwin-$(VSCODE_ARCH)-min-ci VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" \ yarn gulp vscode-reh-web-darwin-$(VSCODE_ARCH)-min-ci displayName: Build Server condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'universal')) - script: | set -e VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" \ yarn npm-run-all -lp "electron $(VSCODE_ARCH)" "playwright-install" displayName: Download Electron and Playwright condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'universal'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - download: current artifact: unsigned_vscode_client_darwin_x64_archive displayName: Download x64 artifact condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'universal')) - download: current artifact: unsigned_vscode_client_darwin_arm64_archive displayName: Download arm64 artifact condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'universal')) - script: | set -e cp $(Pipeline.Workspace)/unsigned_vscode_client_darwin_x64_archive/VSCode-darwin-x64.zip $(agent.builddirectory)/VSCode-darwin-x64.zip cp $(Pipeline.Workspace)/unsigned_vscode_client_darwin_arm64_archive/VSCode-darwin-arm64.zip $(agent.builddirectory)/VSCode-darwin-arm64.zip unzip $(agent.builddirectory)/VSCode-darwin-x64.zip -d $(agent.builddirectory)/VSCode-darwin-x64 unzip $(agent.builddirectory)/VSCode-darwin-arm64.zip -d $(agent.builddirectory)/VSCode-darwin-arm64 DEBUG=* node build/darwin/create-universal-app.js displayName: Create Universal App condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'universal')) # Setting hardened entitlements is a requirement for: # * Apple notarization # * Running tests on Big Sur (because Big Sur has additional security precautions) - script: | set -e security create-keychain -p pwd $(agent.tempdirectory)/buildagent.keychain security default-keychain -s $(agent.tempdirectory)/buildagent.keychain security unlock-keychain -p pwd $(agent.tempdirectory)/buildagent.keychain echo "$(macos-developer-certificate)" | base64 -D > $(agent.tempdirectory)/cert.p12 security import $(agent.tempdirectory)/cert.p12 -k $(agent.tempdirectory)/buildagent.keychain -P "$(macos-developer-certificate-key)" -T /usr/bin/codesign security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k pwd $(agent.tempdirectory)/buildagent.keychain VSCODE_ARCH=$(VSCODE_ARCH) DEBUG=electron-osx-sign* node build/darwin/sign.js displayName: Set Hardened Entitlements - script: | set -e ./scripts/test.sh --build --tfs "Unit Tests" displayName: Run unit tests (Electron) timeoutInMinutes: 15 condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e yarn test-node --build displayName: Run unit tests (node.js) timeoutInMinutes: 15 condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e DEBUG=*browser* yarn test-browser-no-install --sequential --build --browser chromium --browser webkit --tfs "Browser Unit Tests" displayName: Run unit tests (Browser, Chromium & Webkit) timeoutInMinutes: 30 condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | # Figure out the full absolute path of the product we just built # including the remote server and configure the integration tests # to run with these builds instead of running out of sources. set -e APP_ROOT=$(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) APP_NAME="`ls $APP_ROOT | head -n 1`" INTEGRATION_TEST_ELECTRON_PATH="$APP_ROOT/$APP_NAME/Contents/MacOS/Electron" \ VSCODE_REMOTE_SERVER_PATH="$(agent.builddirectory)/vscode-reh-darwin-$(VSCODE_ARCH)" \ ./scripts/test-integration.sh --build --tfs "Integration Tests" displayName: Run integration tests (Electron) timeoutInMinutes: 20 condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e VSCODE_REMOTE_SERVER_PATH="$(agent.builddirectory)/vscode-reh-web-darwin-$(VSCODE_ARCH)" \ ./scripts/test-web-integration.sh --browser webkit displayName: Run integration tests (Browser, Webkit) timeoutInMinutes: 20 condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e APP_ROOT=$(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) APP_NAME="`ls $APP_ROOT | head -n 1`" INTEGRATION_TEST_ELECTRON_PATH="$APP_ROOT/$APP_NAME/Contents/MacOS/Electron" \ VSCODE_REMOTE_SERVER_PATH="$(agent.builddirectory)/vscode-reh-darwin-$(VSCODE_ARCH)" \ ./scripts/test-remote-integration.sh displayName: Run integration tests (Remote) timeoutInMinutes: 20 condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e VSCODE_REMOTE_SERVER_PATH="$(agent.builddirectory)/vscode-reh-web-darwin-$(VSCODE_ARCH)" \ yarn smoketest-no-compile --web --headless timeoutInMinutes: 10 displayName: Run smoke tests (Browser, Chromium) condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e APP_ROOT=$(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) APP_NAME="`ls $APP_ROOT | head -n 1`" yarn smoketest-no-compile --build "$APP_ROOT/$APP_NAME" # Increased timeout because this test downloads stable code timeoutInMinutes: 20 displayName: Run smoke tests (Electron) condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e APP_ROOT=$(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) APP_NAME="`ls $APP_ROOT | head -n 1`" VSCODE_REMOTE_SERVER_PATH="$(agent.builddirectory)/vscode-reh-darwin-$(VSCODE_ARCH)" \ yarn smoketest-no-compile --build "$APP_ROOT/$APP_NAME" --remote timeoutInMinutes: 10 displayName: Run smoke tests (Remote) condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - task: PublishPipelineArtifact@0 inputs: artifactName: crash-dump-macos-$(VSCODE_ARCH) targetPath: .build/crashes displayName: "Publish Crash Reports" continueOnError: true condition: failed() # In order to properly symbolify above crash reports # (if any), we need the compiled native modules too - task: PublishPipelineArtifact@0 inputs: artifactName: node-modules-macos-$(VSCODE_ARCH) targetPath: node_modules displayName: "Publish Node Modules" continueOnError: true condition: failed() - task: PublishPipelineArtifact@0 inputs: artifactName: logs-macos-$(VSCODE_ARCH)-$(System.JobAttempt) targetPath: .build/logs displayName: "Publish Log Files" continueOnError: true condition: and(succeededOrFailed(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - task: PublishTestResults@2 displayName: Publish Tests Results inputs: testResultsFiles: "*-results.xml" searchFolder: "$(Build.ArtifactStagingDirectory)/test-results" condition: and(succeededOrFailed(), eq(variables['VSCODE_ARCH'], 'x64'), eq(variables['VSCODE_STEP_ON_IT'], 'false')) - script: | set -e pushd $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) && zip -r -X -y $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH).zip * && popd displayName: Archive build condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - script: | set -e # package Remote Extension Host pushd .. && mv vscode-reh-darwin-$(VSCODE_ARCH) vscode-server-darwin && zip -Xry vscode-server-darwin-$(VSCODE_ARCH).zip vscode-server-darwin && popd # package Remote Extension Host (Web) pushd .. && mv vscode-reh-web-darwin-$(VSCODE_ARCH) vscode-server-darwin-web && zip -Xry vscode-server-darwin-$(VSCODE_ARCH)-web.zip vscode-server-darwin-web && popd displayName: Prepare to publish servers condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal')) - publish: $(Agent.BuildDirectory)/VSCode-darwin-$(VSCODE_ARCH).zip artifact: unsigned_vscode_client_darwin_$(VSCODE_ARCH)_archive displayName: Publish client archive condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - publish: $(Agent.BuildDirectory)/vscode-server-darwin-$(VSCODE_ARCH).zip artifact: vscode_server_darwin_$(VSCODE_ARCH)_archive-unsigned displayName: Publish server archive condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal')) - publish: $(Agent.BuildDirectory)/vscode-server-darwin-$(VSCODE_ARCH)-web.zip artifact: vscode_web_darwin_$(VSCODE_ARCH)_archive-unsigned displayName: Publish web server archive condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal')) - task: AzureCLI@2 inputs: azureSubscription: "vscode-builds-subscription" scriptType: pscore scriptLocation: inlineScript addSpnToEnvironment: true inlineScript: | Write-Host "##vso[task.setvariable variable=AZURE_TENANT_ID]$env:tenantId" Write-Host "##vso[task.setvariable variable=AZURE_CLIENT_ID]$env:servicePrincipalId" Write-Host "##vso[task.setvariable variable=AZURE_CLIENT_SECRET;issecret=true]$env:servicePrincipalKey" - script: | set -e AZURE_STORAGE_ACCOUNT="ticino" \ AZURE_TENANT_ID="$(AZURE_TENANT_ID)" \ AZURE_CLIENT_ID="$(AZURE_CLIENT_ID)" \ AZURE_CLIENT_SECRET="$(AZURE_CLIENT_SECRET)" \ VSCODE_ARCH="$(VSCODE_ARCH)" \ node build/azure-pipelines/upload-configuration displayName: Upload configuration (for Bing settings search) condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64'), ne(variables['VSCODE_PUBLISH'], 'false')) continueOnError: true - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (client) inputs: BuildDropPath: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH) PackageName: Visual Studio Code condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal')) - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (client) artifact: vscode_client_darwin_$(VSCODE_ARCH)_sbom condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal')) - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (server) inputs: BuildDropPath: $(agent.builddirectory)/vscode-server-darwin PackageName: Visual Studio Code Server condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal')) - publish: $(agent.builddirectory)/vscode-server-darwin/_manifest displayName: Publish SBOM (server) artifact: vscode_server_darwin_$(VSCODE_ARCH)_sbom condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'universal'))
build/azure-pipelines/darwin/product-build-darwin.yml
1
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.0012885414762422442, 0.00026389912818558514, 0.00016592135943938047, 0.0001704459427855909, 0.00024060392752289772 ]
{ "id": 5, "code_window": [ "#### Web\n", "\n", "There is no support for testing an old version to a new one yet.\n", "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-web` for macOS). The server web build is available from the builds page (see previous subsection).\n", "\n", "**macOS**: if you have downloaded the server with web bits, make sure to run the following command before unzipping it to avoid security issues on startup:\n", "\n", "```bash\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-x64-web` for macOS). The server web build is available from the builds page (see previous subsection).\n" ], "file_path": "test/smoke/README.md", "type": "replace", "edit_start_line_idx": 43 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/theme-abyss/yarn.lock
0
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.0001646169985178858, 0.0001646169985178858, 0.0001646169985178858, 0.0001646169985178858, 0 ]
{ "id": 5, "code_window": [ "#### Web\n", "\n", "There is no support for testing an old version to a new one yet.\n", "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-web` for macOS). The server web build is available from the builds page (see previous subsection).\n", "\n", "**macOS**: if you have downloaded the server with web bits, make sure to run the following command before unzipping it to avoid security issues on startup:\n", "\n", "```bash\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-x64-web` for macOS). The server web build is available from the builds page (see previous subsection).\n" ], "file_path": "test/smoke/README.md", "type": "replace", "edit_start_line_idx": 43 }
src/vs/workbench/services/search/test/node/fixtures/examples/subfolder/anotherfolder/anotherfile.txt
0
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.0001670537021709606, 0.0001670537021709606, 0.0001670537021709606, 0.0001670537021709606, 0 ]
{ "id": 5, "code_window": [ "#### Web\n", "\n", "There is no support for testing an old version to a new one yet.\n", "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-web` for macOS). The server web build is available from the builds page (see previous subsection).\n", "\n", "**macOS**: if you have downloaded the server with web bits, make sure to run the following command before unzipping it to avoid security issues on startup:\n", "\n", "```bash\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Instead, simply configure the `--build` command line argument to point to the absolute path of the extracted server web build folder (e.g. `<rest of path here>/vscode-server-darwin-x64-web` for macOS). The server web build is available from the builds page (see previous subsection).\n" ], "file_path": "test/smoke/README.md", "type": "replace", "edit_start_line_idx": 43 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { MarkdownString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace, Uri } from 'vscode'; import { IJSONContribution, ISuggestionsCollector } from './jsonContributions'; import { XHRRequest } from 'request-light'; import { Location } from 'jsonc-parser'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); const USER_AGENT = 'Visual Studio Code'; export class BowerJSONContribution implements IJSONContribution { private topRanked = ['twitter', 'bootstrap', 'angular-1.1.6', 'angular-latest', 'angulerjs', 'd3', 'myjquery', 'jq', 'abcdef1234567890', 'jQuery', 'jquery-1.11.1', 'jquery', 'sushi-vanilla-x-data', 'font-awsome', 'Font-Awesome', 'font-awesome', 'fontawesome', 'html5-boilerplate', 'impress.js', 'homebrew', 'backbone', 'moment1', 'momentjs', 'moment', 'linux', 'animate.css', 'animate-css', 'reveal.js', 'jquery-file-upload', 'blueimp-file-upload', 'threejs', 'express', 'chosen', 'normalize-css', 'normalize.css', 'semantic', 'semantic-ui', 'Semantic-UI', 'modernizr', 'underscore', 'underscore1', 'material-design-icons', 'ionic', 'chartjs', 'Chart.js', 'nnnick-chartjs', 'select2-ng', 'select2-dist', 'phantom', 'skrollr', 'scrollr', 'less.js', 'leancss', 'parser-lib', 'hui', 'bootstrap-languages', 'async', 'gulp', 'jquery-pjax', 'coffeescript', 'hammer.js', 'ace', 'leaflet', 'jquery-mobile', 'sweetalert', 'typeahead.js', 'soup', 'typehead.js', 'sails', 'codeigniter2']; private xhr: XHRRequest; public constructor(xhr: XHRRequest) { this.xhr = xhr; } public getDocumentSelector(): DocumentSelector { return [{ language: 'json', scheme: '*', pattern: '**/bower.json' }, { language: 'json', scheme: '*', pattern: '**/.bower.json' }]; } private isEnabled() { return !!workspace.getConfiguration('npm').get('fetchOnlinePackageInfo'); } public collectDefaultSuggestions(_resource: Uri, collector: ISuggestionsCollector): Thenable<any> { const defaultValue = { 'name': '${1:name}', 'description': '${2:description}', 'authors': ['${3:author}'], 'version': '${4:1.0.0}', 'main': '${5:pathToMain}', 'dependencies': {} }; const proposal = new CompletionItem(localize('json.bower.default', 'Default bower.json')); proposal.kind = CompletionItemKind.Class; proposal.insertText = new SnippetString(JSON.stringify(defaultValue, null, '\t')); collector.add(proposal); return Promise.resolve(null); } public collectPropertySuggestions(_resource: Uri, location: Location, currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable<any> | null { if (!this.isEnabled()) { return null; } if ((location.matches(['dependencies']) || location.matches(['devDependencies']))) { if (currentWord.length > 0) { const queryUrl = 'https://registry.bower.io/packages/search/' + encodeURIComponent(currentWord); return this.xhr({ url: queryUrl, headers: { agent: USER_AGENT } }).then((success) => { if (success.status === 200) { try { const obj = JSON.parse(success.responseText); if (Array.isArray(obj)) { const results = <{ name: string; description: string }[]>obj; for (const result of results) { const name = result.name; const description = result.description || ''; const insertText = new SnippetString().appendText(JSON.stringify(name)); if (addValue) { insertText.appendText(': ').appendPlaceholder('latest'); if (!isLast) { insertText.appendText(','); } } const proposal = new CompletionItem(name); proposal.kind = CompletionItemKind.Property; proposal.insertText = insertText; proposal.filterText = JSON.stringify(name); proposal.documentation = description; collector.add(proposal); } collector.setAsIncomplete(); } } catch (e) { // ignore } } else { collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', success.responseText)); return 0; } return undefined; }, (error) => { collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', error.responseText)); return 0; }); } else { this.topRanked.forEach((name) => { const insertText = new SnippetString().appendText(JSON.stringify(name)); if (addValue) { insertText.appendText(': ').appendPlaceholder('latest'); if (!isLast) { insertText.appendText(','); } } const proposal = new CompletionItem(name); proposal.kind = CompletionItemKind.Property; proposal.insertText = insertText; proposal.filterText = JSON.stringify(name); proposal.documentation = ''; collector.add(proposal); }); collector.setAsIncomplete(); return Promise.resolve(null); } } return null; } public collectValueSuggestions(_resource: Uri, location: Location, collector: ISuggestionsCollector): Promise<any> | null { if (!this.isEnabled()) { return null; } if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) { // not implemented. Could be do done calling the bower command. Waiting for web API: https://github.com/bower/registry/issues/26 const proposal = new CompletionItem(localize('json.bower.latest.version', 'latest')); proposal.insertText = new SnippetString('"${1:latest}"'); proposal.filterText = '""'; proposal.kind = CompletionItemKind.Value; proposal.documentation = 'The latest version of the package'; collector.add(proposal); } return null; } public resolveSuggestion(_resource: Uri | undefined, item: CompletionItem): Thenable<CompletionItem | null> | null { if (item.kind === CompletionItemKind.Property && item.documentation === '') { let label = item.label; if (typeof label !== 'string') { label = label.label; } return this.getInfo(label).then(documentation => { if (documentation) { item.documentation = documentation; return item; } return null; }); } return null; } private getInfo(pack: string): Thenable<string | undefined> { const queryUrl = 'https://registry.bower.io/packages/' + encodeURIComponent(pack); return this.xhr({ url: queryUrl, headers: { agent: USER_AGENT } }).then((success) => { try { const obj = JSON.parse(success.responseText); if (obj && obj.url) { let url: string = obj.url; if (url.indexOf('git://') === 0) { url = url.substring(6); } if (url.length >= 4 && url.substr(url.length - 4) === '.git') { url = url.substring(0, url.length - 4); } return url; } } catch (e) { // ignore } return undefined; }, () => { return undefined; }); } public getInfoContribution(_resource: Uri, location: Location): Thenable<MarkdownString[] | null> | null { if (!this.isEnabled()) { return null; } if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) { const pack = location.path[location.path.length - 1]; if (typeof pack === 'string') { return this.getInfo(pack).then(documentation => { if (documentation) { const str = new MarkdownString(); str.appendText(documentation); return [str]; } return null; }); } } return null; } }
extensions/npm/src/features/bowerJSONContribution.ts
0
https://github.com/microsoft/vscode/commit/b4b5c4d97975212100f2a68f05f8d83394460c2d
[ 0.00017457330250181258, 0.00016996088379528373, 0.00016656826483085752, 0.000169669947354123, 0.000002302597749803681 ]
{ "id": 0, "code_window": [ "import expressWinston = require('express-winston');\n", "import * as winston from 'winston';\n", "import express = require('express');\n", "\n", "const app = express();\n", "\n", "// Logger with all options\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 3 }
// Type definitions for express-winston 3.0 // Project: https://github.com/bithavoc/express-winston#readme // Definitions by: Alex Brick <https://github.com/bricka> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import { ErrorRequestHandler, Handler, Request, Response } from 'express'; import * as winston from 'winston'; import * as Transport from 'winston-transport'; export interface FilterRequest extends Request { [other: string]: any; } export interface FilterResponse extends Response { [other: string]: any; } export type DynamicMetaFunction = (req: Request, res: Response, err: Error) => object; export type DynamicLevelFunction = (req: Request, res: Response, err: Error) => string; export type RequestFilter = (req: FilterRequest, propName: string) => any; export type ResponseFilter = (res: FilterResponse, propName: string) => any; export type RouteFilter = (req: Request, res: Response) => boolean; export type MessageTemplate = string | ((req: Request, res: Response) => string); export interface BaseLoggerOptions { baseMeta?: object; bodyBlacklist?: string[]; bodyWhitelist?: string[]; colorize?: boolean; dynamicMeta?: DynamicMetaFunction; expressFormat?: boolean; ignoreRoute?: RouteFilter; ignoredRoutes?: string[]; level?: string | DynamicLevelFunction; meta?: boolean; metaField?: string; msg?: MessageTemplate; requestFilter?: RequestFilter; requestWhitelist?: string[]; responseFilter?: ResponseFilter; responseWhitelist?: string[]; skip?: RouteFilter; statusLevels?: { error?: string; success?: string; warn?: string; }; } export interface LoggerOptionsWithTransports extends BaseLoggerOptions { transports: Transport[]; } export interface LoggerOptionsWithWinstonInstance extends BaseLoggerOptions { winstonInstance: winston.Logger; } export type LoggerOptions = LoggerOptionsWithTransports | LoggerOptionsWithWinstonInstance; export function logger(options: LoggerOptions): Handler; export interface BaseErrorLoggerOptions { baseMeta?: object; dynamicMeta?: DynamicMetaFunction; level?: string | DynamicLevelFunction; metaField?: string; msg?: MessageTemplate; requestFilter?: RequestFilter; requestWhitelist?: string[]; } export interface ErrorLoggerOptionsWithTransports extends BaseErrorLoggerOptions { transports: Transport[]; } export interface ErrorLoggerOptionsWithWinstonInstance extends BaseErrorLoggerOptions { winstonInstance: winston.Logger; } export type ErrorLoggerOptions = ErrorLoggerOptionsWithTransports | ErrorLoggerOptionsWithWinstonInstance; export function errorLogger(options: ErrorLoggerOptions): ErrorRequestHandler; export let requestWhitelist: string[]; export let bodyWhitelist: string[]; export let bodyBlacklist: string[]; export let responseWhitelist: string[]; export let ignoredRoutes: string[]; export let defaultRequestFilter: RequestFilter; export let defaultResponseFilter: ResponseFilter; export function defaultSkip(): boolean; export interface ExpressWinstonRequest extends Request { _routeWhitelists: { body: string[]; req: string[]; res: string[]; }; }
types/express-winston/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.018303722143173218, 0.004310965072363615, 0.0001668348122620955, 0.0008276661392301321, 0.005878405645489693 ]
{ "id": 0, "code_window": [ "import expressWinston = require('express-winston');\n", "import * as winston from 'winston';\n", "import express = require('express');\n", "\n", "const app = express();\n", "\n", "// Logger with all options\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 3 }
{ "extends": "dtslint/dt.json" }
types/lodash.first/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017143318837042898, 0.00017143318837042898, 0.00017143318837042898, 0.00017143318837042898, 0 ]
{ "id": 0, "code_window": [ "import expressWinston = require('express-winston');\n", "import * as winston from 'winston';\n", "import express = require('express');\n", "\n", "const app = express();\n", "\n", "// Logger with all options\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 3 }
import { mapKeys } from "lodash"; export default mapKeys;
types/lodash-es/mapKeys.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017458196089137346, 0.00017458196089137346, 0.00017458196089137346, 0.00017458196089137346, 0 ]
{ "id": 0, "code_window": [ "import expressWinston = require('express-winston');\n", "import * as winston from 'winston';\n", "import express = require('express');\n", "\n", "const app = express();\n", "\n", "// Logger with all options\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 3 }
// Type definitions for non-npm package Google Google Cloud Machine Learning Engine v1 1.0 // Project: https://cloud.google.com/ml/ // Definitions by: Bolisov Alexey <https://github.com/Bolisov> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 // IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://ml.googleapis.com/$discovery/rest?version=v1 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google Cloud Machine Learning Engine v1 */ function load(name: "ml", version: "v1"): PromiseLike<void>; function load(name: "ml", version: "v1", callback: () => any): void; const projects: ml.ProjectsResource; namespace ml { interface GoogleApi__HttpBody { /** The HTTP Content-Type string representing the content type of the body. */ contentType?: string; /** HTTP body binary data. */ data?: string; /** * Application specific response metadata. Must be set in the first response * for streaming APIs. */ extensions?: Array<Record<string, any>>; } interface GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric { /** The objective value at this training step. */ objectiveValue?: number; /** The global training step for this metric. */ trainingStep?: string; } interface GoogleCloudMlV1__AutoScaling { /** * Optional. The minimum number of nodes to allocate for this model. These * nodes are always up, starting from the time the model is deployed, so the * cost of operating this model will be at least * `rate` &#42; `min_nodes` &#42; number of hours since last billing cycle, * where `rate` is the cost per node-hour as documented in * [pricing](https://cloud.google.com/ml-engine/pricing#prediction_pricing), * even if no predictions are performed. There is additional cost for each * prediction performed. * * Unlike manual scaling, if the load gets too heavy for the nodes * that are up, the service will automatically add nodes to handle the * increased load as well as scale back as traffic drops, always maintaining * at least `min_nodes`. You will be charged for the time in which additional * nodes are used. * * If not specified, `min_nodes` defaults to 0, in which case, when traffic * to a model stops (and after a cool-down period), nodes will be shut down * and no charges will be incurred until traffic to the model resumes. */ minNodes?: number; } interface GoogleCloudMlV1__GetConfigResponse { /** The service account Cloud ML uses to access resources in the project. */ serviceAccount?: string; /** The project number for `service_account`. */ serviceAccountProject?: string; } interface GoogleCloudMlV1__HyperparameterOutput { /** * All recorded object metrics for this trial. This field is not currently * populated. */ allMetrics?: GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric[]; /** The final objective metric seen for this trial. */ finalMetric?: GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric; /** The hyperparameters given to this trial. */ hyperparameters?: Record<string, string>; /** The trial id for these results. */ trialId?: string; } interface GoogleCloudMlV1__HyperparameterSpec { /** * Required. The type of goal to use for tuning. Available types are * `MAXIMIZE` and `MINIMIZE`. * * Defaults to `MAXIMIZE`. */ goal?: string; /** * Optional. The Tensorflow summary tag name to use for optimizing trials. For * current versions of Tensorflow, this tag name should exactly match what is * shown in Tensorboard, including all scopes. For versions of Tensorflow * prior to 0.12, this should be only the tag passed to tf.Summary. * By default, "training/hptuning/metric" will be used. */ hyperparameterMetricTag?: string; /** * Optional. The number of training trials to run concurrently. * You can reduce the time it takes to perform hyperparameter tuning by adding * trials in parallel. However, each trail only benefits from the information * gained in completed trials. That means that a trial does not get access to * the results of trials running at the same time, which could reduce the * quality of the overall optimization. * * Each trial will use the same scale tier and machine types. * * Defaults to one. */ maxParallelTrials?: number; /** * Optional. How many training trials should be attempted to optimize * the specified hyperparameters. * * Defaults to one. */ maxTrials?: number; /** Required. The set of parameters to tune. */ params?: GoogleCloudMlV1__ParameterSpec[]; } interface GoogleCloudMlV1__Job { /** Output only. When the job was created. */ createTime?: string; /** Output only. When the job processing was completed. */ endTime?: string; /** Output only. The details of a failure or a cancellation. */ errorMessage?: string; /** Required. The user-specified id of the job. */ jobId?: string; /** Input parameters to create a prediction job. */ predictionInput?: GoogleCloudMlV1__PredictionInput; /** The current prediction job result. */ predictionOutput?: GoogleCloudMlV1__PredictionOutput; /** Output only. When the job processing was started. */ startTime?: string; /** Output only. The detailed state of a job. */ state?: string; /** Input parameters to create a training job. */ trainingInput?: GoogleCloudMlV1__TrainingInput; /** The current training job result. */ trainingOutput?: GoogleCloudMlV1__TrainingOutput; } interface GoogleCloudMlV1__ListJobsResponse { /** The list of jobs. */ jobs?: GoogleCloudMlV1__Job[]; /** * Optional. Pass this token as the `page_token` field of the request for a * subsequent call. */ nextPageToken?: string; } interface GoogleCloudMlV1__ListModelsResponse { /** The list of models. */ models?: GoogleCloudMlV1__Model[]; /** * Optional. Pass this token as the `page_token` field of the request for a * subsequent call. */ nextPageToken?: string; } interface GoogleCloudMlV1__ListVersionsResponse { /** * Optional. Pass this token as the `page_token` field of the request for a * subsequent call. */ nextPageToken?: string; /** The list of versions. */ versions?: GoogleCloudMlV1__Version[]; } interface GoogleCloudMlV1__ManualScaling { /** * The number of nodes to allocate for this model. These nodes are always up, * starting from the time the model is deployed, so the cost of operating * this model will be proportional to `nodes` &#42; number of hours since * last billing cycle plus the cost for each prediction performed. */ nodes?: number; } interface GoogleCloudMlV1__Model { /** * Output only. The default version of the model. This version will be used to * handle prediction requests that do not specify a version. * * You can change the default version by calling * [projects.methods.versions.setDefault](/ml-engine/reference/rest/v1/projects.models.versions/setDefault). */ defaultVersion?: GoogleCloudMlV1__Version; /** Optional. The description specified for the model when it was created. */ description?: string; /** * Required. The name specified for the model when it was created. * * The model name must be unique within the project it is created in. */ name?: string; /** * Optional. If true, enables StackDriver Logging for online prediction. * Default is false. */ onlinePredictionLogging?: boolean; /** * Optional. The list of regions where the model is going to be deployed. * Currently only one region per model is supported. * Defaults to 'us-central1' if nothing is set. * Note: * &#42; No matter where a model is deployed, it can always be accessed by * users from anywhere, both for online and batch prediction. * &#42; The region for a batch prediction job is set by the region field when * submitting the batch prediction job and does not take its value from * this field. */ regions?: string[]; } interface GoogleCloudMlV1__OperationMetadata { /** The time the operation was submitted. */ createTime?: string; /** The time operation processing completed. */ endTime?: string; /** Indicates whether a request to cancel this operation has been made. */ isCancellationRequested?: boolean; /** Contains the name of the model associated with the operation. */ modelName?: string; /** The operation type. */ operationType?: string; /** The time operation processing started. */ startTime?: string; /** Contains the version associated with the operation. */ version?: GoogleCloudMlV1__Version; } interface GoogleCloudMlV1__ParameterSpec { /** Required if type is `CATEGORICAL`. The list of possible categories. */ categoricalValues?: string[]; /** * Required if type is `DISCRETE`. * A list of feasible points. * The list should be in strictly increasing order. For instance, this * parameter might have possible settings of 1.5, 2.5, and 4.0. This list * should not contain more than 1,000 values. */ discreteValues?: number[]; /** * Required if typeis `DOUBLE` or `INTEGER`. This field * should be unset if type is `CATEGORICAL`. This value should be integers if * type is `INTEGER`. */ maxValue?: number; /** * Required if type is `DOUBLE` or `INTEGER`. This field * should be unset if type is `CATEGORICAL`. This value should be integers if * type is INTEGER. */ minValue?: number; /** * Required. The parameter name must be unique amongst all ParameterConfigs in * a HyperparameterSpec message. E.g., "learning_rate". */ parameterName?: string; /** * Optional. How the parameter should be scaled to the hypercube. * Leave unset for categorical parameters. * Some kind of scaling is strongly recommended for real or integral * parameters (e.g., `UNIT_LINEAR_SCALE`). */ scaleType?: string; /** Required. The type of the parameter. */ type?: string; } interface GoogleCloudMlV1__PredictRequest { /** Required. The prediction request body. */ httpBody?: GoogleApi__HttpBody; } interface GoogleCloudMlV1__PredictionInput { /** * Optional. Number of records per batch, defaults to 64. * The service will buffer batch_size number of records in memory before * invoking one Tensorflow prediction call internally. So take the record * size and memory available into consideration when setting this parameter. */ batchSize?: string; /** Required. The format of the input data files. */ dataFormat?: string; /** * Required. The Google Cloud Storage location of the input data files. * May contain wildcards. */ inputPaths?: string[]; /** * Optional. The maximum number of workers to be used for parallel processing. * Defaults to 10 if not specified. */ maxWorkerCount?: string; /** * Use this field if you want to use the default version for the specified * model. The string must use the following format: * * `"projects/<var>[YOUR_PROJECT]</var>/models/<var>[YOUR_MODEL]</var>"` */ modelName?: string; /** Required. The output Google Cloud Storage location. */ outputPath?: string; /** Required. The Google Compute Engine region to run the prediction job in. */ region?: string; /** * Optional. The Google Cloud ML runtime version to use for this batch * prediction. If not set, Google Cloud ML will pick the runtime version used * during the CreateVersion request for this model version, or choose the * latest stable version when model version information is not available * such as when the model is specified by uri. */ runtimeVersion?: string; /** * Use this field if you want to specify a Google Cloud Storage path for * the model to use. */ uri?: string; /** * Use this field if you want to specify a version of the model to use. The * string is formatted the same way as `model_version`, with the addition * of the version information: * * `"projects/<var>[YOUR_PROJECT]</var>/models/<var>YOUR_MODEL/versions/<var>[YOUR_VERSION]</var>"` */ versionName?: string; } interface GoogleCloudMlV1__PredictionOutput { /** The number of data instances which resulted in errors. */ errorCount?: string; /** Node hours used by the batch prediction job. */ nodeHours?: number; /** The output Google Cloud Storage location provided at the job creation time. */ outputPath?: string; /** The number of generated predictions. */ predictionCount?: string; } interface GoogleCloudMlV1__TrainingInput { /** Optional. Command line arguments to pass to the program. */ args?: string[]; /** Optional. The set of Hyperparameters to tune. */ hyperparameters?: GoogleCloudMlV1__HyperparameterSpec; /** * Optional. A Google Cloud Storage path in which to store training outputs * and other data needed for training. This path is passed to your TensorFlow * program as the 'job_dir' command-line argument. The benefit of specifying * this field is that Cloud ML validates the path for use in training. */ jobDir?: string; /** * Optional. Specifies the type of virtual machine to use for your training * job's master worker. * * The following types are supported: * * <dl> * <dt>standard</dt> * <dd> * A basic machine configuration suitable for training simple models with * small to moderate datasets. * </dd> * <dt>large_model</dt> * <dd> * A machine with a lot of memory, specially suited for parameter servers * when your model is large (having many hidden layers or layers with very * large numbers of nodes). * </dd> * <dt>complex_model_s</dt> * <dd> * A machine suitable for the master and workers of the cluster when your * model requires more computation than the standard machine can handle * satisfactorily. * </dd> * <dt>complex_model_m</dt> * <dd> * A machine with roughly twice the number of cores and roughly double the * memory of <code suppresswarning="true">complex_model_s</code>. * </dd> * <dt>complex_model_l</dt> * <dd> * A machine with roughly twice the number of cores and roughly double the * memory of <code suppresswarning="true">complex_model_m</code>. * </dd> * <dt>standard_gpu</dt> * <dd> * A machine equivalent to <code suppresswarning="true">standard</code> that * also includes a * <a href="/ml-engine/docs/how-tos/using-gpus"> * GPU that you can use in your trainer</a>. * </dd> * <dt>complex_model_m_gpu</dt> * <dd> * A machine equivalent to * <code suppresswarning="true">complex_model_m</code> that also includes * four GPUs. * </dd> * </dl> * * You must set this value when `scaleTier` is set to `CUSTOM`. */ masterType?: string; /** * Required. The Google Cloud Storage location of the packages with * the training program and any additional dependencies. * The maximum number of package URIs is 100. */ packageUris?: string[]; /** * Optional. The number of parameter server replicas to use for the training * job. Each replica in the cluster will be of the type specified in * `parameter_server_type`. * * This value can only be used when `scale_tier` is set to `CUSTOM`.If you * set this value, you must also set `parameter_server_type`. */ parameterServerCount?: string; /** * Optional. Specifies the type of virtual machine to use for your training * job's parameter server. * * The supported values are the same as those described in the entry for * `master_type`. * * This value must be present when `scaleTier` is set to `CUSTOM` and * `parameter_server_count` is greater than zero. */ parameterServerType?: string; /** Required. The Python module name to run after installing the packages. */ pythonModule?: string; /** Required. The Google Compute Engine region to run the training job in. */ region?: string; /** * Optional. The Google Cloud ML runtime version to use for training. If not * set, Google Cloud ML will choose the latest stable version. */ runtimeVersion?: string; /** * Required. Specifies the machine types, the number of replicas for workers * and parameter servers. */ scaleTier?: string; /** * Optional. The number of worker replicas to use for the training job. Each * replica in the cluster will be of the type specified in `worker_type`. * * This value can only be used when `scale_tier` is set to `CUSTOM`. If you * set this value, you must also set `worker_type`. */ workerCount?: string; /** * Optional. Specifies the type of virtual machine to use for your training * job's worker nodes. * * The supported values are the same as those described in the entry for * `masterType`. * * This value must be present when `scaleTier` is set to `CUSTOM` and * `workerCount` is greater than zero. */ workerType?: string; } interface GoogleCloudMlV1__TrainingOutput { /** * The number of hyperparameter tuning trials that completed successfully. * Only set for hyperparameter tuning jobs. */ completedTrialCount?: string; /** The amount of ML units consumed by the job. */ consumedMLUnits?: number; /** Whether this job is a hyperparameter tuning job. */ isHyperparameterTuningJob?: boolean; /** * Results for individual Hyperparameter trials. * Only set for hyperparameter tuning jobs. */ trials?: GoogleCloudMlV1__HyperparameterOutput[]; } interface GoogleCloudMlV1__Version { /** * Automatically scale the number of nodes used to serve the model in * response to increases and decreases in traffic. Care should be * taken to ramp up traffic according to the model's ability to scale * or you will start seeing increases in latency and 429 response codes. */ autoScaling?: GoogleCloudMlV1__AutoScaling; /** Output only. The time the version was created. */ createTime?: string; /** * Required. The Google Cloud Storage location of the trained model used to * create the version. See the * [overview of model * deployment](/ml-engine/docs/concepts/deployment-overview) for more * information. * * When passing Version to * [projects.models.versions.create](/ml-engine/reference/rest/v1/projects.models.versions/create) * the model service uses the specified location as the source of the model. * Once deployed, the model version is hosted by the prediction service, so * this location is useful only as a historical record. * The total number of model files can't exceed 1000. */ deploymentUri?: string; /** Optional. The description specified for the version when it was created. */ description?: string; /** Output only. The details of a failure or a cancellation. */ errorMessage?: string; /** * Output only. If true, this version will be used to handle prediction * requests that do not specify a version. * * You can change the default version by calling * [projects.methods.versions.setDefault](/ml-engine/reference/rest/v1/projects.models.versions/setDefault). */ isDefault?: boolean; /** Output only. The time the version was last used for prediction. */ lastUseTime?: string; /** * Manually select the number of nodes to use for serving the * model. You should generally use `auto_scaling` with an appropriate * `min_nodes` instead, but this option is available if you want more * predictable billing. Beware that latency and error rates will increase * if the traffic exceeds that capability of the system to serve it based * on the selected number of nodes. */ manualScaling?: GoogleCloudMlV1__ManualScaling; /** * Required.The name specified for the version when it was created. * * The version name must be unique within the model it is created in. */ name?: string; /** * Optional. The Google Cloud ML runtime version to use for this deployment. * If not set, Google Cloud ML will choose a version. */ runtimeVersion?: string; /** Output only. The state of a version. */ state?: string; } interface GoogleIamV1__AuditConfig { /** * The configuration for logging of each type of permission. * Next ID: 4 */ auditLogConfigs?: GoogleIamV1__AuditLogConfig[]; exemptedMembers?: string[]; /** * Specifies a service that will be enabled for audit logging. * For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. * `allServices` is a special value that covers all services. */ service?: string; } interface GoogleIamV1__AuditLogConfig { /** * Specifies the identities that do not cause logging for this type of * permission. * Follows the same format of Binding.members. */ exemptedMembers?: string[]; /** The log type that this config enables. */ logType?: string; } interface GoogleIamV1__Binding { /** * The condition that is associated with this binding. * NOTE: an unsatisfied condition will not allow user access via current * binding. Different bindings, including their conditions, are examined * independently. * This field is GOOGLE_INTERNAL. */ condition?: GoogleType__Expr; /** * Specifies the identities requesting access for a Cloud Platform resource. * `members` can have the following values: * * &#42; `allUsers`: A special identifier that represents anyone who is * on the internet; with or without a Google account. * * &#42; `allAuthenticatedUsers`: A special identifier that represents anyone * who is authenticated with a Google account or a service account. * * &#42; `user:{emailid}`: An email address that represents a specific Google * account. For example, `[email protected]` or `[email protected]`. * * * &#42; `serviceAccount:{emailid}`: An email address that represents a service * account. For example, `[email protected]`. * * &#42; `group:{emailid}`: An email address that represents a Google group. * For example, `[email protected]`. * * * &#42; `domain:{domain}`: A Google Apps domain name that represents all the * users of that domain. For example, `google.com` or `example.com`. */ members?: string[]; /** * Role that is assigned to `members`. * For example, `roles/viewer`, `roles/editor`, or `roles/owner`. * Required */ role?: string; } interface GoogleIamV1__Policy { /** Specifies cloud audit logging configuration for this policy. */ auditConfigs?: GoogleIamV1__AuditConfig[]; /** * Associates a list of `members` to a `role`. * `bindings` with no members will result in an error. */ bindings?: GoogleIamV1__Binding[]; /** * `etag` is used for optimistic concurrency control as a way to help * prevent simultaneous updates of a policy from overwriting each other. * It is strongly suggested that systems make use of the `etag` in the * read-modify-write cycle to perform policy updates in order to avoid race * conditions: An `etag` is returned in the response to `getIamPolicy`, and * systems are expected to put that etag in the request to `setIamPolicy` to * ensure that their change will be applied to the same version of the policy. * * If no `etag` is provided in the call to `setIamPolicy`, then the existing * policy is overwritten blindly. */ etag?: string; iamOwned?: boolean; /** Version of the `Policy`. The default version is 0. */ version?: number; } interface GoogleIamV1__SetIamPolicyRequest { /** * REQUIRED: The complete policy to be applied to the `resource`. The size of * the policy is limited to a few 10s of KB. An empty policy is a * valid policy but certain Cloud Platform services (such as Projects) * might reject them. */ policy?: GoogleIamV1__Policy; /** * OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only * the fields in the mask will be modified. If no mask is provided, the * following default mask is used: * paths: "bindings, etag" * This field is only used by Cloud IAM. */ updateMask?: string; } interface GoogleIamV1__TestIamPermissionsRequest { /** * The set of permissions to check for the `resource`. Permissions with * wildcards (such as '&#42;' or 'storage.&#42;') are not allowed. For more * information see * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). */ permissions?: string[]; } interface GoogleIamV1__TestIamPermissionsResponse { /** * A subset of `TestPermissionsRequest.permissions` that the caller is * allowed. */ permissions?: string[]; } interface GoogleLongrunning__ListOperationsResponse { /** The standard List next-page token. */ nextPageToken?: string; /** A list of operations that matches the specified filter in the request. */ operations?: GoogleLongrunning__Operation[]; } interface GoogleLongrunning__Operation { /** * If the value is `false`, it means the operation is still in progress. * If `true`, the operation is completed, and either `error` or `response` is * available. */ done?: boolean; /** The error result of the operation in case of failure or cancellation. */ error?: GoogleRpc__Status; /** * Service-specific metadata associated with the operation. It typically * contains progress information and common metadata such as create time. * Some services might not provide such metadata. Any method that returns a * long-running operation should document the metadata type, if any. */ metadata?: Record<string, any>; /** * The server-assigned name, which is only unique within the same service that * originally returns it. If you use the default HTTP mapping, the * `name` should have the format of `operations/some/unique/name`. */ name?: string; /** * The normal response of the operation in case of success. If the original * method returns no data on success, such as `Delete`, the response is * `google.protobuf.Empty`. If the original method is standard * `Get`/`Create`/`Update`, the response should be the resource. For other * methods, the response should have the type `XxxResponse`, where `Xxx` * is the original method name. For example, if the original method name * is `TakeSnapshot()`, the inferred response type is * `TakeSnapshotResponse`. */ response?: Record<string, any>; } interface GoogleRpc__Status { /** The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: Array<Record<string, any>>; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } interface GoogleType__Expr { /** * An optional description of the expression. This is a longer text which * describes the expression, e.g. when hovered over it in a UI. */ description?: string; /** * Textual representation of an expression in * Common Expression Language syntax. * * The application context of the containing message determines which * well-known feature set of CEL is supported. */ expression?: string; /** * An optional string indicating the location of the expression for error * reporting, e.g. a file name and a position in the file. */ location?: string; /** * An optional title for the expression, i.e. a short string describing * its purpose. This can be used e.g. in UIs which allow to enter the * expression. */ title?: string; } interface JobsResource { /** Cancels a running job. */ cancel(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the job to cancel. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** Creates a training or a batch prediction job. */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Required. The project name. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Job>; /** Describes a job. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the job to get the description of. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Job>; /** * Gets the access control policy for a resource. * Returns an empty policy if the resource exists and does not have a policy * set. */ getIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** Lists the jobs in the project. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Optional. Specifies the subset of jobs to retrieve. */ filter?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Optional. The number of jobs to retrieve per "page" of results. If there * are more remaining results than this number, the response message will * contain a valid value in the `next_page_token` field. * * The default value is 20, and the maximum page size is 100. */ pageSize?: number; /** * Optional. A page token to request the next page of results. * * You get the token from the `next_page_token` field of the response from * the previous call. */ pageToken?: string; /** Required. The name of the project for which to list jobs. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__ListJobsResponse>; /** * Sets the access control policy on the specified resource. Replaces any * existing policy. */ setIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being specified. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** * Returns permissions that a caller has on the specified resource. * If the resource does not exist, this will return an empty set of * permissions, not a NOT_FOUND error. * * Note: This operation is designed to be used for building permission-aware * UIs and command-line tools, not for authorization checking. This operation * may "fail open" without warning. */ testIamPermissions(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy detail is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__TestIamPermissionsResponse>; } interface VersionsResource { /** * Creates a new version of a model from a trained TensorFlow model. * * If the version created in the cloud by this call is the first deployed * version of the specified model, it will be made the default version of the * model. When you add a version to a model that already has one or more * versions, the default version does not automatically change. If you want a * new version to be the default, you must call * [projects.models.versions.setDefault](/ml-engine/reference/rest/v1/projects.models.versions/setDefault). */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Required. The name of the model. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Deletes a model version. * * Each model can have multiple versions deployed and in use at any given * time. Use this method to remove a single version. * * Note: You cannot delete the version that is set as the default version * of the model unless it is the only remaining version. */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Required. The name of the version. You can get the names of all the * versions of a model by calling * [projects.models.versions.list](/ml-engine/reference/rest/v1/projects.models.versions/list). */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Gets information about a model version. * * Models can have multiple versions. You can call * [projects.models.versions.list](/ml-engine/reference/rest/v1/projects.models.versions/list) * to get the same information that this method returns for all of the * versions of a model. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the version. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Version>; /** * Gets basic information about all the versions of a model. * * If you expect that a model has a lot of versions, or if you need to handle * only a limited number of results at a time, you can request that the list * be retrieved in batches (called pages): */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Optional. The number of versions to retrieve per "page" of results. If * there are more remaining results than this number, the response message * will contain a valid value in the `next_page_token` field. * * The default value is 20, and the maximum page size is 100. */ pageSize?: number; /** * Optional. A page token to request the next page of results. * * You get the token from the `next_page_token` field of the response from * the previous call. */ pageToken?: string; /** Required. The name of the model for which to list the version. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__ListVersionsResponse>; /** * Updates the specified Version resource. * * Currently the only supported field to update is `description`. */ patch(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the model. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Required. Specifies the path, relative to `Version`, of the field to * update. Must be present and non-empty. * * For example, to change the description of a version to "foo", the * `update_mask` parameter would be specified as `description`, and the * `PATCH` request body would specify the new value, as follows: * { * "description": "foo" * } * In this example, the version is blindly overwritten since no etag is given. * * To adopt etag mechanism, include `etag` field in the mask, and include the * `etag` value in your version resource. * * Currently the only supported update masks are `description`, `labels`, and * `etag`. */ updateMask?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Designates a version to be the default for the model. * * The default version is used for prediction requests made against the model * that don't specify a version. * * The first version to be created for a model is automatically set as the * default. You must make any subsequent changes to the default version * setting manually using this method. */ setDefault(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Required. The name of the version to make the default for the model. You * can get the names of all the versions of a model by calling * [projects.models.versions.list](/ml-engine/reference/rest/v1/projects.models.versions/list). */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Version>; } interface ModelsResource { /** * Creates a model which will later contain one or more versions. * * You must add at least one version before you can request predictions from * the model. Add versions by calling * [projects.models.versions.create](/ml-engine/reference/rest/v1/projects.models.versions/create). */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Required. The project name. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Model>; /** * Deletes a model. * * You can only delete a model if there are no versions in it. You can delete * versions by calling * [projects.models.versions.delete](/ml-engine/reference/rest/v1/projects.models.versions/delete). */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the model. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Gets information about a model, including its name, the description (if * set), and the default version (if at least one version of the model has * been deployed). */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the model. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Model>; /** * Gets the access control policy for a resource. * Returns an empty policy if the resource exists and does not have a policy * set. */ getIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** * Lists the models in a project. * * Each project can contain multiple models, and each model can have multiple * versions. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Optional. The number of models to retrieve per "page" of results. If there * are more remaining results than this number, the response message will * contain a valid value in the `next_page_token` field. * * The default value is 20, and the maximum page size is 100. */ pageSize?: number; /** * Optional. A page token to request the next page of results. * * You get the token from the `next_page_token` field of the response from * the previous call. */ pageToken?: string; /** Required. The name of the project whose models are to be listed. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__ListModelsResponse>; /** * Updates a specific model resource. * * Currently the only supported fields to update are `description` and * `default_version.name`. */ patch(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The project name. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Required. Specifies the path, relative to `Model`, of the field to update. * * For example, to change the description of a model to "foo" and set its * default version to "version_1", the `update_mask` parameter would be * specified as `description`, `default_version.name`, and the `PATCH` * request body would specify the new value, as follows: * { * "description": "foo", * "defaultVersion": { * "name":"version_1" * } * } * In this example, the model is blindly overwritten since no etag is given. * * To adopt etag mechanism, include `etag` field in the mask, and include the * `etag` value in your model resource. * * Currently the supported update masks are `description`, * `default_version.name`, `labels`, and `etag`. */ updateMask?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Sets the access control policy on the specified resource. Replaces any * existing policy. */ setIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being specified. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** * Returns permissions that a caller has on the specified resource. * If the resource does not exist, this will return an empty set of * permissions, not a NOT_FOUND error. * * Note: This operation is designed to be used for building permission-aware * UIs and command-line tools, not for authorization checking. This operation * may "fail open" without warning. */ testIamPermissions(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy detail is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__TestIamPermissionsResponse>; versions: VersionsResource; } interface OperationsResource { /** * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * Operations.GetOperation or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an Operation.error value with a google.rpc.Status.code of 1, * corresponding to `Code.CANCELLED`. */ cancel(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation resource to be cancelled. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation resource to be deleted. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation resource. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;/operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The standard list filter. */ filter?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation's parent resource. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The standard list page size. */ pageSize?: number; /** The standard list page token. */ pageToken?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__ListOperationsResponse>; } interface ProjectsResource { /** * Get the service account information associated with your project. You need * this information in order to grant the service account persmissions for * the Google Cloud Storage location where you put your model training code * for training the model with Google Cloud Machine Learning. */ getConfig(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The project name. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__GetConfigResponse>; /** * Performs prediction on the data in the request. * * &#42;&#42;&#42;&#42; REMOVE FROM GENERATED DOCUMENTATION */ predict(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Required. The resource name of a model or a version. * * Authorization: requires the `predict` permission on the specified resource. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleApi__HttpBody>; jobs: JobsResource; models: ModelsResource; operations: OperationsResource; } } }
types/gapi.client.ml/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00023532513296231627, 0.0001689599739620462, 0.00016258579853456467, 0.00016853050328791142, 0.000006269429377425695 ]
{ "id": 1, "code_window": [ " colorize: true,\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " expressFormat: true,\n", " ignoreRoute: (req, res) => true,\n", " ignoredRoutes: ['foo'],\n", " level: (req, res) => 'level',\n", " meta: true,\n", " metaField: 'metaField',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 14 }
// Type definitions for express-winston 3.0 // Project: https://github.com/bithavoc/express-winston#readme // Definitions by: Alex Brick <https://github.com/bricka> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import { ErrorRequestHandler, Handler, Request, Response } from 'express'; import * as winston from 'winston'; import * as Transport from 'winston-transport'; export interface FilterRequest extends Request { [other: string]: any; } export interface FilterResponse extends Response { [other: string]: any; } export type DynamicMetaFunction = (req: Request, res: Response, err: Error) => object; export type DynamicLevelFunction = (req: Request, res: Response, err: Error) => string; export type RequestFilter = (req: FilterRequest, propName: string) => any; export type ResponseFilter = (res: FilterResponse, propName: string) => any; export type RouteFilter = (req: Request, res: Response) => boolean; export type MessageTemplate = string | ((req: Request, res: Response) => string); export interface BaseLoggerOptions { baseMeta?: object; bodyBlacklist?: string[]; bodyWhitelist?: string[]; colorize?: boolean; dynamicMeta?: DynamicMetaFunction; expressFormat?: boolean; ignoreRoute?: RouteFilter; ignoredRoutes?: string[]; level?: string | DynamicLevelFunction; meta?: boolean; metaField?: string; msg?: MessageTemplate; requestFilter?: RequestFilter; requestWhitelist?: string[]; responseFilter?: ResponseFilter; responseWhitelist?: string[]; skip?: RouteFilter; statusLevels?: { error?: string; success?: string; warn?: string; }; } export interface LoggerOptionsWithTransports extends BaseLoggerOptions { transports: Transport[]; } export interface LoggerOptionsWithWinstonInstance extends BaseLoggerOptions { winstonInstance: winston.Logger; } export type LoggerOptions = LoggerOptionsWithTransports | LoggerOptionsWithWinstonInstance; export function logger(options: LoggerOptions): Handler; export interface BaseErrorLoggerOptions { baseMeta?: object; dynamicMeta?: DynamicMetaFunction; level?: string | DynamicLevelFunction; metaField?: string; msg?: MessageTemplate; requestFilter?: RequestFilter; requestWhitelist?: string[]; } export interface ErrorLoggerOptionsWithTransports extends BaseErrorLoggerOptions { transports: Transport[]; } export interface ErrorLoggerOptionsWithWinstonInstance extends BaseErrorLoggerOptions { winstonInstance: winston.Logger; } export type ErrorLoggerOptions = ErrorLoggerOptionsWithTransports | ErrorLoggerOptionsWithWinstonInstance; export function errorLogger(options: ErrorLoggerOptions): ErrorRequestHandler; export let requestWhitelist: string[]; export let bodyWhitelist: string[]; export let bodyBlacklist: string[]; export let responseWhitelist: string[]; export let ignoredRoutes: string[]; export let defaultRequestFilter: RequestFilter; export let defaultResponseFilter: ResponseFilter; export function defaultSkip(): boolean; export interface ExpressWinstonRequest extends Request { _routeWhitelists: { body: string[]; req: string[]; res: string[]; }; }
types/express-winston/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.0030912759248167276, 0.001296093687415123, 0.00016756562399677932, 0.0011904751881957054, 0.0010041833156719804 ]
{ "id": 1, "code_window": [ " colorize: true,\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " expressFormat: true,\n", " ignoreRoute: (req, res) => true,\n", " ignoredRoutes: ['foo'],\n", " level: (req, res) => 'level',\n", " meta: true,\n", " metaField: 'metaField',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 14 }
{ "extends": "dtslint/dt.json" }
types/emoji-regex/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017225509509444237, 0.00017225509509444237, 0.00017225509509444237, 0.00017225509509444237, 0 ]
{ "id": 1, "code_window": [ " colorize: true,\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " expressFormat: true,\n", " ignoreRoute: (req, res) => true,\n", " ignoredRoutes: ['foo'],\n", " level: (req, res) => 'level',\n", " meta: true,\n", " metaField: 'metaField',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 14 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../../", "typeRoots": [ "../../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, "paths": { "socket.io": [ "socket.io/v1" ] } }, "files": [ "index.d.ts", "socket.io-tests.ts" ] }
types/socket.io/v1/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017430233128834516, 0.00017382037185598165, 0.00017309165559709072, 0.00017406717233825475, 5.241573717285064e-7 ]
{ "id": 1, "code_window": [ " colorize: true,\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " expressFormat: true,\n", " ignoreRoute: (req, res) => true,\n", " ignoredRoutes: ['foo'],\n", " level: (req, res) => 'level',\n", " meta: true,\n", " metaField: 'metaField',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 14 }
import parseChangelog = require('changelog-parser'); const options = { filePath: 'path/to/CHANGELOG.md', removeMarkdown: false }; const fn = (obj: object): void => {}; parseChangelog({filePath: 'path/to/CHANGELOG.md'}, (error, result) => { if (error) { throw error; } fn(result); }); parseChangelog(options, (error, result) => {}); parseChangelog({filePath: 'path/to/CHANGELOG.md'}, (error) => {}); parseChangelog(options).then((result) => {}); parseChangelog('path/to/CHANGELOG.md').then((result) => {});
types/changelog-parser/changelog-parser-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.0001739374129101634, 0.00017342997307423502, 0.00017316760204266757, 0.00017318493337370455, 3.5887705962522887e-7 ]
{ "id": 2, "code_window": [ "\n", "// Error Logger with all options\n", "app.use(expressWinston.errorLogger({\n", " baseMeta: { foo: 'foo', nested: { bar: 'baz' } },\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " level: (req, res) => 'level',\n", " metaField: 'metaField',\n", " msg: 'msg',\n", " requestFilter: (req, prop) => true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 47 }
import expressWinston = require('express-winston'); import * as winston from 'winston'; import express = require('express'); const app = express(); // Logger with all options app.use(expressWinston.logger({ baseMeta: { foo: 'foo', nested: { bar: 'baz' } }, bodyBlacklist: ['foo'], bodyWhitelist: ['bar'], colorize: true, dynamicMeta: (req, res, err) => ({ foo: 'bar' }), expressFormat: true, ignoreRoute: (req, res) => true, ignoredRoutes: ['foo'], level: (req, res) => 'level', meta: true, metaField: 'metaField', msg: 'msg', requestFilter: (req, prop) => req[prop], requestWhitelist: ['foo', 'bar'], skip: (req, res) => false, statusLevels: ({ error: 'error', success: 'success', warn: 'warn' }), transports: [ new winston.transports.Console({}) ] })); // Logger with minimum options (transport) app.use(expressWinston.logger({ transports: [ new winston.transports.Console({}) ], })); const logger = winston.createLogger(); // Logger with minimum options (winstonInstance) app.use(expressWinston.logger({ winstonInstance: logger, })); // Error Logger with all options app.use(expressWinston.errorLogger({ baseMeta: { foo: 'foo', nested: { bar: 'baz' } }, dynamicMeta: (req, res, err) => ({ foo: 'bar' }), level: (req, res) => 'level', metaField: 'metaField', msg: 'msg', requestFilter: (req, prop) => true, requestWhitelist: ['foo', 'bar'], transports: [ new winston.transports.Console({}) ] })); // Error Logger with min options (transports) app.use(expressWinston.errorLogger({ transports: [ new winston.transports.Console({}) ], })); // Error Logger with min options (winstonInstance) app.use(expressWinston.errorLogger({ winstonInstance: logger, })); // Request and error logger with function type msg app.use(expressWinston.logger({ msg: (req, res) => `HTTP ${req.method} ${req.url} - ${res.statusCode}`, transports: [ new winston.transports.Console({}) ], })); app.use(expressWinston.errorLogger({ msg: (req, res) => `HTTP ${req.method} ${req.url} - ${res.statusCode}`, winstonInstance: logger, })); expressWinston.bodyBlacklist.push('potato'); expressWinston.bodyWhitelist.push('apple'); expressWinston.defaultRequestFilter = (req: expressWinston.FilterRequest, prop: string) => req[prop]; expressWinston.defaultResponseFilter = (res: expressWinston.FilterResponse, prop: string) => res[prop]; expressWinston.defaultSkip = () => true; expressWinston.ignoredRoutes.push('/ignored'); expressWinston.responseWhitelist.push('body'); const router = express.Router(); router.post('/user/register', (req, res, next) => { const expressWinstonReq = req as expressWinston.ExpressWinstonRequest; expressWinstonReq._routeWhitelists.body = ['username', 'email', 'age']; expressWinstonReq._routeWhitelists.req = ['userId']; expressWinstonReq._routeWhitelists.res = ['_headers']; });
types/express-winston/express-winston-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.9146378040313721, 0.10092146694660187, 0.0018288898281753063, 0.009073570370674133, 0.27137893438339233 ]
{ "id": 2, "code_window": [ "\n", "// Error Logger with all options\n", "app.use(expressWinston.errorLogger({\n", " baseMeta: { foo: 'foo', nested: { bar: 'baz' } },\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " level: (req, res) => 'level',\n", " metaField: 'metaField',\n", " msg: 'msg',\n", " requestFilter: (req, prop) => true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 47 }
declare var hiddenField: ASPxClientHiddenField; declare var mainCallbackPanel: ASPxClientCallbackPanel; declare var loginPopup: ASPxClientPopupControl; declare var searchButton: ASPxClientButton; declare var searchComboBox: ASPxClientComboBox; declare var roomsNumberSpinEdit: ASPxClientSpinEdit; declare var adultsNumberSpinEdit: ASPxClientSpinEdit; declare var childrenNumberSpinEdit: ASPxClientSpinEdit; declare var checkInDateEdit: ASPxClientDateEdit; declare var checkOutDateEdit: ASPxClientDateEdit; declare var backSlider: ASPxClientImageSlider; declare var locationComboBox: ASPxClientComboBox; declare var nightyRateTrackBar: ASPxClientTrackBar; declare var customerRatingTrackBar: ASPxClientTrackBar; declare var ourRatingCheckBoxList: ASPxClientCheckBoxList; declare var startFilterPopupControl: ASPxClientPopupControl; declare var imagePopupControl: ASPxClientPopupControl; declare var emailTextBox: ASPxClientTextBox; declare var creditCardEmailTextBox: ASPxClientTextBox; declare var accountEmailTextBox: ASPxClientTextBox; declare var bookingPageControl: ASPxClientPageControl; declare var paymentTypePageControl: ASPxClientPageControl; declare var offerFormPopup: ASPxClientPopupControl; declare var roomsSpinEdit: ASPxClientSpinEdit; declare var adultsSpinEdit: ASPxClientSpinEdit; declare var childrenSpinEdit: ASPxClientSpinEdit; declare var hotelDetailsCallbackPanel: ASPxClientCallbackPanel; declare var leftPanel: ASPxClientPanel; declare var menuButton: ASPxClientButton; declare var aboutWindow: ASPxClientPopupControl; declare var offersZone: ASPxClientDockZone; module DXDemo { function showPage(page: string, params: { [key: string]: any }, skipHistory?: boolean): void { var queryString = getQueryString(params || {}); hiddenField.Set("page", page); hiddenField.Set("parameters", queryString); hideMenu(); var uri = queryString.length ? (page + "?" + queryString) : page; try { if (!skipHistory && window.history && window.history.pushState) window.history.pushState(uri, "", uri || "Default.aspx"); } catch (e) { } mainCallbackPanel.PerformCallback(uri); }; export function onMainMenuItemClick(s: ASPxClientMenu, e: ASPxClientMenuItemClickEventArgs): void { switch (e.item.name) { case "login": hideMenu(); setTimeout(function () { loginPopup.ShowAtElementByID("MainCallbackPanel_ContentPane"); }, 300); break; case "offers": showPage("SpecialOffers", {}); break; default: hideMenu(); setTimeout(function () { showAboutWindow(); }, 300); break; } }; export function onLoginButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void { loginPopup.Hide(); showAboutWindow(); }; export function onSearchButtonClick(): void { if (ASPxClientEdit.ValidateGroup("DateEditors")) { showPage("ShowHotels", { location: searchComboBox.GetValue(), checkin: getFormattedDate(<Date>checkInDateEdit.GetValue()), checkout: getFormattedDate(<Date>checkOutDateEdit.GetValue()), rooms: roomsNumberSpinEdit.GetValue() || 1, adults: adultsNumberSpinEdit.GetValue() || 1, children: childrenNumberSpinEdit.GetValue() || 0 }); } }; export function onSearchComboBoxIndexChanged(s: ASPxClientComboBox, e: ASPxClientProcessingModeEventArgs): void { hideMenu(); searchButton.AdjustControl(); }; export function onIndexOfferCloseClick(index: number): void { var panel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("OfferDockPanel" + index); var sibPanel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("OfferDockPanel" + (index == 1 ? 2 : 1)); panel.Hide(); sibPanel.MakeFloat(); sibPanel.SetWidth(offersZone.GetWidth()); sibPanel.Dock(offersZone); }; export function onLogoClick(): void { showPage("", null, false); }; export function onMenuNavButtonCheckedChanged(s: ASPxClientCheckBox, e: ASPxClientProcessingModeEventArgs): void { var mainContainer = mainCallbackPanel.GetMainElement(); if (s.GetChecked()) { backSlider.Pause(); showMenu(); } else { hideMenu(); backSlider.Play(); } }; export function onBackNavButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void { var params = getCurrentQueryParams(); switch (getCurrentPage()) { case "PrintInvoice": showPage("Booking", params, false); break; case "Booking": if (bookingPageControl.GetActiveTabIndex() > 0) bookingPageControl.SetActiveTabIndex(bookingPageControl.GetActiveTabIndex() - 1); else showPage("ShowRooms", params, false); break; case "ShowRooms": showPage("ShowHotels", params, false); break; case "ShowDetails": showPage("ShowHotels", params, false); break; case "ShowHotels": case "SpecialOffers": showPage("", null, false); break; } }; export function updateSearchResults(): void { var params = getCurrentQueryParams(); params["location"] = locationComboBox.GetValue(); params["minprice"] = nightyRateTrackBar.GetPositionStart(); params["maxprice"] = nightyRateTrackBar.GetPositionEnd(); params["custrating"] = customerRatingTrackBar.GetPosition(); params["ourrating"] = ourRatingCheckBoxList.GetSelectedValues().join(","); showPage("ShowHotels", params); }; export function onBookHotelButtonClick(hotelID: string): void { var queryParams = getCurrentQueryParams(); queryParams["hotelID"] = hotelID; showPage("ShowRooms", queryParams); }; export function onDetailsHotelButtonClick(hotelID: string): void { var queryParams = getCurrentQueryParams(); queryParams["hotelID"] = hotelID; showPage("ShowDetails", queryParams); }; export function onShowStartFilterButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void { startFilterPopupControl.ShowAtElementByID("MainCallbackPanel_ContentPane"); }; export function onChangeStartFilterButtonClick(s: ASPxClientButton, e: ASPxClientButtonClickEventArgs): void { if (ASPxClientEdit.ValidateGroup("DateEditors")) { var params = getCurrentQueryParams(); params["checkin"] = getFormattedDate(<Date>checkInDateEdit.GetValue()); params["checkout"] = getFormattedDate(<Date>checkOutDateEdit.GetValue()); params["rooms"] = roomsNumberSpinEdit.GetValue() || 1; params["adults"] = adultsNumberSpinEdit.GetValue() || 1; params["children"] = childrenNumberSpinEdit.GetValue() || 0; startFilterPopupControl.Hide(); showPage(hiddenField.Get("page").toString(), params); } }; export function onBookRoomButtonClick(roomID: string): void { var params = getCurrentQueryParams(); params["roomID"] = roomID; showPage("Booking", params); }; export function onShowRoomsButtonClick(): void { var queryParams = getCurrentQueryParams(); showPage("ShowRooms", queryParams); }; export function onShowDetailsButtonClick(): void { var queryParams = getCurrentQueryParams(); showPage("ShowDetails", queryParams); }; export function onRoomImageNavItemClick(roomID: string, pictureName: string): void { setTimeout(function () { imagePopupControl.PerformCallback(roomID + "|" + pictureName); imagePopupControl.ShowAtElementByID("MainCallbackPanel_ContentPane"); }, 500); }; export function onRoomsNavBarExpandedChanged(s: ASPxClientNavBar, e: ASPxClientNavBarGroupEventArgs): void { ASPxClientControl.AdjustControls(s.GetMainElement()); }; export function onNextBookingStepButtonClick(step: number): void { var valid = true; var validationGroup = ""; if (step == 1) validationGroup = "Account"; if (step == 2) validationGroup = "RoomDetails"; if (step == 3) validationGroup = "PaymentDetails"; switch (step) { case 1: valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "Account"); if (valid) { emailTextBox.SetValue(accountEmailTextBox.GetValue()); creditCardEmailTextBox.SetValue(accountEmailTextBox.GetValue()); showPage("Booking", getCurrentQueryParams()); return; } break; case 2: valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "RoomDetails"); emailTextBox.SetValue(accountEmailTextBox.GetValue()); break; case 3: var paymentType = paymentTypePageControl.GetActiveTabIndex(); if (paymentType == 0) valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "CreditCard"); else if (paymentType == 1) valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "Cash"); else if (paymentType == 2) valid = ASPxClientEdit.ValidateEditorsInContainer(bookingPageControl.GetMainElement(), "PayPal"); break; } if (valid) { bookingPageControl.GetTab(step).SetEnabled(true); bookingPageControl.SetActiveTabIndex(step); } }; export function onAccountCaptchaHiddenFieldInit(s: ASPxClientHiddenField, e: ASPxClientEventArgs): void { if (s.Get("IsCaptchaValid")) { bookingPageControl.GetTab(1).SetEnabled(true); bookingPageControl.SetActiveTabIndex(1); } }; export function onFinishBookingStepButtonClick(): void { showAboutWindow(); }; export function OnPrintInvoiceButtonClick(): void { showPage("PrintInvoice", getCurrentQueryParams()); }; export function onOfferClick(offerID: string): void { offerFormPopup.SetContentHtml(""); offerFormPopup.PerformCallback(offerID); var panel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("DockPanel" + offerID); var panelElement = <HTMLElement>panel.GetMainElement(); if (panelElement.offsetWidth < 330 || panelElement.offsetHeight < 250) { offerFormPopup.SetWidth(400); offerFormPopup.SetHeight(280); offerFormPopup.ShowAtElementByID("SpecialOffersContainer"); } else { offerFormPopup.SetWidth(panelElement.offsetWidth); offerFormPopup.SetHeight(panelElement.offsetHeight); offerFormPopup.ShowAtElement(panelElement); } }; export function onSpecialOfferCheckButtonClick(hotelID: string, locationID: string): void { if (ASPxClientEdit.ValidateGroup("DateEditors")) { var queryParams: { [key: string]: any } = { location: locationID, hotelID: hotelID, checkin: getFormattedDate(<Date>checkInDateEdit.GetValue()), checkout: getFormattedDate(<Date>checkOutDateEdit.GetValue()), rooms: roomsSpinEdit.GetValue() || 1, adults: adultsSpinEdit.GetValue() || 1, children: childrenSpinEdit.GetValue() || 0 }; showPage("ShowRooms", queryParams); } }; export function onIndexOfferClick(): void { showPage("SpecialOffers", {}); }; export function onControlsInit(): void { ASPxClientUtils.AttachEventToElement(window, 'popstate', onHistoryPopState); var pathParts = document.location.href.split("/"); var url = pathParts[pathParts.length - 1]; try { if (window.history) window.history.replaceState(url, ""); } catch (e) { } ASPxClientUtils.AttachEventToElement(window, "resize", onWindowResize); if (ASPxClientUtils.iOSPlatform) { // animate } }; export function updateRatingLabels(ratingControl: ASPxClientTrackBar) { var start = ratingControl.GetPositionStart().toString(); var end = ratingControl.GetPositionEnd().toString(); document.getElementById("cpLeftLabelID").innerHTML = start + " " + end; }; export function onRatingControlItemClick(s: ASPxClientRatingControl, e: ASPxClientRatingControlItemClickEventArgs): void { hotelDetailsCallbackPanel.PerformCallback(s.GetValue().toString()); }; export function onInputKeyDown(s: ASPxClientTextBox, e: ASPxClientEditKeyEventArgs): void { var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent); if (keyCode == 13) (<HTMLElement>s.GetInputElement()).blur(); }; function getCurrentPage(): string { var hfPage = <string>hiddenField.Get("page"); if (hfPage) return hfPage; var pathParts = document.location.pathname.split("/"); return pathParts[pathParts.length - 1]; }; function showAboutWindow(): void { aboutWindow.ShowAtElementByID("MainCallbackPanel_ContentPane"); }; function hideMenu(): void { leftPanel.Collapse(); if (menuButton.GetMainElement() && menuButton.GetChecked()) menuButton.SetChecked(false); }; function showMenu(): void { leftPanel.Expand(); }; var _resizeSpecialOffersTimeoutID = -1; function onWindowResize(): void { switch (<string>hiddenField.Get("page")) { case "SpecialOffers": if (_resizeSpecialOffersTimeoutID == -1) _resizeSpecialOffersTimeoutID = setTimeout(resizeSpecialOffers, 200); break; } hidePopups("AboutWindow", "StartFilterPopupControl", "LoginPopup", "OfferFormPopup", "ImagePopupControl"); }; function hidePopups(...names: string[]): void { for (var i = 0; i < names.length; i++) { var popupControl = <ASPxClientPopupControl>ASPxClientControl.GetControlCollection().GetByName(names[i]); popupControl.Hide(); } }; function resizeSpecialOffers(): void { for (var i = 1; i <= 4; i++) { var panel = <ASPxClientDockPanel>ASPxClientControl.GetControlCollection().GetByName("DockPanel" + i); if (panel && panel.IsVisible()) { var zone = panel.GetOwnerZone(); zone.SetWidth((<HTMLElement>(<HTMLElement>zone.GetMainElement()).parentNode).offsetWidth) } } _resizeSpecialOffersTimeoutID = -1; }; function getFormattedDate(date: Date): string { return (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear(); }; function getCurrentQueryParams(): { [key:string]: any } { var hfParams = <string>hiddenField.Get("parameters"); if (hfParams) return getParamsByQueryString(hfParams); var query = document.location.search; if (query[0] === "?") query = query.substr(1); return getParamsByQueryString(query); }; function getQueryString(params: { [key:string]: any }): string { var queryItems: any[] = []; for (var key in params) { if (!params.hasOwnProperty(key)) continue; queryItems.push(key + "=" + params[key]); } if (queryItems.length > 0) return queryItems.join("&"); return ""; }; function getParamsByQueryString(queryString: string): { [key: string]: string } { var result: { [key: string]: any } = {}; if (queryString) { var queryStringArray = queryString.split("&"); for (var i = 0; i < queryStringArray.length; i++) { var part = queryStringArray[i].split('='); if (part.length != 2) continue; result[part[0]] = decodeURIComponent(part[1].replace(/\+/g, " ")); } } return result; }; function onHistoryPopState(evt: any): void { if (evt.state !== null && evt.state !== undefined) { var uriParts = evt.state.split("?"); showPage(uriParts[0], getParamsByQueryString(uriParts[1]), true); } }; }
types/devexpress-web/v171/devexpress-web-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00023426645202562213, 0.00017190778453368694, 0.00016567076090723276, 0.0001705677277641371, 0.000009972845873562619 ]
{ "id": 2, "code_window": [ "\n", "// Error Logger with all options\n", "app.use(expressWinston.errorLogger({\n", " baseMeta: { foo: 'foo', nested: { bar: 'baz' } },\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " level: (req, res) => 'level',\n", " metaField: 'metaField',\n", " msg: 'msg',\n", " requestFilter: (req, prop) => true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 47 }
import isFunction = require("is-function"); const a: boolean = isFunction("string"); const b: boolean = isFunction(true); const c: boolean = isFunction((x: number) => x * x); const d: boolean = isFunction({ type: "number" }); const e: boolean = isFunction(() => { return "I am anounymous!"; });
types/is-function/is-function-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.0001767336652847007, 0.0001767336652847007, 0.0001767336652847007, 0.0001767336652847007, 0 ]
{ "id": 2, "code_window": [ "\n", "// Error Logger with all options\n", "app.use(expressWinston.errorLogger({\n", " baseMeta: { foo: 'foo', nested: { bar: 'baz' } },\n", " dynamicMeta: (req, res, err) => ({ foo: 'bar' }),\n", " level: (req, res) => 'level',\n", " metaField: 'metaField',\n", " msg: 'msg',\n", " requestFilter: (req, prop) => true,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " format: new Format(),\n" ], "file_path": "types/express-winston/express-winston-tests.ts", "type": "add", "edit_start_line_idx": 47 }
import * as gulp from 'gulp'; import revReplace = require('gulp-rev-replace'); import rev = require('gulp-rev'); import useref = require('gulp-useref'); gulp.task("index", () => { return gulp.src("src/index.html") .pipe(useref()) // Concatenate with gulp-useref .pipe(rev()) // Rename the concatenated files .pipe(revReplace()) // Substitute in new filenames .pipe(gulp.dest('public')); }); var opt = { srcFolder: 'src', distFolder: 'dist' } gulp.task("revision", gulp.parallel("dist:css", "dist:js", () => gulp.src(["dist/**/*.css", "dist/**/*.js"]) .pipe(rev()) .pipe(gulp.dest(opt.distFolder)) .pipe(rev.manifest()) .pipe(gulp.dest(opt.distFolder)) )); gulp.task("revreplace", gulp.parallel("revision", () => { var manifest = gulp.src("./" + opt.distFolder + "/rev-manifest.json"); return gulp.src(opt.srcFolder + "/index.html") .pipe(revReplace({ manifest: manifest })) .pipe(gulp.dest(opt.distFolder)); })); function replaceJsIfMap(filename: string): string { if (filename.indexOf('.map') > -1) { return filename.replace('js/', ''); } return filename; } gulp.task("revreplace", gulp.parallel("revision", () => { var manifest = gulp.src("./" + opt.distFolder + "/rev-manifest.json"); return gulp.src(opt.distFolder + '**/*.js') .pipe(revReplace({ manifest: manifest, modifyUnreved: replaceJsIfMap, modifyReved: replaceJsIfMap })) .pipe(gulp.dest(opt.distFolder)); }));
types/gulp-rev-replace/gulp-rev-replace-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.0001786354259820655, 0.000175549226696603, 0.00017295537691097707, 0.00017590311472304165, 0.0000020107329419261077 ]
{ "id": 3, "code_window": [ "// Definitions by: Alex Brick <https://github.com/bricka>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.2\n", "\n", "import { ErrorRequestHandler, Handler, Request, Response } from 'express';\n", "import * as winston from 'winston';\n", "import * as Transport from 'winston-transport';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 7 }
// Type definitions for express-winston 3.0 // Project: https://github.com/bithavoc/express-winston#readme // Definitions by: Alex Brick <https://github.com/bricka> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import { ErrorRequestHandler, Handler, Request, Response } from 'express'; import * as winston from 'winston'; import * as Transport from 'winston-transport'; export interface FilterRequest extends Request { [other: string]: any; } export interface FilterResponse extends Response { [other: string]: any; } export type DynamicMetaFunction = (req: Request, res: Response, err: Error) => object; export type DynamicLevelFunction = (req: Request, res: Response, err: Error) => string; export type RequestFilter = (req: FilterRequest, propName: string) => any; export type ResponseFilter = (res: FilterResponse, propName: string) => any; export type RouteFilter = (req: Request, res: Response) => boolean; export type MessageTemplate = string | ((req: Request, res: Response) => string); export interface BaseLoggerOptions { baseMeta?: object; bodyBlacklist?: string[]; bodyWhitelist?: string[]; colorize?: boolean; dynamicMeta?: DynamicMetaFunction; expressFormat?: boolean; ignoreRoute?: RouteFilter; ignoredRoutes?: string[]; level?: string | DynamicLevelFunction; meta?: boolean; metaField?: string; msg?: MessageTemplate; requestFilter?: RequestFilter; requestWhitelist?: string[]; responseFilter?: ResponseFilter; responseWhitelist?: string[]; skip?: RouteFilter; statusLevels?: { error?: string; success?: string; warn?: string; }; } export interface LoggerOptionsWithTransports extends BaseLoggerOptions { transports: Transport[]; } export interface LoggerOptionsWithWinstonInstance extends BaseLoggerOptions { winstonInstance: winston.Logger; } export type LoggerOptions = LoggerOptionsWithTransports | LoggerOptionsWithWinstonInstance; export function logger(options: LoggerOptions): Handler; export interface BaseErrorLoggerOptions { baseMeta?: object; dynamicMeta?: DynamicMetaFunction; level?: string | DynamicLevelFunction; metaField?: string; msg?: MessageTemplate; requestFilter?: RequestFilter; requestWhitelist?: string[]; } export interface ErrorLoggerOptionsWithTransports extends BaseErrorLoggerOptions { transports: Transport[]; } export interface ErrorLoggerOptionsWithWinstonInstance extends BaseErrorLoggerOptions { winstonInstance: winston.Logger; } export type ErrorLoggerOptions = ErrorLoggerOptionsWithTransports | ErrorLoggerOptionsWithWinstonInstance; export function errorLogger(options: ErrorLoggerOptions): ErrorRequestHandler; export let requestWhitelist: string[]; export let bodyWhitelist: string[]; export let bodyBlacklist: string[]; export let responseWhitelist: string[]; export let ignoredRoutes: string[]; export let defaultRequestFilter: RequestFilter; export let defaultResponseFilter: ResponseFilter; export function defaultSkip(): boolean; export interface ExpressWinstonRequest extends Request { _routeWhitelists: { body: string[]; req: string[]; res: string[]; }; }
types/express-winston/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.9853891730308533, 0.09610006213188171, 0.00016615548520348966, 0.0008056355291046202, 0.28144803643226624 ]
{ "id": 3, "code_window": [ "// Definitions by: Alex Brick <https://github.com/bricka>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.2\n", "\n", "import { ErrorRequestHandler, Handler, Request, Response } from 'express';\n", "import * as winston from 'winston';\n", "import * as Transport from 'winston-transport';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 7 }
import { findKey } from "../fp"; export = findKey;
types/lodash/fp/findKey.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017432744789402932, 0.00017432744789402932, 0.00017432744789402932, 0.00017432744789402932, 0 ]
{ "id": 3, "code_window": [ "// Definitions by: Alex Brick <https://github.com/bricka>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.2\n", "\n", "import { ErrorRequestHandler, Handler, Request, Response } from 'express';\n", "import * as winston from 'winston';\n", "import * as Transport from 'winston-transport';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 7 }
{ "extends": "dtslint/dt.json" }
types/async-retry/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017067980661522597, 0.00017067980661522597, 0.00017067980661522597, 0.00017067980661522597, 0 ]
{ "id": 3, "code_window": [ "// Definitions by: Alex Brick <https://github.com/bricka>\n", "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.2\n", "\n", "import { ErrorRequestHandler, Handler, Request, Response } from 'express';\n", "import * as winston from 'winston';\n", "import * as Transport from 'winston-transport';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { Format } from 'logform';\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 7 }
import PluginError = require('plugin-error'); let e: PluginError; // string message e = new PluginError('my-plugin', 'message'); e = new PluginError('my-plugin', 'message', { showProperties: false, showStack: false }); e = new PluginError('my-plugin', { showProperties: false, showStack: false, message: 'message' }); e = new PluginError({ showProperties: false, showStack: false, message: 'message', plugin: 'my-plugin' }); // error instead of message e = new PluginError('my-plugin', new Error('message')); e = new PluginError('my-plugin', new Error('message'), { showProperties: false, showStack: false }); e = new PluginError('my-plugin', { showProperties: false, showStack: false, message: new Error('message') }); e = new PluginError({ showProperties: false, showStack: false, message: new Error('message'), plugin: 'my-plugin' }); // without non-mandatory options e = new PluginError('my-plugin', 'message', {}); e = new PluginError('my-plugin', { message: 'message' }); e = new PluginError({ message: 'message', plugin: 'my-plugin' }); // check Error base class const f: Error = e;
types/plugin-error/plugin-error-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017542998830322176, 0.00017171567014884204, 0.00016575372137594968, 0.00017396330076735467, 0.000004258045009919442 ]
{ "id": 4, "code_window": [ " bodyWhitelist?: string[];\n", " colorize?: boolean;\n", " dynamicMeta?: DynamicMetaFunction;\n", " expressFormat?: boolean;\n", " ignoreRoute?: RouteFilter;\n", " ignoredRoutes?: string[];\n", " level?: string | DynamicLevelFunction;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 32 }
import expressWinston = require('express-winston'); import * as winston from 'winston'; import express = require('express'); const app = express(); // Logger with all options app.use(expressWinston.logger({ baseMeta: { foo: 'foo', nested: { bar: 'baz' } }, bodyBlacklist: ['foo'], bodyWhitelist: ['bar'], colorize: true, dynamicMeta: (req, res, err) => ({ foo: 'bar' }), expressFormat: true, ignoreRoute: (req, res) => true, ignoredRoutes: ['foo'], level: (req, res) => 'level', meta: true, metaField: 'metaField', msg: 'msg', requestFilter: (req, prop) => req[prop], requestWhitelist: ['foo', 'bar'], skip: (req, res) => false, statusLevels: ({ error: 'error', success: 'success', warn: 'warn' }), transports: [ new winston.transports.Console({}) ] })); // Logger with minimum options (transport) app.use(expressWinston.logger({ transports: [ new winston.transports.Console({}) ], })); const logger = winston.createLogger(); // Logger with minimum options (winstonInstance) app.use(expressWinston.logger({ winstonInstance: logger, })); // Error Logger with all options app.use(expressWinston.errorLogger({ baseMeta: { foo: 'foo', nested: { bar: 'baz' } }, dynamicMeta: (req, res, err) => ({ foo: 'bar' }), level: (req, res) => 'level', metaField: 'metaField', msg: 'msg', requestFilter: (req, prop) => true, requestWhitelist: ['foo', 'bar'], transports: [ new winston.transports.Console({}) ] })); // Error Logger with min options (transports) app.use(expressWinston.errorLogger({ transports: [ new winston.transports.Console({}) ], })); // Error Logger with min options (winstonInstance) app.use(expressWinston.errorLogger({ winstonInstance: logger, })); // Request and error logger with function type msg app.use(expressWinston.logger({ msg: (req, res) => `HTTP ${req.method} ${req.url} - ${res.statusCode}`, transports: [ new winston.transports.Console({}) ], })); app.use(expressWinston.errorLogger({ msg: (req, res) => `HTTP ${req.method} ${req.url} - ${res.statusCode}`, winstonInstance: logger, })); expressWinston.bodyBlacklist.push('potato'); expressWinston.bodyWhitelist.push('apple'); expressWinston.defaultRequestFilter = (req: expressWinston.FilterRequest, prop: string) => req[prop]; expressWinston.defaultResponseFilter = (res: expressWinston.FilterResponse, prop: string) => res[prop]; expressWinston.defaultSkip = () => true; expressWinston.ignoredRoutes.push('/ignored'); expressWinston.responseWhitelist.push('body'); const router = express.Router(); router.post('/user/register', (req, res, next) => { const expressWinstonReq = req as expressWinston.ExpressWinstonRequest; expressWinstonReq._routeWhitelists.body = ['username', 'email', 'age']; expressWinstonReq._routeWhitelists.req = ['userId']; expressWinstonReq._routeWhitelists.res = ['_headers']; });
types/express-winston/express-winston-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.8155069351196289, 0.0918559581041336, 0.00016565386613365263, 0.00025723755243234336, 0.24306415021419525 ]
{ "id": 4, "code_window": [ " bodyWhitelist?: string[];\n", " colorize?: boolean;\n", " dynamicMeta?: DynamicMetaFunction;\n", " expressFormat?: boolean;\n", " ignoreRoute?: RouteFilter;\n", " ignoredRoutes?: string[];\n", " level?: string | DynamicLevelFunction;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 32 }
const params: ReCaptchaV2.Parameters = { sitekey: "mySuperSecretKey", theme: "light", type: "image", size: "normal", tabindex: 5, isolated: false, callback: (response: string) => { }, "expired-callback": () => { }, "error-callback": () => { }, }; const size1: ReCaptchaV2.Size = "compact"; const size2: ReCaptchaV2.Size = "invisible"; const size3: ReCaptchaV2.Size = "normal"; const badge1: ReCaptchaV2.Badge = "bottomleft"; const badge2: ReCaptchaV2.Badge = "bottomright"; const badge3: ReCaptchaV2.Badge = "inline"; const invisibleParams1: ReCaptchaV2.Parameters = { sitekey: "siteKey", badge: badge1, }; const invisibleParams2: ReCaptchaV2.Parameters = { badge: badge2, }; const id1: number = grecaptcha.render("foo"); const id2: number = grecaptcha.render("foo", params); const id3: number = grecaptcha.render(document.getElementById("foo")); const id4: number = grecaptcha.render(document.getElementById("foo"), params); const id5: number = grecaptcha.render(document.getElementById("foo"), params, true); // response takes a number and returns a string const response1: string = grecaptcha.getResponse(id1); // reset takes a number grecaptcha.reset(id1); grecaptcha.execute(); grecaptcha.execute(id1);
types/grecaptcha/grecaptcha-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.0001755484554450959, 0.0001713723613647744, 0.00016303958545904607, 0.00017270688840653747, 0.000004354902102932101 ]
{ "id": 4, "code_window": [ " bodyWhitelist?: string[];\n", " colorize?: boolean;\n", " dynamicMeta?: DynamicMetaFunction;\n", " expressFormat?: boolean;\n", " ignoreRoute?: RouteFilter;\n", " ignoredRoutes?: string[];\n", " level?: string | DynamicLevelFunction;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 32 }
{ "private": true, "dependencies": { "csstype": "^2.0.0", "indefinite-observable": "^1.0.1" } }
types/jss/package.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.0001752756506903097, 0.0001752756506903097, 0.0001752756506903097, 0.0001752756506903097, 0 ]
{ "id": 4, "code_window": [ " bodyWhitelist?: string[];\n", " colorize?: boolean;\n", " dynamicMeta?: DynamicMetaFunction;\n", " expressFormat?: boolean;\n", " ignoreRoute?: RouteFilter;\n", " ignoredRoutes?: string[];\n", " level?: string | DynamicLevelFunction;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 32 }
// Type definitions for express-session 1.15 // Project: https://github.com/expressjs/session // Definitions by: Hiroki Horiuchi <https://github.com/horiuchi> // Jacob Bogers <https://github.com/jacobbogers> // Naoto Yokoyama <https://github.com/builtinnya> // Ryan Cannon <https://github.com/ry7n> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /// <reference types="node" /> import express = require('express'); import node = require('events'); declare global { namespace Express { interface Request { session?: Session; sessionID?: string; } interface SessionData { [key: string]: any; cookie: SessionCookieData; } interface SessionCookieData { originalMaxAge: number; path: string; maxAge: number | null; secure?: boolean; httpOnly: boolean; domain?: string; expires: Date | boolean; sameSite?: boolean | string; } interface SessionCookie extends SessionCookieData { serialize(name: string, value: string): string; } interface Session extends SessionData { id: string; regenerate(callback: (err: any) => void): void; destroy(callback: (err: any) => void): void; reload(callback: (err: any) => void): void; save(callback: (err: any) => void): void; touch(callback: (err: any) => void): void; cookie: SessionCookie; } } } declare function session(options?: session.SessionOptions): express.RequestHandler; declare namespace session { interface SessionOptions { secret: string | string[]; name?: string; store?: Store | MemoryStore; cookie?: express.CookieOptions; genid?(req: express.Request): string; rolling?: boolean; resave?: boolean; proxy?: boolean; saveUninitialized?: boolean; unset?: string; } interface BaseMemoryStore { get: (sid: string, callback: (err: any, session?: Express.SessionData | null) => void) => void; set: (sid: string, session: Express.Session, callback?: (err?: any) => void) => void; destroy: (sid: string, callback?: (err?: any) => void) => void; length?: (callback: (err: any, length?: number | null) => void) => void; clear?: (callback?: (err?: any) => void) => void; } abstract class Store extends node.EventEmitter { constructor(config?: any); regenerate: (req: express.Request, fn: (err?: any) => any) => void; load: (sid: string, fn: (err: any, session?: Express.SessionData | null) => any) => void; createSession: (req: express.Request, sess: Express.SessionData) => void; get: (sid: string, callback: (err: any, session?: Express.SessionData | null) => void) => void; set: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; destroy: (sid: string, callback?: (err?: any) => void) => void; all: (callback: (err: any, obj?: { [sid: string]: Express.SessionData; } | null) => void) => void; length: (callback: (err: any, length?: number | null) => void) => void; clear: (callback?: (err?: any) => void) => void; touch: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; } class MemoryStore implements BaseMemoryStore { get: (sid: string, callback: (err: any, session?: Express.SessionData | null) => void) => void; set: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; destroy: (sid: string, callback?: (err?: any) => void) => void; all: (callback: (err: any, obj?: { [sid: string]: Express.SessionData; } | null) => void) => void; length: (callback: (err: any, length?: number | null) => void) => void; clear: (callback?: (err?: any) => void) => void; touch: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; } } export = session;
types/express-session/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00019916622841265053, 0.00017506172298453748, 0.00016648662858642638, 0.00017209010547958314, 0.000010169665983994491 ]
{ "id": 5, "code_window": [ "export function logger(options: LoggerOptions): Handler;\n", "\n", "export interface BaseErrorLoggerOptions {\n", " baseMeta?: object;\n", " dynamicMeta?: DynamicMetaFunction;\n", " level?: string | DynamicLevelFunction;\n", " metaField?: string;\n", " msg?: MessageTemplate;\n", " requestFilter?: RequestFilter;\n", " requestWhitelist?: string[];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 65 }
import expressWinston = require('express-winston'); import * as winston from 'winston'; import express = require('express'); const app = express(); // Logger with all options app.use(expressWinston.logger({ baseMeta: { foo: 'foo', nested: { bar: 'baz' } }, bodyBlacklist: ['foo'], bodyWhitelist: ['bar'], colorize: true, dynamicMeta: (req, res, err) => ({ foo: 'bar' }), expressFormat: true, ignoreRoute: (req, res) => true, ignoredRoutes: ['foo'], level: (req, res) => 'level', meta: true, metaField: 'metaField', msg: 'msg', requestFilter: (req, prop) => req[prop], requestWhitelist: ['foo', 'bar'], skip: (req, res) => false, statusLevels: ({ error: 'error', success: 'success', warn: 'warn' }), transports: [ new winston.transports.Console({}) ] })); // Logger with minimum options (transport) app.use(expressWinston.logger({ transports: [ new winston.transports.Console({}) ], })); const logger = winston.createLogger(); // Logger with minimum options (winstonInstance) app.use(expressWinston.logger({ winstonInstance: logger, })); // Error Logger with all options app.use(expressWinston.errorLogger({ baseMeta: { foo: 'foo', nested: { bar: 'baz' } }, dynamicMeta: (req, res, err) => ({ foo: 'bar' }), level: (req, res) => 'level', metaField: 'metaField', msg: 'msg', requestFilter: (req, prop) => true, requestWhitelist: ['foo', 'bar'], transports: [ new winston.transports.Console({}) ] })); // Error Logger with min options (transports) app.use(expressWinston.errorLogger({ transports: [ new winston.transports.Console({}) ], })); // Error Logger with min options (winstonInstance) app.use(expressWinston.errorLogger({ winstonInstance: logger, })); // Request and error logger with function type msg app.use(expressWinston.logger({ msg: (req, res) => `HTTP ${req.method} ${req.url} - ${res.statusCode}`, transports: [ new winston.transports.Console({}) ], })); app.use(expressWinston.errorLogger({ msg: (req, res) => `HTTP ${req.method} ${req.url} - ${res.statusCode}`, winstonInstance: logger, })); expressWinston.bodyBlacklist.push('potato'); expressWinston.bodyWhitelist.push('apple'); expressWinston.defaultRequestFilter = (req: expressWinston.FilterRequest, prop: string) => req[prop]; expressWinston.defaultResponseFilter = (res: expressWinston.FilterResponse, prop: string) => res[prop]; expressWinston.defaultSkip = () => true; expressWinston.ignoredRoutes.push('/ignored'); expressWinston.responseWhitelist.push('body'); const router = express.Router(); router.post('/user/register', (req, res, next) => { const expressWinstonReq = req as expressWinston.ExpressWinstonRequest; expressWinstonReq._routeWhitelists.body = ['username', 'email', 'age']; expressWinstonReq._routeWhitelists.req = ['userId']; expressWinstonReq._routeWhitelists.res = ['_headers']; });
types/express-winston/express-winston-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.9283770322799683, 0.1552775353193283, 0.00016992309247143567, 0.011679085902869701, 0.2985479235649109 ]
{ "id": 5, "code_window": [ "export function logger(options: LoggerOptions): Handler;\n", "\n", "export interface BaseErrorLoggerOptions {\n", " baseMeta?: object;\n", " dynamicMeta?: DynamicMetaFunction;\n", " level?: string | DynamicLevelFunction;\n", " metaField?: string;\n", " msg?: MessageTemplate;\n", " requestFilter?: RequestFilter;\n", " requestWhitelist?: string[];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 65 }
// Type definitions for makeup-floating-label 0.0 // Project: https://github.com/makeup-js/makeup-floating-label#readme // Definitions by: Timur Manyanov <https://github.com/darkwebdev> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 declare class FloatingLabel { constructor(el: any, userOptions?: any); refresh(): void; } export = FloatingLabel;
types/makeup-floating-label/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.0001687359035713598, 0.00016816882998682559, 0.00016760175640229136, 0.00016816882998682559, 5.670735845342278e-7 ]
{ "id": 5, "code_window": [ "export function logger(options: LoggerOptions): Handler;\n", "\n", "export interface BaseErrorLoggerOptions {\n", " baseMeta?: object;\n", " dynamicMeta?: DynamicMetaFunction;\n", " level?: string | DynamicLevelFunction;\n", " metaField?: string;\n", " msg?: MessageTemplate;\n", " requestFilter?: RequestFilter;\n", " requestWhitelist?: string[];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 65 }
import * as glVec from "gl-vec4"; import glVecAdd from "gl-vec4/add"; import glVecClone from "gl-vec4/clone"; import glVecCopy from "gl-vec4/copy"; import glVecCreate from "gl-vec4/create"; import glVecDistance from "gl-vec4/distance"; import glVecDivide from "gl-vec4/divide"; import glVecDot from "gl-vec4/dot"; import glVecFromValues from "gl-vec4/fromValues"; import glVecInverse from "gl-vec4/inverse"; import glVecLength from "gl-vec4/length"; import glVecLerp from "gl-vec4/lerp"; import glVecMax from "gl-vec4/max"; import glVecMin from "gl-vec4/min"; import glVecMultiply from "gl-vec4/multiply"; import glVecNegate from "gl-vec4/negate"; import glVecNormalize from "gl-vec4/normalize"; import glVecRandom from "gl-vec4/random"; import glVecScale from "gl-vec4/scale"; import glVecScaleAndAdd from "gl-vec4/scaleAndAdd"; import glVecSet from "gl-vec4/set"; import glVecSqrdDistance from "gl-vec4/squaredDistance"; import glVecSqrdLength from "gl-vec4/squaredLength"; import glVecSubtract from "gl-vec4/subtract"; import glVecTransformMat4 from "gl-vec4/transformMat4"; import glVecTransformQuat from "gl-vec4/transformQuat"; glVec.add([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecAdd([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVec.clone([1, 2, 3]); glVecClone([1, 2, 3]); glVec.copy([1, 2, 3], [1, 2, 3]); glVecCopy([1, 2, 3], [1, 2, 3]); glVec.create(); glVecCreate(); glVec.distance([1, 2, 3], [1, 2, 3]); glVecDistance([1, 2, 3], [1, 2, 3]); glVec.divide([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecDivide([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVec.dot([1, 2, 3], [1, 2, 3]); glVecDot([1, 2, 3], [1, 2, 3]); glVec.fromValues(1, 2, 4, 5); glVecFromValues(1, 2, 4, 5); glVec.inverse([1, 2, 3], [1, 2, 3]); glVecInverse([1, 2, 3], [1, 2, 3]); glVec.length([1, 2, 3]); glVecLength([1, 2, 3]); glVec.lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); glVecLerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); glVec.max([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecMax([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVec.min([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecMin([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVec.multiply([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecMultiply([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVec.negate([1, 2, 3], [1, 2, 3]); glVecNegate([1, 2, 3], [1, 2, 3]); glVec.normalize([1, 2, 3], [1, 2, 3]); glVecNormalize([1, 2, 3], [1, 2, 3]); glVec.random([1, 2, 3], 6); glVecRandom([1, 2, 3], 6); glVec.scale([1, 2, 3], [1, 2, 3], 6); glVecScale([1, 2, 3], [1, 2, 3], 6); glVec.scaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); glVecScaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); glVec.set([1, 2, 3], [1, 2, 3], [1, 2, 3], 6, 6); glVecSet([1, 2, 3], [1, 2, 3], [1, 2, 3], 6, 6); glVec.squaredDistance([1, 2, 3], [1, 2, 3]); glVecSqrdDistance([1, 2, 3], [1, 2, 3]); glVec.squaredLength([1, 2, 3]); glVecSqrdLength([1, 2, 3]); glVec.subtract([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecSubtract([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVec.transformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecTransformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVec.transformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); glVecTransformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]);
types/gl-vec4/gl-vec4-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00017912202747538686, 0.00017710396787151694, 0.00017525193106848747, 0.00017724299686960876, 0.0000012046966730849817 ]
{ "id": 5, "code_window": [ "export function logger(options: LoggerOptions): Handler;\n", "\n", "export interface BaseErrorLoggerOptions {\n", " baseMeta?: object;\n", " dynamicMeta?: DynamicMetaFunction;\n", " level?: string | DynamicLevelFunction;\n", " metaField?: string;\n", " msg?: MessageTemplate;\n", " requestFilter?: RequestFilter;\n", " requestWhitelist?: string[];\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " format?: Format;\n" ], "file_path": "types/express-winston/index.d.ts", "type": "add", "edit_start_line_idx": 65 }
import { createContext, getDefaultWatermarks, summarizers, Watermarks } from 'istanbul-lib-report'; import { CoverageMap } from 'istanbul-lib-coverage'; const watermarks: Watermarks = { statements: [], branches: [], functions: [], lines: [] }; createContext(); createContext({}); const context = createContext({ dir: 'foo', watermarks, sourceFinder: (filepath: string) => '' }); context.watermarks; context.sourceFinder('foo').trim(); const defaultMarks: Watermarks = getDefaultWatermarks(); const map = new CoverageMap({}); summarizers.flat(map).getRoot(); summarizers.nested(map).getRoot(); summarizers.pkg(map).getRoot();
types/istanbul-lib-report/istanbul-lib-report-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/dfa678e14395f3e0739af90a17cf1c4e68619bf0
[ 0.00018022223957814276, 0.00017719579045660794, 0.00017439262592233717, 0.0001770841481629759, 0.0000020729498828586657 ]
{ "id": 0, "code_window": [ " <ListItemText primary={`Line item ${value + 1}`} />\n", " <ListItemSecondaryAction>\n", " <Checkbox\n", " onClick={this.handleToggle(value)}\n", " checked={this.state.checked.indexOf(value) !== -1}\n", " />\n", " </ListItemSecondaryAction>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle(value)}\n" ], "file_path": "docs/src/pages/demos/lists/CheckboxListSecondary.js", "type": "replace", "edit_start_line_idx": 50 }
/* eslint-disable flowtype/require-valid-file-annotation */ import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import List, { ListItem, ListItemSecondaryAction, ListItemText } from 'material-ui/List'; import Checkbox from 'material-ui/Checkbox'; import Avatar from 'material-ui/Avatar'; const styles = theme => ({ root: { width: '100%', maxWidth: 360, background: theme.palette.background.paper, }, }); class CheckboxListSecondary extends React.Component { state = { checked: [1], }; handleToggle = value => () => { const { checked } = this.state; const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } this.setState({ checked: newChecked, }); }; render() { const { classes } = this.props; return ( <div className={classes.root}> <List> {[0, 1, 2, 3].map(value => ( <ListItem key={value} dense button className={classes.listItem}> <Avatar alt="Remy Sharp" src="/static/images/remy.jpg" /> <ListItemText primary={`Line item ${value + 1}`} /> <ListItemSecondaryAction> <Checkbox onClick={this.handleToggle(value)} checked={this.state.checked.indexOf(value) !== -1} /> </ListItemSecondaryAction> </ListItem> ))} </List> </div> ); } } CheckboxListSecondary.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(CheckboxListSecondary);
docs/src/pages/demos/lists/CheckboxListSecondary.js
1
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.9937762022018433, 0.14977990090847015, 0.00016458625032100827, 0.0030800984241068363, 0.3448721170425415 ]
{ "id": 0, "code_window": [ " <ListItemText primary={`Line item ${value + 1}`} />\n", " <ListItemSecondaryAction>\n", " <Checkbox\n", " onClick={this.handleToggle(value)}\n", " checked={this.state.checked.indexOf(value) !== -1}\n", " />\n", " </ListItemSecondaryAction>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle(value)}\n" ], "file_path": "docs/src/pages/demos/lists/CheckboxListSecondary.js", "type": "replace", "edit_start_line_idx": 50 }
// flow-typed signature: 0d8dc35f8a477a72673435242d172674 // flow-typed version: <<STUB>>/babel-plugin-istanbul_v^4.1.5/flow_v0.56.0 /** * This is an autogenerated libdef stub for: * * 'babel-plugin-istanbul' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-plugin-istanbul' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-plugin-istanbul/lib/index' { declare module.exports: any; } // Filename aliases declare module 'babel-plugin-istanbul/lib/index.js' { declare module.exports: $Exports<'babel-plugin-istanbul/lib/index'>; }
flow-typed/npm/babel-plugin-istanbul_vx.x.x.js
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.00017339941405225545, 0.000168465863680467, 0.00016428096569143236, 0.00016809155931696296, 0.000004080109647475183 ]
{ "id": 0, "code_window": [ " <ListItemText primary={`Line item ${value + 1}`} />\n", " <ListItemSecondaryAction>\n", " <Checkbox\n", " onClick={this.handleToggle(value)}\n", " checked={this.state.checked.indexOf(value) !== -1}\n", " />\n", " </ListItemSecondaryAction>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle(value)}\n" ], "file_path": "docs/src/pages/demos/lists/CheckboxListSecondary.js", "type": "replace", "edit_start_line_idx": 50 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let PhonelinkErase = props => <SvgIconCustom {...props}> <path d="M13 8.2l-1-1-4 4-4-4-1 1 4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4zM19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2z" /> </SvgIconCustom>; PhonelinkErase = pure(PhonelinkErase); PhonelinkErase.muiName = 'SvgIcon'; export default PhonelinkErase;
packages/material-ui-icons/src/PhonelinkErase.js
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.00017241893510799855, 0.00017237011343240738, 0.0001723212917568162, 0.00017237011343240738, 4.882167559117079e-8 ]
{ "id": 0, "code_window": [ " <ListItemText primary={`Line item ${value + 1}`} />\n", " <ListItemSecondaryAction>\n", " <Checkbox\n", " onClick={this.handleToggle(value)}\n", " checked={this.state.checked.indexOf(value) !== -1}\n", " />\n", " </ListItemSecondaryAction>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle(value)}\n" ], "file_path": "docs/src/pages/demos/lists/CheckboxListSecondary.js", "type": "replace", "edit_start_line_idx": 50 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let HdrStrong = props => <SvgIconCustom {...props}> <path d="M17 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zM5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z" /> </SvgIconCustom>; HdrStrong = pure(HdrStrong); HdrStrong.muiName = 'SvgIcon'; export default HdrStrong;
packages/material-ui-icons/src/HdrStrong.js
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.00017254245176445693, 0.0001715450780466199, 0.00017054770432878286, 0.0001715450780466199, 9.973737178370357e-7 ]
{ "id": 1, "code_window": [ " <ListItemText primary=\"Wi-Fi\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('wifi')}\n", " checked={this.state.checked.indexOf('wifi') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('wifi')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 58 }
/* eslint-disable flowtype/require-valid-file-annotation */ import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import List, { ListItem, ListItemIcon, ListItemSecondaryAction, ListItemText, ListSubheader, } from 'material-ui/List'; import Switch from 'material-ui/Switch'; import WifiIcon from 'material-ui-icons/Wifi'; import BluetoothIcon from 'material-ui-icons/Bluetooth'; const styles = theme => ({ root: { width: '100%', maxWidth: 360, background: theme.palette.background.paper, }, }); class SwitchListSecondary extends React.Component { state = { checked: ['wifi'], }; handleToggle = value => () => { const { checked } = this.state; const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } this.setState({ checked: newChecked, }); }; render() { const { classes } = this.props; return ( <div className={classes.root}> <List subheader={<ListSubheader>Settings</ListSubheader>}> <ListItem> <ListItemIcon> <WifiIcon /> </ListItemIcon> <ListItemText primary="Wi-Fi" /> <ListItemSecondaryAction> <Switch onClick={this.handleToggle('wifi')} checked={this.state.checked.indexOf('wifi') !== -1} /> </ListItemSecondaryAction> </ListItem> <ListItem> <ListItemIcon> <BluetoothIcon /> </ListItemIcon> <ListItemText primary="Bluetooth" /> <ListItemSecondaryAction> <Switch onClick={this.handleToggle('bluetooth')} checked={this.state.checked.indexOf('bluetooth') !== -1} /> </ListItemSecondaryAction> </ListItem> </List> </div> ); } } SwitchListSecondary.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(SwitchListSecondary);
docs/src/pages/demos/lists/SwitchListSecondary.js
1
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.9978736639022827, 0.11451192945241928, 0.0001667758187977597, 0.0021874343510717154, 0.31235605478286743 ]
{ "id": 1, "code_window": [ " <ListItemText primary=\"Wi-Fi\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('wifi')}\n", " checked={this.state.checked.indexOf('wifi') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('wifi')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 58 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Email = props => <SvgIconCustom {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z" /> </SvgIconCustom>; Email = pure(Email); Email.muiName = 'SvgIcon'; export default Email;
packages/material-ui-icons/src/Email.js
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.0001727676426526159, 0.00017146591562777758, 0.00017016420315485448, 0.00017146591562777758, 0.0000013017197488807142 ]
{ "id": 1, "code_window": [ " <ListItemText primary=\"Wi-Fi\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('wifi')}\n", " checked={this.state.checked.indexOf('wifi') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('wifi')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 58 }
--- filename: /src/Paper/Paper.js --- <!--- This documentation is automatically generated, do not try to edit it. --> # Paper ## Props | Name | Type | Default | Description | |:-----|:-----|:--------|:------------| | classes | Object | | Useful to extend the style applied to components. | | component | ElementType | 'div' | The component used for the root node. Either a string to use a DOM element or a component. | | elevation | number | 2 | Shadow depth, corresponds to `dp` in the spec. It's accepting values between 0 and 24 inclusive. | | square | boolean | false | If `true`, rounded corners are disabled. | Any other properties supplied will be [spread to the root element](/customization/api#spread). ## CSS API You can override all the class names injected by Material-UI thanks to the `classes` property. This property accepts the following keys: - `root` - `rounded` - `shadow0` - `shadow1` - `shadow2` - `shadow3` - `shadow4` - `shadow5` - `shadow6` - `shadow7` - `shadow8` - `shadow9` - `shadow10` - `shadow11` - `shadow12` - `shadow13` - `shadow14` - `shadow15` - `shadow16` - `shadow17` - `shadow18` - `shadow19` - `shadow20` - `shadow21` - `shadow22` - `shadow23` - `shadow24` Have a look at [overriding with classes](/customization/overrides#overriding-with-classes) section and the [implementation of the component](https://github.com/callemall/material-ui/tree/v1-beta/src/Paper/Paper.js) for more detail. If using the `overrides` key of the theme as documented [here](/customization/themes#customizing-all-instances-of-a-component-type), you need to use the following style sheet name: `MuiPaper`. ## Demos - [Autocomplete](/demos/autocomplete) - [Paper](/demos/paper)
pages/api/paper.md
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.0001746042544255033, 0.00017035107885021716, 0.00015955750131979585, 0.00017155124805867672, 0.000004727596660814015 ]
{ "id": 1, "code_window": [ " <ListItemText primary=\"Wi-Fi\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('wifi')}\n", " checked={this.state.checked.indexOf('wifi') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('wifi')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 58 }
// @flow import React from 'react'; import keycode from 'keycode'; import { assert } from 'chai'; import { ReactWrapper } from 'enzyme'; import TestUtils from 'react-dom/test-utils'; import { createMount } from 'src/test-utils'; import Popover from 'src/Popover'; import SimpleMenu from './fixtures/menus/SimpleMenu'; import mockPortal from '../../test/utils/mockPortal'; function simulateEvent(node, event, mock) { const eventFn = TestUtils.Simulate[event]; if (!eventFn) { throw new TypeError(`simulateEvent: event '${event}' does not exist`); } eventFn(node, mock); } describe('<Menu> integration', () => { let mount; before(() => { mount = createMount(); mockPortal.init(); }); after(() => { mount.cleanUp(); mockPortal.reset(); }); describe('mounted open', () => { let wrapper; let portalLayer; before(() => { wrapper = mount(<SimpleMenu transitionDuration={0} />); }); it('should not be open', () => { const popover = wrapper.find(Popover); assert.strictEqual(popover.props().open, false, 'should have passed open=false to Popover'); const menuEl = document.getElementById('simple-menu'); assert.strictEqual(menuEl, null, 'should not render the menu to the DOM'); }); it('should focus the first item as nothing has been selected', () => { wrapper.setState({ open: true }); portalLayer = wrapper .find('Portal') .instance() .getLayer(); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[0], 'should be the first menu item', ); }); it('should change focus to the 2nd item when down arrow is pressed', () => { simulateEvent(portalLayer.querySelector('ul'), 'keyDown', { which: keycode('down') }); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[1], 'should be the 2nd menu item', ); }); it('should change focus to the 3rd item when down arrow is pressed', () => { simulateEvent(portalLayer.querySelector('ul'), 'keyDown', { which: keycode('down') }); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[2], 'should be the 3rd menu item', ); }); it('should keep focus on the 3rd item (last item) when down arrow is pressed', () => { simulateEvent(portalLayer.querySelector('ul'), 'keyDown', { which: keycode('down') }); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[2], 'should be the 3rd menu item', ); }); it('should keep focus on the last item when a key with no associated action is pressed', () => { simulateEvent(portalLayer.querySelector('ul'), 'keyDown', { which: keycode('right') }); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[2], 'should be the 3rd menu item', ); }); it('should change focus to the 2nd item when up arrow is pressed', () => { simulateEvent(portalLayer.querySelector('ul'), 'keyDown', { which: keycode('up') }); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[1], 'should be the 2nd menu item', ); }); it('should select the 2nd item and close the menu', () => { portalLayer.querySelectorAll('li')[1].click(); assert.strictEqual(wrapper.state().selectedIndex, 1, 'should be index 1'); assert.strictEqual(wrapper.state().open, false, 'should have closed'); }); }); describe('opening with a selected item', () => { let wrapper; before(() => { wrapper = mount(<SimpleMenu transitionDuration={0} />); wrapper.setState({ selectedIndex: 2 }); }); it('should not be open', () => { const popover = wrapper.find(Popover); assert.strictEqual(popover.props().open, false, 'should have passed open=false to Popover'); const menuEl = document.getElementById('simple-menu'); assert.strictEqual(menuEl, null, 'should not render the menu to the DOM'); }); it('should focus the selected item', () => { wrapper.setState({ open: true }); const portalLayer = wrapper .find('Portal') .instance() .getLayer(); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[2], 'should be the 3rd menu item', ); }); it('should select the 2nd item and close the menu', () => { const portalLayer = wrapper .find('Portal') .instance() .getLayer(); const item = portalLayer.querySelector('ul').children[1]; item.click(); assert.strictEqual(wrapper.state().selectedIndex, 1, 'should be index 1'); assert.strictEqual(wrapper.state().open, false, 'should have closed'); }); it('should focus the selected item', () => { wrapper.setState({ open: true }); const portalLayer = wrapper .find('Portal') .instance() .getLayer(); assert.strictEqual( document.activeElement, portalLayer.querySelectorAll('li')[1], 'should be the 2nd menu item', ); }); }); describe('closing', () => { let wrapper; let list; let backdrop; beforeEach(() => { wrapper = mount(<SimpleMenu transitionDuration={0} />); wrapper.setState({ open: true }); const portal = wrapper.find('Portal').props().children; const portalWrapper = new ReactWrapper(portal); list = portalWrapper.find('List'); backdrop = portalWrapper.find('Backdrop'); assert.strictEqual(backdrop.length, 1, 'find a backdrop'); }); it('should close the menu with tab', done => { wrapper.setProps({ onExited() { assert.strictEqual(document.getElementById('[data-mui-test="Menu"]'), null); done(); }, }); assert.strictEqual(wrapper.state().open, true, 'should start open'); list.simulate('keyDown', { which: keycode('tab') }); assert.strictEqual(wrapper.state().open, false, 'should be closed'); }); it('should close the menu using the backdrop', done => { wrapper.setProps({ onExited() { assert.strictEqual(document.getElementById('[data-mui-test="Menu"]'), null); done(); }, }); assert.strictEqual(wrapper.state().open, true, 'should start open'); backdrop.simulate('click'); assert.strictEqual(wrapper.state().open, false, 'should be closed'); }); }); });
test/integration/Menu.spec.js
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.00017564957670401782, 0.0001714233949314803, 0.00016108894487842917, 0.00017157381807919592, 0.0000032751520393503597 ]
{ "id": 2, "code_window": [ " </ListItemIcon>\n", " <ListItemText primary=\"Bluetooth\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('bluetooth')}\n", " checked={this.state.checked.indexOf('bluetooth') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n", " </List>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('bluetooth')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 70 }
/* eslint-disable flowtype/require-valid-file-annotation */ import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import List, { ListItem, ListItemIcon, ListItemSecondaryAction, ListItemText, ListSubheader, } from 'material-ui/List'; import Switch from 'material-ui/Switch'; import WifiIcon from 'material-ui-icons/Wifi'; import BluetoothIcon from 'material-ui-icons/Bluetooth'; const styles = theme => ({ root: { width: '100%', maxWidth: 360, background: theme.palette.background.paper, }, }); class SwitchListSecondary extends React.Component { state = { checked: ['wifi'], }; handleToggle = value => () => { const { checked } = this.state; const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } this.setState({ checked: newChecked, }); }; render() { const { classes } = this.props; return ( <div className={classes.root}> <List subheader={<ListSubheader>Settings</ListSubheader>}> <ListItem> <ListItemIcon> <WifiIcon /> </ListItemIcon> <ListItemText primary="Wi-Fi" /> <ListItemSecondaryAction> <Switch onClick={this.handleToggle('wifi')} checked={this.state.checked.indexOf('wifi') !== -1} /> </ListItemSecondaryAction> </ListItem> <ListItem> <ListItemIcon> <BluetoothIcon /> </ListItemIcon> <ListItemText primary="Bluetooth" /> <ListItemSecondaryAction> <Switch onClick={this.handleToggle('bluetooth')} checked={this.state.checked.indexOf('bluetooth') !== -1} /> </ListItemSecondaryAction> </ListItem> </List> </div> ); } } SwitchListSecondary.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(SwitchListSecondary);
docs/src/pages/demos/lists/SwitchListSecondary.js
1
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.9964259266853333, 0.12363656610250473, 0.00016481099009979516, 0.005997634958475828, 0.3098289370536804 ]
{ "id": 2, "code_window": [ " </ListItemIcon>\n", " <ListItemText primary=\"Bluetooth\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('bluetooth')}\n", " checked={this.state.checked.indexOf('bluetooth') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n", " </List>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('bluetooth')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 70 }
// flow-typed signature: fbf80a98d7e0a1254cbdcc2ad5bbd54c // flow-typed version: <<STUB>>/karma-mocha-reporter_v^2.2.5/flow_v0.56.0 /** * This is an autogenerated libdef stub for: * * 'karma-mocha-reporter' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'karma-mocha-reporter' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ // Filename aliases declare module 'karma-mocha-reporter/index' { declare module.exports: $Exports<'karma-mocha-reporter'>; } declare module 'karma-mocha-reporter/index.js' { declare module.exports: $Exports<'karma-mocha-reporter'>; }
flow-typed/npm/karma-mocha-reporter_vx.x.x.js
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.00017134576046373695, 0.0001682404981693253, 0.00016236565716098994, 0.0001696252729743719, 0.000003642370529632899 ]
{ "id": 2, "code_window": [ " </ListItemIcon>\n", " <ListItemText primary=\"Bluetooth\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('bluetooth')}\n", " checked={this.state.checked.indexOf('bluetooth') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n", " </List>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('bluetooth')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 70 }
// @flow import React from 'react'; import type { Node, ElementType } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = (theme: Object) => ({ root: { color: 'inherit', display: 'table-row', height: 48, '&:focus': { outline: 'none', }, verticalAlign: 'middle', }, head: { height: 56, }, footer: { height: 56, }, hover: { '&:hover': { background: theme.palette.background.contentFrame, }, }, selected: { background: theme.palette.background.appBar, }, }); export type Context = { table: Object, }; type ProvidedProps = { classes: Object, component: ElementType, hover: boolean, selected: boolean, }; export type Props = { /** * Should be valid `<tr>` children such as `TableCell`. */ children?: Node, /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component?: ElementType, /** * If `true`, the table row will shade on hover. */ hover?: boolean, /** * If `true`, the table row will have the selected shading. */ selected?: boolean, }; /** * Will automatically set dynamic row height * based on the material table element parent (head, body, etc). */ function TableRow(props: ProvidedProps & Props, context: Context) { const { classes, className: classNameProp, children, component: Component, hover, selected, ...other } = props; const { table } = context; const className = classNames( classes.root, { [classes.head]: table && table.head, [classes.footer]: table && table.footer, [classes.hover]: table && hover, [classes.selected]: table && selected, }, classNameProp, ); return ( <Component className={className} {...other}> {children} </Component> ); } TableRow.defaultProps = { hover: false, selected: false, component: 'tr', }; TableRow.contextTypes = { table: PropTypes.object, }; export default withStyles(styles, { name: 'MuiTableRow' })(TableRow);
src/Table/TableRow.js
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.00017635188123676926, 0.0001726009213598445, 0.00016391952522099018, 0.00017358582408633083, 0.0000031800225315237185 ]
{ "id": 2, "code_window": [ " </ListItemIcon>\n", " <ListItemText primary=\"Bluetooth\" />\n", " <ListItemSecondaryAction>\n", " <Switch\n", " onClick={this.handleToggle('bluetooth')}\n", " checked={this.state.checked.indexOf('bluetooth') !== -1}\n", " />\n", " </ListItemSecondaryAction>\n", " </ListItem>\n", " </List>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onChange={this.handleToggle('bluetooth')}\n" ], "file_path": "docs/src/pages/demos/lists/SwitchListSecondary.js", "type": "replace", "edit_start_line_idx": 70 }
import * as React from 'react'; import { StandardProps } from '..'; export interface GridListTileProps extends StandardProps< React.HTMLAttributes<HTMLLIElement>, GridListTileClassKey > { cols?: number; component?: React.ReactType; rows?: number; } export type GridListTileClassKey = | 'root' | 'tile' | 'imgFullHeight' | 'imgFullWidth' ; declare const GridListTile: React.ComponentType<GridListTileProps>; export default GridListTile;
src/GridList/GridListTile.d.ts
0
https://github.com/mui/material-ui/commit/5c2c3e869ea483ae9008af71bad1d477351fe3d6
[ 0.00016933016013354063, 0.00016721822612453252, 0.0001635959924897179, 0.0001687285111984238, 0.000002573052825027844 ]
{ "id": 0, "code_window": [ "- name: release-npm-packages\n", " image: grafana/build-container:1.3.1\n", " commands:\n", " - ./scripts/build/release-packages.sh ${DRONE_TAG}\n", " environment:\n", " NPM_TOKEN:\n", " from_secret: npm_token\n", " depends_on:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " GITHUB_PACKAGE_TOKEN:\n", " from_secret: github_package_token\n" ], "file_path": ".drone.yml", "type": "add", "edit_start_line_idx": 968 }
load( 'scripts/lib.star', 'test_release_ver', 'build_image', 'publish_image', 'pipeline', 'lint_backend_step', 'codespell_step', 'shellcheck_step', 'dashboard_schemas_check', 'test_backend_step', 'test_frontend_step', 'build_backend_step', 'build_frontend_step', 'build_plugins_step', 'gen_version_step', 'package_step', 'e2e_tests_server_step', 'e2e_tests_step', 'build_storybook_step', 'copy_packages_for_docker_step', 'build_docker_images_step', 'postgres_integration_tests_step', 'mysql_integration_tests_step', 'get_windows_steps', 'benchmark_ldap_step', 'ldap_service', 'frontend_metrics_step', 'publish_storybook_step', 'upload_packages_step', 'notify_pipeline', 'integration_test_services', 'publish_packages_step', ) def release_npm_packages_step(edition, ver_mode): if edition == 'enterprise': return None if ver_mode == 'release': commands = ['./scripts/build/release-packages.sh ${DRONE_TAG}'] else: commands = [] return { 'name': 'release-npm-packages', 'image': build_image, 'depends_on': [ # Has to run after publish-storybook since this step cleans the files publish-storybook depends on 'publish-storybook', ], 'environment': { 'NPM_TOKEN': { 'from_secret': 'npm_token', }, }, 'commands': commands, } def get_steps(edition, ver_mode): should_publish = ver_mode in ('release', 'test-release',) should_upload = should_publish or ver_mode in ('release-branch',) include_enterprise2 = edition == 'enterprise' steps = [ lint_backend_step(edition=edition), codespell_step(), shellcheck_step(), dashboard_schemas_check(), test_backend_step(edition=edition), test_frontend_step(), build_backend_step(edition=edition, ver_mode=ver_mode), build_frontend_step(edition=edition, ver_mode=ver_mode), build_plugins_step(edition=edition, sign=True), ] # Have to insert Enterprise2 steps before they're depended on (in the gen-version step) if include_enterprise2: edition2 = 'enterprise2' steps.extend([ lint_backend_step(edition=edition2), test_backend_step(edition=edition2), build_backend_step(edition=edition2, ver_mode=ver_mode, variants=['linux-x64']), ]) # Insert remaining steps steps.extend([ gen_version_step(ver_mode=ver_mode, include_enterprise2=include_enterprise2), package_step(edition=edition, ver_mode=ver_mode), e2e_tests_server_step(edition=edition), e2e_tests_step(edition=edition), build_storybook_step(edition=edition, ver_mode=ver_mode), copy_packages_for_docker_step(), build_docker_images_step(edition=edition, ver_mode=ver_mode, publish=should_publish), build_docker_images_step(edition=edition, ver_mode=ver_mode, ubuntu=True, publish=should_publish), postgres_integration_tests_step(), mysql_integration_tests_step(), ]) if should_upload: steps.append(upload_packages_step(edition=edition, ver_mode=ver_mode)) if should_publish: steps.extend([ publish_storybook_step(edition=edition, ver_mode=ver_mode), release_npm_packages_step(edition=edition, ver_mode=ver_mode), ]) windows_steps = get_windows_steps(edition=edition, ver_mode=ver_mode) if include_enterprise2: edition2 = 'enterprise2' steps.extend([ package_step(edition=edition2, ver_mode=ver_mode, variants=['linux-x64']), e2e_tests_server_step(edition=edition2, port=3002), e2e_tests_step(edition=edition2, port=3002), ]) if should_upload: steps.append(upload_packages_step(edition=edition2, ver_mode=ver_mode)) return steps, windows_steps def get_oss_pipelines(trigger, ver_mode): services = integration_test_services() steps, windows_steps = get_steps(edition='oss', ver_mode=ver_mode) return [ pipeline( name='oss-build-{}'.format(ver_mode), edition='oss', trigger=trigger, services=services, steps=steps, ver_mode=ver_mode, ), pipeline( name='oss-windows-{}'.format(ver_mode), edition='oss', trigger=trigger, steps=windows_steps, platform='windows', depends_on=['oss-build-{}'.format(ver_mode)], ver_mode=ver_mode, ), ] def get_enterprise_pipelines(trigger, ver_mode): services = integration_test_services() steps, windows_steps = get_steps(edition='enterprise', ver_mode=ver_mode) return [ pipeline( name='enterprise-build-{}'.format(ver_mode), edition='enterprise', trigger=trigger, services=services, steps=steps, ver_mode=ver_mode, ), pipeline( name='enterprise-windows-{}'.format(ver_mode), edition='enterprise', trigger=trigger, steps=windows_steps, platform='windows', depends_on=['enterprise-build-{}'.format(ver_mode)], ver_mode=ver_mode, ), ] def release_pipelines(ver_mode='release', trigger=None): services = integration_test_services() if not trigger: trigger = { 'ref': ['refs/tags/v*',], } should_publish = ver_mode in ('release', 'test-release',) # The release pipelines include also enterprise ones, so both editions are built for a release. # We could also solve this by triggering a downstream build for the enterprise repo, but by including enterprise # in OSS release builds, we simplify the UX for the release engineer. oss_pipelines = get_oss_pipelines(ver_mode=ver_mode, trigger=trigger) enterprise_pipelines = get_enterprise_pipelines(ver_mode=ver_mode, trigger=trigger) pipelines = oss_pipelines + enterprise_pipelines if should_publish: publish_pipeline = pipeline( name='publish-{}'.format(ver_mode), trigger=trigger, edition='oss', steps=[ publish_packages_step(edition='oss', ver_mode=ver_mode), publish_packages_step(edition='enterprise', ver_mode=ver_mode), ], depends_on=[p['name'] for p in oss_pipelines + enterprise_pipelines], install_deps=False, ver_mode=ver_mode, ) pipelines.append(publish_pipeline) pipelines.append(notify_pipeline( name='notify-{}'.format(ver_mode), slack_channel='grafana-ci-notifications', trigger=trigger, depends_on=[p['name'] for p in pipelines], )) return pipelines def test_release_pipelines(): ver_mode = 'test-release' services = integration_test_services() trigger = { 'event': ['custom',], } oss_pipelines = get_oss_pipelines(ver_mode=ver_mode, trigger=trigger) enterprise_pipelines = get_enterprise_pipelines(ver_mode=ver_mode, trigger=trigger) publish_cmd = './bin/grabpl publish-packages --edition {{}} --dry-run {}'.format(test_release_ver) publish_pipeline = pipeline( name='publish-{}'.format(ver_mode), trigger=trigger, edition='oss', steps=[ publish_packages_step(edition='oss', ver_mode=ver_mode), publish_packages_step(edition='enterprise', ver_mode=ver_mode), ], depends_on=[p['name'] for p in oss_pipelines + enterprise_pipelines], install_deps=False, ver_mode=ver_mode, ) pipelines = oss_pipelines + enterprise_pipelines + [publish_pipeline,] pipelines.append(notify_pipeline( name='notify-{}'.format(ver_mode), slack_channel='grafana-ci-notifications', trigger=trigger, depends_on=[p['name'] for p in pipelines], )) return pipelines
scripts/release.star
1
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.008495952934026718, 0.0007327472558245063, 0.00016542027879040688, 0.00017272827972192317, 0.0017687565414234996 ]
{ "id": 0, "code_window": [ "- name: release-npm-packages\n", " image: grafana/build-container:1.3.1\n", " commands:\n", " - ./scripts/build/release-packages.sh ${DRONE_TAG}\n", " environment:\n", " NPM_TOKEN:\n", " from_secret: npm_token\n", " depends_on:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " GITHUB_PACKAGE_TOKEN:\n", " from_secret: github_package_token\n" ], "file_path": ".drone.yml", "type": "add", "edit_start_line_idx": 968 }
elasticsearch5: image: elasticsearch:5 command: elasticsearch ports: - '10200:9200' - '10300:9300' fake-elastic5-data: image: grafana/fake-data-gen links: - elasticsearch5 environment: FD_SERVER: elasticsearch5 FD_DATASOURCE: elasticsearch FD_PORT: 9200
devenv/docker/blocks/elastic5/docker-compose.yaml
0
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.0001677331601968035, 0.00016718200640752912, 0.0001666308380663395, 0.00016718200640752912, 5.511610652320087e-7 ]
{ "id": 0, "code_window": [ "- name: release-npm-packages\n", " image: grafana/build-container:1.3.1\n", " commands:\n", " - ./scripts/build/release-packages.sh ${DRONE_TAG}\n", " environment:\n", " NPM_TOKEN:\n", " from_secret: npm_token\n", " depends_on:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " GITHUB_PACKAGE_TOKEN:\n", " from_secret: github_package_token\n" ], "file_path": ".drone.yml", "type": "add", "edit_start_line_idx": 968 }
+++ title = "Share query results" weight = 310 +++ # Share query results between panels Grafana let you use the query result from one panel for any other panel in the dashboard. Sharing query results across panels reduces the number of queries made to your data source, which can improve the performance of your dashboard. The Dashboard data source lets you select a panel in your dashboard that contains the queries โ€Œyou want to share the results for. Instead of sending a separate query for each panel, Grafana sends one query and other panels use the query results to construct visualizations. This strategy can drastically reduce the number of queries being made when you for example have several panels visualizing the same data. To share data source queries with another panel: 1. [Create a dashboard]({{< relref "../getting-started/getting-started.md#create-a-dashboard" >}}). 1. [Add a panel]({{< relref "add-a-panel.md" >}}) to the dashboard. 1. Change the title to "Source panel". You'll use this panel as a source for the other panels. Define the [query]({{< relref "queries.md" >}}) or queries that will be shared. If you don't have a data source available at the moment, then you can use the **Grafana** data source, which returns a random time series that you can use for testing. 1. Add a second panel and select the **Dashboard** data source in the query editor. 1. In the **Use results from panel list**, select the first panel you created. All queries defined in the source panel are now available to the new panel. Queries made in the source panel can be shared with multiple panels. You can click on any of the queries to go to the panel where they are defined.
docs/sources/panels/share-query-results.md
0
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.00016471357957925647, 0.00016403426707256585, 0.000163366217748262, 0.00016402303299400955, 5.501156010723207e-7 ]
{ "id": 0, "code_window": [ "- name: release-npm-packages\n", " image: grafana/build-container:1.3.1\n", " commands:\n", " - ./scripts/build/release-packages.sh ${DRONE_TAG}\n", " environment:\n", " NPM_TOKEN:\n", " from_secret: npm_token\n", " depends_on:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " GITHUB_PACKAGE_TOKEN:\n", " from_secret: github_package_token\n" ], "file_path": ".drone.yml", "type": "add", "edit_start_line_idx": 968 }
package plugins import ( "fmt" "runtime" "strings" ) func ComposePluginStartCommand(executable string) string { os := strings.ToLower(runtime.GOOS) arch := runtime.GOARCH extension := "" if os == "windows" { extension = ".exe" } return fmt.Sprintf("%s_%s_%s%s", executable, os, strings.ToLower(arch), extension) }
pkg/plugins/backend_utils.go
0
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.00018501990416552871, 0.0001767325884429738, 0.00016844527272041887, 0.0001767325884429738, 0.000008287315722554922 ]
{ "id": 2, "code_window": [ " 'NPM_TOKEN': {\n", " 'from_secret': 'npm_token',\n", " },\n", " },\n", " 'commands': commands,\n", " }\n", "\n", "def get_steps(edition, ver_mode):\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'GITHUB_PACKAGE_TOKEN': {\n", " 'from_secret': 'github_package_token',\n", " },\n" ], "file_path": "scripts/release.star", "type": "add", "edit_start_line_idx": 55 }
load( 'scripts/lib.star', 'test_release_ver', 'build_image', 'publish_image', 'pipeline', 'lint_backend_step', 'codespell_step', 'shellcheck_step', 'dashboard_schemas_check', 'test_backend_step', 'test_frontend_step', 'build_backend_step', 'build_frontend_step', 'build_plugins_step', 'gen_version_step', 'package_step', 'e2e_tests_server_step', 'e2e_tests_step', 'build_storybook_step', 'copy_packages_for_docker_step', 'build_docker_images_step', 'postgres_integration_tests_step', 'mysql_integration_tests_step', 'get_windows_steps', 'benchmark_ldap_step', 'ldap_service', 'frontend_metrics_step', 'publish_storybook_step', 'upload_packages_step', 'notify_pipeline', 'integration_test_services', 'publish_packages_step', ) def release_npm_packages_step(edition, ver_mode): if edition == 'enterprise': return None if ver_mode == 'release': commands = ['./scripts/build/release-packages.sh ${DRONE_TAG}'] else: commands = [] return { 'name': 'release-npm-packages', 'image': build_image, 'depends_on': [ # Has to run after publish-storybook since this step cleans the files publish-storybook depends on 'publish-storybook', ], 'environment': { 'NPM_TOKEN': { 'from_secret': 'npm_token', }, }, 'commands': commands, } def get_steps(edition, ver_mode): should_publish = ver_mode in ('release', 'test-release',) should_upload = should_publish or ver_mode in ('release-branch',) include_enterprise2 = edition == 'enterprise' steps = [ lint_backend_step(edition=edition), codespell_step(), shellcheck_step(), dashboard_schemas_check(), test_backend_step(edition=edition), test_frontend_step(), build_backend_step(edition=edition, ver_mode=ver_mode), build_frontend_step(edition=edition, ver_mode=ver_mode), build_plugins_step(edition=edition, sign=True), ] # Have to insert Enterprise2 steps before they're depended on (in the gen-version step) if include_enterprise2: edition2 = 'enterprise2' steps.extend([ lint_backend_step(edition=edition2), test_backend_step(edition=edition2), build_backend_step(edition=edition2, ver_mode=ver_mode, variants=['linux-x64']), ]) # Insert remaining steps steps.extend([ gen_version_step(ver_mode=ver_mode, include_enterprise2=include_enterprise2), package_step(edition=edition, ver_mode=ver_mode), e2e_tests_server_step(edition=edition), e2e_tests_step(edition=edition), build_storybook_step(edition=edition, ver_mode=ver_mode), copy_packages_for_docker_step(), build_docker_images_step(edition=edition, ver_mode=ver_mode, publish=should_publish), build_docker_images_step(edition=edition, ver_mode=ver_mode, ubuntu=True, publish=should_publish), postgres_integration_tests_step(), mysql_integration_tests_step(), ]) if should_upload: steps.append(upload_packages_step(edition=edition, ver_mode=ver_mode)) if should_publish: steps.extend([ publish_storybook_step(edition=edition, ver_mode=ver_mode), release_npm_packages_step(edition=edition, ver_mode=ver_mode), ]) windows_steps = get_windows_steps(edition=edition, ver_mode=ver_mode) if include_enterprise2: edition2 = 'enterprise2' steps.extend([ package_step(edition=edition2, ver_mode=ver_mode, variants=['linux-x64']), e2e_tests_server_step(edition=edition2, port=3002), e2e_tests_step(edition=edition2, port=3002), ]) if should_upload: steps.append(upload_packages_step(edition=edition2, ver_mode=ver_mode)) return steps, windows_steps def get_oss_pipelines(trigger, ver_mode): services = integration_test_services() steps, windows_steps = get_steps(edition='oss', ver_mode=ver_mode) return [ pipeline( name='oss-build-{}'.format(ver_mode), edition='oss', trigger=trigger, services=services, steps=steps, ver_mode=ver_mode, ), pipeline( name='oss-windows-{}'.format(ver_mode), edition='oss', trigger=trigger, steps=windows_steps, platform='windows', depends_on=['oss-build-{}'.format(ver_mode)], ver_mode=ver_mode, ), ] def get_enterprise_pipelines(trigger, ver_mode): services = integration_test_services() steps, windows_steps = get_steps(edition='enterprise', ver_mode=ver_mode) return [ pipeline( name='enterprise-build-{}'.format(ver_mode), edition='enterprise', trigger=trigger, services=services, steps=steps, ver_mode=ver_mode, ), pipeline( name='enterprise-windows-{}'.format(ver_mode), edition='enterprise', trigger=trigger, steps=windows_steps, platform='windows', depends_on=['enterprise-build-{}'.format(ver_mode)], ver_mode=ver_mode, ), ] def release_pipelines(ver_mode='release', trigger=None): services = integration_test_services() if not trigger: trigger = { 'ref': ['refs/tags/v*',], } should_publish = ver_mode in ('release', 'test-release',) # The release pipelines include also enterprise ones, so both editions are built for a release. # We could also solve this by triggering a downstream build for the enterprise repo, but by including enterprise # in OSS release builds, we simplify the UX for the release engineer. oss_pipelines = get_oss_pipelines(ver_mode=ver_mode, trigger=trigger) enterprise_pipelines = get_enterprise_pipelines(ver_mode=ver_mode, trigger=trigger) pipelines = oss_pipelines + enterprise_pipelines if should_publish: publish_pipeline = pipeline( name='publish-{}'.format(ver_mode), trigger=trigger, edition='oss', steps=[ publish_packages_step(edition='oss', ver_mode=ver_mode), publish_packages_step(edition='enterprise', ver_mode=ver_mode), ], depends_on=[p['name'] for p in oss_pipelines + enterprise_pipelines], install_deps=False, ver_mode=ver_mode, ) pipelines.append(publish_pipeline) pipelines.append(notify_pipeline( name='notify-{}'.format(ver_mode), slack_channel='grafana-ci-notifications', trigger=trigger, depends_on=[p['name'] for p in pipelines], )) return pipelines def test_release_pipelines(): ver_mode = 'test-release' services = integration_test_services() trigger = { 'event': ['custom',], } oss_pipelines = get_oss_pipelines(ver_mode=ver_mode, trigger=trigger) enterprise_pipelines = get_enterprise_pipelines(ver_mode=ver_mode, trigger=trigger) publish_cmd = './bin/grabpl publish-packages --edition {{}} --dry-run {}'.format(test_release_ver) publish_pipeline = pipeline( name='publish-{}'.format(ver_mode), trigger=trigger, edition='oss', steps=[ publish_packages_step(edition='oss', ver_mode=ver_mode), publish_packages_step(edition='enterprise', ver_mode=ver_mode), ], depends_on=[p['name'] for p in oss_pipelines + enterprise_pipelines], install_deps=False, ver_mode=ver_mode, ) pipelines = oss_pipelines + enterprise_pipelines + [publish_pipeline,] pipelines.append(notify_pipeline( name='notify-{}'.format(ver_mode), slack_channel='grafana-ci-notifications', trigger=trigger, depends_on=[p['name'] for p in pipelines], )) return pipelines
scripts/release.star
1
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.9952023029327393, 0.14173099398612976, 0.000166505211382173, 0.002218091394752264, 0.3316791355609894 ]
{ "id": 2, "code_window": [ " 'NPM_TOKEN': {\n", " 'from_secret': 'npm_token',\n", " },\n", " },\n", " 'commands': commands,\n", " }\n", "\n", "def get_steps(edition, ver_mode):\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'GITHUB_PACKAGE_TOKEN': {\n", " 'from_secret': 'github_package_token',\n", " },\n" ], "file_path": "scripts/release.star", "type": "add", "edit_start_line_idx": 55 }
# Lines starting with '#' are comments. # Each line is a file pattern followed by one or more owners. # More details are here: https://help.github.com/articles/about-codeowners/ # The '*' pattern is global owners. # Order is important. The last matching pattern has the most precedence. # The folders are ordered as follows: # In each subsection folders are ordered first by depth, then alphabetically. # This should make it easy to add new rules without breaking existing ones. # Documentation owner: Diana Payton /docs/ @grafana/docs-squad /contribute/ @marcusolsson @grafana/docs-squad /docs/sources/developers/plugins/ @marcusolsson /docs/sources/enterprise/ @osg-grafana # Backend code *.go @grafana/backend-platform go.mod @grafana/backend-platform go.sum @grafana/backend-platform # Backend code docs /contribute/style-guides/backend.md @grafana/backend-platform /e2e @grafana/grafana-frontend-platform /packages @grafana/grafana-frontend-platform /plugins-bundled @grafana/grafana-frontend-platform /public @grafana/grafana-frontend-platform /scripts/build/release-packages.sh @grafana/grafana-frontend-platform /scripts/circle-release-next-packages.sh @grafana/grafana-frontend-platform /scripts/ci-frontend-metrics.sh @grafana/grafana-frontend-platform /scripts/grunt @grafana/grafana-frontend-platform /scripts/webpack @grafana/grafana-frontend-platform package.json @grafana/grafana-frontend-platform tsconfig.json @grafana/grafana-frontend-platform lerna.json @grafana/grafana-frontend-platform .babelrc @grafana/grafana-frontend-platform .prettierrc.js @grafana/grafana-frontend-platform .eslintrc @grafana/grafana-frontend-platform # @grafana/ui component documentation *.mdx @marcusolsson @jessover9000 @grafana/grafana-frontend-platform /public/app/features/explore/ @grafana/observability-squad /packages/jaeger-ui-components/ @grafana/observability-squad # Core datasources /public/app/plugins/datasource/cloudwatch @grafana/backend-platform @grafana/observability-squad /public/app/plugins/datasource/elasticsearch @grafana/observability-squad /public/app/plugins/datasource/grafana-azure-monitor-datasource @grafana/backend-platform /public/app/plugins/datasource/graphite @grafana/observability-squad /public/app/plugins/datasource/influxdb @grafana/observability-squad /public/app/plugins/datasource/jaeger @grafana/observability-squad /public/app/plugins/datasource/loki @grafana/observability-squad /public/app/plugins/datasource/mssql @grafana/backend-platform /public/app/plugins/datasource/mysql @grafana/backend-platform /public/app/plugins/datasource/opentsdb @grafana/backend-platform /public/app/plugins/datasource/postgres @grafana/backend-platform /public/app/plugins/datasource/prometheus @grafana/observability-squad /public/app/plugins/datasource/cloud-monitoring @grafana/backend-platform /public/app/plugins/datasource/zipkin @grafana/observability-squad # Cloud middleware /grafana-mixin/ @grafana/cloud-middleware
.github/CODEOWNERS
0
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.00017338336328975856, 0.00017144759476650506, 0.00017001386731863022, 0.00017081282567232847, 0.000001366916649203631 ]
{ "id": 2, "code_window": [ " 'NPM_TOKEN': {\n", " 'from_secret': 'npm_token',\n", " },\n", " },\n", " 'commands': commands,\n", " }\n", "\n", "def get_steps(edition, ver_mode):\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'GITHUB_PACKAGE_TOKEN': {\n", " 'from_secret': 'github_package_token',\n", " },\n" ], "file_path": "scripts/release.star", "type": "add", "edit_start_line_idx": 55 }
import React, { HTMLProps, useEffect } from 'react'; import { useForm, Mode, OnSubmit, DeepPartial } from 'react-hook-form'; import { FormAPI } from '../../types'; import { css } from 'emotion'; interface FormProps<T> extends Omit<HTMLProps<HTMLFormElement>, 'onSubmit'> { validateOn?: Mode; validateOnMount?: boolean; validateFieldsOnMount?: string[]; defaultValues?: DeepPartial<T>; onSubmit: OnSubmit<T>; children: (api: FormAPI<T>) => React.ReactNode; /** Sets max-width for container. Use it instead of setting individual widths on inputs.*/ maxWidth?: number | 'none'; } export function Form<T>({ defaultValues, onSubmit, validateOnMount = false, validateFieldsOnMount, children, validateOn = 'onSubmit', maxWidth = 600, ...htmlProps }: FormProps<T>) { const { handleSubmit, register, errors, control, triggerValidation, getValues, formState, watch } = useForm<T>({ mode: validateOn, defaultValues, }); useEffect(() => { if (validateOnMount) { triggerValidation(validateFieldsOnMount); } }, [triggerValidation, validateFieldsOnMount, validateOnMount]); return ( <form className={css` max-width: ${maxWidth !== 'none' ? maxWidth + 'px' : maxWidth}; width: 100%; `} onSubmit={handleSubmit(onSubmit)} {...htmlProps} > {children({ register, errors, control, getValues, formState, watch })} </form> ); }
packages/grafana-ui/src/components/Forms/Form.tsx
0
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.00017251759709324688, 0.0001707950868876651, 0.00016920120106078684, 0.0001705754257272929, 0.000001132363195210928 ]
{ "id": 2, "code_window": [ " 'NPM_TOKEN': {\n", " 'from_secret': 'npm_token',\n", " },\n", " },\n", " 'commands': commands,\n", " }\n", "\n", "def get_steps(edition, ver_mode):\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'GITHUB_PACKAGE_TOKEN': {\n", " 'from_secret': 'github_package_token',\n", " },\n" ], "file_path": "scripts/release.star", "type": "add", "edit_start_line_idx": 55 }
import React, { ComponentProps, useState } from 'react'; import { InlineField, Input } from '@grafana/ui'; import { useDispatch } from '../../../../hooks/useStatelessReducer'; import { changeMetricSetting } from '../state/actions'; import { ChangeMetricSettingAction } from '../state/types'; import { SettingKeyOf } from '../../../types'; import { MetricAggregationWithSettings } from '../aggregations'; import { uniqueId } from 'lodash'; interface Props<T extends MetricAggregationWithSettings, K extends SettingKeyOf<T>> { label: string; settingName: K; metric: T; placeholder?: ComponentProps<typeof Input>['placeholder']; tooltip?: ComponentProps<typeof InlineField>['tooltip']; } export function SettingField<T extends MetricAggregationWithSettings, K extends SettingKeyOf<T>>({ label, settingName, metric, placeholder, tooltip, }: Props<T, K>) { const dispatch = useDispatch<ChangeMetricSettingAction<T>>(); const [id] = useState(uniqueId(`es-field-id-`)); const settings = metric.settings; return ( <InlineField label={label} labelWidth={16} tooltip={tooltip}> <Input id={id} placeholder={placeholder} onBlur={(e) => dispatch(changeMetricSetting(metric, settingName, e.target.value as any))} defaultValue={settings?.[settingName as keyof typeof settings]} /> </InlineField> ); }
public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/SettingsEditor/SettingField.tsx
0
https://github.com/grafana/grafana/commit/54b1ce2cdb7afefcdf5745c54d72344bbfc4175b
[ 0.0001749459042912349, 0.00017404186655767262, 0.00017329180263914168, 0.00017396488692611456, 5.903415853936167e-7 ]
{ "id": 1, "code_window": [ "\n", "#### --use-npm flag in storybook CLI\n", "\n", "The `--use-npm` is now removed. Use `--package-manager=npm` instead. [More info here](#cli-option---use-npm-deprecated).\n", "\n", "##### `setGlobalConfig` from `@storybook/react`\n", "\n", "The `setGlobalConfig` (used for reusing stories in your tests) is now removed in favor of `setProjectAnnotations`.\n", "\n", "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "#### `setGlobalConfig` from `@storybook/react`\n" ], "file_path": "MIGRATION.md", "type": "replace", "edit_start_line_idx": 576 }
// noinspection JSUnusedGlobalSymbols import * as fs from 'fs-extra'; import type { RequestHandler } from 'express'; import type { ViteDevServer } from 'vite'; import express from 'express'; import { dirname, join, parse } from 'path'; import type { Options, StorybookConfig as StorybookBaseConfig } from '@storybook/types'; import { transformIframeHtml } from './transform-iframe-html'; import { createViteServer } from './vite-server'; import { build as viteBuild } from './build'; import type { ViteBuilder, StorybookConfigVite } from './types'; export { withoutVitePlugins } from './utils/without-vite-plugins'; export { hasVitePlugins } from './utils/has-vite-plugins'; export * from './types'; /** * @deprecated * * Import `StorybookConfig` from your framework, such as: * * `import type { StorybookConfig } from '@storybook/react-vite';` */ export type StorybookViteConfig = StorybookBaseConfig & StorybookConfigVite; const getAbsolutePath = <I extends string>(input: I): I => dirname(require.resolve(join(input, 'package.json'))) as any; function iframeMiddleware(options: Options, server: ViteDevServer): RequestHandler { return async (req, res, next) => { if (!req.url.match(/^\/iframe\.html($|\?)/)) { next(); return; } // We need to handle `html-proxy` params for style tag HMR https://github.com/storybookjs/builder-vite/issues/266#issuecomment-1055677865 // e.g. /iframe.html?html-proxy&index=0.css if (req.query['html-proxy'] !== undefined) { next(); return; } const indexHtml = await fs.readFile( require.resolve('@storybook/builder-vite/input/iframe.html'), 'utf-8' ); const generated = await transformIframeHtml(indexHtml, options); const transformed = await server.transformIndexHtml('/iframe.html', generated); res.setHeader('Content-Type', 'text/html'); res.status(200).send(transformed); }; } let server: ViteDevServer; export async function bail(): Promise<void> { return server?.close(); } export const start: ViteBuilder['start'] = async ({ startTime, options, router, server: devServer, }) => { server = await createViteServer(options as Options, devServer); const previewResolvedDir = getAbsolutePath('@storybook/preview'); const previewDirOrigin = join(previewResolvedDir, 'dist'); router.use(`/sb-preview`, express.static(previewDirOrigin, { immutable: true, maxAge: '5m' })); router.use(iframeMiddleware(options as Options, server)); router.use(server.middlewares); return { bail, stats: { toJson: () => null }, totalTime: process.hrtime(startTime), }; }; export const build: ViteBuilder['build'] = async ({ options }) => { const viteCompilation = viteBuild(options as Options); const previewResolvedDir = getAbsolutePath('@storybook/preview'); const previewDirOrigin = join(previewResolvedDir, 'dist'); const previewDirTarget = join(options.outputDir || '', `sb-preview`); const previewFiles = fs.copy(previewDirOrigin, previewDirTarget, { filter: (src) => { const { ext } = parse(src); if (ext) { return ext === '.js'; } return true; }, }); const [out] = await Promise.all([viteCompilation, previewFiles]); return out; };
code/builders/builder-vite/src/index.ts
1
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00023302649788092822, 0.0001923091331264004, 0.00016888463869690895, 0.00018003863806370646, 0.000024069249775493518 ]
{ "id": 1, "code_window": [ "\n", "#### --use-npm flag in storybook CLI\n", "\n", "The `--use-npm` is now removed. Use `--package-manager=npm` instead. [More info here](#cli-option---use-npm-deprecated).\n", "\n", "##### `setGlobalConfig` from `@storybook/react`\n", "\n", "The `setGlobalConfig` (used for reusing stories in your tests) is now removed in favor of `setProjectAnnotations`.\n", "\n", "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "#### `setGlobalConfig` from `@storybook/react`\n" ], "file_path": "MIGRATION.md", "type": "replace", "edit_start_line_idx": 576 }
```js // Button.stories.js|jsx export const Basic { parameters: { docs: { story: { autoplay: true }, }, }, }; ```
docs/snippets/common/api-doc-block-story-parameter.js.mdx
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00017833437595982105, 0.0001724474277580157, 0.00016656047955621034, 0.0001724474277580157, 0.000005886948201805353 ]
{ "id": 1, "code_window": [ "\n", "#### --use-npm flag in storybook CLI\n", "\n", "The `--use-npm` is now removed. Use `--package-manager=npm` instead. [More info here](#cli-option---use-npm-deprecated).\n", "\n", "##### `setGlobalConfig` from `@storybook/react`\n", "\n", "The `setGlobalConfig` (used for reusing stories in your tests) is now removed in favor of `setProjectAnnotations`.\n", "\n", "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "#### `setGlobalConfig` from `@storybook/react`\n" ], "file_path": "MIGRATION.md", "type": "replace", "edit_start_line_idx": 576 }
import React from 'react'; export enum EnumWithExtraProps { key1 = 'key1', key2 = 'key2', } export const component = () => <div>hello</div>;
code/renderers/react/template/stories/docgen-components/9832-ts-enum-export/input.tsx
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00017115307855419815, 0.00017115307855419815, 0.00017115307855419815, 0.00017115307855419815, 0 ]
{ "id": 1, "code_window": [ "\n", "#### --use-npm flag in storybook CLI\n", "\n", "The `--use-npm` is now removed. Use `--package-manager=npm` instead. [More info here](#cli-option---use-npm-deprecated).\n", "\n", "##### `setGlobalConfig` from `@storybook/react`\n", "\n", "The `setGlobalConfig` (used for reusing stories in your tests) is now removed in favor of `setProjectAnnotations`.\n", "\n", "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "#### `setGlobalConfig` from `@storybook/react`\n" ], "file_path": "MIGRATION.md", "type": "replace", "edit_start_line_idx": 576 }
```ts // .storybook/preview.ts // Replace your-framework with the framework you are using (e.g., react, vue3) import { Preview } from '@storybook/your-framework'; import { themes, ensure } from '@storybook/theming'; const preview: Preview = { parameters: { controls: { matchers: { color: /(background|color)$/i, date: /Date$/, }, }, docs: { theme: ensure(themes.dark), // The replacement theme to use }, }, }; export default preview; ```
docs/snippets/common/storybook-preview-auto-docs-override-theme.ts.mdx
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00025568102137185633, 0.00019711740605998784, 0.0001664886949583888, 0.00016918248729780316, 0.00004142533362028189 ]
{ "id": 2, "code_window": [ "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n", "```\n", "\n", "## From version 7.5.0 to 7.6.0\n", "\n", "#### CommonJS with Vite is deprecated\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "#### StorybookViteConfig type from @storybook/builder-vite\n", "\n", "The `StorybookViteConfig` type is now removed in favor of `StorybookConfig`:\n", "\n", "```ts\n", "import type { StorybookConfig } from '@storybook/react-vite';\n", "```\n", "\n" ], "file_path": "MIGRATION.md", "type": "add", "edit_start_line_idx": 584 }
// noinspection JSUnusedGlobalSymbols import * as fs from 'fs-extra'; import type { RequestHandler } from 'express'; import type { ViteDevServer } from 'vite'; import express from 'express'; import { dirname, join, parse } from 'path'; import type { Options, StorybookConfig as StorybookBaseConfig } from '@storybook/types'; import { transformIframeHtml } from './transform-iframe-html'; import { createViteServer } from './vite-server'; import { build as viteBuild } from './build'; import type { ViteBuilder, StorybookConfigVite } from './types'; export { withoutVitePlugins } from './utils/without-vite-plugins'; export { hasVitePlugins } from './utils/has-vite-plugins'; export * from './types'; /** * @deprecated * * Import `StorybookConfig` from your framework, such as: * * `import type { StorybookConfig } from '@storybook/react-vite';` */ export type StorybookViteConfig = StorybookBaseConfig & StorybookConfigVite; const getAbsolutePath = <I extends string>(input: I): I => dirname(require.resolve(join(input, 'package.json'))) as any; function iframeMiddleware(options: Options, server: ViteDevServer): RequestHandler { return async (req, res, next) => { if (!req.url.match(/^\/iframe\.html($|\?)/)) { next(); return; } // We need to handle `html-proxy` params for style tag HMR https://github.com/storybookjs/builder-vite/issues/266#issuecomment-1055677865 // e.g. /iframe.html?html-proxy&index=0.css if (req.query['html-proxy'] !== undefined) { next(); return; } const indexHtml = await fs.readFile( require.resolve('@storybook/builder-vite/input/iframe.html'), 'utf-8' ); const generated = await transformIframeHtml(indexHtml, options); const transformed = await server.transformIndexHtml('/iframe.html', generated); res.setHeader('Content-Type', 'text/html'); res.status(200).send(transformed); }; } let server: ViteDevServer; export async function bail(): Promise<void> { return server?.close(); } export const start: ViteBuilder['start'] = async ({ startTime, options, router, server: devServer, }) => { server = await createViteServer(options as Options, devServer); const previewResolvedDir = getAbsolutePath('@storybook/preview'); const previewDirOrigin = join(previewResolvedDir, 'dist'); router.use(`/sb-preview`, express.static(previewDirOrigin, { immutable: true, maxAge: '5m' })); router.use(iframeMiddleware(options as Options, server)); router.use(server.middlewares); return { bail, stats: { toJson: () => null }, totalTime: process.hrtime(startTime), }; }; export const build: ViteBuilder['build'] = async ({ options }) => { const viteCompilation = viteBuild(options as Options); const previewResolvedDir = getAbsolutePath('@storybook/preview'); const previewDirOrigin = join(previewResolvedDir, 'dist'); const previewDirTarget = join(options.outputDir || '', `sb-preview`); const previewFiles = fs.copy(previewDirOrigin, previewDirTarget, { filter: (src) => { const { ext } = parse(src); if (ext) { return ext === '.js'; } return true; }, }); const [out] = await Promise.all([viteCompilation, previewFiles]); return out; };
code/builders/builder-vite/src/index.ts
1
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.0003166973765473813, 0.0001928436104208231, 0.0001651638449402526, 0.00017054576892405748, 0.00004559645094559528 ]
{ "id": 2, "code_window": [ "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n", "```\n", "\n", "## From version 7.5.0 to 7.6.0\n", "\n", "#### CommonJS with Vite is deprecated\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "#### StorybookViteConfig type from @storybook/builder-vite\n", "\n", "The `StorybookViteConfig` type is now removed in favor of `StorybookConfig`:\n", "\n", "```ts\n", "import type { StorybookConfig } from '@storybook/react-vite';\n", "```\n", "\n" ], "file_path": "MIGRATION.md", "type": "add", "edit_start_line_idx": 584 }
/* eslint-disable no-underscore-dangle */ import type { Component } from './types'; const titleCase = (str: string): string => str .split('-') .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) .join(''); export const getComponentName = (component: Component): string => { if (!component) { return undefined; } if (typeof component === 'string') { if (component.includes('-')) { return titleCase(component); } return component; } if (component.__docgenInfo && component.__docgenInfo.displayName) { return component.__docgenInfo.displayName; } return component.name; }; export function scrollToElement(element: any, block = 'start') { element.scrollIntoView({ behavior: 'smooth', block, inline: 'nearest', }); }
code/ui/blocks/src/blocks/utils.ts
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00017301047046203166, 0.0001703985035419464, 0.00016783428145572543, 0.0001703746384009719, 0.000002365595946685062 ]
{ "id": 2, "code_window": [ "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n", "```\n", "\n", "## From version 7.5.0 to 7.6.0\n", "\n", "#### CommonJS with Vite is deprecated\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "#### StorybookViteConfig type from @storybook/builder-vite\n", "\n", "The `StorybookViteConfig` type is now removed in favor of `StorybookConfig`:\n", "\n", "```ts\n", "import type { StorybookConfig } from '@storybook/react-vite';\n", "```\n", "\n" ], "file_path": "MIGRATION.md", "type": "add", "edit_start_line_idx": 584 }
```tsx // YourComponent.stories.ts|tsx import type { Meta } from 'storybook-solidjs'; import { YourComponent } from './YourComponent'; // Replacing the <Story/> element with a Story function is also a good way of writing decorators. // Useful to prevent the full remount of the component's story. const meta: Meta<typeof YourComponent> = { component: YourComponent, decorators: [(Story) => <div style={{ margin: '3em' }}>{Story()}</div>], }; export default meta; ```
docs/snippets/solid/your-component-with-decorator.story-function-ts.ts.mdx
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00017099420074373484, 0.00016877346206456423, 0.0001665527088334784, 0.00016877346206456423, 0.0000022207459551282227 ]
{ "id": 2, "code_window": [ "```ts\n", "import { setProjectAnnotations } from `@storybook/testing-react`.\n", "```\n", "\n", "## From version 7.5.0 to 7.6.0\n", "\n", "#### CommonJS with Vite is deprecated\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "#### StorybookViteConfig type from @storybook/builder-vite\n", "\n", "The `StorybookViteConfig` type is now removed in favor of `StorybookConfig`:\n", "\n", "```ts\n", "import type { StorybookConfig } from '@storybook/react-vite';\n", "```\n", "\n" ], "file_path": "MIGRATION.md", "type": "add", "edit_start_line_idx": 584 }
import React from 'react'; import { LocationProvider } from '@storybook/router'; import type { Meta, StoryObj } from '@storybook/react'; import { NotificationList } from './NotificationList'; import * as itemStories from './NotificationItem.stories'; const meta = { component: NotificationList, title: 'Notifications/NotificationList', decorators: [ (StoryFn) => ( <LocationProvider> <StoryFn /> </LocationProvider> ), (storyFn) => ( <div style={{ width: '240px', margin: '1rem', position: 'relative', height: '100%' }}> {storyFn()} </div> ), ], excludeStories: /.*Data$/, } satisfies Meta<typeof NotificationList>; export default meta; type Story = StoryObj<typeof meta>; type ItemStories = typeof itemStories & { [key: string]: any }; const items = Array.from(Object.keys(itemStories as ItemStories)) .filter((key) => !['default', '__namedExportsOrder'].includes(key)) .map((key) => (itemStories as ItemStories)[key].args.notification); export const Single: Story = { args: { notifications: [items[0]], clearNotification: () => {}, }, }; export const Multiple: Story = { args: { notifications: items.slice(0, 3), clearNotification: () => {}, }, };
code/ui/manager/src/components/notifications/NotificationList.stories.tsx
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00016644346760585904, 0.0001658237015362829, 0.0001650723716011271, 0.00016574915207456797, 4.841857048631937e-7 ]
{ "id": 4, "code_window": [ "import { transformIframeHtml } from './transform-iframe-html';\n", "import { createViteServer } from './vite-server';\n", "import { build as viteBuild } from './build';\n", "import type { ViteBuilder, StorybookConfigVite } from './types';\n", "\n", "export { withoutVitePlugins } from './utils/without-vite-plugins';\n", "export { hasVitePlugins } from './utils/has-vite-plugins';\n", "\n", "export * from './types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { ViteBuilder } from './types';\n" ], "file_path": "code/builders/builder-vite/src/index.ts", "type": "replace", "edit_start_line_idx": 11 }
// noinspection JSUnusedGlobalSymbols import * as fs from 'fs-extra'; import type { RequestHandler } from 'express'; import type { ViteDevServer } from 'vite'; import express from 'express'; import { dirname, join, parse } from 'path'; import type { Options, StorybookConfig as StorybookBaseConfig } from '@storybook/types'; import { transformIframeHtml } from './transform-iframe-html'; import { createViteServer } from './vite-server'; import { build as viteBuild } from './build'; import type { ViteBuilder, StorybookConfigVite } from './types'; export { withoutVitePlugins } from './utils/without-vite-plugins'; export { hasVitePlugins } from './utils/has-vite-plugins'; export * from './types'; /** * @deprecated * * Import `StorybookConfig` from your framework, such as: * * `import type { StorybookConfig } from '@storybook/react-vite';` */ export type StorybookViteConfig = StorybookBaseConfig & StorybookConfigVite; const getAbsolutePath = <I extends string>(input: I): I => dirname(require.resolve(join(input, 'package.json'))) as any; function iframeMiddleware(options: Options, server: ViteDevServer): RequestHandler { return async (req, res, next) => { if (!req.url.match(/^\/iframe\.html($|\?)/)) { next(); return; } // We need to handle `html-proxy` params for style tag HMR https://github.com/storybookjs/builder-vite/issues/266#issuecomment-1055677865 // e.g. /iframe.html?html-proxy&index=0.css if (req.query['html-proxy'] !== undefined) { next(); return; } const indexHtml = await fs.readFile( require.resolve('@storybook/builder-vite/input/iframe.html'), 'utf-8' ); const generated = await transformIframeHtml(indexHtml, options); const transformed = await server.transformIndexHtml('/iframe.html', generated); res.setHeader('Content-Type', 'text/html'); res.status(200).send(transformed); }; } let server: ViteDevServer; export async function bail(): Promise<void> { return server?.close(); } export const start: ViteBuilder['start'] = async ({ startTime, options, router, server: devServer, }) => { server = await createViteServer(options as Options, devServer); const previewResolvedDir = getAbsolutePath('@storybook/preview'); const previewDirOrigin = join(previewResolvedDir, 'dist'); router.use(`/sb-preview`, express.static(previewDirOrigin, { immutable: true, maxAge: '5m' })); router.use(iframeMiddleware(options as Options, server)); router.use(server.middlewares); return { bail, stats: { toJson: () => null }, totalTime: process.hrtime(startTime), }; }; export const build: ViteBuilder['build'] = async ({ options }) => { const viteCompilation = viteBuild(options as Options); const previewResolvedDir = getAbsolutePath('@storybook/preview'); const previewDirOrigin = join(previewResolvedDir, 'dist'); const previewDirTarget = join(options.outputDir || '', `sb-preview`); const previewFiles = fs.copy(previewDirOrigin, previewDirTarget, { filter: (src) => { const { ext } = parse(src); if (ext) { return ext === '.js'; } return true; }, }); const [out] = await Promise.all([viteCompilation, previewFiles]); return out; };
code/builders/builder-vite/src/index.ts
1
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.8504577279090881, 0.07976559549570084, 0.00016696086095180362, 0.00043209854629822075, 0.24373850226402283 ]
{ "id": 4, "code_window": [ "import { transformIframeHtml } from './transform-iframe-html';\n", "import { createViteServer } from './vite-server';\n", "import { build as viteBuild } from './build';\n", "import type { ViteBuilder, StorybookConfigVite } from './types';\n", "\n", "export { withoutVitePlugins } from './utils/without-vite-plugins';\n", "export { hasVitePlugins } from './utils/has-vite-plugins';\n", "\n", "export * from './types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { ViteBuilder } from './types';\n" ], "file_path": "code/builders/builder-vite/src/index.ts", "type": "replace", "edit_start_line_idx": 11 }
```ts // List.stories.ts|tsx import type { Meta, StoryObj } from '@storybook/react'; import { List } from './List'; const meta: Meta<typeof List> = { component: List, }; export default meta; type Story = StoryObj<typeof List>; //๐Ÿ‘‡ Always an empty list, not super interesting export const Empty: Story = {}; ```
docs/snippets/react/list-story-starter.ts.mdx
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.0004345457418821752, 0.0003006521728821099, 0.000166758632985875, 0.0003006521728821099, 0.0001338935544481501 ]
{ "id": 4, "code_window": [ "import { transformIframeHtml } from './transform-iframe-html';\n", "import { createViteServer } from './vite-server';\n", "import { build as viteBuild } from './build';\n", "import type { ViteBuilder, StorybookConfigVite } from './types';\n", "\n", "export { withoutVitePlugins } from './utils/without-vite-plugins';\n", "export { hasVitePlugins } from './utils/has-vite-plugins';\n", "\n", "export * from './types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { ViteBuilder } from './types';\n" ], "file_path": "code/builders/builder-vite/src/index.ts", "type": "replace", "edit_start_line_idx": 11 }
import mapValues from 'lodash/mapValues.js'; import { logger } from '@storybook/client-logger'; import type { Renderer, ArgTypesEnhancer, SBEnumType, StrictInputType } from '@storybook/types'; import { filterArgTypes } from './filterArgTypes'; import { combineParameters } from './parameters'; export type ControlsMatchers = { date: RegExp; color: RegExp; }; const inferControl = (argType: StrictInputType, name: string, matchers: ControlsMatchers): any => { const { type, options } = argType; if (!type) { return undefined; } // args that end with background or color e.g. iconColor if (matchers.color && matchers.color.test(name)) { const controlType = type.name; if (controlType === 'string') { return { control: { type: 'color' } }; } if (controlType !== 'enum') { logger.warn( `Addon controls: Control of type color only supports string, received "${controlType}" instead` ); } } // args that end with date e.g. purchaseDate if (matchers.date && matchers.date.test(name)) { return { control: { type: 'date' } }; } switch (type.name) { case 'array': return { control: { type: 'object' } }; case 'boolean': return { control: { type: 'boolean' } }; case 'string': return { control: { type: 'text' } }; case 'number': return { control: { type: 'number' } }; case 'enum': { const { value } = type as SBEnumType; return { control: { type: value?.length <= 5 ? 'radio' : 'select' }, options: value }; } case 'function': case 'symbol': return null; default: return { control: { type: options ? 'select' : 'object' } }; } }; export const inferControls: ArgTypesEnhancer<Renderer> = (context) => { const { argTypes, // eslint-disable-next-line @typescript-eslint/naming-convention parameters: { __isArgsStory, controls: { include = null, exclude = null, matchers = {} } = {} }, } = context; if (!__isArgsStory) return argTypes; const filteredArgTypes = filterArgTypes(argTypes, include, exclude); const withControls = mapValues(filteredArgTypes, (argType, name) => { return argType?.type && inferControl(argType, name, matchers); }); return combineParameters(withControls, filteredArgTypes); }; inferControls.secondPass = true; export const argTypesEnhancers = [inferControls];
code/lib/preview-api/src/modules/store/inferControls.ts
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00017451171879656613, 0.00017058437515515834, 0.0001667665783315897, 0.0001700685388641432, 0.000002528360710130073 ]
{ "id": 4, "code_window": [ "import { transformIframeHtml } from './transform-iframe-html';\n", "import { createViteServer } from './vite-server';\n", "import { build as viteBuild } from './build';\n", "import type { ViteBuilder, StorybookConfigVite } from './types';\n", "\n", "export { withoutVitePlugins } from './utils/without-vite-plugins';\n", "export { hasVitePlugins } from './utils/has-vite-plugins';\n", "\n", "export * from './types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { ViteBuilder } from './types';\n" ], "file_path": "code/builders/builder-vite/src/index.ts", "type": "replace", "edit_start_line_idx": 11 }
```js // Button.stories.js|jsx import { fn } from '@storybook/test'; import { Button } from './Button'; export default { component: Button, // ๐Ÿ‘‡ Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked args: { onClick: fn() }, }; ```
docs/snippets/common/button-story-onclick-action-spy.js.mdx
0
https://github.com/storybookjs/storybook/commit/8c305f9d53d7e3bf5d0b60c7dbe6880e77c25dae
[ 0.00017536476661916822, 0.00017393131565768272, 0.0001724978646961972, 0.00017393131565768272, 0.000001433450961485505 ]