type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
ArrowFunction |
async (module: string, interpreter: PythonInterpreter, cancelToken?: CancellationToken): Promise<boolean> => {
if (interpreter && interpreter !== null) {
const newOptions: SpawnOptions = { throwOnStdErr: true, encoding: 'utf8', token: cancelToken };
newOptions.env = await this.fixupCondaEnv(newOptions.env, interpreter);
const pythonService = await this.executionFactory.create({ pythonPath: interpreter.path });
try {
// Special case for ipykernel
const actualModule = module === KernelCreateCommand ? module : 'jupyter';
const args = module === KernelCreateCommand ? ['--version'] : [module, '--version'];
const result = await pythonService.execModule(actualModule, args, newOptions);
return !result.stderr;
} catch (err) {
this.logger.logWarning(`${err} for ${interpreter.path}`);
return false;
}
} else {
return false;
}
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
ArrowFunction |
async (command?: string, cancelToken?: CancellationToken): Promise<boolean> => {
const newOptions: SpawnOptions = { throwOnStdErr: true, encoding: 'utf8', token: cancelToken };
const args = command ? [command, '--version'] : ['--version'];
const processService = await this.processServicePromise;
try {
const result = await processService.exec('jupyter', args, newOptions);
return !result.stderr;
} catch (err) {
this.logger.logWarning(err);
return false;
}
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
ClassDeclaration | // JupyterCommand objects represent some process that can be launched that should be guaranteed to work because it
// was found by testing it previously
class JupyterCommand {
private exe: string;
private requiredArgs: string[];
private launcher: IProcessService;
private interpreterPromise: Promise<PythonInterpreter | undefined>;
private condaService: ICondaService;
constructor(exe: string, args: string[], launcher: IProcessService, interpreter: IInterpreterService | PythonInterpreter, condaService: ICondaService) {
this.exe = exe;
this.requiredArgs = args;
this.launcher = launcher;
this.condaService = condaService;
if (interpreter.hasOwnProperty('getInterpreterDetails')) {
const interpreterService = interpreter as IInterpreterService;
this.interpreterPromise = interpreterService.getInterpreterDetails(this.exe).catch(e => undefined);
} else {
const interpreterDetails = interpreter as PythonInterpreter;
this.interpreterPromise = Promise.resolve(interpreterDetails);
}
}
public async mainVersion(): Promise<number> {
const interpreter = await this.interpreterPromise;
if (interpreter && interpreter.version) {
return interpreter.version.major;
} else {
return this.execVersion();
}
}
public interpreter() : Promise<PythonInterpreter | undefined> {
return this.interpreterPromise;
}
public async execObservable(args: string[], options: SpawnOptions): Promise<ObservableExecutionResult<string>> {
const newOptions = { ...options };
newOptions.env = await this.fixupCondaEnv(newOptions.env);
const newArgs = [...this.requiredArgs, ...args];
return this.launcher.execObservable(this.exe, newArgs, newOptions);
}
public async exec(args: string[], options: SpawnOptions): Promise<ExecutionResult<string>> {
const newOptions = { ...options };
newOptions.env = await this.fixupCondaEnv(newOptions.env);
const newArgs = [...this.requiredArgs, ...args];
return this.launcher.exec(this.exe, newArgs, newOptions);
}
/**
* Conda needs specific paths and env vars set to be happy. Call this function to fix up
* (or created if not present) our environment to run jupyter
*/
// Base Node.js SpawnOptions uses any for environment, so use that here as well
// tslint:disable-next-line:no-any
private async fixupCondaEnv(inputEnv?: NodeJS.ProcessEnv): Promise<any> {
if (!inputEnv) {
inputEnv = process.env;
}
const interpreter = await this.interpreterPromise;
if (interpreter && interpreter.type === InterpreterType.Conda) {
return this.condaService.getActivatedCondaEnvironment(interpreter, inputEnv);
}
return inputEnv;
}
private async execVersion(): Promise<number> {
if (this.launcher) {
const output = await this.launcher.exec(this.exe, ['--version'], { throwOnStdErr: false, encoding: 'utf8' });
// First number should be our result
const matches = /.*(\d+).*/m.exec(output.stdout);
if (matches && matches.length > 1) {
return parseInt(matches[1], 10);
}
}
return 0;
}
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public async mainVersion(): Promise<number> {
const interpreter = await this.interpreterPromise;
if (interpreter && interpreter.version) {
return interpreter.version.major;
} else {
return this.execVersion();
}
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public interpreter() : Promise<PythonInterpreter | undefined> {
return this.interpreterPromise;
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public async execObservable(args: string[], options: SpawnOptions): Promise<ObservableExecutionResult<string>> {
const newOptions = { ...options };
newOptions.env = await this.fixupCondaEnv(newOptions.env);
const newArgs = [...this.requiredArgs, ...args];
return this.launcher.execObservable(this.exe, newArgs, newOptions);
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public async exec(args: string[], options: SpawnOptions): Promise<ExecutionResult<string>> {
const newOptions = { ...options };
newOptions.env = await this.fixupCondaEnv(newOptions.env);
const newArgs = [...this.requiredArgs, ...args];
return this.launcher.exec(this.exe, newArgs, newOptions);
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration | /**
* Conda needs specific paths and env vars set to be happy. Call this function to fix up
* (or created if not present) our environment to run jupyter
*/
// Base Node.js SpawnOptions uses any for environment, so use that here as well
// tslint:disable-next-line:no-any
private async fixupCondaEnv(inputEnv?: NodeJS.ProcessEnv): Promise<any> {
if (!inputEnv) {
inputEnv = process.env;
}
const interpreter = await this.interpreterPromise;
if (interpreter && interpreter.type === InterpreterType.Conda) {
return this.condaService.getActivatedCondaEnvironment(interpreter, inputEnv);
}
return inputEnv;
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
private async execVersion(): Promise<number> {
if (this.launcher) {
const output = await this.launcher.exec(this.exe, ['--version'], { throwOnStdErr: false, encoding: 'utf8' });
// First number should be our result
const matches = /.*(\d+).*/m.exec(output.stdout);
if (matches && matches.length > 1) {
return parseInt(matches[1], 10);
}
}
return 0;
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public dispose() {
// Clear our usableJupyterInterpreter
this.usablePythonInterpreter = undefined;
this.commands = {};
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public isNotebookSupported(cancelToken?: CancellationToken): Promise<boolean> {
// See if we can find the command notebook
return Cancellation.race(() => this.isCommandSupported(NotebookCommand, cancelToken), cancelToken);
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public async getUsableJupyterPython(cancelToken?: CancellationToken): Promise<PythonInterpreter | undefined> {
// Only try to compute this once.
if (!this.usablePythonInterpreter) {
this.usablePythonInterpreter = await Cancellation.race(() => this.getUsableJupyterPythonImpl(cancelToken), cancelToken);
}
return this.usablePythonInterpreter;
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
public connectToNotebookServer(uri: string | undefined, useDefaultConfig: boolean, cancelToken?: CancellationToken, workingDir?: string): Promise<INotebookServer | undefined> {
// Return nothing if we cancel
return Cancellation.race(async () => {
let connection: IConnection;
let kernelSpec: IJupyterKernelSpec | undefined;
// If our uri is undefined or if it's set to local launch we need to launch a server locally
if (!uri) {
const launchResults = await this.startNotebookServer(useDefaultConfig, cancelToken);
if (launchResults) {
connection = launchResults.connection;
kernelSpec = launchResults.kernelSpec;
} else {
// Throw a cancellation error if we were canceled.
Cancellation.throwIfCanceled(cancelToken);
// Otherwise we can't connect
throw new Error(localize.DataScience.jupyterNotebookFailure().format(''));
}
} else {
// If we have a URI spec up a connection info for it
connection = this.createRemoteConnectionInfo(uri);
kernelSpec = undefined;
}
try {
// If we don't have a kernel spec yet, check using our current connection
if (!kernelSpec) {
kernelSpec = await this.getMatchingKernelSpec(connection, cancelToken);
}
// If still not found, log an error (this seems possible for some people, so use the default)
if (!kernelSpec) {
this.logger.logError(localize.DataScience.jupyterKernelSpecNotFound());
}
// Try to connect to our jupyter process
const result = this.serviceContainer.get<INotebookServer>(INotebookServer);
await result.connect(connection, kernelSpec, cancelToken, workingDir);
return result;
} catch (err) {
// Something else went wrong
throw new Error(localize.DataScience.jupyterNotebookConnectFailed().format(connection.baseUrl));
}
}, cancelToken);
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
protected async getMatchingKernelSpec(connection?: IConnection, cancelToken?: CancellationToken): Promise<IJupyterKernelSpec | undefined> {
// If not using an active connection, check on disk
if (!connection) {
// Get our best interpreter. We want its python path
const bestInterpreter = await this.getUsableJupyterPython(cancelToken);
// Enumerate our kernel specs that jupyter will know about and see if
// one of them already matches based on path
if (bestInterpreter && !await this.hasSpecPathMatch(bestInterpreter, cancelToken)) {
// Nobody matches on path, so generate a new kernel spec
if (await this.isKernelCreateSupported(cancelToken)) {
await this.addMatchingSpec(bestInterpreter, cancelToken);
}
}
}
// Now enumerate them again
const enumerator = connection ? () => this.sessionManager.getActiveKernelSpecs(connection) : () => this.enumerateSpecs(cancelToken);
// Then find our match
return this.findSpecMatch(enumerator);
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
@captureTelemetry(Telemetry.StartJupyter)
private async startNotebookServer(useDefaultConfig: boolean, cancelToken?: CancellationToken): Promise<{ connection: IConnection; kernelSpec: IJupyterKernelSpec | undefined }> {
// First we find a way to start a notebook server
const notebookCommand = await this.findBestCommand(NotebookCommand, cancelToken);
if (!notebookCommand) {
throw new Error(localize.DataScience.jupyterNotSupported());
}
// Now actually launch it
try {
// Generate a temp dir with a unique GUID, both to match up our started server and to easily clean up after
const tempDir = await this.generateTempDir();
this.disposableRegistry.push(tempDir);
// In the temp dir, create an empty config python file. This is the same
// as starting jupyter with all of the defaults.
const configFile = useDefaultConfig ? path.join(tempDir.path, 'jupyter_notebook_config.py') : undefined;
if (configFile) {
await this.fileSystem.writeFile(configFile, '');
this.logger.logInformation(`Generating custom default config at ${configFile}`);
}
// Create extra args based on if we have a config or not
const extraArgs: string[] = [];
if (useDefaultConfig) {
extraArgs.push(`--config=${configFile}`);
}
// Check for the debug environment variable being set. Setting this
// causes Jupyter to output a lot more information about what it's doing
// under the covers and can be used to investigate problems with Jupyter.
if (process.env && process.env.VSCODE_PYTHON_DEBUG_JUPYTER) {
extraArgs.push('--debug');
}
// Use this temp file and config file to generate a list of args for our command
const args: string[] = [...['--no-browser', `--notebook-dir=${tempDir.path}`], ...extraArgs];
// Before starting the notebook process, make sure we generate a kernel spec
const kernelSpec = await this.getMatchingKernelSpec(undefined, cancelToken);
// Then use this to launch our notebook process.
const launchResult = await notebookCommand.execObservable(args, { throwOnStdErr: false, encoding: 'utf8', token: cancelToken });
// Make sure this process gets cleaned up. We might be canceled before the connection finishes.
if (launchResult && cancelToken) {
cancelToken.onCancellationRequested(() => {
launchResult.dispose();
});
}
// Wait for the connection information on this result
const connection = await JupyterConnection.waitForConnection(
tempDir.path, this.getJupyterServerInfo, launchResult, this.serviceContainer, cancelToken);
return {
connection: connection,
kernelSpec: kernelSpec
};
} catch (err) {
if (err instanceof CancellationError) {
throw err;
}
// Something else went wrong
throw new Error(localize.DataScience.jupyterNotebookFailure().format(err));
}
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
private onSettingsChanged() {
// Do the same thing as dispose so that we regenerate
// all of our commands
this.dispose();
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
private async addMatchingSpec(bestInterpreter: PythonInterpreter, cancelToken?: CancellationToken): Promise<void> {
const displayName = localize.DataScience.historyTitle();
const ipykernelCommand = await this.findBestCommand(KernelCreateCommand, cancelToken);
// If this fails, then we just skip this spec
try {
// Run the ipykernel install command. This will generate a new kernel spec. However
// it will be pointing to the python that ran it. We'll fix that up afterwards
const name = uuid();
if (ipykernelCommand) {
const result = await ipykernelCommand.exec(['install', '--user', '--name', name, '--display-name', `'${displayName}'`], { throwOnStdErr: true, encoding: 'utf8', token: cancelToken });
// Result should have our file name.
const match = PyKernelOutputRegEx.exec(result.stdout);
const diskPath = match && match !== null && match.length > 1 ? path.join(match[1], 'kernel.json') : await this.findSpecPath(name);
// Make sure we delete this file at some point. When we close VS code is probably good. It will also be destroy when
// the kernel spec goes away
this.asyncRegistry.push({
dispose: async () => {
if (!diskPath) {
return;
}
try {
await fs.remove(path.dirname(diskPath));
} catch {
noop();
}
}
});
// If that works, rewrite our active interpreter into the argv
if (diskPath && bestInterpreter) {
if (await fs.pathExists(diskPath)) {
const specModel: Kernel.ISpecModel = await fs.readJSON(diskPath);
specModel.argv[0] = bestInterpreter.path;
await fs.writeJSON(diskPath, specModel, { flag: 'w', encoding: 'utf8' });
}
}
}
} catch (err) {
this.logger.logError(err);
}
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
private async generateTempDir(): Promise<TemporaryDirectory> {
const resultDir = path.join(os.tmpdir(), uuid());
await this.fileSystem.createDirectory(resultDir);
return {
path: resultDir,
dispose: async () => {
// Try ten times. Process may still be up and running.
// We don't want to do async as async dispose means it may never finish and then we don't
// delete
let count = 0;
while (count < 10) {
try {
await fs.remove(resultDir);
count = 10;
} catch {
count += 1;
}
}
}
};
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
private async readSpec(kernelSpecOutputLine: string) : Promise<JupyterKernelSpec | undefined> {
const match = KernelSpecOutputRegEx.exec(kernelSpecOutputLine);
if (match && match !== null && match.length > 2) {
// Second match should be our path to the kernel spec
const file = path.join(match[2], 'kernel.json');
if (await fs.pathExists(file)) {
// Turn this into a IJupyterKernelSpec
const model = await fs.readJSON(file, { encoding: 'utf8' });
model.name = match[1];
return new JupyterKernelSpec(model, file);
}
}
return undefined;
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
MethodDeclaration |
private supportsSearchingForCommands() : boolean {
if (this.configuration) {
const settings = this.configuration.getSettings();
if (settings) {
return settings.datascience.searchForJupyter;
}
}
return true;
} | Flamefire/vscode-python | src/client/datascience/jupyter/jupyterExecution.ts | TypeScript |
FunctionDeclaration |
function handleChange(evt) {
setValue(evt.target.value);
} | JustUtahCoders/comunidades-unidas-internal | frontend/view-edit-client/interactions/custom-question-inputs/custom-text.tsx | TypeScript |
ArrowFunction |
(props, ref) => {
const [value, setValue] = useState<string>(
props.initialAnswer ? (props.initialAnswer as string) : ""
);
useImperativeHandle(ref, () => ({
getAnswer() {
return {
questionId: props.question.id,
answer: value,
};
},
}));
return <input type="text" value={value} onChange={handleChange} />;
function handleChange(evt) {
setValue(evt.target.value);
}
} | JustUtahCoders/comunidades-unidas-internal | frontend/view-edit-client/interactions/custom-question-inputs/custom-text.tsx | TypeScript |
ArrowFunction |
() => ({
getAnswer() {
return {
questionId: props.question.id,
answer: value,
};
},
}) | JustUtahCoders/comunidades-unidas-internal | frontend/view-edit-client/interactions/custom-question-inputs/custom-text.tsx | TypeScript |
MethodDeclaration |
getAnswer() {
return {
questionId: props.question.id,
answer: value,
};
} | JustUtahCoders/comunidades-unidas-internal | frontend/view-edit-client/interactions/custom-question-inputs/custom-text.tsx | TypeScript |
ArrowFunction |
(color: string) => (
<>
<circle
cx="127.99707" | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
(color: string) => (
<>
<path
d="M187.06231,203.68216l-10.731-10.75225a7.99991,7.99991,0,0,0-3.6318-2.08674l-21.45845-5.63128a8,8,0,0,1-5.884-8.90337l2.38477-16.19606a8,8,0,0,1,4.84416-6.22191l30.45054-12.65666a8,8,0,0,1,8.4696,1.48392l24.89413,22.76769.05166-.118a96.30537,96.30537,0,0,1-29.18668,38.157Z" | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
() => (
<>
<path d="M223.4873,169.18066a7.96262,7.96262,0,0,0,.49805-1.166A103.91753,103.91753,0,0,0,187.772,42.94336a8.06306,8.06306,0,0,0-1.13965-.79053A103.94567,103.94567,0,0,0,42.61768,187.31152c.04.07129.07324.145.11572.21582a7.9667,7.9667,0,0,0,.80664,1.08985A103.847,103.847,0,0,0,191.2627,210.48242a7.98,7.98,0,0,0,1.40283-1.0957A104.572,104.572,0,0,0,223.4873,169.18066ZM61.48,185.55664l3.91345-2.362A16.00133,16.00133,0,0,0,73.126,169.585l.18967-33.81841a8.0001,8.0001,0,0,1,1.25578-4.2583L88.60582,109.513a8,8,0,0,1,11.43777-2.17522l12.78356,9.26186a15.95634,15.95634,0,0,0,11.53418,2.89844l31.48144-4.26367a15.99269,15.99269,0,0,0,9.94971-5.38477L187.94873,84.25A15.92874,15.92874,0,0,0,191.833,73.01074l-.2793-5.813a87.914,87.914,0,0,1,21.28272,84.187l-15.93116-14.57032a16.05451,16.05451,0,0,0-16.939-2.96777l-30.45166,12.65723a15.99852,15.99852,0,0,0-9.68738,12.44255l-2.38489,16.19612a15.98468,15.98468,0,0,0,11.76807,17.80762l21.4585,5.63085,3.98828,3.9961A87.85932,87.85932,0,0,1,61.48,185.55664Z" />
</> | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
(color: string) => (
<>
<circle
cx="127.99805" | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
(color: string) => (
<>
<circle
cx="127.99902" | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
(color: string) => (
<>
<circle
cx="128" | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
(weight: IconWeight, color: string) =>
renderPathForWeight(weight, color, pathsByWeight) | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
(props, ref) => <IconBase ref | duongdev/phosphor-react | src/icons/GlobeHemisphereEast.tsx | TypeScript |
ArrowFunction |
props => {
const { size, withHoverEffect, color, margin, ...restProps } = props;
return (
<SvgIcon {...{ size, withHoverEffect, color, margin, ...restProps }}>
<PermContactCalendarIconSvg {...restProps} width="1em" height="1em" />
</SvgIcon> | IshanKute/medly-components | packages/icons/src/icons/Action/PermContactCalendarIcon.tsx | TypeScript |
InterfaceDeclaration | // Button component props type
export interface ButtonProps {
children?: ReactNode;
disabled?: boolean | null;
isDark: boolean;
loading?: boolean;
label: string;
// can be changed
type: 'primary' | 'secondary' | 'default';
onPress?: () => void;
customStyles: StyleType;
// to show some loading state
// inside the button its self
} | SwarajRenghe/super | src/components/Button/types.tsx | TypeScript |
ClassDeclaration |
export default class NotFoundPage extends React.Component<INotFoundPageProps, INotFoundPageState> {
constructor(props: INotFoundPageProps) {
super(props);
this.state = {
name: this.props.history.location.pathname.substring(1, this.props.history.location.pathname.length)
}
}
componentWillMount() {
// TODO
}
componentDidUpdate() {
// TODO
}
componentWillUpdate() {
// TODO
}
render() {
return (
<div className="NotFoundPage">
{this.state.name} Component
</div>);
}
} | EliEladElrom/react-tutorials | react-routing-ts/src/pages/NotFoundPage/NotFoundPage.tsx | TypeScript |
InterfaceDeclaration |
interface INotFoundPageProps extends RouteComponentProps<{ name: string }> {
// TODO
} | EliEladElrom/react-tutorials | react-routing-ts/src/pages/NotFoundPage/NotFoundPage.tsx | TypeScript |
InterfaceDeclaration |
interface INotFoundPageState {
name: string
} | EliEladElrom/react-tutorials | react-routing-ts/src/pages/NotFoundPage/NotFoundPage.tsx | TypeScript |
MethodDeclaration |
componentWillMount() {
// TODO
} | EliEladElrom/react-tutorials | react-routing-ts/src/pages/NotFoundPage/NotFoundPage.tsx | TypeScript |
MethodDeclaration |
componentDidUpdate() {
// TODO
} | EliEladElrom/react-tutorials | react-routing-ts/src/pages/NotFoundPage/NotFoundPage.tsx | TypeScript |
MethodDeclaration |
componentWillUpdate() {
// TODO
} | EliEladElrom/react-tutorials | react-routing-ts/src/pages/NotFoundPage/NotFoundPage.tsx | TypeScript |
MethodDeclaration |
render() {
return (
<div className="NotFoundPage">
{this.state.name} Component
</div>);
} | EliEladElrom/react-tutorials | react-routing-ts/src/pages/NotFoundPage/NotFoundPage.tsx | TypeScript |
ArrowFunction |
(res: any) => {
if (res.status_code == 200) {
this.setState({ list: res.data.list, total: res.data.total, last_page: res.data.last_page, page: this.state.page + 1 })
} else {
Taro.showToast({ title: res.message, icon: 'none' })
}
} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
ArrowFunction |
err => {
Taro.showToast({ title: '请求失败', icon: 'none' })
} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
ArrowFunction |
(res: any) => {
if (res.status_code == 200) {
that.setState({ list: that.state.list.concat(res.data.list), total: res.data.total, last_page: res.data.last_page, page: that.state.page + 1 })
} else {
Taro.showToast({ title: res.message, icon: 'none' })
}
} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
ArrowFunction |
err => {
Taro.showToast({ title: '请求失败', icon: 'none' })
} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
ArrowFunction |
(item: any, index: any) => {
return (
<View className='invitation-item' key={item}>
<View className='invitation-item-uesr'>
<View className='invitation-photo'>
<Image className="invitation-img" src={item.avatar} />
</View>
<View className='invitation-name'>{item.name}</View>
</View>
<View className='invitation-item-time'>{item.created_at}</View>
</View> | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
ClassDeclaration |
export default class AppreActivity extends Component {
config = {
navigationBarTitleText: "我的邀请列表",
enablePullDownRefresh: false
};
state = {
page: 1,
total: 0,
last_page: 0,
list: [
]
};
/**
*第一次请求,替代
*/
componentDidShow() {
userRelationShip({ page: 1 }).then((res: any) => {
if (res.status_code == 200) {
this.setState({ list: res.data.list, total: res.data.total, last_page: res.data.last_page, page: this.state.page + 1 })
} else {
Taro.showToast({ title: res.message, icon: 'none' })
}
}).catch(err => {
Taro.showToast({ title: '请求失败', icon: 'none' })
})
}
/**
*加载更多,衔接
*/
onReachBottom() {
let that = this;
if (this.state.page <= this.state.last_page) {
userRelationShip({ page: that.state.page }).then((res: any) => {
if (res.status_code == 200) {
that.setState({ list: that.state.list.concat(res.data.list), total: res.data.total, last_page: res.data.last_page, page: that.state.page + 1 })
} else {
Taro.showToast({ title: res.message, icon: 'none' })
}
}).catch(err => {
Taro.showToast({ title: '请求失败', icon: 'none' })
})
}
}
render() {
return (
<View className="invitation-list">
<View className="invitation-list-nav">
<View className="invitation-title">邀请的用户数量</View>
<View className="invitation-num">{this.state.total}</View>
</View>
<View className='invitation-title-left-box' style={{ background: this.state.list.length ? '#f3f4f8' : '#fff' }} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
MethodDeclaration | /**
*第一次请求,替代
*/
componentDidShow() {
userRelationShip({ page: 1 }).then((res: any) => {
if (res.status_code == 200) {
this.setState({ list: res.data.list, total: res.data.total, last_page: res.data.last_page, page: this.state.page + 1 })
} else {
Taro.showToast({ title: res.message, icon: 'none' })
}
}).catch(err => {
Taro.showToast({ title: '请求失败', icon: 'none' })
})
} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
MethodDeclaration | /**
*加载更多,衔接
*/
onReachBottom() {
let that = this;
if (this.state.page <= this.state.last_page) {
userRelationShip({ page: that.state.page }).then((res: any) => {
if (res.status_code == 200) {
that.setState({ list: that.state.list.concat(res.data.list), total: res.data.total, last_page: res.data.last_page, page: that.state.page + 1 })
} else {
Taro.showToast({ title: res.message, icon: 'none' })
}
}).catch(err => {
Taro.showToast({ title: '请求失败', icon: 'none' })
})
}
} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
MethodDeclaration |
render() {
return (
<View className="invitation-list">
<View className="invitation-list-nav">
<View className="invitation-title">邀请的用户数量</View>
<View className="invitation-num">{this.state.total}</View>
</View>
<View className='invitation-title-left-box' style={{ background: this.state.list.length ? '#f3f4f8' : '#fff' }} | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
MethodDeclaration |
require('@/assets/index/no-data.png') | vvcxxc/tuan-mai-wu-lian | src/pages/my/invitation-list/index.tsx | TypeScript |
ArrowFunction |
({ Component, pageProps }: AppProps): JSX.Element => {
return (
<>
<Head>
<title>Ethereum DAPP Demo</title>
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width"
/>
</Head>
<Component {...pageProps} />
</> | VarunSAthreya/ethereum_dapp_demo | pages/_app.tsx | TypeScript |
ArrowFunction |
() => {
return (
<HomeContainer>
<h1>Nice, you are logged in</h1>
</HomeContainer> | return-main/aws-cognito-boilerplate | src/pages/Home.tsx | TypeScript |
ClassDeclaration |
@Component({
selector: 'tabs-section',
template: `
<demo-section [name]="name" [src]="src" [titleDoc]="titleDoc" [html]="html" [ts]="ts" [doc]="doc">
<tabs-demo></tabs-demo>
</demo-section>`
})
export class TabsSectionComponent {
public name:string = 'Tabs';
public src:string = 'https://github.com/valor-software/ng2-bootstrap/blob/master/components/tabs';
public html:string = html;
public ts:string = ts;
public titleDoc:string = titleDoc;
public doc:string = doc;
} | formio/ng2-bootstrap | demo/components/tabs-section.ts | TypeScript |
ClassDeclaration |
export class CreateUserUseCaseImpl implements ICreateUserUseCase {
constructor(private readonly userRepository: IUserRepository) {}
async execute(params: CreateUserParams): Promise<CreateUserResponse> {
return await this.userRepository.create(params)
}
} | ErickLuizA/rn-music-app | src/data/useCases/CreateUserUseCaseImpl.ts | TypeScript |
MethodDeclaration |
async execute(params: CreateUserParams): Promise<CreateUserResponse> {
return await this.userRepository.create(params)
} | ErickLuizA/rn-music-app | src/data/useCases/CreateUserUseCaseImpl.ts | TypeScript |
ClassDeclaration | /**
* Perform operations with the group backend microservice.
*/
@Injectable()
export class GroupService {
private groups: Group[];
// Maven fills in these variables from the pom.xml
private url = '${group.service.url}';
constructor(private http: HttpClient) {
this.url = this.url + ((this.url.indexOf('/', this.url.length - 1) === -1) ? '/': '') ;
if (sessionStorage.jwt == null) {
console.log('JSON Web Token is not available. Login before you continue.');
}
}
getGroups(userId: string): Observable<Groups> {
let headers = new HttpHeaders();
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.get<Groups>(this.url + '?userId=' + userId, { headers: headers })
.map(data => data)
}
getGroup(groupId: string): Observable<Group> {
let headers = new HttpHeaders();
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.get<Group>(this.url + groupId, { headers: headers })
.map(data => data)
}
createGroup(payload: string): Observable<HttpResponse<any>> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.post<HttpResponse<any>>(this.url, payload, { headers: headers })
.map(data => data);
}
updateGroup(groupId: string, payload: string): Observable<HttpResponse<any>> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.put<HttpResponse<any>>(this.url + groupId, payload, { headers: headers })
.map(data => data);
}
deleteGroup(groupId: string): Observable<HttpResponse<any>> {
let headers = new HttpHeaders();
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.delete<HttpResponse<any>>(this.url + groupId, { headers: headers })
.map(data => data);
}
} | OpenLiberty/sample-acmegifts | front-end-ui/src/app/group/services/group.service.ts | TypeScript |
MethodDeclaration |
getGroups(userId: string): Observable<Groups> {
let headers = new HttpHeaders();
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.get<Groups>(this.url + '?userId=' + userId, { headers: headers })
.map(data => data)
} | OpenLiberty/sample-acmegifts | front-end-ui/src/app/group/services/group.service.ts | TypeScript |
MethodDeclaration |
getGroup(groupId: string): Observable<Group> {
let headers = new HttpHeaders();
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.get<Group>(this.url + groupId, { headers: headers })
.map(data => data)
} | OpenLiberty/sample-acmegifts | front-end-ui/src/app/group/services/group.service.ts | TypeScript |
MethodDeclaration |
createGroup(payload: string): Observable<HttpResponse<any>> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.post<HttpResponse<any>>(this.url, payload, { headers: headers })
.map(data => data);
} | OpenLiberty/sample-acmegifts | front-end-ui/src/app/group/services/group.service.ts | TypeScript |
MethodDeclaration |
updateGroup(groupId: string, payload: string): Observable<HttpResponse<any>> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.put<HttpResponse<any>>(this.url + groupId, payload, { headers: headers })
.map(data => data);
} | OpenLiberty/sample-acmegifts | front-end-ui/src/app/group/services/group.service.ts | TypeScript |
MethodDeclaration |
deleteGroup(groupId: string): Observable<HttpResponse<any>> {
let headers = new HttpHeaders();
headers = headers.set('Authorization', sessionStorage.jwt);
return this.http.delete<HttpResponse<any>>(this.url + groupId, { headers: headers })
.map(data => data);
} | OpenLiberty/sample-acmegifts | front-end-ui/src/app/group/services/group.service.ts | TypeScript |
ArrowFunction |
(rows: Packet[] | Flow[], property: PacketTableSortProperty | FlowTableSortProperty, direction: SortDirection) => {
let sortedRows = [...rows];
sortedRows.sort((a, b) => {
let propertyA = a[property] || '';
let propertyB = b[property] || '';
if (propertyA < propertyB) {
return direction === 'asc' ? -1 : 1;
}
if (propertyA > propertyB) {
return direction === 'asc' ? 1 : -1;
}
return 0;
});
return sortedRows;
} | JuroUhlar/pcapfunnel | frontend/src/charts/DataTable/tableUtils.ts | TypeScript |
ArrowFunction |
(a, b) => {
let propertyA = a[property] || '';
let propertyB = b[property] || '';
if (propertyA < propertyB) {
return direction === 'asc' ? -1 : 1;
}
if (propertyA > propertyB) {
return direction === 'asc' ? 1 : -1;
}
return 0;
} | JuroUhlar/pcapfunnel | frontend/src/charts/DataTable/tableUtils.ts | TypeScript |
TypeAliasDeclaration |
export type SortDirection = 'asc' | 'desc'; | JuroUhlar/pcapfunnel | frontend/src/charts/DataTable/tableUtils.ts | TypeScript |
ArrowFunction |
() => this.onPageIndexChange(lastIndex) | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
ArrowFunction |
() => {
this.locale = this.i18n.getLocaleData('Pagination');
this.cdr.markForCheck();
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
ArrowFunction |
total => {
this.onTotalChange(total);
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
ArrowFunction |
bp => {
if (this.nzResponsive) {
this.size = bp === NzBreakpointEnum.xs ? 'small' : 'default';
this.cdr.markForCheck();
}
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
ClassDeclaration |
@Component({
selector: 'nz-pagination',
exportAs: 'nzPagination',
preserveWhitespaces: false,
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-container *ngIf="showPagination">
<ng-container *ngIf="nzSimple; else defaultPagination.template">
<ng-template [ngTemplateOutlet]="simplePagination.template"></ng-template>
</ng-container>
</ng-container>
<nz-pagination-simple
#simplePagination
[disabled]="nzDisabled"
[itemRender]="nzItemRender"
[locale]="locale"
[pageSize]="nzPageSize"
[total]="nzTotal"
[pageIndex]="nzPageIndex"
(pageIndexChange)="onPageIndexChange($event)"
></nz-pagination-simple>
<nz-pagination-default
#defaultPagination
[nzSize]="size"
[itemRender]="nzItemRender"
[showTotal]="nzShowTotal"
[disabled]="nzDisabled"
[locale]="locale"
[showSizeChanger]="nzShowSizeChanger"
[showQuickJumper]="nzShowQuickJumper"
[total]="nzTotal"
[pageIndex]="nzPageIndex"
[pageSize]="nzPageSize"
[pageSizeOptions]="nzPageSizeOptions"
(pageIndexChange)="onPageIndexChange($event)"
(pageSizeChange)="onPageSizeChange($event)"
></nz-pagination-default>
`,
host: {
'[class.ant-pagination]': 'true',
'[class.ant-pagination-simple]': 'nzSimple',
'[class.ant-pagination-disabled]': 'nzDisabled',
'[class.mini]': `!nzSimple && size === 'small'`
}
})
export class NzPaginationComponent implements OnInit, OnDestroy, OnChanges {
static ngAcceptInputType_nzDisabled: BooleanInput;
static ngAcceptInputType_nzShowSizeChanger: BooleanInput;
static ngAcceptInputType_nzHideOnSinglePage: BooleanInput;
static ngAcceptInputType_nzShowQuickJumper: BooleanInput;
static ngAcceptInputType_nzSimple: BooleanInput;
static ngAcceptInputType_nzResponsive: BooleanInput;
static ngAcceptInputType_nzTotal: NumberInput;
static ngAcceptInputType_nzPageIndex: NumberInput;
static ngAcceptInputType_nzPageSize: NumberInput;
@Output() readonly nzPageSizeChange: EventEmitter<number> = new EventEmitter();
@Output() readonly nzPageIndexChange: EventEmitter<number> = new EventEmitter();
@Input() nzShowTotal: TemplateRef<{ $implicit: number; range: [number, number] }> | null = null;
@Input() nzSize: 'default' | 'small' = 'default';
@Input() nzPageSizeOptions = [10, 20, 30, 40];
@Input() nzItemRender: TemplateRef<PaginationItemRenderContext> | null = null;
@Input() @InputBoolean() nzDisabled = false;
@Input() @InputBoolean() nzShowSizeChanger = false;
@Input() @InputBoolean() nzHideOnSinglePage = false;
@Input() @InputBoolean() nzShowQuickJumper = false;
@Input() @InputBoolean() nzSimple = false;
@Input() @InputBoolean() nzResponsive = false;
@Input() @InputNumber() nzTotal = 0;
@Input() @InputNumber() nzPageIndex = 1;
@Input() @InputNumber() nzPageSize = 10;
showPagination = true;
locale!: NzPaginationI18nInterface;
size: 'default' | 'small' = 'default';
private destroy$ = new Subject<void>();
private total$ = new ReplaySubject<number>(1);
validatePageIndex(value: number, lastIndex: number): number {
if (value > lastIndex) {
return lastIndex;
} else if (value < 1) {
return 1;
} else {
return value;
}
}
onPageIndexChange(index: number): void {
const lastIndex = this.getLastIndex(this.nzTotal, this.nzPageSize);
const validIndex = this.validatePageIndex(index, lastIndex);
if (validIndex !== this.nzPageIndex && !this.nzDisabled) {
this.nzPageIndex = validIndex;
this.nzPageIndexChange.emit(this.nzPageIndex);
}
}
onPageSizeChange(size: number): void {
this.nzPageSize = size;
this.nzPageSizeChange.emit(size);
const lastIndex = this.getLastIndex(this.nzTotal, this.nzPageSize);
if (this.nzPageIndex > lastIndex) {
this.onPageIndexChange(lastIndex);
}
}
onTotalChange(total: number): void {
const lastIndex = this.getLastIndex(total, this.nzPageSize);
if (this.nzPageIndex > lastIndex) {
Promise.resolve().then(() => this.onPageIndexChange(lastIndex));
}
}
getLastIndex(total: number, pageSize: number): number {
return Math.ceil(total / pageSize);
}
constructor(private i18n: NzI18nService, private cdr: ChangeDetectorRef, private breakpointService: NzBreakpointService) {}
ngOnInit(): void {
this.i18n.localeChange.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.locale = this.i18n.getLocaleData('Pagination');
this.cdr.markForCheck();
});
this.total$.pipe(takeUntil(this.destroy$)).subscribe(total => {
this.onTotalChange(total);
});
this.breakpointService
.subscribe(gridResponsiveMap)
.pipe(takeUntil(this.destroy$))
.subscribe(bp => {
if (this.nzResponsive) {
this.size = bp === NzBreakpointEnum.xs ? 'small' : 'default';
this.cdr.markForCheck();
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
ngOnChanges(changes: SimpleChanges): void {
const { nzHideOnSinglePage, nzTotal, nzPageSize, nzSize } = changes;
if (nzTotal) {
this.total$.next(this.nzTotal);
}
if (nzHideOnSinglePage || nzTotal || nzPageSize) {
this.showPagination = (this.nzHideOnSinglePage && this.nzTotal > this.nzPageSize) || (this.nzTotal > 0 && !this.nzHideOnSinglePage);
}
if (nzSize) {
this.size = nzSize.currentValue;
}
}
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
validatePageIndex(value: number, lastIndex: number): number {
if (value > lastIndex) {
return lastIndex;
} else if (value < 1) {
return 1;
} else {
return value;
}
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
onPageIndexChange(index: number): void {
const lastIndex = this.getLastIndex(this.nzTotal, this.nzPageSize);
const validIndex = this.validatePageIndex(index, lastIndex);
if (validIndex !== this.nzPageIndex && !this.nzDisabled) {
this.nzPageIndex = validIndex;
this.nzPageIndexChange.emit(this.nzPageIndex);
}
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
onPageSizeChange(size: number): void {
this.nzPageSize = size;
this.nzPageSizeChange.emit(size);
const lastIndex = this.getLastIndex(this.nzTotal, this.nzPageSize);
if (this.nzPageIndex > lastIndex) {
this.onPageIndexChange(lastIndex);
}
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
onTotalChange(total: number): void {
const lastIndex = this.getLastIndex(total, this.nzPageSize);
if (this.nzPageIndex > lastIndex) {
Promise.resolve().then(() => this.onPageIndexChange(lastIndex));
}
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
getLastIndex(total: number, pageSize: number): number {
return Math.ceil(total / pageSize);
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
ngOnInit(): void {
this.i18n.localeChange.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.locale = this.i18n.getLocaleData('Pagination');
this.cdr.markForCheck();
});
this.total$.pipe(takeUntil(this.destroy$)).subscribe(total => {
this.onTotalChange(total);
});
this.breakpointService
.subscribe(gridResponsiveMap)
.pipe(takeUntil(this.destroy$))
.subscribe(bp => {
if (this.nzResponsive) {
this.size = bp === NzBreakpointEnum.xs ? 'small' : 'default';
this.cdr.markForCheck();
}
});
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
MethodDeclaration |
ngOnChanges(changes: SimpleChanges): void {
const { nzHideOnSinglePage, nzTotal, nzPageSize, nzSize } = changes;
if (nzTotal) {
this.total$.next(this.nzTotal);
}
if (nzHideOnSinglePage || nzTotal || nzPageSize) {
this.showPagination = (this.nzHideOnSinglePage && this.nzTotal > this.nzPageSize) || (this.nzTotal > 0 && !this.nzHideOnSinglePage);
}
if (nzSize) {
this.size = nzSize.currentValue;
}
} | Bahubali-Dev/ng-zorro-antd | components/pagination/pagination.component.ts | TypeScript |
ClassDeclaration |
export default class ResearcherGloves extends Item {
static get name(): string {
return 'Researcher\'s Gloves';
}
static get isPassive(): boolean {
return false;
}
static get desc(): string {
return 'A heavy sword.';
}
static get buyPrice(): number {
return 30.0;
}
static get sellPrice(): number {
return 15.0;
}
static get isAvailable(): boolean {
return true;
}
static get itemType(): ItemType {
return 'equipment';
}
static toSymbol() {
return 'ResearcherGloves';
}
public static equip(kaiScript: AvatarKaiScript) {
kaiScript.addBonus.intelligence += 30;
kaiScript.addBonus.knowledge -= 30;
}
static get accessibility() {
return consts.StoreAccessbility.Rank2;
}
} | awdogsgo2heaven/kaiscripts | lib/items/researcher-gloves.ts | TypeScript |
MethodDeclaration |
static toSymbol() {
return 'ResearcherGloves';
} | awdogsgo2heaven/kaiscripts | lib/items/researcher-gloves.ts | TypeScript |
MethodDeclaration |
public static equip(kaiScript: AvatarKaiScript) {
kaiScript.addBonus.intelligence += 30;
kaiScript.addBonus.knowledge -= 30;
} | awdogsgo2heaven/kaiscripts | lib/items/researcher-gloves.ts | TypeScript |
ArrowFunction |
(evt) => {
this.fullscreen = !!document.fullscreenElement;
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
val => {
this.setVolume(val / 100);
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
_ => this.showControls = true | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
_ => this.showControls = false | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
_ => {
this._ended = false;
this.playing = true;
this.starting = false;
this.interactionRequired = false;
this._progressSub = timer(0, 50)
.pipe(
takeWhile(_ => !this._ended)
).subscribe(
_ => {
this.currTime = this.getCurrentTime();
this.percentPlayed = Math.floor((this.currTime / this.length) * 100);
}
)
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
_ => !this._ended | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
_ => {
this.currTime = this.getCurrentTime();
this.percentPlayed = Math.floor((this.currTime / this.length) * 100);
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
err => this.interactionRequired = true | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ArrowFunction |
_ => {
this.currTime = this.getCurrentTime();
this.percentPlayed = Math.floor((this.currTime / this.length) * 100);
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
ClassDeclaration |
@Component({
selector: 'video-player',
templateUrl: './template.html',
styleUrls: ['./styles.scss']
})
export class VideoPlayerComponent extends SubscriberComponent {
@ViewChild('player') set player(p: ElementRef<HTMLVideoElement>) {
if (p && p.nativeElement) {
this._player = p.nativeElement;
}
}
@ViewChild('playercontainer') set playercontainer(pc: ElementRef<HTMLDivElement>) {
if (pc && pc.nativeElement) {
this._playerContainer = pc.nativeElement;
}
}
@Input('video') set video(v: VideoInfo) {
this._video = v;
this._ready = false;
this.ready.emit(false);
if (v) {
if (v.Url) {
this.loading = true;
this.videoSrc = this._sanitizer.bypassSecurityTrustResourceUrl(v.Url);
}
if (v['Poster']) {
this.videoPoster = this._sanitizer.bypassSecurityTrustResourceUrl(v['Poster']);
}
}
}
@Input('isHost') isHost: boolean = false;
@Input('startTime') startTime: string | Date | number;
@Output('ready') ready: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output('resumed') resumed: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output('ended') ended: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output('hostStart') hostStart: EventEmitter<VideoInfo> = new EventEmitter<VideoInfo>();
@Output('hostStop') hostStop: EventEmitter<VideoInfo> = new EventEmitter<VideoInfo>();
@Output('hostSelect') hostSelect: EventEmitter<VideoInfo> = new EventEmitter<VideoInfo>();
volumeControl = new FormControl(100);
videoSrc: SafeResourceUrl;
videoPoster: SafeResourceUrl;
muted: boolean = false;
premuteVolume: number = 100;
currTime: number = 0;
length: number = 0; // duration, but shadows pipe name
percentPlayed: number = 0;
starting: boolean;
stopping: boolean;
playing: boolean;
loading: boolean;
private _ended: boolean = false;
get video(): VideoInfo {
return this._video;
}
fullscreen: boolean = false;
showControls: boolean = false;
interactionRequired: boolean = false;
private _player: HTMLVideoElement;
private _playerContainer: HTMLDivElement;
private _video: VideoInfo;
private _progressSub: Subscription;
private _ready: boolean = false;
private _mouseSubject: Subject<any> = new Subject<any>();
constructor(
private _sanitizer: DomSanitizer
) {
super();
document.onfullscreenchange = (evt) => {
this.fullscreen = !!document.fullscreenElement;
}
this.addSubscription(
this.volumeControl.valueChanges
.pipe(
debounceTime(100),
distinctUntilChanged()
)
.subscribe(
val => {
this.setVolume(val / 100);
}
)
);
this.addSubscription(
this._mouseSubject
.pipe(
tap(_ => this.showControls = true),
debounceTime(1500)
).subscribe(
_ => this.showControls = false
)
);
}
testSeek(event: MouseEvent) {
console.log(event);
}
mouseMove(evt) {
this._mouseSubject.next(evt);
}
getCurrentTime(): number {
if (this._player) {
return this._player.currentTime;
}
}
seekTo(seconds: number) {
if (seconds < 0) {
return;
}
if (this._player) {
if (this._player.duration > seconds) {
this._player.currentTime = seconds;
}
}
}
play(startTime?: string | number | Date) {
if (this._player && this.videoSrc && this._ready) {
const now = new Date().valueOf();
const start = startTime || this.startTime;
if (!start) {
return; // no known start time
}
const seekTime = Math.floor(Math.max(0, now - new Date(start).valueOf())/1000);
if (seekTime > this.video.Length) {
return; // movie is over
}
this.seekTo(seekTime);
this._player.play()
.then(
_ => {
this._ended = false;
this.playing = true;
this.starting = false;
this.interactionRequired = false;
this._progressSub = timer(0, 50)
.pipe(
takeWhile(_ => !this._ended)
).subscribe(
_ => {
this.currTime = this.getCurrentTime();
this.percentPlayed = Math.floor((this.currTime / this.length) * 100);
}
)
},
err => this.interactionRequired = true
);
}
}
stop() {
if (this._player) {
this._player.pause();
this._player.currentTime = 0;
this.currTime = 0;
this.percentPlayed = 0;
this._ended = true;
this.playing = false;
this.stopping = false;
this._cancelProgress();
}
}
toggleMute() {
this.muted = !this.muted;
}
setVolume(volume: number) {
this._player.volume = volume;
}
goFullScreen() {
if (!this._player || !this._playerContainer) {
console.log('no player found');
return;
}
if (document.fullscreenEnabled) {
if (!!document.fullscreenElement) {
document.exitFullscreen();
} else {
this._playerContainer.requestFullscreen();
}
}
}
videoReady() {
this._ready = true;
this.ready.emit(true);
this.loading = false;
this.length = this._player.duration;
}
videoEnded() {
this.playing = false;
this._ended = true;
this.percentPlayed = 100;
this.ended.emit(true);
}
playerWaiting() {
this.resumed.emit(false);
this.playing = false;
}
playbackResumed() {
this.resumed.emit(true);
this._cancelProgress();
this._progressSub = timer(0, 50)
.pipe(
takeWhile(_ => !this._ended)
).subscribe(
_ => {
this.currTime = this.getCurrentTime();
this.percentPlayed = Math.floor((this.currTime / this.length) * 100);
}
)
}
// Host-only controls
startVideo() {
this.starting = true;
this.hostStart.emit(this.video);
}
stopVideo() {
this.stopping = true;
this.hostStop.emit(this.video);
}
selectVideo() {
this.hostSelect.emit(this.video);
}
private _cancelProgress() {
if (this._progressSub) {
try {
this._progressSub.unsubscribe();
this._progressSub = null;
} catch (e) {
// do nothing
}
}
}
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
testSeek(event: MouseEvent) {
console.log(event);
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
mouseMove(evt) {
this._mouseSubject.next(evt);
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
getCurrentTime(): number {
if (this._player) {
return this._player.currentTime;
}
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
seekTo(seconds: number) {
if (seconds < 0) {
return;
}
if (this._player) {
if (this._player.duration > seconds) {
this._player.currentTime = seconds;
}
}
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
play(startTime?: string | number | Date) {
if (this._player && this.videoSrc && this._ready) {
const now = new Date().valueOf();
const start = startTime || this.startTime;
if (!start) {
return; // no known start time
}
const seekTime = Math.floor(Math.max(0, now - new Date(start).valueOf())/1000);
if (seekTime > this.video.Length) {
return; // movie is over
}
this.seekTo(seekTime);
this._player.play()
.then(
_ => {
this._ended = false;
this.playing = true;
this.starting = false;
this.interactionRequired = false;
this._progressSub = timer(0, 50)
.pipe(
takeWhile(_ => !this._ended)
).subscribe(
_ => {
this.currTime = this.getCurrentTime();
this.percentPlayed = Math.floor((this.currTime / this.length) * 100);
}
)
},
err => this.interactionRequired = true
);
}
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
stop() {
if (this._player) {
this._player.pause();
this._player.currentTime = 0;
this.currTime = 0;
this.percentPlayed = 0;
this._ended = true;
this.playing = false;
this.stopping = false;
this._cancelProgress();
}
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
toggleMute() {
this.muted = !this.muted;
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
setVolume(volume: number) {
this._player.volume = volume;
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
MethodDeclaration |
goFullScreen() {
if (!this._player || !this._playerContainer) {
console.log('no player found');
return;
}
if (document.fullscreenEnabled) {
if (!!document.fullscreenElement) {
document.exitFullscreen();
} else {
this._playerContainer.requestFullscreen();
}
}
} | swimmadude66/movienight | src/client/components/player/component.ts | TypeScript |
Subsets and Splits