commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
ecf0279af0491d889f9d40039b5174116eaea6fc
src/js/Reducers/Settings.ts
src/js/Reducers/Settings.ts
import Reducify from 'Helpers/State/Reducify'; import ActionConstants from 'Constants/Actions/Index'; import { cronPeriods } from 'Constants/Lang/Date'; import * as objectAssign from 'object-assign'; const initialState: IStateSettings = { pollPeriod : cronPeriods.fifteenMinute, accountSettings : {} }; let reducingMethods = { [ActionConstants.settings.SET_SETTINGS_VALUE] : (state: IStateSettings, action) => { return objectAssign({}, state, { [action.key] : action.value }); } }; export default Reducify(initialState, reducingMethods);
import Reducify from 'Helpers/State/Reducify'; import ActionConstants from 'Constants/Actions/Index'; import { cronPeriods } from 'Constants/Lang/Date'; import * as objectAssign from 'object-assign'; const initialState: IStateSettings = { pollPeriod : 'fifteenMinute', // @todo: const accountSettings : {} }; let reducingMethods = { [ActionConstants.settings.SET_SETTINGS_VALUE] : (state: IStateSettings, action) => { return objectAssign({}, state, { [action.key] : action.value }); } }; export default Reducify(initialState, reducingMethods);
Fix default pollPeriod for fresh state
Fix default pollPeriod for fresh state
TypeScript
mit
harksys/HawkEye,harksys/HawkEye,harksys/HawkEye
--- +++ @@ -6,7 +6,7 @@ import * as objectAssign from 'object-assign'; const initialState: IStateSettings = { - pollPeriod : cronPeriods.fifteenMinute, + pollPeriod : 'fifteenMinute', // @todo: const accountSettings : {} };
1c480fdad766b30a64bfdb6b4559e12ffd482059
src/main/system/WindowsAppProvider.ts
src/main/system/WindowsAppProvider.ts
/// <reference path="../main.d.ts"/> /// <reference path="../../shared.d.ts"/> import * as path from "path"; import {spawn} from "child_process"; import {app} from "electron"; import {Promise} from "core-js"; import Utils from "../Utils"; export class WindowsAppProvider implements SystemAppProvider { private systemApps: Promise<SystemApp[]> = null; public loadApps(forceReload: boolean): Promise<SystemApp[]> { if (this.systemApps == null || forceReload) { this.systemApps = this.reloadApps(); } return this.systemApps; } private reloadApps(): Promise<SystemApp[]> { return new Promise<SystemApp[]>((resolve, reject) => { const psScript = path.join(app.getAppPath(), "scripts", "readSystemApps.ps1"); // run ps command const child = spawn("PowerShell.exe", ["-ExecutionPolicy", "RemoteSigned", "-File", psScript]); child.stdout.on("data", data => resolve(Utils.parseJson<SystemApp[]>(data))); child.stderr.on("data", data => reject(`Error while loading system apps: ${data}`)); //child.on("exit", () => {}); child.stdin.end(); }); } }
/// <reference path="../main.d.ts"/> /// <reference path="../../shared.d.ts"/> import * as path from "path"; import {spawn} from "child_process"; import {app} from "electron"; import {Promise} from "core-js"; import Utils from "../Utils"; export class WindowsAppProvider implements SystemAppProvider { private systemApps: Promise<SystemApp[]> = null; public loadApps(forceReload: boolean): Promise<SystemApp[]> { if (this.systemApps == null || forceReload) { this.systemApps = this.reloadApps(); } return this.systemApps; } private reloadApps(): Promise<SystemApp[]> { return new Promise<SystemApp[]>((resolve, reject) => { const psScript = path.join(app.getAppPath(), "scripts", "readSystemApps.ps1"); // run ps command const child = spawn("PowerShell.exe", ["-ExecutionPolicy", "RemoteSigned", "-File", psScript]); let result = ""; child.stdout.on("data", data => result += data.toString()); child.stderr.on("data", data => reject(`Error while loading system apps: ${data}`)); child.on("exit", () => resolve(Utils.parseJson<SystemApp[]>(result))); child.stdin.end(); }); } }
Resolve promise when powershell process exits
Resolve promise when powershell process exits
TypeScript
mit
foxable/app-manager,foxable/app-manager,foxable/app-manager
--- +++ @@ -29,10 +29,11 @@ const psScript = path.join(app.getAppPath(), "scripts", "readSystemApps.ps1"); // run ps command const child = spawn("PowerShell.exe", ["-ExecutionPolicy", "RemoteSigned", "-File", psScript]); + let result = ""; - child.stdout.on("data", data => resolve(Utils.parseJson<SystemApp[]>(data))); + child.stdout.on("data", data => result += data.toString()); child.stderr.on("data", data => reject(`Error while loading system apps: ${data}`)); - //child.on("exit", () => {}); + child.on("exit", () => resolve(Utils.parseJson<SystemApp[]>(result))); child.stdin.end(); }); }
c3326a5bffe47df2fdeba8c61959fac065b77960
components/collapse/Collapse.tsx
components/collapse/Collapse.tsx
import * as React from 'react'; import RcCollapse from 'rc-collapse'; import classNames from 'classnames'; import animation from '../_util/openAnimation'; import CollapsePanel from './CollapsePanel'; export interface CollapseProps { activeKey?: Array<string> | string; defaultActiveKey?: Array<string>; /** ζ‰‹ι£Žη΄ζ•ˆζžœ */ accordion?: boolean; onChange?: (key: string | string[]) => void; style?: React.CSSProperties; className?: string; bordered?: boolean; prefixCls?: string; } export default class Collapse extends React.Component<CollapseProps, any> { static Panel = CollapsePanel; static defaultProps = { prefixCls: 'ant-collapse', bordered: true, openAnimation: { ...animation, appear() { } }, }; render() { const { prefixCls, className = '', bordered } = this.props; const collapseClassName = classNames({ [`${prefixCls}-borderless`]: !bordered, }, className); return <RcCollapse {...this.props} className={collapseClassName} />; } }
import * as React from 'react'; import RcCollapse from 'rc-collapse'; import classNames from 'classnames'; import animation from '../_util/openAnimation'; import CollapsePanel from './CollapsePanel'; export interface CollapseProps { activeKey?: Array<string> | string; defaultActiveKey?: Array<string>; /** ζ‰‹ι£Žη΄ζ•ˆζžœ */ accordion?: boolean; destroyInactivePanel?: boolean; onChange?: (key: string | string[]) => void; style?: React.CSSProperties; className?: string; bordered?: boolean; prefixCls?: string; } export default class Collapse extends React.Component<CollapseProps, any> { static Panel = CollapsePanel; static defaultProps = { prefixCls: 'ant-collapse', bordered: true, openAnimation: { ...animation, appear() { } }, }; render() { const { prefixCls, className = '', bordered } = this.props; const collapseClassName = classNames({ [`${prefixCls}-borderless`]: !bordered, }, className); return <RcCollapse {...this.props} className={collapseClassName} />; } }
Add missing prop signature destroyInactivePanel
Add missing prop signature destroyInactivePanel
TypeScript
mit
zheeeng/ant-design,zheeeng/ant-design,icaife/ant-design,ant-design/ant-design,ant-design/ant-design,zheeeng/ant-design,zheeeng/ant-design,ant-design/ant-design,icaife/ant-design,ant-design/ant-design,elevensky/ant-design,icaife/ant-design,elevensky/ant-design,elevensky/ant-design,icaife/ant-design,elevensky/ant-design
--- +++ @@ -9,6 +9,7 @@ defaultActiveKey?: Array<string>; /** ζ‰‹ι£Žη΄ζ•ˆζžœ */ accordion?: boolean; + destroyInactivePanel?: boolean; onChange?: (key: string | string[]) => void; style?: React.CSSProperties; className?: string;
9aeb53ef176f93958bafc4db2ecfd29eec3b2dfa
app/src/ui/history/commit-list-item.tsx
app/src/ui/history/commit-list-item.tsx
import * as React from 'react' import * as moment from 'moment' import { Commit } from '../../lib/local-git-operations' interface ICommitProps { commit: Commit } /** A component which displays a single commit in a commit list. */ export default class CommitListItem extends React.Component<ICommitProps, void> { public render() { const relative = moment(this.props.commit.authorDate).fromNow() return ( <div className='commit'> <img className='avatar' src={getAvatarURL(this.props.commit)}/> <div className='info'> <div className='summary'>{this.props.commit.summary}</div> <div className='byline' title={this.props.commit.authorDate.toString()}>{relative} by {this.props.commit.authorName}</div> </div> </div> ) } public shouldComponentUpdate(nextProps: ICommitProps, nextState: void): boolean { return this.props.commit.sha !== nextProps.commit.sha || this.props.commit.apiCommit !== nextProps.commit.apiCommit } } function getAvatarURL(commit: Commit): string { const apiCommit = commit.apiCommit if (apiCommit) { return apiCommit.author.avatarUrl } return 'https://github.com/hubot.png' }
import * as React from 'react' import * as moment from 'moment' import { Commit } from '../../lib/local-git-operations' interface ICommitProps { commit: Commit } /** A component which displays a single commit in a commit list. */ export default class CommitListItem extends React.Component<ICommitProps, void> { public render() { const relative = moment(this.props.commit.authorDate).fromNow() return ( <div className='commit'> <img className='avatar' src='https://github.com/hubot.png'/> <div className='info'> <div className='summary'>{this.props.commit.summary}</div> <div className='byline' title={this.props.commit.authorDate.toString()}>{relative} by {this.props.commit.authorName}</div> </div> </div> ) } public shouldComponentUpdate(nextProps: ICommitProps, nextState: void): boolean { return this.props.commit.sha !== nextProps.commit.sha } }
Revert "Load the avatar URL"
Revert "Load the avatar URL" This reverts commit 7c7209c0822ccf12bc277ffa165283be13bfc083.
TypeScript
mit
say25/desktop,gengjiawen/desktop,BugTesterTest/desktops,hjobrien/desktop,say25/desktop,hjobrien/desktop,BugTesterTest/desktops,kactus-io/kactus,artivilla/desktop,kactus-io/kactus,BugTesterTest/desktops,j-f1/forked-desktop,say25/desktop,say25/desktop,shiftkey/desktop,gengjiawen/desktop,j-f1/forked-desktop,desktop/desktop,BugTesterTest/desktops,j-f1/forked-desktop,gengjiawen/desktop,j-f1/forked-desktop,kactus-io/kactus,hjobrien/desktop,gengjiawen/desktop,hjobrien/desktop,artivilla/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,shiftkey/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop
--- +++ @@ -12,7 +12,7 @@ const relative = moment(this.props.commit.authorDate).fromNow() return ( <div className='commit'> - <img className='avatar' src={getAvatarURL(this.props.commit)}/> + <img className='avatar' src='https://github.com/hubot.png'/> <div className='info'> <div className='summary'>{this.props.commit.summary}</div> <div className='byline' title={this.props.commit.authorDate.toString()}>{relative} by {this.props.commit.authorName}</div> @@ -22,15 +22,6 @@ } public shouldComponentUpdate(nextProps: ICommitProps, nextState: void): boolean { - return this.props.commit.sha !== nextProps.commit.sha || this.props.commit.apiCommit !== nextProps.commit.apiCommit + return this.props.commit.sha !== nextProps.commit.sha } } - -function getAvatarURL(commit: Commit): string { - const apiCommit = commit.apiCommit - if (apiCommit) { - return apiCommit.author.avatarUrl - } - - return 'https://github.com/hubot.png' -}
506df5821846e8d778db5491146adc92c47eadd4
src/svg/base/SvgStrategy.ts
src/svg/base/SvgStrategy.ts
import Container from '../components/Container'; import Component from '../components/Component'; import XYAxes from '../components/XYAxes'; import Annotations from '../components/Annotations'; import Config from '../../Config'; import inject from '../../inject'; import ErrorSet from '../components/ErrorSet'; abstract class SvgStrategy { protected container: Container; @inject('Config') protected config: Config; constructor() { } initialize() { this.container = new Container(this.config); } abstract draw(data: [{}], events: Map<string, any>): void; public addComponent(component: Function, config: any) { switch (component.name) { case Annotations.name: let axes: XYAxes = <XYAxes>this.container.getComponent(XYAxes.name); this.container.add(new Annotations(axes.x, axes.y, config)); break; case ErrorSet.name: this.container.add(new ErrorSet()); break; } } public clear() { let components = this.container.getComponents(); for (const c of components) { c.clear(); } } } export default SvgStrategy;
import Container from '../components/Container'; import Component from '../components/Component'; import XYAxes from '../components/XYAxes'; import Annotations from '../components/Annotations'; import Config from '../../Config'; import inject from '../../inject'; import ErrorSet from '../components/ErrorSet'; abstract class SvgStrategy { protected container: Container; @inject('Config') protected config: Config; constructor() { } initialize() { this.container = new Container(this.config); } abstract draw(data: [{}], events: Map<string, any>): void; public addComponent(component: Function, config: any) { switch (component.name) { case Annotations.name: let axes: XYAxes = this.container.getComponent(XYAxes.name) as XYAxes; this.container.add(new Annotations(axes.x, axes.y, config)); break; case ErrorSet.name: this.container.add(new ErrorSet()); break; } } public clear() { let components = this.container.getComponents(); for (const c of components) { c.clear(); } } } export default SvgStrategy;
Use as operator instead of type assertion
Use as operator instead of type assertion
TypeScript
apache-2.0
proteus-h2020/proteus-charts,proteus-h2020/proteic,proteus-h2020/proteic,proteus-h2020/proteic
--- +++ @@ -26,7 +26,7 @@ public addComponent(component: Function, config: any) { switch (component.name) { case Annotations.name: - let axes: XYAxes = <XYAxes>this.container.getComponent(XYAxes.name); + let axes: XYAxes = this.container.getComponent(XYAxes.name) as XYAxes; this.container.add(new Annotations(axes.x, axes.y, config)); break; case ErrorSet.name:
0be05daee0178256eb796465a7f599a344780d58
src/app/components/BookmarksDialog/index.tsx
src/app/components/BookmarksDialog/index.tsx
import { observer } from 'mobx-react'; import React, { Component, SyntheticEvent } from 'react'; import Store from '../../store'; import { ButtonType } from '../../../shared/enums'; import Textfield from '../../../shared/components/Textfield'; import Button from '../../../shared/components/Button'; import colors from '../../../shared/defaults/colors'; import { Root, Title, ButtonsContainer } from './styles'; export interface IProps { visible: boolean; } @observer export default class BookmarksDialog extends Component<IProps, {}> { private textField: Textfield; public onMouseDown = (e?: SyntheticEvent<any>) => { e.preventDefault(); e.stopPropagation(); this.textField.inputElement.blur(); }; public onDoneClick = () => { Store.bookmarksDialogVisible = false; }; public render() { const { visible } = this.props; return ( <Root visible={visible} onMouseDown={this.onMouseDown}> <Title>New bookmark</Title> <Textfield ref={r => (this.textField = r)} label="Name" style={{ marginTop: 16 }} /> <ButtonsContainer> <Button foreground={colors.blue['500']} type={ButtonType.Outlined}> REMOVE </Button> <Button onClick={this.onDoneClick}>DONE</Button> </ButtonsContainer> </Root> ); } }
import { observer } from 'mobx-react'; import React, { Component, SyntheticEvent } from 'react'; import Store from '../../store'; import { ButtonType } from '../../../shared/enums'; import Textfield from '../../../shared/components/Textfield'; import Button from '../../../shared/components/Button'; import colors from '../../../shared/defaults/colors'; import { Root, Title, ButtonsContainer } from './styles'; export interface IProps { visible: boolean; } @observer export default class BookmarksDialog extends Component<IProps, {}> { private textField: Textfield; public onMouseDown = (e?: SyntheticEvent<any>) => { e.stopPropagation(); this.textField.inputElement.blur(); }; public onDoneClick = () => { Store.bookmarksDialogVisible = false; }; public render() { const { visible } = this.props; return ( <Root visible={visible} onMouseDown={this.onMouseDown}> <Title>New bookmark</Title> <Textfield ref={r => (this.textField = r)} label="Name" style={{ marginTop: 16 }} /> <ButtonsContainer> <Button foreground={colors.blue['500']} type={ButtonType.Outlined}> REMOVE </Button> <Button onClick={this.onDoneClick}>DONE</Button> </ButtonsContainer> </Root> ); } }
Fix selecting text in bookmarks dialog
Fix selecting text in bookmarks dialog
TypeScript
apache-2.0
Nersent/Wexond,Nersent/Wexond
--- +++ @@ -16,9 +16,7 @@ private textField: Textfield; public onMouseDown = (e?: SyntheticEvent<any>) => { - e.preventDefault(); e.stopPropagation(); - this.textField.inputElement.blur(); };
9bbbc925ecff680cc6259d08f737a790decf3e97
src/app/classes/file.ts
src/app/classes/file.ts
import { Field } from './field'; import { statSync } from 'fs'; import { dirname, basename, extname } from 'path'; export class File{ id: number; path: string; name: string; mime: string; metadata: Field[]; tiffProcessing: boolean; tiffImagePreviewPath: string; tiffError: boolean; getField(name: string): Field { return this.metadata.find(field => name === field.name); } getFieldValue(name: string): string { let field: Field = this.getField(name); return (!field) ? null : field.value; } ocrPath(): string { return `${dirname(this.path)}/${this.ocrFilename()}` } ocrFilename(): string { return `${basename(this.name, extname(this.name))}_alto.xml`; } hasOcr(): boolean { try { statSync(this.ocrPath()); } catch(e) { return false; } return true; } }
import { Field } from './field'; import { statSync } from 'fs'; import { dirname, basename, extname } from 'path'; export class File{ id: number; path: string; name: string; mime: string; metadata: Field[]; tiffProcessing: boolean; tiffImagePreviewPath: string; tiffError: boolean; ocr: boolean | null = null; getField(name: string): Field { return this.metadata.find(field => name === field.name); } getFieldValue(name: string): string { let field: Field = this.getField(name); return (!field) ? null : field.value; } ocrPath(): string { return `${dirname(this.path)}/${this.ocrFilename()}` } ocrFilename(): string { return `${basename(this.name, extname(this.name))}_alto.xml`; } hasOcr(): boolean { if (this.ocr === null) { try { statSync(this.ocrPath()); this.ocr = true; } catch(e) { this.ocr = false; } } return this.ocr; } }
Fix issue were UI was slow or unresponsive
Fix issue were UI was slow or unresponsive
TypeScript
mit
uhlibraries-digital/brays,uhlibraries-digital/brays,uhlibraries-digital/brays
--- +++ @@ -11,6 +11,7 @@ tiffProcessing: boolean; tiffImagePreviewPath: string; tiffError: boolean; + ocr: boolean | null = null; getField(name: string): Field { return this.metadata.find(field => name === field.name); @@ -30,12 +31,15 @@ } hasOcr(): boolean { - try { - statSync(this.ocrPath()); + if (this.ocr === null) { + try { + statSync(this.ocrPath()); + this.ocr = true; + } + catch(e) { + this.ocr = false; + } } - catch(e) { - return false; - } - return true; + return this.ocr; } }
554b2fccd9ff48c206d7274083155cf6a9d023ea
packages/revival-adapter-rxjs/src/rxjs-call-adapter.ts
packages/revival-adapter-rxjs/src/rxjs-call-adapter.ts
import { Call, CallAdapter } from "revival"; import { Observable, Observer } from "rxjs"; /** * A {@link CallAdapter} implemented by rxjs. * * @author Vincent Cheung ([email protected]) */ export class RxjsCallAdapter<T> implements CallAdapter<T> { private constructor() {} static create(): CallAdapter<any> { return new RxjsCallAdapter(); } check(returnType: string): boolean { return returnType === "Observable"; } adapt(call: Call<T>, returnRaw: boolean): any { return Observable.create((observer: Observer<any>) => { try { call.enqueue( response => observer.next(returnRaw ? response : response.body), error => Observable.throw(error) ); } catch (e) { return Observable.throw(e); } }); } }
import { Call, CallAdapter } from "revival"; import { Observable, Observer } from "rxjs"; /** * A {@link CallAdapter} implemented by rxjs. * * @author Vincent Cheung ([email protected]) */ export class RxjsCallAdapter<T> implements CallAdapter<T> { private constructor() {} static create(): CallAdapter<any> { return new RxjsCallAdapter(); } check(returnType: string): boolean { return returnType === "Observable"; } adapt(call: Call<T>, returnRaw: boolean): any { return Observable.create((observer: Observer<any>) => { try { call.enqueue( response => observer.next(returnRaw ? response : response.body), error => observer.error(error) ); } catch (e) { return observer.error(e); } }); } }
Fix rxjs call adapter throw error.
Fix rxjs call adapter throw error.
TypeScript
mit
Coolerfall/revival
--- +++ @@ -22,10 +22,10 @@ try { call.enqueue( response => observer.next(returnRaw ? response : response.body), - error => Observable.throw(error) + error => observer.error(error) ); } catch (e) { - return Observable.throw(e); + return observer.error(e); } }); }
2af4f66177f156e474a23ba0b4a2c837f31b5205
app/src/ui/lib/theme-change-monitor.ts
app/src/ui/lib/theme-change-monitor.ts
import { remote } from 'electron' import { ApplicationTheme } from './application-theme' import { IDisposable, Disposable, Emitter } from 'event-kit' import { supportsDarkMode, isDarkModeEnabled } from './dark-theme' class ThemeChangeMonitor implements IDisposable { private readonly emitter = new Emitter() public constructor() { this.subscribe() } public dispose() { if (remote.nativeTheme) { remote.nativeTheme.removeAllListeners() } } private subscribe = () => { if (!supportsDarkMode() || !remote.nativeTheme) { return } remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS) } private onThemeNotificationFromOS = (event: string, userInfo: any) => { const darkModeEnabled = isDarkModeEnabled() const theme = darkModeEnabled ? ApplicationTheme.Dark : ApplicationTheme.Light this.emitThemeChanged(theme) } public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable { return this.emitter.on('theme-changed', fn) } private emitThemeChanged(theme: ApplicationTheme) { this.emitter.emit('theme-changed', theme) } } // this becomes our singleton that we can subscribe to from anywhere export const themeChangeMonitor = new ThemeChangeMonitor() // this ensures we cleanup any existing subscription on exit remote.app.on('will-quit', () => { themeChangeMonitor.dispose() })
import { remote } from 'electron' import { ApplicationTheme } from './application-theme' import { IDisposable, Disposable, Emitter } from 'event-kit' import { supportsDarkMode, isDarkModeEnabled } from './dark-theme' class ThemeChangeMonitor implements IDisposable { private readonly emitter = new Emitter() public constructor() { this.subscribe() } public dispose() { remote.nativeTheme.removeAllListeners() } private subscribe = () => { if (!supportsDarkMode()) { return } remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS) } private onThemeNotificationFromOS = (event: string, userInfo: any) => { const darkModeEnabled = isDarkModeEnabled() const theme = darkModeEnabled ? ApplicationTheme.Dark : ApplicationTheme.Light this.emitThemeChanged(theme) } public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable { return this.emitter.on('theme-changed', fn) } private emitThemeChanged(theme: ApplicationTheme) { this.emitter.emit('theme-changed', theme) } } // this becomes our singleton that we can subscribe to from anywhere export const themeChangeMonitor = new ThemeChangeMonitor() // this ensures we cleanup any existing subscription on exit remote.app.on('will-quit', () => { themeChangeMonitor.dispose() })
Revert "Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+"
Revert "Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+" This reverts commit b8a7c8c5c73439e20df6398d62709f72a5206e0d.
TypeScript
mit
shiftkey/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,desktop/desktop
--- +++ @@ -11,13 +11,11 @@ } public dispose() { - if (remote.nativeTheme) { - remote.nativeTheme.removeAllListeners() - } + remote.nativeTheme.removeAllListeners() } private subscribe = () => { - if (!supportsDarkMode() || !remote.nativeTheme) { + if (!supportsDarkMode()) { return }
4103e382af8447624b51d394f194150fcbb1d475
AngularJSWithTS/UseTypesEffectivelyInTS/Classes/demo.ts
AngularJSWithTS/UseTypesEffectivelyInTS/Classes/demo.ts
// demo.ts "use strict"; interface Opponent { alias: string; health: number; } class ComicBookCharacter { // by default all class properties have public access alias: string; health: number; strength: number; secretIdentity: string; attackFunc(opponent: Opponent, attackWith: number) { opponent.health -= attackWith; console.log(`${this.alias} attacked ${opponent.alias}, who's health = ${opponent.health}`); return opponent.health; } } let storm = new ComicBookCharacter(); storm.alias = "Storm"; storm.health = 100; storm.strength = 100; storm.secretIdentity = "Ororo Munroe"; let theBlob = new ComicBookCharacter(); theBlob.alias = "The Blob"; theBlob.health = 1000; theBlob.strength = 5000; theBlob.secretIdentity = "Fred J. Dukes"; storm.attackFunc(theBlob, storm.strength);
// demo.ts "use strict"; interface Opponent { alias: string; health: number; } class ComicBookCharacter { // by default all class properties have public access constructor( // without access level we will get wrong behavior public alias: string, public health: number, public strength: number, private secretIdentity: string ) {} attackFunc(opponent: Opponent, attackWith: number) { opponent.health -= attackWith; console.log(`${this.alias} attacked ${opponent.alias}, who's health = ${opponent.health}`); return opponent.health; } getSecretIdentity() { console.log(`${this.alias} is ${this.secretIdentity}`); } } let storm = new ComicBookCharacter("Storm", 100, 100, "Ororo Munroe"); let theBlob = new ComicBookCharacter("The Blob", 1000, 5000, "Fred J. Dukes"); storm.attackFunc(theBlob, storm.strength); storm.getSecretIdentity();
Replace class properties to constructor. Add getSecretIdentity method
Replace class properties to constructor. Add getSecretIdentity method
TypeScript
mit
var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training
--- +++ @@ -9,10 +9,14 @@ class ComicBookCharacter { // by default all class properties have public access - alias: string; - health: number; - strength: number; - secretIdentity: string; + + constructor( + // without access level we will get wrong behavior + public alias: string, + public health: number, + public strength: number, + private secretIdentity: string + ) {} attackFunc(opponent: Opponent, attackWith: number) { opponent.health -= attackWith; @@ -21,18 +25,15 @@ return opponent.health; } + + getSecretIdentity() { + console.log(`${this.alias} is ${this.secretIdentity}`); + } } -let storm = new ComicBookCharacter(); -storm.alias = "Storm"; -storm.health = 100; -storm.strength = 100; -storm.secretIdentity = "Ororo Munroe"; +let storm = new ComicBookCharacter("Storm", 100, 100, "Ororo Munroe"); -let theBlob = new ComicBookCharacter(); -theBlob.alias = "The Blob"; -theBlob.health = 1000; -theBlob.strength = 5000; -theBlob.secretIdentity = "Fred J. Dukes"; +let theBlob = new ComicBookCharacter("The Blob", 1000, 5000, "Fred J. Dukes"); storm.attackFunc(theBlob, storm.strength); +storm.getSecretIdentity();
c8b8931de6c6a7cea848aca0382a1d8609d51ee4
src/ts/worker/caches.ts
src/ts/worker/caches.ts
/// <reference path="../../../node_modules/typescript/lib/lib.webworker.d.ts" /> import { arrayStartsWith } from '../util' interface ICharCache { part: string[] full: string[] } export class CharCache { private cache: ICharCache /** * @returns true if the cache is invalidated */ update(input: string): boolean { const chars = Array.from(input) if (this.cache === undefined) { this.cache = { part: chars, full: chars } } else if (arrayStartsWith(chars, this.cache.full)) { const len = this.cache.full.length this.cache.part.push(...chars.slice(len)) this.cache.full = chars } else { this.cache = { part: chars, full: chars } return true } return false } /** * @returns the next character to display */ next(): string { return this.cache.part.shift() } }
/// <reference path="../../../node_modules/typescript/lib/lib.webworker.d.ts" /> import { arrayStartsWith } from '../util' interface ICharCache { part: string[] full: string[] } export class CharCache { private cache: ICharCache /** * @returns true if the cache is invalidated */ update(input: string): boolean { const chars = Array.from(input) if (this.cache === undefined) { this.cache = { part: chars, full: chars.slice() } } else if (arrayStartsWith(chars, this.cache.full)) { const len = this.cache.full.length this.cache.part.push(...chars.slice(len)) this.cache.full = chars } else { this.cache = { part: chars, full: chars.slice() } return true } return false } /** * @returns the next character to display */ next(): string { return this.cache.part.shift() } }
Make a copy of chars array in cache to avoid errors
Make a copy of chars array in cache to avoid errors
TypeScript
mit
Alexendoo/utf,Alexendoo/utf,Alexendoo/utf,Alexendoo/utf
--- +++ @@ -18,7 +18,7 @@ if (this.cache === undefined) { this.cache = { part: chars, - full: chars + full: chars.slice() } } else if (arrayStartsWith(chars, this.cache.full)) { const len = this.cache.full.length @@ -27,7 +27,7 @@ } else { this.cache = { part: chars, - full: chars + full: chars.slice() } return true }
98aeb14a26496c97850adb0eea28913d08c9a771
src/utils/get-link.ts
src/utils/get-link.ts
// import from npm import { assignIn } from 'lodash'; // declare an interface for the object that is // used to describe each link and stored in the // map interface LinkState { hasLoaded: boolean; wasRejected: boolean; error?: any; link: HTMLLinkElement; } /** * map for link names against utility objects * @type {Map<string, LinkState>} */ const loadedLinks = new Map<string, LinkState>(); /** * Get a style or other linked resource from a remote location. * @param name {string} - The name of the resource to be retrieved. * @param url {string} - The URL/location of the resource to be retrieved. */ export function getLink(url: string, name: string) { if (!loadedLinks.has(name)) { const link: HTMLLinkElement = document.createElement('link'); const body = document.getElementsByTagName('body')[0]; assignIn(link, { type: 'text/css', href: url, }); body.appendChild(link); const linkObject: LinkState = { hasLoaded: false, wasRejected: false, link, }; loadedLinks.set(name, linkObject); } return loadedLinks.get(name); } // make the 'getLink' method the default export export default getLink;
// import from npm import { assignIn } from 'lodash'; // declare an interface for the object that is // used to describe each link and stored in the // map interface LinkState { hasLoaded: boolean; wasRejected: boolean; error?: any; link: HTMLLinkElement; } /** * map for link names against utility objects * @type {Map<string, LinkState>} */ const loadedLinks = new Map<string, LinkState>(); /** * Get a style or other linked resource from a remote location. * @param name {string} - The name of the resource to be retrieved. * @param url {string} - The URL/location of the resource to be retrieved. */ export function getLink(url: string, name: string) { if (!loadedLinks.has(name)) { const link: HTMLLinkElement = document.createElement('link'); const body = document.getElementsByTagName('body')[0]; assignIn(link, { type: 'text/css', href: url, rel: 'stylesheet', }); body.appendChild(link); const linkObject: LinkState = { hasLoaded: false, wasRejected: false, link, }; loadedLinks.set(name, linkObject); } return loadedLinks.get(name); } // make the 'getLink' method the default export export default getLink;
Add the stylesheet rel to the generated links.
Add the stylesheet rel to the generated links.
TypeScript
mit
Josh-ES/react-here-maps,Josh-ES/react-here-maps
--- +++ @@ -30,6 +30,7 @@ assignIn(link, { type: 'text/css', href: url, + rel: 'stylesheet', }); body.appendChild(link);
ed40f7720ea0c48893e965d82191d7cf63f87786
test/helloEndpoints.spec.ts
test/helloEndpoints.spec.ts
import chaiHttp = require("chai-http"); import * as chai from "chai"; import {server} from "../src/app"; const expect = chai.expect; chai.use(chaiHttp); describe("/hello/:name endpoint", () => { it("should return a welcome message for a name with only alphabetic characters", () => { chai.request(server) .get("/hello/ed") .then((res) => { expect(res).to.have.status(200); }) .catch((err) => { throw err; }); }); it("should error for a name with numeric characters"); it("should error for a name with special characters"); });
import chaiHttp = require("chai-http"); import * as chai from "chai"; import {server} from "../src/app"; const expect = chai.expect; chai.use(chaiHttp); describe("/hello/:name endpoint", () => { it("should return a welcome message for a name with only alphabetic characters", (done) => { chai.request(server) .get("/hello/ed") .end((err, res) => { expect(res).to.have.status(200); done(); }); }); it("should 400 for a name with numeric characters", (done) => { chai.request(server) .get("/hello/ed1") .end((err, res) => { expect(res).to.have.status(400); done(); }); }); it("should 400 for a name with special characters", (done) => { chai.request(server) .get("/hello/edΒ£") .end((err, res) => { expect(res).to.have.status(400); done(); }); }); });
Complete full set of hello service tests
Complete full set of hello service tests
TypeScript
mit
hlouw/node-hack
--- +++ @@ -7,17 +7,30 @@ chai.use(chaiHttp); describe("/hello/:name endpoint", () => { - it("should return a welcome message for a name with only alphabetic characters", () => { + it("should return a welcome message for a name with only alphabetic characters", (done) => { chai.request(server) .get("/hello/ed") - .then((res) => { + .end((err, res) => { expect(res).to.have.status(200); - }) - .catch((err) => { - throw err; + done(); }); }); - it("should error for a name with numeric characters"); - it("should error for a name with special characters"); + it("should 400 for a name with numeric characters", (done) => { + chai.request(server) + .get("/hello/ed1") + .end((err, res) => { + expect(res).to.have.status(400); + done(); + }); + }); + + it("should 400 for a name with special characters", (done) => { + chai.request(server) + .get("/hello/edΒ£") + .end((err, res) => { + expect(res).to.have.status(400); + done(); + }); + }); });
2f0337113465ba1f85624994904dc850284527f3
src/bin/user-manager/auth0-manager.ts
src/bin/user-manager/auth0-manager.ts
import * as rp from 'request-promise' export namespace Auth0Manager { export function getEncryptedUserDetailsByID(auth0_id: string): PromiseLike<string> { let req_opts = { method: 'POST', url: process.env.AUTH0_BASE_URL + "/oauth/token", headers: { 'content-type': 'application/json' }, body: { grant_type: 'client_credentials', client_id: '0nUX32BCmm16aWmtfiDi3TSryXgYiJm9', client_secret: 'GC9aRT84s_8Uv5kMWRVEP4qh3VzyuK6QNZyylCfe5bgaXOB-eOziQImTgEv_dBqZ', audience: process.env.AUTH0_CLIENT_API_IDENTIFER }, json: true } return rp(req_opts) .then(function (body) { return body }) // Do verification of JWT } }
import * as rp from 'request-promise' export namespace Auth0Manager { export function getEncryptedUserDetailsByID(auth0_id: string): PromiseLike<string> { let req_opts = { method: 'POST', url: process.env.AUTH0_BASE_URL + "/oauth/token", headers: { 'content-type': 'application/json' }, body: { grant_type: 'client_credentials', client_id: process.env.AUTH0_CLIENT_ID, client_secret: process.env.AUTH0_CLIENT_SECRET, audience: process.env.AUTH0_CLIENT_API_IDENTIFER }, json: true } return rp(req_opts) .then(function (body) { return body }) // Do verification of JWT } }
Use secrets in env vars, not hardcoded!
Use secrets in env vars, not hardcoded!
TypeScript
mit
calmcl1/voluble,calmcl1/voluble
--- +++ @@ -10,8 +10,8 @@ body: { grant_type: 'client_credentials', - client_id: '0nUX32BCmm16aWmtfiDi3TSryXgYiJm9', - client_secret: 'GC9aRT84s_8Uv5kMWRVEP4qh3VzyuK6QNZyylCfe5bgaXOB-eOziQImTgEv_dBqZ', + client_id: process.env.AUTH0_CLIENT_ID, + client_secret: process.env.AUTH0_CLIENT_SECRET, audience: process.env.AUTH0_CLIENT_API_IDENTIFER }, json: true
954abe92bbc0125ed0c11d2e5ea11db5fc6e74d2
server/routes/basic.router.ts
server/routes/basic.router.ts
import { CrudRouter } from './crud.router'; export class BasicRouter implements CrudRouter { /** * Set status and returns a JSON object containing the error message * @param res * @param message * @param status */ public throwError(res, message: string, status = 500): void { // Set response status and message res.status(status); res.json({ message: message }); } /** * Log the given message as an error * @param message */ public logError(message: string): void { console.error(message); } }
import { CrudRouter } from './crud.router'; export class BasicRouter implements CrudRouter { /** * Set status and returns a JSON object containing the error message * @param res * @param message * @param status */ public throwError(res, message: string, status = 500): void { // Set response status and message res.status(status); res.json({ message: message }); } /** * Log the given message as an error * @param message */ public logError(message: string, stack?: string): void { console.error(message); } }
Add 'stack' parameter to log function
Add 'stack' parameter to log function
TypeScript
mit
DavidLevayer/countable,DavidLevayer/countable,DavidLevayer/countable
--- +++ @@ -20,7 +20,7 @@ * Log the given message as an error * @param message */ - public logError(message: string): void { + public logError(message: string, stack?: string): void { console.error(message); } }
caf2b6bb8c0c16c6c56c39848a663404d13e08d9
addons/docs/src/blocks/DocsStory.tsx
addons/docs/src/blocks/DocsStory.tsx
import React, { FunctionComponent } from 'react'; import deprecate from 'util-deprecate'; import dedent from 'ts-dedent'; import { Subheading } from './Subheading'; import { DocsStoryProps } from './types'; import { Anchor } from './Anchor'; import { Description } from './Description'; import { Story } from './Story'; import { Canvas } from './Canvas'; const warnStoryDescription = deprecate( () => {}, dedent` Deprecated parameter: docs.storyDescription => docs.description.story https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#docs-description-parameter ` ); export const DocsStory: FunctionComponent<DocsStoryProps> = ({ id, name, expanded = true, withToolbar = false, parameters, }) => { let description = expanded && parameters?.docs?.description?.story; if (!description) { description = parameters?.docs?.storyDescription; if (description) warnStoryDescription(); } const subheading = expanded && name; return ( <Anchor storyId={id}> {subheading && <Subheading>{subheading}</Subheading>} {description && <Description markdown={description} />} <Canvas withToolbar={withToolbar}> <Story id={id} /> </Canvas> </Anchor> ); };
import React, { FunctionComponent } from 'react'; import deprecate from 'util-deprecate'; import dedent from 'ts-dedent'; import { Subheading } from './Subheading'; import { DocsStoryProps } from './types'; import { Anchor } from './Anchor'; import { Description } from './Description'; import { Story } from './Story'; import { Canvas } from './Canvas'; const warnStoryDescription = deprecate( () => {}, dedent` Deprecated parameter: docs.storyDescription => docs.description.story https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#docs-description-parameter ` ); export const DocsStory: FunctionComponent<DocsStoryProps> = ({ id, name, expanded = true, withToolbar = false, parameters = {}, }) => { let description; const { docs } = parameters; if (expanded && docs) { description = docs.description?.story; if (!description) { description = docs.storyDescription; if (description) warnStoryDescription(); } } const subheading = expanded && name; return ( <Anchor storyId={id}> {subheading && <Subheading>{subheading}</Subheading>} {description && <Description markdown={description} />} <Canvas withToolbar={withToolbar}> <Story id={id} /> </Canvas> </Anchor> ); };
Fix story description to only show when expanded
Addon-docs: Fix story description to only show when expanded
TypeScript
mit
storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook
--- +++ @@ -22,13 +22,18 @@ name, expanded = true, withToolbar = false, - parameters, + parameters = {}, }) => { - let description = expanded && parameters?.docs?.description?.story; - if (!description) { - description = parameters?.docs?.storyDescription; - if (description) warnStoryDescription(); + let description; + const { docs } = parameters; + if (expanded && docs) { + description = docs.description?.story; + if (!description) { + description = docs.storyDescription; + if (description) warnStoryDescription(); + } } + const subheading = expanded && name; return (
14d50bcee7f3bdffeb7c76d5a9b3b478799a8535
tools/env/base.ts
tools/env/base.ts
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.5.0', RELEASEVERSION: '0.5.0' }; export = BaseConfig;
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.6.0', RELEASEVERSION: '0.6.0' }; export = BaseConfig;
Update release version to 0.6.0
Update release version to 0.6.0
TypeScript
mit
nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website
--- +++ @@ -3,8 +3,8 @@ const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', - RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.5.0', - RELEASEVERSION: '0.5.0' + RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.6.0', + RELEASEVERSION: '0.6.0' }; export = BaseConfig;
411dd3bf40fa53e7588a40ffda5e9f44b20f5b4c
src/app/app.component.spec.ts
src/app/app.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule, MatFormFieldModule, MatInputModule, MatListModule } from '@angular/material'; import { BrowserModule, By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { AppModule } from './app.module'; describe('Component: AppComponent', () => { let fixture: ComponentFixture<AppComponent>; beforeEach(() => { TestBed.configureTestingModule({ imports: [ AppModule, BrowserModule, BrowserAnimationsModule, FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatListModule, ReactiveFormsModule, ], }); fixture = TestBed.createComponent(AppComponent); }); it('App should have file select', () => { expect(fixture.debugElement.query(By.css('app-file-select'))).toBeTruthy(); }); it('App should have audio player controls', () => { expect(fixture.debugElement.query(By.css('app-audio-player-controls'))).toBeTruthy(); }); it('App should have exporter', () => { expect(fixture.debugElement.query(By.css('app-exporter'))).toBeTruthy(); }); });
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule, MatFormFieldModule, MatInputModule, MatListModule } from '@angular/material'; import { BrowserModule, By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { AppModule } from './app.module'; describe('Component: AppComponent', () => { let fixture: ComponentFixture<AppComponent>; beforeEach(() => { TestBed.configureTestingModule({ imports: [ AppModule, BrowserModule, BrowserAnimationsModule, FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatListModule, ReactiveFormsModule, ], }); fixture = TestBed.createComponent(AppComponent); }); it('App should have file select', () => { expect(fixture.debugElement.query(By.css('app-file-select'))).toBeTruthy(); }); it('App should have audio player controls', () => { expect(fixture.debugElement.query(By.css('app-audio-player-controls'))).toBeTruthy(); }); it('Apps hould have editor', () => { expect(fixture.debugElement.query(By.css('app-editor'))).toBeTruthy(); }); it('App should have exporter', () => { expect(fixture.debugElement.query(By.css('app-exporter'))).toBeTruthy(); }); });
Add missing test case to AppComponent
test: Add missing test case to AppComponent
TypeScript
mit
nb48/chart-hero,nb48/chart-hero,nb48/chart-hero
--- +++ @@ -37,6 +37,10 @@ expect(fixture.debugElement.query(By.css('app-audio-player-controls'))).toBeTruthy(); }); + it('Apps hould have editor', () => { + expect(fixture.debugElement.query(By.css('app-editor'))).toBeTruthy(); + }); + it('App should have exporter', () => { expect(fixture.debugElement.query(By.css('app-exporter'))).toBeTruthy(); });
cbce666321378908ce8879b1b00e6f61a105ac23
packages/core/src/core/routes/convert-error-to-response.ts
packages/core/src/core/routes/convert-error-to-response.ts
import { renderError } from '../../common'; import { IAppController } from '../app.controller.interface'; import { Config } from '../config'; import { Context, HttpResponse } from '../http'; export async function convertErrorToResponse( error: Error, ctx: Context, appController: IAppController, log = console.error ): Promise<HttpResponse> { if (Config.get('settings.logErrors', 'boolean', true)) { log(error.stack); } if (appController.handleError) { try { return await appController.handleError(error, ctx); } catch (error2) { return renderError(error2, ctx); } } return renderError(error, ctx); }
import { renderError } from '../../common'; import { IAppController } from '../app.controller.interface'; import { Config } from '../config'; import { Context, HttpResponse } from '../http'; export async function convertErrorToResponse( error: Error, ctx: Context, appController: IAppController, log = console.error ): Promise<HttpResponse> { if (Config.get('settings.logErrors', 'boolean', true)) { log(error.stack); } if (appController.handleError) { try { return await appController.handleError(error, ctx); } catch (error2: any) { return renderError(error2, ctx); } } return renderError(error, ctx); }
Add type to "catch" to support higher TS versions
Add type to "catch" to support higher TS versions
TypeScript
mit
FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal
--- +++ @@ -13,7 +13,7 @@ if (appController.handleError) { try { return await appController.handleError(error, ctx); - } catch (error2) { + } catch (error2: any) { return renderError(error2, ctx); } }
183ea27f6f73931d97b44816a3ed87492b6350f4
src/core/fcm/FcmLogService.ts
src/core/fcm/FcmLogService.ts
import FcmLog from '@app/core/fcm/model/FcmLog'; import FcmLogRepository = require('@app/core/fcm/FcmLogRepository'); export function addFcmLog(to: string, author: string, message: string, cause: string, response: string): Promise<void> { let fcmLog: FcmLog = { date: new Date(), to: to, author: author, message: message, cause: cause, response: response } return FcmLogRepository.insertFcmLog(fcmLog); } export function getRecentFcmLog(): Promise<FcmLog[]>{ return FcmLogRepository.findRecentFcmLog(); }
import FcmLog from '@app/core/fcm/model/FcmLog'; import FcmLogRepository = require('@app/core/fcm/FcmLogRepository'); export function addFcmLog(to: string, author: string, message: string, cause: string, response: any): Promise<void> { let fcmLog: FcmLog = { date: new Date(), to: to, author: author, message: message, cause: cause, response: JSON.stringify(response) } return FcmLogRepository.insertFcmLog(fcmLog); } export function getRecentFcmLog(): Promise<FcmLog[]>{ return FcmLogRepository.findRecentFcmLog(); }
Fix response string validation error
Fix response string validation error
TypeScript
mit
wafflestudio/snutt,wafflestudio/snutt
--- +++ @@ -1,14 +1,14 @@ import FcmLog from '@app/core/fcm/model/FcmLog'; import FcmLogRepository = require('@app/core/fcm/FcmLogRepository'); -export function addFcmLog(to: string, author: string, message: string, cause: string, response: string): Promise<void> { +export function addFcmLog(to: string, author: string, message: string, cause: string, response: any): Promise<void> { let fcmLog: FcmLog = { date: new Date(), to: to, author: author, message: message, cause: cause, - response: response + response: JSON.stringify(response) } return FcmLogRepository.insertFcmLog(fcmLog); }
afd220aa4f20dd4a996294b069fe0dd0cb1a8768
jSlider/JSliderOptions.ts
jSlider/JSliderOptions.ts
module jSlider { export class JSliderOptions { private static _defaults = { "delay" : 100, //Delay between each slide "duration" : 100 //The duration of the slide animation }; private options : Object<string, string> = { "delay" : null, "duration" : null }; constructor(options : Object<string, string> = {})Β { var option : string; for (option in this.options) { if (!this.options.hasOwnProperty(option)) continue; this.options[option] = options[option] || JSliderOptions._defaults[option] || null; } } /** * Get an option * @param optionName * @returns {string} */ public get(optionName : string) { return this.options[optionName]; } } }
module jSlider { export class JSliderOptions { private static _defaults = { "delay" : 4000, //Delay between each slide "duration" : 200 //The duration of the slide animation }; private options : Object<string, string> = { "delay" : null, "duration" : null }; constructor(options : Object<string, string> = {})Β { var option : string; for (option in this.options) { if (!this.options.hasOwnProperty(option)) continue; this.options[option] = options[option] || JSliderOptions._defaults[option] || null; } } /** * Get an option * @param optionName * @returns {string} */ public get(optionName : string) { return this.options[optionName]; } } }
Change the default value for the "delay" option
Change the default value for the "delay" option
TypeScript
lgpl-2.1
sigurdsvela/JSlider
--- +++ @@ -1,8 +1,8 @@ module jSlider { export class JSliderOptions { private static _defaults = { - "delay" : 100, //Delay between each slide - "duration" : 100 //The duration of the slide animation + "delay" : 4000, //Delay between each slide + "duration" : 200 //The duration of the slide animation }; private options : Object<string, string> = {
27fbc810442cf3117dafb0447f77977bdaef49cc
src/utils/prompt.ts
src/utils/prompt.ts
import * as vscode from 'vscode'; export function name(filename: string) { return vscode.window.showInputBox({ placeHolder: 'Enter the new path for the duplicate.', value: filename + '-copy' }); } export function overwrite(filepath: string) { const message = `The path **${filepath}** alredy exists. Do you want to overwrite the existing path?`; const action = { title: 'OK', isCloseAffordance: false }; return vscode.window.showWarningMessage(message, action); }
import * as vscode from 'vscode'; export function name(filename: string) { return vscode.window.showInputBox({ placeHolder: 'Enter the new path for the duplicate.', value: filename.split('.').map((el, i) => i === 0 ? `${el}-copy` : el).join('.') }); } export function overwrite(filepath: string) { const message = `The path **${filepath}** alredy exists. Do you want to overwrite the existing path?`; const action = { title: 'OK', isCloseAffordance: false }; return vscode.window.showWarningMessage(message, action); }
Add `-copy` to the file, rather than extension
Add `-copy` to the file, rather than extension
TypeScript
mit
mrmlnc/vscode-duplicate
--- +++ @@ -3,7 +3,7 @@ export function name(filename: string) { return vscode.window.showInputBox({ placeHolder: 'Enter the new path for the duplicate.', - value: filename + '-copy' + value: filename.split('.').map((el, i) => i === 0 ? `${el}-copy` : el).join('.') }); }
3f0bdaf3fc854a91471253d778f83d741800ee81
src/examples/01_defining_a_model.ts
src/examples/01_defining_a_model.ts
import '../polyfills'; import * as rev from '../index'; // EXAMPLE: // import * as rev from 'rev-models' let TITLES = [ ['Mr', 'Mr.'], ['Mrs', 'Mrs.'], ['Miss', 'Miss.'], ['Dr', 'Dr.'] ]; export class Person { title: string; first_name: string; last_name: string; age: number; email: string; newsletter: boolean; } rev.register(Person, { fields: [ new rev.SelectionField('title', 'Title', TITLES, { required: false }), new rev.TextField('first_name', 'First Name'), new rev.TextField('last_name', 'Last Name'), new rev.IntegerField('age', 'Age', { required: false }), new rev.EmailField('email', 'Email'), new rev.BooleanField('newsletter', 'Registered for Newsletter?') ] });
import '../polyfills'; import * as m from '../index'; // EXAMPLE: // import * as rev from 'rev-models' let TITLES = [ ['Mr', 'Mr.'], ['Mrs', 'Mrs.'], ['Miss', 'Miss.'], ['Dr', 'Dr.'] ]; export class Person { @m.SelectionField('Title', TITLES, { required: false }) title: string; @m.TextField('First Name') first_name: string; @m.TextField('Last Name') last_name: string; @m.IntegerField('Age', { required: false }) age: number; @m.EmailField('Email') email: string; @m.BooleanField('Registered for Newsletter?') newsletter: boolean; } m.register(Person);
Update example to use Decorators
Update example to use Decorators
TypeScript
mit
RevFramework/rev-framework,RevFramework/rev-framework
--- +++ @@ -1,9 +1,10 @@ import '../polyfills'; -import * as rev from '../index'; +import * as m from '../index'; // EXAMPLE: // import * as rev from 'rev-models' + let TITLES = [ ['Mr', 'Mr.'], @@ -13,22 +14,20 @@ ]; export class Person { - title: string; - first_name: string; - last_name: string; - age: number; - email: string; - newsletter: boolean; + @m.SelectionField('Title', TITLES, { required: false }) + title: string; + @m.TextField('First Name') + first_name: string; + @m.TextField('Last Name') + last_name: string; + @m.IntegerField('Age', { required: false }) + age: number; + + @m.EmailField('Email') + email: string; + @m.BooleanField('Registered for Newsletter?') + newsletter: boolean; } -rev.register(Person, { - fields: [ - new rev.SelectionField('title', 'Title', TITLES, { required: false }), - new rev.TextField('first_name', 'First Name'), - new rev.TextField('last_name', 'Last Name'), - new rev.IntegerField('age', 'Age', { required: false }), - new rev.EmailField('email', 'Email'), - new rev.BooleanField('newsletter', 'Registered for Newsletter?') - ] -}); +m.register(Person);
cab069f41456bee3d2739885995cad326ea5c373
src/modules/uploads/entity.ts
src/modules/uploads/entity.ts
import { BaseEntity, JSONData } from '../../fsrepo/entity' export class Upload extends BaseEntity { constructor( @BaseEntity.Serialize('id') public id: string, @BaseEntity.Serialize('filename') public filename: string, @BaseEntity.Serialize('mime') public mime: string, @BaseEntity.Serialize('date') public date: Date, @BaseEntity.Serialize('lifespan') public lifespan: number, @BaseEntity.Serialize('size') public size: number, @BaseEntity.Serialize('views') public views: number = 0 ) { super() } static fromJSON({id, filename, mime, date, lifespan, size, views}: JSONData<Upload>): Upload { return new Upload(id, filename, mime, new Date(date), lifespan, size, views) } }
import { BaseEntity, JSONData } from '../../fsrepo/entity' export class Upload extends BaseEntity { constructor( @BaseEntity.Serialize('id') public id: string, @BaseEntity.Serialize('filename') public filename: string, @BaseEntity.Serialize('mime') public mime: string, @BaseEntity.Serialize('date') public date: Date, @BaseEntity.Serialize('lifespan') public lifespan: number, @BaseEntity.Serialize('size') public size: number ) { super() } static fromJSON({id, filename, mime, date, lifespan, size}: JSONData<Upload>): Upload { return new Upload(id, filename, mime, new Date(date), lifespan, size) } }
Remove views counter from uploads
Remove views counter from uploads It's pretty useless...any query on the old site would cause it to increment so it was never accurate. I will set up some metric later on.
TypeScript
apache-2.0
m1cr0man/m1cr0blog,m1cr0man/m1cr0blog,m1cr0man/m1cr0blog
--- +++ @@ -13,15 +13,13 @@ @BaseEntity.Serialize('lifespan') public lifespan: number, @BaseEntity.Serialize('size') - public size: number, - @BaseEntity.Serialize('views') - public views: number = 0 + public size: number ) { super() } - static fromJSON({id, filename, mime, date, lifespan, size, views}: JSONData<Upload>): Upload { + static fromJSON({id, filename, mime, date, lifespan, size}: JSONData<Upload>): Upload { return new Upload(id, filename, mime, new Date(date), - lifespan, size, views) + lifespan, size) } }
a34d3f76971aa5025018754e0bde8d1c2dc4dbcd
src/shared/parser/ocamldoc/index.ts
src/shared/parser/ocamldoc/index.ts
const parser = require("./grammar"); // tslint:disable-line export const ignore = new RegExp([ /^No documentation available/, /^Not a valid identifier/, /^Not in environment '.*'/, ].map((rx) => rx.source).join("|")); export function intoMarkdown(ocamldoc: string): string { let result = ocamldoc; try { result = parser.parse(ocamldoc); } catch (err) { // } return result; }
const parser = require("./grammar"); // tslint:disable-line export const ignore = new RegExp([ /^Needed cmti file of module/, /^No documentation available/, /^Not a valid identifier/, /^Not in environment '.*'/, /^didn't manage to find/, ].map((rx) => rx.source).join("|")); export function intoMarkdown(ocamldoc: string): string { let result = ocamldoc; try { result = parser.parse(ocamldoc); } catch (err) { // } return result; }
Add more ignore patterns to ocamldoc parser
Add more ignore patterns to ocamldoc parser
TypeScript
apache-2.0
freebroccolo/vscode-reasonml,freebroccolo/vscode-reasonml
--- +++ @@ -1,9 +1,11 @@ const parser = require("./grammar"); // tslint:disable-line export const ignore = new RegExp([ + /^Needed cmti file of module/, /^No documentation available/, /^Not a valid identifier/, /^Not in environment '.*'/, + /^didn't manage to find/, ].map((rx) => rx.source).join("|")); export function intoMarkdown(ocamldoc: string): string {
5edf6bbfe6fd23ba83b3a268d179b0f6001098f8
addons/storyshots/storyshots-core/src/frameworks/frameworkLoader.ts
addons/storyshots/storyshots-core/src/frameworks/frameworkLoader.ts
/* eslint-disable global-require,import/no-dynamic-require */ import fs from 'fs'; import path from 'path'; import { Loader } from './Loader'; import { StoryshotsOptions } from '../api/StoryshotsOptions'; const loaderScriptName = 'loader'; const isDirectory = (source: string) => fs.lstatSync(source).isDirectory(); function getLoaders(): Loader[] { return fs .readdirSync(__dirname) .map(name => path.join(__dirname, name)) .filter(isDirectory) .reduce((acc, framework) => { const filename = path.join(framework, loaderScriptName); const jsFile = `${filename}.js`; const tsFile = `${filename}.ts`; return acc.concat([jsFile, tsFile]); }, [] as string[]) .filter(fs.existsSync) .map(loader => require(loader).default); } function loadFramework(options: StoryshotsOptions) { const loaders = getLoaders(); const loader = loaders.find(frameworkLoader => frameworkLoader.test(options)); if (!loader) { throw new Error( "Couldn't find an appropriate framework loader -- do you need to set the `framework` option?" ); } return loader.load(options); } export default loadFramework;
/* eslint-disable global-require,import/no-dynamic-require */ import fs from 'fs'; import path from 'path'; import { Loader } from './Loader'; import { StoryshotsOptions } from '../api/StoryshotsOptions'; const loaderScriptName = 'loader.js'; const isDirectory = (source: string) => fs.lstatSync(source).isDirectory(); function getLoaders(): Loader[] { return fs .readdirSync(__dirname) .map(name => path.join(__dirname, name)) .filter(isDirectory) .map(framework => path.join(framework, loaderScriptName)) .filter(fs.existsSync) .map(loader => require(loader).default); } function loadFramework(options: StoryshotsOptions) { const loaders = getLoaders(); const loader = loaders.find(frameworkLoader => frameworkLoader.test(options)); if (!loader) { throw new Error( "Couldn't find an appropriate framework loader -- do you need to set the `framework` option?" ); } return loader.load(options); } export default loadFramework;
Revert "feat: make frameworkerLoader load both JS and TS loaders as they will be migrated to TS"
Revert "feat: make frameworkerLoader load both JS and TS loaders as they will be migrated to TS" This reverts commit 83e9b5f1
TypeScript
mit
storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook
--- +++ @@ -4,7 +4,7 @@ import { Loader } from './Loader'; import { StoryshotsOptions } from '../api/StoryshotsOptions'; -const loaderScriptName = 'loader'; +const loaderScriptName = 'loader.js'; const isDirectory = (source: string) => fs.lstatSync(source).isDirectory(); @@ -13,13 +13,7 @@ .readdirSync(__dirname) .map(name => path.join(__dirname, name)) .filter(isDirectory) - .reduce((acc, framework) => { - const filename = path.join(framework, loaderScriptName); - const jsFile = `${filename}.js`; - const tsFile = `${filename}.ts`; - - return acc.concat([jsFile, tsFile]); - }, [] as string[]) + .map(framework => path.join(framework, loaderScriptName)) .filter(fs.existsSync) .map(loader => require(loader).default); }
c14f81623dc8959ebace503f62f289fc11b80fce
tests/__tests__/transpile-if-ts.spec.ts
tests/__tests__/transpile-if-ts.spec.ts
import { transpileIfTypescript } from '../../src'; describe('transpileIfTypescript', () => { it('should ignore anything non-TS', () => { const contents = 'unaltered'; expect(transpileIfTypescript('some.js', contents)).toBe(contents); }); it('should be able to transpile some TS', () => { const ts = 'const x:string = "anything";'; expect(transpileIfTypescript('some.ts', ts)).toMatch('var x = "anything";'); expect(transpileIfTypescript('some.tsx', ts)).toMatch('var x = "anything";'); }); it('should be possible to pass a custom config', () => { const customTsConfigFile = 'not-existant.json'; const customConfig = { __TS_CONFIG__: customTsConfigFile}; expect(() => transpileIfTypescript('some.ts', '', customConfig)).toThrow(new RegExp(customTsConfigFile)); }); });
import { transpileIfTypescript } from '../../src'; describe('transpileIfTypescript', () => { it('should ignore anything non-TS', () => { const contents = 'unaltered'; expect(transpileIfTypescript('some.js', contents)).toBe(contents); }); it('should be able to transpile some TS', () => { const ts = 'const x:string = "anything";'; expect(transpileIfTypescript('some.ts', ts)).toMatch('var x = "anything";'); expect(transpileIfTypescript('some.tsx', ts)).toMatch('var x = "anything";'); }); it('should be possible to pass a custom config (Deprecated)', () => { const customTsConfigFile = 'not-existant.json'; const customConfig = { __TS_CONFIG__: customTsConfigFile }; expect(() => transpileIfTypescript('some.ts', '', customConfig)).toThrow(new RegExp(customTsConfigFile)); }); it('should be possible to pass a custom config', () => { const customTsConfigFile = 'not-existant.json'; const customConfig = { 'ts-jest': { tsConfigFile: customTsConfigFile }}; expect(() => transpileIfTypescript('some.ts', '', customConfig)).toThrow(new RegExp(customTsConfigFile)); }); });
Add new config schema tests
Add new config schema tests
TypeScript
mit
kulshekhar/ts-jest,kulshekhar/ts-jest
--- +++ @@ -11,9 +11,15 @@ expect(transpileIfTypescript('some.tsx', ts)).toMatch('var x = "anything";'); }); + it('should be possible to pass a custom config (Deprecated)', () => { + const customTsConfigFile = 'not-existant.json'; + const customConfig = { __TS_CONFIG__: customTsConfigFile }; + expect(() => transpileIfTypescript('some.ts', '', customConfig)).toThrow(new RegExp(customTsConfigFile)); + }); + it('should be possible to pass a custom config', () => { const customTsConfigFile = 'not-existant.json'; - const customConfig = { __TS_CONFIG__: customTsConfigFile}; + const customConfig = { 'ts-jest': { tsConfigFile: customTsConfigFile }}; expect(() => transpileIfTypescript('some.ts', '', customConfig)).toThrow(new RegExp(customTsConfigFile)); }); });
90333cd2cfd31107de363f29cadff4f7fffc81d6
src/app/components/inline-assessment/inline-assessment.component.ts
src/app/components/inline-assessment/inline-assessment.component.ts
import {Component, Input, Output, OnInit, EventEmitter} from "@angular/core"; @Component({ selector: 'editor-assessment', template: ` <div class="tooltip-editor" [hidden]="hidden" [style.top.px]="posY"> <button class="action-button btn btn-success" (click)="vote(true)"><span class="action-icon glyphicon glyphicon-ok"></span></button> <button class="action-button btn btn-danger" (click)="vote(false)"><span class="action-icon glyphicon glyphicon-remove"></span></button> </div> `, styles:[` .tooltip-editor { float: right; position: absolute; background-color: rgba(255,255,255,0.5); color: white; margin-top: -20px; margin-left: -2px; font-size: 9pt; font-weight: normal; font-style: normal; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; z-index: 400; padding: 20px; } `] }) export class InlineAssessment implements OnInit { @Input() posY: number; @Input() hidden: boolean; @Output() onVoted = new EventEmitter<boolean>(); voted = false; ngOnInit() { this.hidden = false; } vote(agreed: boolean) { console.log("Emitiendo voto... "); this.onVoted.emit(agreed); this.voted = true; } }
import {Component, Input, Output, OnInit, EventEmitter} from "@angular/core"; @Component({ selector: 'editor-assessment', template: ` <div class="tooltip-editor" [hidden]="hidden" [style.top.px]="posY"> <button class="action-button btn btn-success" (click)="vote(true)"><span class="action-icon glyphicon glyphicon-thumbs-up"></span></button> <button class="action-button btn btn-danger" (click)="vote(false)"><span class="action-icon glyphicon glyphicon-thumbs-down"></span></button> </div> `, styles:[` .tooltip-editor { float: right; position: absolute; background-color: rgba(255,255,255,0.5); color: white; margin-top: -20px; margin-left: -2px; font-size: 9pt; font-weight: normal; font-style: normal; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; z-index: 9; padding: 20px; } `] }) export class InlineAssessment implements OnInit { @Input() posY: number; @Input() hidden: boolean; @Output() onVoted = new EventEmitter<boolean>(); voted = false; ngOnInit() { this.hidden = false; } vote(agreed: boolean) { console.log("Emitiendo voto... "); this.onVoted.emit(agreed); this.voted = true; } }
Change emitted vote structure and improve styles in assessments inline view
Change emitted vote structure and improve styles in assessments inline view
TypeScript
agpl-3.0
llopv/jetpad-ic,llopv/jetpad-ic,llopv/jetpad-ic
--- +++ @@ -4,8 +4,8 @@ selector: 'editor-assessment', template: ` <div class="tooltip-editor" [hidden]="hidden" [style.top.px]="posY"> - <button class="action-button btn btn-success" (click)="vote(true)"><span class="action-icon glyphicon glyphicon-ok"></span></button> - <button class="action-button btn btn-danger" (click)="vote(false)"><span class="action-icon glyphicon glyphicon-remove"></span></button> + <button class="action-button btn btn-success" (click)="vote(true)"><span class="action-icon glyphicon glyphicon-thumbs-up"></span></button> + <button class="action-button btn btn-danger" (click)="vote(false)"><span class="action-icon glyphicon glyphicon-thumbs-down"></span></button> </div> `, styles:[` @@ -20,7 +20,7 @@ font-weight: normal; font-style: normal; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; - z-index: 400; + z-index: 9; padding: 20px; } `]
1d2673927f0741f7dff01695d12f7be5a305a2e6
src/lib/NativeModules/Events.tsx
src/lib/NativeModules/Events.tsx
import { NativeModules } from "react-native" const { AREventsModule } = NativeModules function postEvent(info: any) { AREventsModule.postEvent(info) } export default { postEvent }
import { NativeModules } from "react-native" const { AREventsModule } = NativeModules function postEvent(info: any) { if (__DEV__) { console.log("[Event tracked]", info) } AREventsModule.postEvent(info) } export default { postEvent }
Add logging events in Dev mode
Add logging events in Dev mode
TypeScript
mit
artsy/eigen,artsy/emission,artsy/eigen,artsy/emission,artsy/emission,artsy/eigen,artsy/emission,artsy/emission,artsy/eigen,artsy/emission,artsy/eigen,artsy/eigen,artsy/emission,artsy/eigen
--- +++ @@ -2,6 +2,9 @@ const { AREventsModule } = NativeModules function postEvent(info: any) { + if (__DEV__) { + console.log("[Event tracked]", info) + } AREventsModule.postEvent(info) }
5aee05b5ed59fae752387894a328dba21dd32178
src/Test/Ast/SpoilerLink.ts
src/Test/Ast/SpoilerLink.ts
import { expect } from 'chai' import Up from '../../index' import { insideDocumentAndParagraph } from './Helpers' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' import { LinkNode } from '../../SyntaxNodes/LinkNode' import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode' describe('A spoiler followed immediately by a parenthesized/bracketd URL"', () => { it('produces a spoiler node whose contents are put inside a link pointing to that URL', () => { expect(Up.toAst('After you beat the Elite Four, [SPOILER: you fight Gary](http://example.com/finalbattle).')).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode('After you beat the Elite Four, '), new SpoilerNode([ new LinkNode([ new PlainTextNode('you fight Gary') ], 'http://example.com/finalbattle') ]), new PlainTextNode('.') ])) }) })
import { expect } from 'chai' import Up from '../../index' import { insideDocumentAndParagraph, expectEveryCombinationOf } from './Helpers' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' import { LinkNode } from '../../SyntaxNodes/LinkNode' import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode' describe('A spoiler followed immediately by a parenthesized/bracketd URL"', () => { it('produces a spoiler node whose contents are put inside a link pointing to that URL', () => { expect(Up.toAst('After you beat the Elite Four, [SPOILER: you fight Gary](http://example.com/finalbattle).')).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode('After you beat the Elite Four, '), new SpoilerNode([ new LinkNode([ new PlainTextNode('you fight Gary') ], 'http://example.com/finalbattle') ]), new PlainTextNode('.') ])) }) }) describe('A spoiler produced by parenthesized, square bracketed, or curly bracketed text followed immediately by a parenthesized, a square bracketed, or a curly bracketed URL', () => { it('produces a spoiler node whose contents are put inside a link pointing to that URL. The type of bracket surrounding the spoiler can be different from the type of bracket surrounding the URL', () => { expectEveryCombinationOf({ firstHalves: [ '[SPOILER: you fight Gary]', '(SPOILER: you fight Gary)', '{SPOILER: you fight Gary}' ], secondHalves: [ '[http://example.com/finalbattle]', '(http://example.com/finalbattle)', '{http://example.com/finalbattle}' ], toProduce: insideDocumentAndParagraph([ new SpoilerNode([ new LinkNode([ new PlainTextNode('you fight Gary') ], 'http://example.com/finalbattle') ]), ]) }) }) })
Add failing spoiler link tests
Add failing spoiler link tests
TypeScript
mit
start/up,start/up
--- +++ @@ -1,6 +1,6 @@ import { expect } from 'chai' import Up from '../../index' -import { insideDocumentAndParagraph } from './Helpers' +import { insideDocumentAndParagraph, expectEveryCombinationOf } from './Helpers' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' import { LinkNode } from '../../SyntaxNodes/LinkNode' import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode' @@ -20,3 +20,28 @@ ])) }) }) + + +describe('A spoiler produced by parenthesized, square bracketed, or curly bracketed text followed immediately by a parenthesized, a square bracketed, or a curly bracketed URL', () => { + it('produces a spoiler node whose contents are put inside a link pointing to that URL. The type of bracket surrounding the spoiler can be different from the type of bracket surrounding the URL', () => { + expectEveryCombinationOf({ + firstHalves: [ + '[SPOILER: you fight Gary]', + '(SPOILER: you fight Gary)', + '{SPOILER: you fight Gary}' + ], + secondHalves: [ + '[http://example.com/finalbattle]', + '(http://example.com/finalbattle)', + '{http://example.com/finalbattle}' + ], + toProduce: insideDocumentAndParagraph([ + new SpoilerNode([ + new LinkNode([ + new PlainTextNode('you fight Gary') + ], 'http://example.com/finalbattle') + ]), + ]) + }) + }) +})
d07d6d4aa84a173aeb1f46417bcd06ae85720526
tests/__tests__/tsx-errors.spec.ts
tests/__tests__/tsx-errors.spec.ts
import runJest from '../__helpers__/runJest'; xdescribe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => { const result = runJest('../button', ['--no-cache', '-u']); const stderr = result.stderr.toString(); expect(result.status).toBe(1); expect(stderr).toContain('Button.tsx:18:17'); expect(stderr).toContain('Button.test.tsx:15:12'); }); });
import runJest from '../__helpers__/runJest'; const tmpDescribe = parseInt(process.version.substr(1, 2)) >= 8 ? xdescribe : describe; tmpDescribe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => { const result = runJest('../button', ['--no-cache', '-u']); const stderr = result.stderr.toString(); expect(result.status).toBe(1); expect(stderr).toContain('Button.tsx:18:17'); expect(stderr).toContain('Button.test.tsx:15:12'); }); });
Drop the tsx error test only for node versions >= 8
Drop the tsx error test only for node versions >= 8
TypeScript
mit
kulshekhar/ts-jest,kulshekhar/ts-jest
--- +++ @@ -1,6 +1,9 @@ import runJest from '../__helpers__/runJest'; -xdescribe('TSX Errors', () => { +const tmpDescribe = + parseInt(process.version.substr(1, 2)) >= 8 ? xdescribe : describe; + +tmpDescribe('TSX Errors', () => { it('should show the correct error locations in the typescript files', () => { const result = runJest('../button', ['--no-cache', '-u']);
0c69fbf4a0ccbdf18dfd87ae85e2fe5667c946aa
packages/lesswrong/components/common/Home2.tsx
packages/lesswrong/components/common/Home2.tsx
import { Components, registerComponent } from '../../lib/vulcan-lib'; import React from 'react'; import { AnalyticsContext } from "../../lib/analyticsEvents"; const Home2 = () => { const { RecentDiscussionFeed, HomeLatestPosts, AnalyticsInViewTracker, RecommendationsAndCurated, GatherTown, SingleColumnSection } = Components return ( <AnalyticsContext pageContext="homePage"> <React.Fragment> <SingleColumnSection> <AnalyticsContext pageSectionContext="gatherTownWelcome"> <GatherTown/> </AnalyticsContext> </SingleColumnSection> <RecommendationsAndCurated configName="frontpage" /> <AnalyticsInViewTracker eventProps={{inViewType: "latestPosts"}} observerProps={{threshold:[0, 0.5, 1]}} > <HomeLatestPosts /> </AnalyticsInViewTracker> <AnalyticsContext pageSectionContext="recentDiscussion"> <AnalyticsInViewTracker eventProps={{inViewType: "recentDiscussion"}}> <RecentDiscussionFeed af={false} commentsLimit={4} maxAgeHours={18} /> </AnalyticsInViewTracker> </AnalyticsContext> </React.Fragment> </AnalyticsContext> ) } const Home2Component = registerComponent('Home2', Home2); declare global { interface ComponentTypes { Home2: typeof Home2Component } }
import { Components, registerComponent } from '../../lib/vulcan-lib'; import React from 'react'; import { AnalyticsContext } from "../../lib/analyticsEvents"; import { useLocation } from '../../lib/routeUtil'; import { isServer } from '../../lib/executionEnvironment'; const Home2 = () => { const { RecentDiscussionFeed, HomeLatestPosts, AnalyticsInViewTracker, RecommendationsAndCurated, GatherTown, SingleColumnSection, PermanentRedirect } = Components const { query } = useLocation(); return ( <AnalyticsContext pageContext="homePage"> {!query?.avoidAprilFools && isServer && <PermanentRedirect url={"https://lesswrong.substack.com"} status={302} />} <React.Fragment> <SingleColumnSection> <AnalyticsContext pageSectionContext="gatherTownWelcome"> <GatherTown/> </AnalyticsContext> </SingleColumnSection> <RecommendationsAndCurated configName="frontpage" /> <AnalyticsInViewTracker eventProps={{inViewType: "latestPosts"}} observerProps={{threshold:[0, 0.5, 1]}} > <HomeLatestPosts /> </AnalyticsInViewTracker> <AnalyticsContext pageSectionContext="recentDiscussion"> <AnalyticsInViewTracker eventProps={{inViewType: "recentDiscussion"}}> <RecentDiscussionFeed af={false} commentsLimit={4} maxAgeHours={18} /> </AnalyticsInViewTracker> </AnalyticsContext> </React.Fragment> </AnalyticsContext> ) } const Home2Component = registerComponent('Home2', Home2); declare global { interface ComponentTypes { Home2: typeof Home2Component } }
Implement redirect for April Fools
Implement redirect for April Fools
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -1,12 +1,16 @@ import { Components, registerComponent } from '../../lib/vulcan-lib'; import React from 'react'; import { AnalyticsContext } from "../../lib/analyticsEvents"; +import { useLocation } from '../../lib/routeUtil'; +import { isServer } from '../../lib/executionEnvironment'; const Home2 = () => { - const { RecentDiscussionFeed, HomeLatestPosts, AnalyticsInViewTracker, RecommendationsAndCurated, GatherTown, SingleColumnSection } = Components + const { RecentDiscussionFeed, HomeLatestPosts, AnalyticsInViewTracker, RecommendationsAndCurated, GatherTown, SingleColumnSection, PermanentRedirect } = Components + const { query } = useLocation(); return ( <AnalyticsContext pageContext="homePage"> + {!query?.avoidAprilFools && isServer && <PermanentRedirect url={"https://lesswrong.substack.com"} status={302} />} <React.Fragment> <SingleColumnSection> <AnalyticsContext pageSectionContext="gatherTownWelcome">
cf55fe0262d18c99986c1a2981a9970d87f5c30e
src/delir-core/src/index.ts
src/delir-core/src/index.ts
// @flow import * as Project from './project/index' import Renderer from './renderer/renderer' import * as Services from './services' import * as Exceptions from './exceptions' import ColorRGB from './struct/color-rgb' import ColorRGBA from './struct/color-rgba' import Type, {TypeDescriptor} from './plugin/type-descriptor' import PluginBase from './plugin/plugin-base' import RenderRequest from './renderer/render-request' import PluginPreRenderRequest from './renderer/plugin-pre-rendering-request' import LayerPluginBase from './plugin/layer-plugin-base' import * as ProjectHelper from './helper/project-helper' export { // Core Project, Renderer, Services, Exceptions, // Structure ColorRGB, ColorRGBA, // Plugins Type, TypeDescriptor, PluginBase, LayerPluginBase, PluginPreRenderRequest, RenderRequest, // import shorthand ProjectHelper, }
// @flow import * as Project from './project/index' import Renderer from './renderer/renderer' import * as Services from './services' import * as Exceptions from './exceptions' import ColorRGB from './struct/color-rgb' import ColorRGBA from './struct/color-rgba' import Type, {TypeDescriptor} from './plugin/type-descriptor' import PluginBase from './plugin/plugin-base' import RenderRequest from './renderer/render-request' import PluginPreRenderRequest from './renderer/plugin-pre-rendering-request' import LayerPluginBase from './plugin/layer-plugin-base' import * as ProjectHelper from './helper/project-helper' export { // Core Project, Renderer, Services, Exceptions, // Structure ColorRGB, ColorRGBA, // Plugins Type, TypeDescriptor, PluginBase, LayerPluginBase, PluginPreRenderRequest, RenderRequest, // import shorthand ProjectHelper, } export default exports
Add default exports in delir-core
Add default exports in delir-core
TypeScript
mit
Ragg-/Delir,Ragg-/Delir,Ragg-/Delir,Ragg-/Delir
--- +++ @@ -37,3 +37,5 @@ // import shorthand ProjectHelper, } + +export default exports
d2b38963703bbca141f04f54db9c6624196cab1a
generators/app/templates/src/routes.ts
generators/app/templates/src/routes.ts
/// <reference path="../typings/index.d.ts" /> <% if (modules === 'inject') { -%> angular .module('app') .config(routesConfig); <% } else { -%> export default routesConfig; <% } -%> interface IComponentState extends angular.ui.IState { component?: string; } interface IStateProvider extends angular.IServiceProvider { state(name: string, config: IComponentState): IStateProvider; state(config: IComponentState): IStateProvider; decorator(name?: string, decorator?: (state: IComponentState, parent: Function) => any): any; } /** @ngInject */ function routesConfig($stateProvider: IStateProvider, $urlRouterProvider: angular.ui.IUrlRouterProvider, $locationProvider: angular.ILocationProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); $urlRouterProvider.otherwise('/'); $stateProvider .state('app', { url: '/', component: 'app' }); }
/// <reference path="../typings/index.d.ts" /> <% if (modules === 'inject') { -%> angular .module('app') .config(routesConfig); <% } else { -%> export default routesConfig; <% } -%> /** @ngInject */ function routesConfig($stateProvider: angular.ui.IStateProvider, $urlRouterProvider: angular.ui.IUrlRouterProvider, $locationProvider: angular.ILocationProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); $urlRouterProvider.otherwise('/'); $stateProvider .state('app', { url: '/', component: 'app' }); }
Remove typings workaround since angular-ui-router typings are updated
Remove typings workaround since angular-ui-router typings are updated
TypeScript
mit
FountainJS/generator-fountain-angular1,rkori215/generator-angular1-gulp,FountainJS/generator-fountain-angular1,rkori215/generator-angular1-gulp,FountainJS/generator-fountain-angular1,rkori215/generator-angular1-gulp
--- +++ @@ -8,18 +8,8 @@ export default routesConfig; <% } -%> -interface IComponentState extends angular.ui.IState { - component?: string; -} - -interface IStateProvider extends angular.IServiceProvider { - state(name: string, config: IComponentState): IStateProvider; - state(config: IComponentState): IStateProvider; - decorator(name?: string, decorator?: (state: IComponentState, parent: Function) => any): any; -} - /** @ngInject */ -function routesConfig($stateProvider: IStateProvider, $urlRouterProvider: angular.ui.IUrlRouterProvider, $locationProvider: angular.ILocationProvider) { +function routesConfig($stateProvider: angular.ui.IStateProvider, $urlRouterProvider: angular.ui.IUrlRouterProvider, $locationProvider: angular.ILocationProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); $urlRouterProvider.otherwise('/');
439d0fc34b49bd89f8bc586940d29f5075336822
src/relay/config.ts
src/relay/config.ts
import * as Relay from "react-relay" const sharify = require("sharify") export const metaphysicsURL = "https://metaphysics-production.artsy.net" export function artsyNetworkLayer(user?: any) { return new Relay.DefaultNetworkLayer(metaphysicsURL, { headers: !!user ? { "X-USER-ID": user.id, "X-ACCESS-TOKEN": user.accessToken, } : {}, }) } /* * For the client. */ export function artsyRelayEnvironment() { Relay.injectNetworkLayer(artsyNetworkLayer()) }
import * as Relay from "react-relay" const sharify = require("sharify") export function artsyNetworkLayer(user?: any) { return new Relay.DefaultNetworkLayer(sharify.data.METAPHYSICS_ENDPOINT, { headers: !!user ? { "X-USER-ID": user.id, "X-ACCESS-TOKEN": user.accessToken, } : {}, }) } /* * For the client. */ export function artsyRelayEnvironment() { Relay.injectNetworkLayer(artsyNetworkLayer()) }
Use metaphysics url from ENV rather than hard-coded value
Use metaphysics url from ENV rather than hard-coded value
TypeScript
mit
craigspaeth/reaction,xtina-starr/reaction,craigspaeth/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,xtina-starr/reaction,craigspaeth/reaction,artsy/reaction,artsy/reaction-force,artsy/reaction
--- +++ @@ -1,10 +1,8 @@ import * as Relay from "react-relay" const sharify = require("sharify") -export const metaphysicsURL = "https://metaphysics-production.artsy.net" - export function artsyNetworkLayer(user?: any) { - return new Relay.DefaultNetworkLayer(metaphysicsURL, { + return new Relay.DefaultNetworkLayer(sharify.data.METAPHYSICS_ENDPOINT, { headers: !!user ? { "X-USER-ID": user.id, "X-ACCESS-TOKEN": user.accessToken,
338b2e6b853e1b6dae0487fe4a15e1f3955134e5
src/app/error/error.component.spec.ts
src/app/error/error.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ErrorComponent } from './error.component'; describe('ErrorComponent', () => { let component: ErrorComponent; let fixture: ComponentFixture<ErrorComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ErrorComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ErrorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ErrorComponent } from './error.component'; describe('ErrorComponent', () => { let component: ErrorComponent; let fixture: ComponentFixture<ErrorComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ErrorComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ErrorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create and show 404 text', () => { expect(component).toBeTruthy(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('404'); expect(compiled.querySelector('.content-area > p > strong').textContent) .toContain('You’re looking a little lost there.'); }); });
Add basic test for error component
Add basic test for error component
TypeScript
apache-2.0
jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog
--- +++ @@ -19,7 +19,12 @@ fixture.detectChanges(); }); - it('should create', () => { + it('should create and show 404 text', () => { expect(component).toBeTruthy(); + + const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain('404'); + expect(compiled.querySelector('.content-area > p > strong').textContent) + .toContain('You’re looking a little lost there.'); }); });
5158abc945d02ef28a0de60b5dd09322da8aacf1
test/index.ts
test/index.ts
import * as bootstrap from './bootstrap'; // // PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING // // This file is providing the test runner to use when running extension tests. // By default the test runner in use is Mocha based. // // You can provide your own test runner if you want to override it by exporting // a function run(testRoot: string, clb: (error:Error) => void) that the extension // host can call to run the tests. The test runner is expected to use console.log // to report the results back to the caller. When the tests are finished, return // a possible error to the callback or null if none. var testRunner = require('vscode/lib/testrunner'); // You can directly control Mocha options by uncommenting the following lines // See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info testRunner.configure({ ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.) useColors: true // colored output from test results }); export function run(testsRoot:string, callback: (error:Error, failures?:number) => void):void { testRunner.run(testsRoot, (e, failures) => { bootstrap.callback(() => { if (failures > 0) { callback(new Error(failures + ' test(s) failed'), failures); } }); }); };
import * as bootstrap from './bootstrap'; // // PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING // // This file is providing the test runner to use when running extension tests. // By default the test runner in use is Mocha based. // // You can provide your own test runner if you want to override it by exporting // a function run(testRoot: string, clb: (error:Error) => void) that the extension // host can call to run the tests. The test runner is expected to use console.log // to report the results back to the caller. When the tests are finished, return // a possible error to the callback or null if none. var testRunner = require('vscode/lib/testrunner'); // You can directly control Mocha options by uncommenting the following lines // See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info testRunner.configure({ ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.) useColors: true // colored output from test results }); export function run(testsRoot:string, callback: (error:Error, failures?:number) => void):void { testRunner.run(testsRoot, (e, failures) => { bootstrap.callback(() => { if (failures > 0) { callback(new Error(failures + ' test(s) failed'), failures); } else { callback(null); } }); }); };
Add missing callback on test complete
Add missing callback on test complete
TypeScript
mit
neild3r/vscode-php-docblocker
--- +++ @@ -26,6 +26,8 @@ bootstrap.callback(() => { if (failures > 0) { callback(new Error(failures + ' test(s) failed'), failures); + } else { + callback(null); } }); });
5eb393d828328b34567566d3c0d622b4aef1e202
packages/keccak256/src.ts/index.ts
packages/keccak256/src.ts/index.ts
"use strict"; import sha3 = require("js-sha3"); import { arrayify, BytesLike } from "@ethersproject/bytes"; export function keccak256(data: BytesLike): string { return '0x' + sha3.keccak_256(arrayify(data)); }
"use strict"; import sha3 from "js-sha3"; import { arrayify, BytesLike } from "@ethersproject/bytes"; export function keccak256(data: BytesLike): string { return '0x' + sha3.keccak_256(arrayify(data)); }
Fix non-ES6 import in keccak256.
Fix non-ES6 import in keccak256.
TypeScript
mit
ethers-io/ethers.js,ethers-io/ethers.js,ethers-io/ethers.js,ethers-io/ethers.js,ethers-io/ethers.js,ethers-io/ethers.js,ethers-io/ethers.js
--- +++ @@ -1,6 +1,6 @@ "use strict"; -import sha3 = require("js-sha3"); +import sha3 from "js-sha3"; import { arrayify, BytesLike } from "@ethersproject/bytes";
6d8a6224cff503004684b4c0d2d79654b0781e7f
src/ng2-smart-table/components/cell/cell-editors/completer-editor.component.ts
src/ng2-smart-table/components/cell/cell-editors/completer-editor.component.ts
import { Component, OnInit } from '@angular/core'; import { CompleterService } from 'ng2-completer'; import { DefaultEditor } from './default-editor'; @Component({ selector: 'completer-editor', template: ` <ng2-completer [(ngModel)]="completerStr" [dataService]="cell.getColumn().getConfig().completer.dataService" [minSearchLength]="cell.getColumn().getConfig().completer.minSearchLength || 0" [pause]="cell.getColumn().getConfig().completer.pause || 0" [placeholder]="cell.getColumn().getConfig().completer.placeholder || 'Start typing...'" (selected)="onEditedCompleter($event)"> </ng2-completer> `, }) export class CompleterEditorComponent extends DefaultEditor implements OnInit { completerStr: string = ''; constructor(private completerService: CompleterService) { super(); } ngOnInit() { if (this.cell.getColumn().editor && this.cell.getColumn().editor.type === 'completer') { const config = this.cell.getColumn().getConfig().completer; config.dataService = this.completerService.local(config.data, config.searchFields, config.titleField); config.dataService.descriptionField(config.descriptionField); } } onEditedCompleter(event: { title: '' }): boolean { this.cell.newValue = event.title; return false; } }
import { Component, OnInit } from '@angular/core'; import { CompleterService } from 'ng2-completer'; import { DefaultEditor } from './default-editor'; @Component({ selector: 'completer-editor', template: ` <ng2-completer [(ngModel)]="completerStr" [dataService]="cell.getColumn().getConfig().completer.dataService" [minSearchLength]="cell.getColumn().getConfig().completer.minSearchLength || 0" [pause]="cell.getColumn().getConfig().completer.pause || 0" [placeholder]="cell.getColumn().getConfig().completer.placeholder || 'Start typing...'" (selected)="onEditedCompleter($event)"> </ng2-completer> `, }) export class CompleterEditorComponent extends DefaultEditor implements OnInit { completerStr: string = ''; constructor(private completerService: CompleterService) { super(); } ngOnInit() { if (this.cell.getColumn().editor && this.cell.getColumn().editor.type === 'completer') { const config = this.cell.getColumn().getConfig().completer; if (!config.dataService) { config.dataService = this.completerService.local(config.data, config.searchFields, config.titleField); config.dataService.descriptionField(config.descriptionField); } } } onEditedCompleter(event: { title: '' }): boolean { this.cell.newValue = event.title; return false; } }
Allow to provide a data service for the completer
Allow to provide a data service for the completer
TypeScript
mit
guilleva/ng2-smart-table,guilleva/ng2-smart-table,guilleva/ng2-smart-table
--- +++ @@ -26,8 +26,10 @@ ngOnInit() { if (this.cell.getColumn().editor && this.cell.getColumn().editor.type === 'completer') { const config = this.cell.getColumn().getConfig().completer; - config.dataService = this.completerService.local(config.data, config.searchFields, config.titleField); - config.dataService.descriptionField(config.descriptionField); + if (!config.dataService) { + config.dataService = this.completerService.local(config.data, config.searchFields, config.titleField); + config.dataService.descriptionField(config.descriptionField); + } } }
52f18407761d5c7e5c54568d291931306f056663
todo-angular2/typings/tsd.d.ts
todo-angular2/typings/tsd.d.ts
/// <reference path="jquery/jquery.d.ts" /> /// <reference path="material/material.d.ts" /> /// <reference path="moment/moment-node.d.ts" /> /// <reference path="moment/moment.d.ts" />
/// <reference path="jquery/jquery.d.ts" /> /// <reference path="semantic/semantic.d.ts" /> /// <reference path="moment/moment-node.d.ts" /> /// <reference path="moment/moment.d.ts" />
Change Materialize Reference to Semantic reference.
Change Materialize Reference to Semantic reference.
TypeScript
mit
codeknowledge/curso-ferias-unifil-aplicacoes-web-modernas,codeknowledge/curso-ferias-unifil-aplicacoes-web-modernas,codeknowledge/curso-ferias-unifil-aplicacoes-web-modernas
--- +++ @@ -1,4 +1,4 @@ /// <reference path="jquery/jquery.d.ts" /> -/// <reference path="material/material.d.ts" /> +/// <reference path="semantic/semantic.d.ts" /> /// <reference path="moment/moment-node.d.ts" /> /// <reference path="moment/moment.d.ts" />
35289a54b3873f36826016b1905f0a082ffc1da1
terminus-terminal/src/components/searchPanel.component.ts
terminus-terminal/src/components/searchPanel.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core' import { ToastrService } from 'ngx-toastr' import { Frontend, SearchOptions } from '../frontends/frontend' @Component({ selector: 'search-panel', template: require('./searchPanel.component.pug'), styles: [require('./searchPanel.component.scss')], }) export class SearchPanelComponent { static globalOptions: SearchOptions = {} @Input() query: string @Input() frontend: Frontend notFound = false options: SearchOptions = SearchPanelComponent.globalOptions @Output() close = new EventEmitter() constructor ( private toastr: ToastrService, ) { } findNext () { if (!this.frontend.findNext(this.query, this.options)) { this.notFound = true this.toastr.error('Not found') } } findPrevious () { if (!this.frontend.findPrevious(this.query, this.options)) { this.notFound = true this.toastr.error('Not found') } } }
import { Component, Input, Output, EventEmitter } from '@angular/core' import { ToastrService } from 'ngx-toastr' import { Frontend, SearchOptions } from '../frontends/frontend' @Component({ selector: 'search-panel', template: require('./searchPanel.component.pug'), styles: [require('./searchPanel.component.scss')], }) export class SearchPanelComponent { @Input() query: string @Input() frontend: Frontend notFound = false options: SearchOptions = {} @Output() close = new EventEmitter() constructor ( private toastr: ToastrService, ) { } findNext () { if (!this.frontend.findNext(this.query, this.options)) { this.notFound = true this.toastr.error('Not found') } } findPrevious () { if (!this.frontend.findPrevious(this.query, this.options)) { this.notFound = true this.toastr.error('Not found') } } }
Change search options to not be static/global
Change search options to not be static/global
TypeScript
mit
Eugeny/terminus,Eugeny/terminus,Eugeny/terminus,Eugeny/terminus,Eugeny/terminus,Eugeny/terminus
--- +++ @@ -8,11 +8,10 @@ styles: [require('./searchPanel.component.scss')], }) export class SearchPanelComponent { - static globalOptions: SearchOptions = {} @Input() query: string @Input() frontend: Frontend notFound = false - options: SearchOptions = SearchPanelComponent.globalOptions + options: SearchOptions = {} @Output() close = new EventEmitter()
c1d89eadc9ba15459cb97b727b070184b29a6ab7
dom_pl.ts
dom_pl.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="pl"> <context> <name>TreeWindow</name> <message> <location filename="../../../treewindow.ui" line="14"/> <source>Panel DOM tree</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../treewindow.ui" line="63"/> <location filename="../../../treewindow.ui" line="96"/> <source>Property</source> <translation>WΕ‚aΕ›ciwoΕ›Δ‡</translation> </message> <message> <location filename="../../../treewindow.ui" line="68"/> <source>Value</source> <translation>WartoΕ›Δ‡</translation> </message> <message> <location filename="../../../treewindow.ui" line="76"/> <source>All properties</source> <translation>Wszystkie wΕ‚aΕ›ciwoΕ›ci</translation> </message> <message> <location filename="../../../treewindow.ui" line="101"/> <source>Type</source> <translation>Rodzaj</translation> </message> <message> <location filename="../../../treewindow.ui" line="106"/> <source>String value</source> <translation>CiΔ…g znakΓ³w</translation> </message> </context> </TS>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="pl"> <context> <name>TreeWindow</name> <message> <location filename="../../../treewindow.ui" line="14"/> <source>Panel DOM tree</source> <translation>Drzewo DOM panelu</translation> </message> <message> <location filename="../../../treewindow.ui" line="63"/> <location filename="../../../treewindow.ui" line="96"/> <source>Property</source> <translation>WΕ‚aΕ›ciwoΕ›Δ‡</translation> </message> <message> <location filename="../../../treewindow.ui" line="68"/> <source>Value</source> <translation>WartoΕ›Δ‡</translation> </message> <message> <location filename="../../../treewindow.ui" line="76"/> <source>All properties</source> <translation>Wszystkie wΕ‚aΕ›ciwoΕ›ci</translation> </message> <message> <location filename="../../../treewindow.ui" line="101"/> <source>Type</source> <translation>Rodzaj</translation> </message> <message> <location filename="../../../treewindow.ui" line="106"/> <source>String value</source> <translation>CiΔ…g znakΓ³w</translation> </message> </context> </TS>
Update to current sources (no new strings) + update Polish translation
Update to current sources (no new strings) + update Polish translation
TypeScript
lgpl-2.1
stefonarch/lxqt-panel,lxde/lxqt-panel,stefonarch/lxqt-panel,stefonarch/lxqt-panel,lxde/lxqt-panel
--- +++ @@ -6,7 +6,7 @@ <message> <location filename="../../../treewindow.ui" line="14"/> <source>Panel DOM tree</source> - <translation type="unfinished"></translation> + <translation>Drzewo DOM panelu</translation> </message> <message> <location filename="../../../treewindow.ui" line="63"/>
f33f2425752772219aebd0a2fc2f20cf313d4d58
src/app-artem/courses/courses.service.ts
src/app-artem/courses/courses.service.ts
import * as coursesMockData from './courses.api-mock.json'; import { CourseModel } from './course/course.model'; export class CoursesService { private coursesList: CourseModel[]; constructor() { this.coursesList = coursesMockData; console.log('CoursesService: constructor() this.coursesList', this.coursesList); } public getCourses() { // imitate async return new Promise((resolve, reject) => { setTimeout(() => resolve(this.coursesList), 1000); }); } }
import * as coursesMockData from './courses.api-mock.json'; import { CourseModel } from './course/course.model'; export class CoursesService { private coursesList: CourseModel[]; constructor() { this.coursesList = coursesMockData; console.log('CoursesService: constructor() this.coursesList', this.coursesList); } // TODO: shouldn't this be inferred from the -- private coursesList: CourseModel[] --- ??? public getCourses(): Promise<CourseModel[]> { // imitate async return new Promise((resolve, reject) => { setTimeout(() => resolve(this.coursesList), 1000); }); } }
Fix typings problem of the [at-loader]:
Fix typings problem of the [at-loader]: [at-loader] Checking finished with 2 errors [at-loader] src\app-artem\courses\courses.component.ts:17:9 TS2322: Type '{}' is not assignable to type 'CourseModel[]'. [at-loader] src\app-artem\courses\courses.component.ts:17:9 TS2322: Type '{}' is not assignable to type 'CourseModel[]'. Property 'find' is missing in type '{}'.
TypeScript
mit
last-indigo/angular-mp,last-indigo/angular-mp,last-indigo/angular-mp
--- +++ @@ -9,7 +9,8 @@ console.log('CoursesService: constructor() this.coursesList', this.coursesList); } - public getCourses() { + // TODO: shouldn't this be inferred from the -- private coursesList: CourseModel[] --- ??? + public getCourses(): Promise<CourseModel[]> { // imitate async return new Promise((resolve, reject) => { setTimeout(() => resolve(this.coursesList), 1000);
3702a15bad2e668958159c61874ad23dc0c91619
src/components/atoms/Image.tsx
src/components/atoms/Image.tsx
import React, { CSSProperties } from 'react' interface ImageProps { src: string className?: string style?: CSSProperties alt?: string } const Image = ({ src, className, style, alt }: ImageProps) => { if (src.startsWith('/app')) { src = src.slice(1) } return <img src={src} className={className} style={style} alt={alt} /> } export default Image
import React, { CSSProperties } from 'react' import isElectron from 'is-electron' interface ImageProps { src: string className?: string style?: CSSProperties alt?: string } const Image = ({ src, className, style, alt }: ImageProps) => { if (isElectron() && src.startsWith('/app')) { src = src.slice(1) } return <img src={src} className={className} style={style} alt={alt} /> } export default Image
Rewrite src for electron app only
Rewrite src for electron app only
TypeScript
mit
Sarah-Seo/Inpad,Sarah-Seo/Inpad
--- +++ @@ -1,4 +1,5 @@ import React, { CSSProperties } from 'react' +import isElectron from 'is-electron' interface ImageProps { src: string @@ -8,7 +9,7 @@ } const Image = ({ src, className, style, alt }: ImageProps) => { - if (src.startsWith('/app')) { + if (isElectron() && src.startsWith('/app')) { src = src.slice(1) }
bc39c196b73eb8447a3b415194300da7f276be23
spec/components/subtitleoverlay.spec.ts
spec/components/subtitleoverlay.spec.ts
import { MockHelper, TestingPlayerAPI } from '../helper/MockHelper'; import { UIInstanceManager } from '../../src/ts/uimanager'; import {SubtitleOverlay, SubtitleRegionContainerManager } from '../../src/ts/components/subtitleoverlay'; let playerMock: TestingPlayerAPI; let uiInstanceManagerMock: UIInstanceManager; let subtitleOverlay: SubtitleOverlay; jest.mock('../../src/ts/components/label'); let subtitleRegionContainerManagerMock: SubtitleRegionContainerManager; describe('SubtitleOverlay', () => { describe('Subtitle Region Container', () => { beforeEach(() => { playerMock = MockHelper.getPlayerMock(); uiInstanceManagerMock = MockHelper.getUiInstanceManagerMock(); subtitleOverlay = new SubtitleOverlay(); subtitleOverlay.configure(playerMock, uiInstanceManagerMock); subtitleRegionContainerManagerMock = (subtitleOverlay as any).subtitleContainerManager; }); it('adds a subtitle label on cueEnter', () => { const addLabelSpy = jest.spyOn(subtitleRegionContainerManagerMock, 'addLabel'); playerMock.eventEmitter.fireSubtitleCueEnterEvent(); expect(addLabelSpy).toHaveBeenCalled(); }); }); });
import { MockHelper, TestingPlayerAPI } from '../helper/MockHelper'; import { UIInstanceManager } from '../../src/ts/uimanager'; import {SubtitleOverlay, SubtitleRegionContainerManager } from '../../src/ts/components/subtitleoverlay'; let playerMock: TestingPlayerAPI; let uiInstanceManagerMock: UIInstanceManager; let subtitleOverlay: SubtitleOverlay; jest.mock('../../src/ts/components/label'); jest.mock('../../src/ts/components/container'); let subtitleRegionContainerManagerMock: SubtitleRegionContainerManager; describe('SubtitleOverlay', () => { describe('Subtitle Region Container', () => { beforeEach(() => { playerMock = MockHelper.getPlayerMock(); uiInstanceManagerMock = MockHelper.getUiInstanceManagerMock(); subtitleOverlay = new SubtitleOverlay(); subtitleOverlay.configure(playerMock, uiInstanceManagerMock); subtitleRegionContainerManagerMock = (subtitleOverlay as any).subtitleContainerManager; }); it('adds a subtitle label on cueEnter', () => { const addLabelSpy = jest.spyOn(subtitleRegionContainerManagerMock, 'addLabel'); playerMock.eventEmitter.fireSubtitleCueEnterEvent(); expect(addLabelSpy).toHaveBeenCalled(); }); it('removes a subtitle label con cueExit', () => { playerMock.eventEmitter.fireSubtitleCueEnterEvent(); const mockDomElement = MockHelper.generateDOMMock(); const removeLabelSpy = jest.spyOn(subtitleRegionContainerManagerMock, 'removeLabel'); jest.spyOn(subtitleOverlay, 'getDomElement').mockReturnValue(mockDomElement); jest.setTimeout(10); playerMock.eventEmitter.fireSubtitleCueExitEvent(); expect(removeLabelSpy).toHaveBeenCalled(); }); }); });
Add test for removal of subtitle label on cueExit
Add test for removal of subtitle label on cueExit
TypeScript
mit
bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui
--- +++ @@ -7,6 +7,7 @@ let subtitleOverlay: SubtitleOverlay; jest.mock('../../src/ts/components/label'); +jest.mock('../../src/ts/components/container'); let subtitleRegionContainerManagerMock: SubtitleRegionContainerManager; @@ -26,5 +27,15 @@ playerMock.eventEmitter.fireSubtitleCueEnterEvent(); expect(addLabelSpy).toHaveBeenCalled(); }); + + it('removes a subtitle label con cueExit', () => { + playerMock.eventEmitter.fireSubtitleCueEnterEvent(); + const mockDomElement = MockHelper.generateDOMMock(); + const removeLabelSpy = jest.spyOn(subtitleRegionContainerManagerMock, 'removeLabel'); + jest.spyOn(subtitleOverlay, 'getDomElement').mockReturnValue(mockDomElement); + jest.setTimeout(10); + playerMock.eventEmitter.fireSubtitleCueExitEvent(); + expect(removeLabelSpy).toHaveBeenCalled(); + }); }); });
f0cdbbfe68b05577ee93c6c74ffe3361320438f0
src/Cursor.ts
src/Cursor.ts
export class Cursor { private _show = true; private _blink = false; constructor(private position: RowColumn = { row: 0, column: 0 }) { } moveAbsolute(position: PartialRowColumn, homePosition: RowColumn): this { if (typeof position.column === "number") { this.position.column = position.column + homePosition.column; } if (typeof position.row === "number") { this.position.row = position.row + homePosition.row; } return this; } moveRelative(advancement: Advancement): this { const row = Math.max(0, this.row + (advancement.vertical || 0)); const column = Math.max(0, this.column + (advancement.horizontal || 0)); this.moveAbsolute({ row: row, column: column }, { column: 0, row: 0 }); return this; } getPosition(): RowColumn { return this.position; } get column(): number { return this.position.column; } get row(): number { return this.position.row; } get blink(): boolean { return this._blink; } set blink(value: boolean) { this._blink = value; } get show(): boolean { return this._show; } set show(value: boolean) { this._show = value; } }
export class Cursor { private _show = true; private _blink = false; constructor(private position: RowColumn = { row: 0, column: 0 }) { } moveAbsolute(position: PartialRowColumn, homePosition: RowColumn): this { if (typeof position.column === "number") { this.position.column = Math.max(position.column, 0) + homePosition.column; } if (typeof position.row === "number") { this.position.row = Math.max(position.row, 0) + homePosition.row; } return this; } moveRelative(advancement: Advancement): this { const row = Math.max(0, this.row + (advancement.vertical || 0)); const column = Math.max(0, this.column + (advancement.horizontal || 0)); this.moveAbsolute({ row: row, column: column }, { column: 0, row: 0 }); return this; } getPosition(): RowColumn { return this.position; } get column(): number { return this.position.column; } get row(): number { return this.position.row; } get blink(): boolean { return this._blink; } set blink(value: boolean) { this._blink = value; } get show(): boolean { return this._show; } set show(value: boolean) { this._show = value; } }
Fix the issue when cursor could have been moved to a negative position.
Fix the issue when cursor could have been moved to a negative position. Apt sends an incorrect column 0 instead of 1: e.g. `sudo apt install emacs`.
TypeScript
mit
railsware/upterm,vshatskyi/black-screen,shockone/black-screen,black-screen/black-screen,railsware/upterm,black-screen/black-screen,vshatskyi/black-screen,vshatskyi/black-screen,shockone/black-screen,black-screen/black-screen,vshatskyi/black-screen
--- +++ @@ -7,11 +7,11 @@ moveAbsolute(position: PartialRowColumn, homePosition: RowColumn): this { if (typeof position.column === "number") { - this.position.column = position.column + homePosition.column; + this.position.column = Math.max(position.column, 0) + homePosition.column; } if (typeof position.row === "number") { - this.position.row = position.row + homePosition.row; + this.position.row = Math.max(position.row, 0) + homePosition.row; } return this;
78b87d432939f452fd9fb9a31c6cfb4779d87cad
client/src/app/app.component.ts
client/src/app/app.component.ts
import { Component, OnInit } from '@angular/core'; import { Apollo } from 'apollo-angular'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import helloWorldQuery from 'graphql-tag/loader!./hello-world.query.graphql'; import helloMutantWorldMutation from 'graphql-tag/loader!./hello-mutant-world.mutation.graphql'; import helloRealtimeWorldSubscription from 'graphql-tag/loader!./hello-realtime-world.subscription.graphql'; import { HelloRealtimeWorldSubscription, HelloWorldQuery } from './schema'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app works!'; input: String; data: Observable<HelloWorldQuery>; subscriptionData: Observable<HelloRealtimeWorldSubscription>; constructor(private apollo: Apollo) { } ngOnInit() { this.data = this.apollo.watchQuery({ query: helloWorldQuery }).map(ret => ret.data); this.subscriptionData = this.apollo.subscribe({ query: helloRealtimeWorldSubscription }); } onSubmit() { this.apollo.mutate({ mutation: helloMutantWorldMutation, variables: { val: this.input } }); } }
import { Component, OnInit } from '@angular/core'; import { Apollo } from 'apollo-angular'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import helloWorldQuery from 'graphql-tag/loader!./hello-world.query.graphql'; import helloMutantWorldMutation from 'graphql-tag/loader!./hello-mutant-world.mutation.graphql'; import helloRealtimeWorldSubscription from 'graphql-tag/loader!./hello-realtime-world.subscription.graphql'; import { HelloRealtimeWorldSubscription, HelloWorldQuery } from './schema'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app works!'; input: String; data: Observable<HelloWorldQuery>; subscriptionData: Observable<HelloRealtimeWorldSubscription>; constructor(private apollo: Apollo) { } ngOnInit() { this.data = this.apollo.watchQuery<HelloWorldQuery>({ query: helloWorldQuery }).map(ret => ret.data); this.subscriptionData = this.apollo.subscribe({ query: helloRealtimeWorldSubscription }); } onSubmit() { this.apollo.mutate({ mutation: helloMutantWorldMutation, variables: { val: this.input } }); } }
Use generics on watchQuery call
Use generics on watchQuery call
TypeScript
mit
justindoherty/helloworld-graphql,justindoherty/helloworld-graphql,justindoherty/helloworld-graphql,justindoherty/helloworld-graphql
--- +++ @@ -22,7 +22,7 @@ constructor(private apollo: Apollo) { } ngOnInit() { - this.data = this.apollo.watchQuery({ query: helloWorldQuery }).map(ret => ret.data); + this.data = this.apollo.watchQuery<HelloWorldQuery>({ query: helloWorldQuery }).map(ret => ret.data); this.subscriptionData = this.apollo.subscribe({ query: helloRealtimeWorldSubscription }); }
1e4fdeb30929adee934c65fabbb5ba9714d51d2d
developer/js/tests/test-parse-wordlist.ts
developer/js/tests/test-parse-wordlist.ts
import {parseWordList} from '../lexical-model-compiler/build-trie'; import {assert} from 'chai'; import 'mocha'; import path = require('path'); const BOM = '\ufeff'; describe('parseWordList', function () { it('should remove the UTF-8 byte order mark from files', function () { let word = 'hello'; let count = 1; let expected = [ [word, count] ]; let file = `# this is a comment\n${word}\t${count}`; let withoutBOM = parseWordList(file); assert.deepEqual(withoutBOM, expected, "expected regular file to parse properly"); let withBOM = parseWordList(`${BOM}${file}`) assert.deepEqual(withBOM, expected, "expected BOM to be ignored"); }); });
import {parseWordList} from '../dist/lexical-model-compiler/build-trie'; import {assert} from 'chai'; import 'mocha'; const BOM = '\ufeff'; describe('parseWordList', function () { it('should remove the UTF-8 byte order mark from files', function () { let word = 'hello'; let count = 1; let expected = [ [word, count] ]; let file = `# this is a comment\n${word}\t${count}`; let withoutBOM = parseWordList(file); assert.deepEqual(withoutBOM, expected, "expected regular file to parse properly"); let withBOM = parseWordList(`${BOM}${file}`) assert.deepEqual(withBOM, expected, "expected BOM to be ignored"); }); });
Fix paths issue from merge.
Fix paths issue from merge.
TypeScript
apache-2.0
tavultesoft/keymanweb,tavultesoft/keymanweb
--- +++ @@ -1,8 +1,6 @@ -import {parseWordList} from '../lexical-model-compiler/build-trie'; +import {parseWordList} from '../dist/lexical-model-compiler/build-trie'; import {assert} from 'chai'; import 'mocha'; - -import path = require('path'); const BOM = '\ufeff';
79b3245d7f6d2d1cb8511cc1ce06b34600a44b29
src/index.tsx
src/index.tsx
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import store from './store'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from "mobx-react"; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import configStore from "./stores/ConfigStore"; import projectStore from './stores/ProjectStore'; ReactDOM.render( <Provider configStore={configStore} projectStore={projectStore}> <App /> </Provider>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
Replace redux provider with mobx provider
Replace redux provider with mobx provider
TypeScript
mit
judovana/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin
--- +++ @@ -1,14 +1,18 @@ import React from 'react'; import ReactDOM from 'react-dom'; -import { Provider } from 'react-redux'; +import { Provider } from "mobx-react"; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; -import store from './store'; + +import configStore from "./stores/ConfigStore"; +import projectStore from './stores/ProjectStore'; ReactDOM.render( - <Provider store={store}> + <Provider + configStore={configStore} + projectStore={projectStore}> <App /> </Provider>, document.getElementById('root')
63a0c9ea9cfca3f600bff5bf9e227a0507683490
src/Styleguide/Pages/Artist/Routes/Shows/ShowBlockItem.tsx
src/Styleguide/Pages/Artist/Routes/Shows/ShowBlockItem.tsx
import { Serif } from "@artsy/palette" import React from "react" import { Box } from "Styleguide/Elements/Box" import { Image } from "Styleguide/Elements/Image" interface Props { imageUrl: string blockWidth: string name: string exhibitionInfo: string partner: string href: string // FIXME: Fix container directly by making responsive pr?: number pb?: number } export const ShowBlockItem = (props: Props) => { const FIXME_DOMAIN = "https://www.artsy.net" return ( <Box maxWidth="460px" width={props.blockWidth} height="auto" // FIXME pr={props.pr} pb={props.pb} > <a href={FIXME_DOMAIN + props.href} className="noUnderline"> <Image width="100%" src={props.imageUrl} /> <Serif size="3t">{props.name}</Serif> </a> <Serif size="2" color="black60"> <a href={FIXME_DOMAIN + props.href} className="noUnderline"> {props.partner} </a> </Serif> <Serif size="1" color="black60"> {props.exhibitionInfo} </Serif> </Box> ) }
import { Serif } from "@artsy/palette" import React from "react" import { Box } from "Styleguide/Elements/Box" import { Image } from "Styleguide/Elements/Image" interface Props { imageUrl: string blockWidth: string name: string exhibitionInfo: string partner: string href: string // FIXME: Fix container directly by making responsive pr?: number pb?: number } export const ShowBlockItem = (props: Props) => { const FIXME_DOMAIN = "https://www.artsy.net" return ( <Box width={props.blockWidth} height="auto" // FIXME pr={props.pr} pb={props.pb} > <a href={FIXME_DOMAIN + props.href} className="noUnderline"> <Image width="100%" src={props.imageUrl} /> <Serif size="3t">{props.name}</Serif> </a> <Serif size="2" color="black60"> <a href={FIXME_DOMAIN + props.href} className="noUnderline"> {props.partner} </a> </Serif> <Serif size="1" color="black60"> {props.exhibitionInfo} </Serif> </Box> ) }
Remove max width to make view more flexible
Remove max width to make view more flexible
TypeScript
mit
artsy/reaction-force,artsy/reaction-force,artsy/reaction,artsy/reaction,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction
--- +++ @@ -19,7 +19,6 @@ const FIXME_DOMAIN = "https://www.artsy.net" return ( <Box - maxWidth="460px" width={props.blockWidth} height="auto" // FIXME pr={props.pr}
d3293aeb8e137ccb374b41487d20d32fabfc1d28
packages/common/src/types.ts
packages/common/src/types.ts
export interface TokenRecord { token: string; address: string; when: number; reason: string; } export interface EmailRecord { address: string; verified: boolean; } export interface UserObjectType { username?: string; email?: string; emails?: EmailRecord[]; id: string; profile?: object; services?: object; } export interface CreateUserType { username?: string; email?: string; profile?: object; [additionalKey: string]: any; } export interface LoginUserIdentityType { id?: string; username?: string; email?: string; } export interface TokensType { accessToken?: string; refreshToken?: string; } export interface LoginReturnType { sessionId: string; tokens: TokensType; } export interface ImpersonateReturnType { authorized: boolean; tokens?: TokensType; user?: UserObjectType; } export interface SessionType { sessionId: string; userId: string; valid: boolean; userAgent?: string; createdAt: string; updatedAt: string; } export type HookListener = (event?: object) => void;
export interface TokenRecord { token: string; address: string; when: number; reason: string; } export interface EmailRecord { address: string; verified: boolean; } export interface UserObjectType { username?: string; email?: string; emails?: EmailRecord[]; id: string; profile?: object; services?: object; } export interface CreateUserType { username?: string; email?: string; profile?: object; [additionalKey: string]: any; } export interface LoginUserIdentityType { id?: string; username?: string; email?: string; } export interface TokensType { accessToken?: string; refreshToken?: string; } export interface LoginReturnType { sessionId: string; user: UserObjectType; tokens: TokensType; } export interface ImpersonateReturnType { authorized: boolean; tokens?: TokensType; user?: UserObjectType; } export interface SessionType { sessionId: string; userId: string; valid: boolean; userAgent?: string; createdAt: string; updatedAt: string; } export type HookListener = (event?: object) => void;
Add back user for now
Add back user for now
TypeScript
mit
js-accounts/accounts
--- +++ @@ -38,7 +38,8 @@ } export interface LoginReturnType { - sessionId: string; + sessionId: string; + user: UserObjectType; tokens: TokensType; }
8494a3467feba04a12909e538513c769f61b3132
ui/src/Document.tsx
ui/src/Document.tsx
import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import DocumentDetails from './DocumentDetails'; export default () => { const { id } = useParams(); const [document, setDocument] = useState(null); useEffect (() => { getDocument(id).then(setDocument); }, [id]); return (document && document.resource) ? renderDocument(document) : renderError(); }; const renderDocument = (document: any) => <DocumentDetails document={ document } />; const renderError = () => <div>Error: No matching document found.</div>; const getDocument = async (id: string) => { const response = await fetch(`/documents/${id}`); return await response.json(); };
import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import DocumentDetails from './DocumentDetails'; import { Container } from 'react-bootstrap'; export default () => { const { id } = useParams(); const [document, setDocument] = useState(null); const [error, setError] = useState(null); useEffect (() => { getDocument(id) .then(setDocument) .catch(setError); }, [id]); return (document && document.resource) ? renderDocument(document) : error ? renderError(error) : null; }; const renderDocument = (document: any) => <DocumentDetails document={ document } />; const renderError = (error: any) => <Container fluid>Error: { error.error }</Container>; const getDocument = async (id: string) => { const response = await fetch(`/documents/${id}`); if (response.ok) return await response.json(); else throw(await response.json()); };
Handle errors in document component
Handle errors in document component
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -1,30 +1,37 @@ import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import DocumentDetails from './DocumentDetails'; +import { Container } from 'react-bootstrap'; export default () => { const { id } = useParams(); const [document, setDocument] = useState(null); + const [error, setError] = useState(null); useEffect (() => { - getDocument(id).then(setDocument); + getDocument(id) + .then(setDocument) + .catch(setError); }, [id]); return (document && document.resource) ? renderDocument(document) - : renderError(); + : error + ? renderError(error) + : null; }; const renderDocument = (document: any) => <DocumentDetails document={ document } />; -const renderError = () => <div>Error: No matching document found.</div>; +const renderError = (error: any) => <Container fluid>Error: { error.error }</Container>; const getDocument = async (id: string) => { const response = await fetch(`/documents/${id}`); - return await response.json(); + if (response.ok) return await response.json(); + else throw(await response.json()); };
aacb85d75084c4dfaf2d909affe2a78a821323e4
packages/katex-extension/src/index.ts
packages/katex-extension/src/index.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { JupyterLabPlugin } from '@jupyterlab/application'; import { ILatexTypesetter } from '@jupyterlab/rendermime'; import { renderMathInElement } from './autorender'; import '../style/index.css'; /** * The KaTeX Typesetter. */ export class KatexTypesetter implements ILatexTypesetter { /** * Typeset the math in a node. */ typeset(node: HTMLElement): void { renderMathInElement(node); } } /** * The KaTex extension. */ const katexPlugin: JupyterLabPlugin<ILatexTypesetter> = { id: 'jupyter.extensions.katex', requires: [], activate: () => new KatexTypesetter(), autoStart: true } export default katexPlugin;
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { JupyterLabPlugin } from '@jupyterlab/application'; import { ILatexTypesetter } from '@jupyterlab/rendermime'; import { IRenderMime } from '@jupyterlab/rendermime-interfaces'; import { renderMathInElement } from './autorender'; import '../style/index.css'; /** * The KaTeX Typesetter. */ export class KatexTypesetter implements IRenderMime.ILatexTypesetter { /** * Typeset the math in a node. */ typeset(node: HTMLElement): void { renderMathInElement(node); } } /** * The KaTex extension. */ const katexPlugin: JupyterLabPlugin<ILatexTypesetter> = { id: 'jupyter.extensions.katex', provides: ILatexTypesetter, activate: () => new KatexTypesetter(), autoStart: true } export default katexPlugin;
Refactor katex-extension to take after mathjax2-extension
Refactor katex-extension to take after mathjax2-extension
TypeScript
bsd-3-clause
gnestor/jupyter-renderers,gnestor/jupyter-renderers
--- +++ @@ -10,6 +10,10 @@ } from '@jupyterlab/rendermime'; import { + IRenderMime +} from '@jupyterlab/rendermime-interfaces'; + +import { renderMathInElement } from './autorender'; @@ -19,7 +23,7 @@ * The KaTeX Typesetter. */ export -class KatexTypesetter implements ILatexTypesetter { +class KatexTypesetter implements IRenderMime.ILatexTypesetter { /** * Typeset the math in a node. */ @@ -33,7 +37,7 @@ */ const katexPlugin: JupyterLabPlugin<ILatexTypesetter> = { id: 'jupyter.extensions.katex', - requires: [], + provides: ILatexTypesetter, activate: () => new KatexTypesetter(), autoStart: true }
22b3a5b23304a3069aefc98ee583f4a31836ca5c
src/components/Layout/Link/index.tsx
src/components/Layout/Link/index.tsx
import React, { PropsWithChildren, ReactElement } from 'react' import { Link as HyperLink, LinkProps } from 'react-router-dom' export default function Link({ to, children, ...rest }: PropsWithChildren<LinkProps>): ReactElement { return ( <HyperLink to={to} {...rest} replace> {children} </HyperLink> ) }
import React, { PropsWithChildren, ReactElement } from 'react' import { Link as HyperLink, LinkProps } from 'react-router-dom' import join from 'utils/join' export interface LinkDef extends LinkProps { classNames?: (string | string[])[] } export default function Link({ to, children, classNames, ...rest }: PropsWithChildren<LinkDef>): ReactElement { const URL = String(to || '') const isInternalLink = URL.startsWith('/') || !to const classes = join(classNames ? classNames?.flat() : []) function renderInternalLink() { return ( <HyperLink to={URL} className={classes} {...rest} replace> {children} </HyperLink> ) } function renderExternalLink() { return ( <a href={URL} target="_blank" rel="noreferrer" className={classes} {...rest} > {children} </a> ) } return isInternalLink ? renderInternalLink() : renderExternalLink() }
Update Link component to work with internal and external URLs
Update Link component to work with internal and external URLs
TypeScript
mit
daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io
--- +++ @@ -1,14 +1,42 @@ import React, { PropsWithChildren, ReactElement } from 'react' import { Link as HyperLink, LinkProps } from 'react-router-dom' +import join from 'utils/join' + +export interface LinkDef extends LinkProps { + classNames?: (string | string[])[] +} export default function Link({ to, children, + classNames, ...rest -}: PropsWithChildren<LinkProps>): ReactElement { - return ( - <HyperLink to={to} {...rest} replace> - {children} - </HyperLink> - ) +}: PropsWithChildren<LinkDef>): ReactElement { + const URL = String(to || '') + const isInternalLink = URL.startsWith('/') || !to + const classes = join(classNames ? classNames?.flat() : []) + + function renderInternalLink() { + return ( + <HyperLink to={URL} className={classes} {...rest} replace> + {children} + </HyperLink> + ) + } + + function renderExternalLink() { + return ( + <a + href={URL} + target="_blank" + rel="noreferrer" + className={classes} + {...rest} + > + {children} + </a> + ) + } + + return isInternalLink ? renderInternalLink() : renderExternalLink() }
33ef587e1127c1229ac62ae4356ab50043d73ecc
tessera-frontend/src/ts/app/handlers/dashboard-create.ts
tessera-frontend/src/ts/app/handlers/dashboard-create.ts
import Dashboard from '../../models/dashboard' import manager from '../manager' import { make } from '../../models/items/factory' declare var $, window /* * Logic for the dashboard-create.html template. */ $(document).ready(function() { let tags = $('#ds-dashboard-tags') if (tags.length) { tags .tagsManager({ tagsContainer: '.ds-tag-holder', tagClass: 'badge badge-primary' }) } }) $(document).ready(function() { let form = $('#ds-dashboard-create-form') if (form.length) { form.bootstrapValidator() } }) $(document).on('click', '#ds-new-dashboard-create', function(e) { let title = $('#ds-dashboard-title')[0].value let category = $('#ds-dashboard-category')[0].value let summary = $('#ds-dashboard-summary')[0].value let description = $('#ds-dashboard-description')[0].value let tags = $('#ds-dashboard-tags').tagsManager('tags') if (!$('#ds-dashboard-create-form').data('bootstrapValidator').validate().isValid()) { return } let dashboard = new Dashboard({ title: title, category: category, summary: summary, description: description, tags: tags, definition: make('dashboard_definition') }) manager.create(dashboard, function(data) { window.location = data.view_href }) }) $(document).on('click', '#ds-new-dashboard-cancel', function(e) { window.history.back() })
import Dashboard from '../../models/dashboard' import manager from '../manager' import { make } from '../../models/items/factory' declare var $, window /* * Logic for the dashboard-create.html template. */ $(document).ready(function() { let tags = $('#ds-dashboard-tags') if (tags.length) { tags .tagsManager({ tagsContainer: '.ds-tag-holder', tagClass: 'badge badge-primary' }) } }) $(document).ready(function() { let form = $('#ds-dashboard-create-form') if (form.length) { form.bootstrapValidator() } }) $(document).on('click', '#ds-new-dashboard-create', function(e) { let title = $('#ds-dashboard-title')[0].value let category = $('#ds-dashboard-category')[0].value let summary = $('#ds-dashboard-summary')[0].value let description = $('#ds-dashboard-description')[0].value let tags = $('#ds-dashboard-tags').tagsManager('tags') if (!$('#ds-dashboard-create-form').data('bootstrapValidator').validate().isValid()) { return } let dashboard = new Dashboard({ title: title, category: category, summary: summary, description: description, tags: tags, definition: make('dashboard_definition') }) manager.create(dashboard, function(rsp) { window.location = rsp.data.view_href }) }) $(document).on('click', '#ds-new-dashboard-cancel', function(e) { window.history.back() })
Fix redirection bug on creating a new dashboard
Fix redirection bug on creating a new dashboard
TypeScript
apache-2.0
tessera-metrics/tessera,urbanairship/tessera,tessera-metrics/tessera,tessera-metrics/tessera,tessera-metrics/tessera,urbanairship/tessera,urbanairship/tessera,aalpern/tessera,urbanairship/tessera,urbanairship/tessera,aalpern/tessera,aalpern/tessera,aalpern/tessera,tessera-metrics/tessera,aalpern/tessera
--- +++ @@ -44,8 +44,8 @@ tags: tags, definition: make('dashboard_definition') }) - manager.create(dashboard, function(data) { - window.location = data.view_href + manager.create(dashboard, function(rsp) { + window.location = rsp.data.view_href }) })
22f20b579d9cfa94ea3e0d91a8499f09717c6535
Core/Worker.ts
Core/Worker.ts
module TameGame { /** * Form of a message passed in to a web worker */ export interface WorkerMessage { /** The action to take */ action: string; /** The data for this message */ data?: any; } /** Instruction to the webworker to start a game defined in a JavaScript file */ export var workerStartGame = "start-game"; export var workerRenderQueue = "render-queue"; /** Class that handles messages coming from a webworker */ export class WorkerMessageHandler { constructor(worker: Worker) { worker.onmessage = (evt) => { // Fetch the message data var msgData: WorkerMessage = evt.data; // Dispatch the message to the appropriate handler switch (msgData.action) { case workerRenderQueue: if (this.renderQueue) { this.renderQueue(msgData); } break; } }; } /** Action to take when the render queue message arrives */ renderQueue: (msg: WorkerMessage) => void; } }
module TameGame { /** * Form of a message passed in to a web worker */ export interface WorkerMessage { /** The action to take */ action: string; /** The data for this message */ data?: any; } /** Instruction to the webworker to start a game defined in a JavaScript file */ export var workerStartGame = "start-game"; /** Instruction to the main thread: render a frame */ export var workerRenderQueue = "render-queue"; /** Instruction to the main thread: load a sprite asset */ export var workerLoadSprite = "load-sprite"; /** Instruction to the main thread: load a sprite sheet asset */ export var workerLoadSpriteSheet = "load-sprite-sheet"; /** Class that handles messages coming from a webworker */ export class WorkerMessageHandler { constructor(worker: Worker) { worker.onmessage = (evt) => { // Fetch the message data var msgData: WorkerMessage = evt.data; // Dispatch the message to the appropriate handler switch (msgData.action) { case workerRenderQueue: if (this.renderQueue) { this.renderQueue(msgData); } break; case workerLoadSprite: if (this.loadSprite) { this.loadSprite(msgData); } break; case workerLoadSpriteSheet: if (this.loadSpriteSheet) { this.loadSpriteSheet(msgData); } break; } }; } renderQueue: (msg: WorkerMessage) => void; loadSprite: (msg: WorkerMessage) => void; loadSpriteSheet: (msg: WorkerMessage) => void; } }
Add messages for the asset loader
Add messages for the asset loader
TypeScript
apache-2.0
TameGame/Engine,TameGame/Engine,TameGame/Engine
--- +++ @@ -11,8 +11,16 @@ } /** Instruction to the webworker to start a game defined in a JavaScript file */ - export var workerStartGame = "start-game"; - export var workerRenderQueue = "render-queue"; + export var workerStartGame = "start-game"; + + /** Instruction to the main thread: render a frame */ + export var workerRenderQueue = "render-queue"; + + /** Instruction to the main thread: load a sprite asset */ + export var workerLoadSprite = "load-sprite"; + + /** Instruction to the main thread: load a sprite sheet asset */ + export var workerLoadSpriteSheet = "load-sprite-sheet"; /** Class that handles messages coming from a webworker */ export class WorkerMessageHandler { @@ -28,11 +36,24 @@ this.renderQueue(msgData); } break; + + case workerLoadSprite: + if (this.loadSprite) { + this.loadSprite(msgData); + } + break; + + case workerLoadSpriteSheet: + if (this.loadSpriteSheet) { + this.loadSpriteSheet(msgData); + } + break; } }; } - /** Action to take when the render queue message arrives */ - renderQueue: (msg: WorkerMessage) => void; + renderQueue: (msg: WorkerMessage) => void; + loadSprite: (msg: WorkerMessage) => void; + loadSpriteSheet: (msg: WorkerMessage) => void; } }
070597803262e2de1bfca30ec63e016d35e68f81
cypress/support/opportunities.ts
cypress/support/opportunities.ts
Cypress.Commands.add( 'createOpportunityDataset', function (name: string, filePath: string): Cypress.Chainable<string> { Cypress.log({ displayName: 'creating', message: 'opportunities' }) cy.findButton(/Upload a new dataset/i).click() cy.navComplete() cy.findByLabelText(/Opportunity dataset name/i).type(name) cy.findByLabelText(/Select opportunity dataset/).attachFile({ filePath, encoding: 'base64' }) cy.findButton(/Upload a new opportunity dataset/).click() cy.navComplete() // find the message showing this upload is complete cy.contains(new RegExp(name + ' \\(DONE\\)'), {timeout: 5000}) .parent() .parent() .as('notice') // check number of fields uploaded cy.get('@notice').contains(/Finished uploading 1 feature/i) // close the message cy.get('@notice').findByRole('button', {name: /Close/}).click() // now grab the ID cy.findByText(/Select\.\.\./) .click() .type(`${name} {enter}`) return cy .location('href') .should('match', /.*DatasetId=\w{24}$/) .then((href): string => href.match(/\w{24}$/)[0]) } )
Cypress.Commands.add( 'createOpportunityDataset', function (name: string, filePath: string): Cypress.Chainable<string> { Cypress.log({ displayName: 'creating', message: 'opportunities' }) cy.findButton(/Upload a new dataset/i).click() cy.navComplete() cy.findByLabelText(/Opportunity dataset name/i).type(name) cy.findByLabelText(/Select opportunity dataset/).attachFile({ filePath, encoding: 'base64' }) cy.findButton(/Upload a new opportunity dataset/).click() cy.navComplete() // find the message showing this upload is complete cy.contains(new RegExp(name + ' \\(DONE\\)'), {timeout: 5000}) .parent() .parent() .as('notice') // check number of fields uploaded cy.get('@notice').contains(/Finished uploading 1 layer/i) // close the message cy.get('@notice').findByRole('button', {name: /Close/}).click() // now grab the ID cy.findByText(/Select\.\.\./) .click() .type(`${name} {enter}`) return cy .location('href') .should('match', /.*DatasetId=\w{24}$/) .then((href): string => href.match(/\w{24}$/)[0]) } )
Fix cypress test (features β†’ layers)
Fix cypress test (features β†’ layers)
TypeScript
mit
conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui
--- +++ @@ -21,7 +21,7 @@ .parent() .as('notice') // check number of fields uploaded - cy.get('@notice').contains(/Finished uploading 1 feature/i) + cy.get('@notice').contains(/Finished uploading 1 layer/i) // close the message cy.get('@notice').findByRole('button', {name: /Close/}).click() // now grab the ID
8b7996905b391c3828303c48dfd1a365a78c41da
src/constants/settings.ts
src/constants/settings.ts
import { PersistedStateKey, ImmutablePersistedStateKey } from '../types'; export const PERSISTED_STATE_WHITELIST: PersistedStateKey[] = [ 'tab', 'account', 'hitBlocklist', 'hitDatabase', 'requesterBlocklist', 'sortingOption', 'searchOptions', 'topticonSettings', 'watchers', 'watcherTreeSettings', 'audioSettingsV1', 'dailyEarningsGoal', 'notificationSettings' ]; export const IMMUTABLE_PERSISTED_STATE_WHITELIST: ImmutablePersistedStateKey[] = [ 'hitBlocklist', 'requesterBlocklist', 'watchers', 'hitDatabase' ];
import { PersistedStateKey, ImmutablePersistedStateKey } from '../types'; export const PERSISTED_STATE_WHITELIST: PersistedStateKey[] = [ 'tab', 'account', 'hitBlocklist', 'hitDatabase', 'requesterBlocklist', 'sortingOption', 'searchOptions', 'topticonSettings', 'watchers', 'watcherFolders', 'audioSettingsV1', 'dailyEarningsGoal', 'notificationSettings' ]; export const IMMUTABLE_PERSISTED_STATE_WHITELIST: ImmutablePersistedStateKey[] = [ 'hitBlocklist', 'requesterBlocklist', 'watchers', 'watcherFolders', 'hitDatabase' ];
Fix crash when loading watcherFolders and watcherTreeSettings data from reduxPersist.
Fix crash when loading watcherFolders and watcherTreeSettings data from reduxPersist.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -10,7 +10,7 @@ 'searchOptions', 'topticonSettings', 'watchers', - 'watcherTreeSettings', + 'watcherFolders', 'audioSettingsV1', 'dailyEarningsGoal', 'notificationSettings' @@ -20,5 +20,6 @@ 'hitBlocklist', 'requesterBlocklist', 'watchers', + 'watcherFolders', 'hitDatabase' ];
ebaae380cc7814a0d48844c37995b67e68958658
src/dependument.ts
src/dependument.ts
/// <reference path="../typings/node/node.d.ts" /> import * as fs from 'fs'; export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options) { throw new Error("No options provided"); } if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } this.source = options.source; this.output = options.output; } readInfo(done: () => any) { fs.readFile(this.source, (err, data) => { }); } writeOutput() { fs.writeFile(this.output, 'dependument test writeOutput', (err) => { if (err) throw err; console.log(`Output written to ${this.output}`); }); } }
/// <reference path="../typings/node/node.d.ts" /> import * as fs from 'fs'; export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options) { throw new Error("No options provided"); } if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } this.source = options.source; this.output = options.output; } readInfo(done: () => any) { fs.readFile(this.source, (err, data) => { if (err) { throw err; } }); } writeOutput() { fs.writeFile(this.output, 'dependument test writeOutput', (err) => { if (err) throw err; console.log(`Output written to ${this.output}`); }); } }
Throw error if one exists
Throw error if one exists
TypeScript
unlicense
Jameskmonger/dependument,dependument/dependument,dependument/dependument,Jameskmonger/dependument
--- +++ @@ -25,7 +25,9 @@ readInfo(done: () => any) { fs.readFile(this.source, (err, data) => { - + if (err) { + throw err; + } }); }
970444fce1e567dd5d7ff4cf955ef93e65399954
uGo/src/services/schedule.service.ts
uGo/src/services/schedule.service.ts
export class ScheduleService { places: Array<any>; setSchedule(places) { this.places = places; } getSchedule() { return this.places; } find(item) { for(let i=0; i<this.places.length; i++) { if(this.places[i].id === item.id) return i; } } moveup(item) { let index = this.find(item); if(index - 1 >= 0) return ; let tmp = this.places[index - 1]; this.places[index - 1] = this.places[index]; this.places[index] = tmp; } movedown(item) { let index = this.find(item); if(index + 1 <= this.places.length - 1) return ; let tmp = this.places[index]; this.places[index] = this.places[index + 1]; this.places[index + 1] = tmp; } }
export class ScheduleService { places: Array<any>; setSchedule(places) { this.places = places; } getSchedule() { return this.places; } find(item) { for(let i=0; i<this.places.length; i++) { if(this.places[i].id === item.id) return i; } } moveup(item) { let index = this.find(item); if(index - 1 < 0) return ; let tmp = this.places[index - 1]; this.places[index - 1] = this.places[index]; this.places[index] = tmp; } movedown(item) { let index = this.find(item); if(index + 1 > this.places.length - 1) return ; let tmp = this.places[index]; this.places[index] = this.places[index + 1]; this.places[index + 1] = tmp; } }
Fix bug move up/move down
Fix bug move up/move down
TypeScript
mit
neungkl/u-go-application,neungkl/u-go-application,neungkl/u-go-application
--- +++ @@ -17,7 +17,7 @@ moveup(item) { let index = this.find(item); - if(index - 1 >= 0) return ; + if(index - 1 < 0) return ; let tmp = this.places[index - 1]; this.places[index - 1] = this.places[index]; this.places[index] = tmp; @@ -25,7 +25,7 @@ movedown(item) { let index = this.find(item); - if(index + 1 <= this.places.length - 1) return ; + if(index + 1 > this.places.length - 1) return ; let tmp = this.places[index]; this.places[index] = this.places[index + 1]; this.places[index + 1] = tmp;
12a53c456ab0a6443fa601a08046095d93d42535
new-client/src/index.tsx
new-client/src/index.tsx
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app'; ReactDOM.render(<App />, document.getElementById('root'));
Fix case in file name
Fix case in file name
TypeScript
apache-2.0
ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas
--- +++ @@ -1,5 +1,5 @@ import React from 'react'; import ReactDOM from 'react-dom'; -import App from './App'; +import App from './app'; ReactDOM.render(<App />, document.getElementById('root'));
693d7db847d0c650f113ac3be67771a54d65ff51
tests/intern-saucelabs.ts
tests/intern-saucelabs.ts
export * from './intern'; export const environments = [ { browserName: 'internet explorer', version: [ '10.0', '11.0' ], platform: 'Windows 7' }, { browserName: 'microsoftedge', platform: 'Windows 10' }, { browserName: 'firefox', platform: 'Windows 10' }, { browserName: 'chrome', platform: 'Windows 10' }, { browserName: 'safari', version: '9', platform: 'OS X 10.11' }, { browserName: 'android', deviceName: 'Google Nexus 7 HD Emulator' }, { browserName: 'iphone', version: '7.1' } ]; /* SauceLabs supports more max concurrency */ export const maxConcurrency = 4; export const tunnel = 'SauceLabsTunnel';
export * from './intern'; export const environments = [ { browserName: 'internet explorer', version: [ '10.0', '11.0' ], platform: 'Windows 7' }, { browserName: 'microsoftedge', platform: 'Windows 10' }, { browserName: 'firefox', platform: 'Windows 10' }, { browserName: 'chrome', platform: 'Windows 10' }, { browserName: 'safari', version: '9', platform: 'OS X 10.11' }, { browserName: 'android', deviceName: 'Google Nexus 7 HD Emulator' }, { browserName: 'iphone', version: '9.3' } ]; /* SauceLabs supports more max concurrency */ export const maxConcurrency = 4; export const tunnel = 'SauceLabsTunnel';
Update iOS version for tests
Update iOS version for tests
TypeScript
bsd-3-clause
mwistrand/routing,mwistrand/routing,mwistrand/routing
--- +++ @@ -7,7 +7,7 @@ { browserName: 'chrome', platform: 'Windows 10' }, { browserName: 'safari', version: '9', platform: 'OS X 10.11' }, { browserName: 'android', deviceName: 'Google Nexus 7 HD Emulator' }, - { browserName: 'iphone', version: '7.1' } + { browserName: 'iphone', version: '9.3' } ]; /* SauceLabs supports more max concurrency */
f666923679927850bedc9da2fe7d6658921c2539
src/services/firebase.service.ts
src/services/firebase.service.ts
import { Firebase } from '@ionic-native/firebase'; import { Injectable } from "@angular/core"; @Injectable() export class FirebaseService { constructor(private _firebase: Firebase) { console.log("FirebaseService constructor run"); this._firebase.getToken() .then(token => console.log(`The token is ${token}`)) // save the token server-side and use it to push notifications to this device .catch(error => console.error('Error getting token', error)); this._firebase.onTokenRefresh() .subscribe((token: string) => console.log(`Got a new token ${token}`)); this._firebase.hasPermission().then() .then(() => console.log('Have push permission!')) .catch(() => this._firebase.grantPermission() .then(() => console.log('Got push permission!')) .catch(() => console.warn('Did NOT get push permission!')) ); } }
import { Firebase } from '@ionic-native/firebase'; import { Injectable } from "@angular/core"; @Injectable() export class FirebaseService { constructor(private _firebase: Firebase) { console.log("FirebaseService constructor run"); this._firebase.getToken() .then(token => console.log(`The token is ${token}`)) // save the token server-side and use it to push notifications to this device .catch(error => console.error('Error getting token', error)); this._firebase.onTokenRefresh().subscribe( (token: string) => console.log(`Got a new token ${token}`), err => console.error(`Error getting token: `, err), ); this._firebase.hasPermission().then() .then(() => console.log('Have push permission!')) .catch(() => this._firebase.grantPermission() .then(() => console.log('Got push permission!')) .catch(() => console.warn('Did NOT get push permission!')) ); this._firebase.subscribe("all") .then(() => console.log('Subscribed to "all" topic')) .catch(err => console.error('Error subscribing to "all" topic: ', err)); this._firebase.onNotificationOpen().subscribe( notification => console.log('Got notification: ', JSON.stringify(notification)), err => console.error('Error getting notification: ', err) ); } }
Improve push-related logging, subscribe to 'all' topic on application startup.
Improve push-related logging, subscribe to 'all' topic on application startup.
TypeScript
apache-2.0
sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile
--- +++ @@ -9,8 +9,10 @@ .then(token => console.log(`The token is ${token}`)) // save the token server-side and use it to push notifications to this device .catch(error => console.error('Error getting token', error)); - this._firebase.onTokenRefresh() - .subscribe((token: string) => console.log(`Got a new token ${token}`)); + this._firebase.onTokenRefresh().subscribe( + (token: string) => console.log(`Got a new token ${token}`), + err => console.error(`Error getting token: `, err), + ); this._firebase.hasPermission().then() .then(() => console.log('Have push permission!')) @@ -18,5 +20,14 @@ .then(() => console.log('Got push permission!')) .catch(() => console.warn('Did NOT get push permission!')) ); + + this._firebase.subscribe("all") + .then(() => console.log('Subscribed to "all" topic')) + .catch(err => console.error('Error subscribing to "all" topic: ', err)); + + this._firebase.onNotificationOpen().subscribe( + notification => console.log('Got notification: ', JSON.stringify(notification)), + err => console.error('Error getting notification: ', err) + ); } }
23903a10137aca8f3d7acd9537a061e844b2d2e2
packages/apollo-server-plugin-operation-registry/src/common.ts
packages/apollo-server-plugin-operation-registry/src/common.ts
export const pluginName: string = require('../package.json').name; const envOverrideOperationManifest = 'APOLLO_OPERATION_MANIFEST_BASE_URL'; // Generate and cache our desired operation manifest URL. const urlOperationManifestBase: string = ((): string => { const desiredUrl = process.env[envOverrideOperationManifest] || 'https://storage.googleapis.com/engine-schema-reg-abernix-query-reg/dev/'; // Make sure it has NO trailing slash. return desiredUrl.replace(/\/$/, ''); })(); export function getOperationManifestUrl( hashedServiceId: string, schemaHash: string, ): string { return [urlOperationManifestBase, hashedServiceId, schemaHash].join('/'); }
export const pluginName: string = require('../package.json').name; const envOverrideOperationManifest = 'APOLLO_OPERATION_MANIFEST_BASE_URL'; // Generate and cache our desired operation manifest URL. const urlOperationManifestBase: string = ((): string => { const desiredUrl = process.env[envOverrideOperationManifest] || 'https://storage.googleapis.com/engine-op-manifest-storage-prod/'; // Make sure it has NO trailing slash. return desiredUrl.replace(/\/$/, ''); })(); export function getOperationManifestUrl( hashedServiceId: string, schemaHash: string, ): string { return [urlOperationManifestBase, hashedServiceId, schemaHash].join('/'); }
Switch to the `prod` operation manifest bucket.
Switch to the `prod` operation manifest bucket.
TypeScript
mit
apollostack/apollo-server
--- +++ @@ -6,7 +6,7 @@ const urlOperationManifestBase: string = ((): string => { const desiredUrl = process.env[envOverrideOperationManifest] || - 'https://storage.googleapis.com/engine-schema-reg-abernix-query-reg/dev/'; + 'https://storage.googleapis.com/engine-op-manifest-storage-prod/'; // Make sure it has NO trailing slash. return desiredUrl.replace(/\/$/, '');
5c925c2e23e2d826e02fd0fd343337bf0a176522
tests/cases/fourslash/getMatchingBraces.ts
tests/cases/fourslash/getMatchingBraces.ts
/// <reference path="fourslash.ts"/> //////curly braces ////module Foo [|{ //// class Bar [|{ //// private f() [|{ //// }|] //// //// private f2() [|{ //// if (true) [|{ }|] [|{ }|]; //// }|] //// }|] ////}|] //// //////parenthesis ////class FooBar { //// private f[|()|] { //// return [|([|(1 + 1)|])|]; //// } //// //// private f2[|()|] { //// if [|(true)|] { } //// } ////} //// //////square brackets ////class Baz { //// private f() { //// var a: any[|[]|] = [|[[|[1, 2]|], [|[3, 4]|], 5]|]; //// } ////} //// ////// angular brackets ////class TemplateTest [|<T1, T2 extends Array>|] { //// public foo(a, b) { //// return [|<any>|] a; //// } ////} test.ranges().forEach((range) => { verify.matchingBracePositionInCurrentFile(range.start, range.end - 1); verify.matchingBracePositionInCurrentFile(range.end - 1, range.start); });
/// <reference path="fourslash.ts"/> //////curly braces ////module Foo [|{ //// class Bar [|{ //// private f() [|{ //// }|] //// //// private f2() [|{ //// if (true) [|{ }|] [|{ }|]; //// }|] //// }|] ////}|] //// //////parenthesis ////class FooBar { //// private f[|()|] { //// return [|([|(1 + 1)|])|]; //// } //// //// private f2[|()|] { //// if [|(true)|] { } //// } ////} //// //////square brackets ////class Baz { //// private f() { //// var a: any[|[]|] = [|[[|[1, 2]|], [|[3, 4]|], 5]|]; //// } ////} //// ////// angular brackets ////class TemplateTest [|<T1, T2 extends Array>|] { //// public foo(a, b) { //// return [|<any>|] a; //// } ////} ////const x: Array[|<() => void>|] = []; test.ranges().forEach((range) => { verify.matchingBracePositionInCurrentFile(range.start, range.end - 1); verify.matchingBracePositionInCurrentFile(range.end - 1, range.start); });
Add additional test for brace matching
Add additional test for brace matching
TypeScript
apache-2.0
chuckjaz/TypeScript,Eyas/TypeScript,donaldpipowitch/TypeScript,kpreisser/TypeScript,microsoft/TypeScript,alexeagle/TypeScript,basarat/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,weswigham/TypeScript,Microsoft/TypeScript,chuckjaz/TypeScript,donaldpipowitch/TypeScript,chuckjaz/TypeScript,jwbay/TypeScript,DLehenbauer/TypeScript,synaptek/TypeScript,mihailik/TypeScript,SaschaNaz/TypeScript,erikmcc/TypeScript,RyanCavanaugh/TypeScript,jwbay/TypeScript,microsoft/TypeScript,nojvek/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,thr0w/Thr0wScript,microsoft/TypeScript,erikmcc/TypeScript,alexeagle/TypeScript,mihailik/TypeScript,Eyas/TypeScript,kpreisser/TypeScript,jwbay/TypeScript,nojvek/TypeScript,jeremyepling/TypeScript,basarat/TypeScript,minestarks/TypeScript,alexeagle/TypeScript,thr0w/Thr0wScript,synaptek/TypeScript,kpreisser/TypeScript,RyanCavanaugh/TypeScript,jeremyepling/TypeScript,SaschaNaz/TypeScript,erikmcc/TypeScript,basarat/TypeScript,DLehenbauer/TypeScript,Eyas/TypeScript,TukekeSoft/TypeScript,thr0w/Thr0wScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,jeremyepling/TypeScript,weswigham/TypeScript,DLehenbauer/TypeScript,mihailik/TypeScript,nojvek/TypeScript,synaptek/TypeScript,SaschaNaz/TypeScript,TukekeSoft/TypeScript,erikmcc/TypeScript,mihailik/TypeScript,weswigham/TypeScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,DLehenbauer/TypeScript,chuckjaz/TypeScript,Eyas/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,basarat/TypeScript,thr0w/Thr0wScript,jwbay/TypeScript,Microsoft/TypeScript
--- +++ @@ -36,6 +36,7 @@ //// return [|<any>|] a; //// } ////} +////const x: Array[|<() => void>|] = []; test.ranges().forEach((range) => { verify.matchingBracePositionInCurrentFile(range.start, range.end - 1);
27a1b639837fb2e05fc05ebe47a6173bfe56ea9d
annotator.module.ts
annotator.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MdButtonModule, MdCoreModule, } from '@angular/material'; import { AnnotatorComponent } from './annotator.component'; import { PlayerComponent } from './player/player.component'; import { AnnotationsComponent } from './annotations/annotations.component'; import { AnnotationPipe } from './annotations/annotation.pipe'; import { DurationPipe } from './player/duration.pipe'; import { DurationShortPipe } from './player/duration.pipe'; import { PlayerControlService } from './shared/player-control.service'; @NgModule({ declarations: [ AnnotatorComponent, PlayerComponent, AnnotationsComponent, AnnotationPipe, DurationPipe, DurationShortPipe, ], imports: [ BrowserModule, FormsModule, MdButtonModule, ], exports: [ AnnotatorComponent, ], providers: [ PlayerControlService, ], }) export class AnnotatorModule { }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material'; import { AnnotatorComponent } from './annotator.component'; import { PlayerComponent } from './player/player.component'; import { AnnotationsComponent } from './annotations/annotations.component'; import { AnnotationPipe } from './annotations/annotation.pipe'; import { DurationPipe } from './player/duration.pipe'; import { DurationShortPipe } from './player/duration.pipe'; import { PlayerControlService } from './shared/player-control.service'; @NgModule({ declarations: [ AnnotatorComponent, PlayerComponent, AnnotationsComponent, AnnotationPipe, DurationPipe, DurationShortPipe, ], imports: [ BrowserModule, FormsModule, MatButtonModule, ], exports: [ AnnotatorComponent, ], providers: [ PlayerControlService, ], }) export class AnnotatorModule { }
Support latest version of dependencies
Support latest version of dependencies
TypeScript
bsd-3-clause
Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber
--- +++ @@ -2,10 +2,7 @@ import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; -import { - MdButtonModule, - MdCoreModule, -} from '@angular/material'; +import { MatButtonModule } from '@angular/material'; import { AnnotatorComponent } from './annotator.component'; import { PlayerComponent } from './player/player.component'; @@ -29,7 +26,7 @@ imports: [ BrowserModule, FormsModule, - MdButtonModule, + MatButtonModule, ], exports: [ AnnotatorComponent,
e4313a121d8ec7a872d49abac7fe2edcf7728f39
packages/lesswrong/components/questions/PostsPageQuestionContent.tsx
packages/lesswrong/components/questions/PostsPageQuestionContent.tsx
import { Components, registerComponent } from '../../lib/vulcan-lib'; import React from 'react'; import { useCurrentUser } from '../common/withUser' import Users from '../../lib/collections/users/collection'; import withErrorBoundary from '../common/withErrorBoundary'; const MAX_ANSWERS_QUERIED = 100 const PostsPageQuestionContent = ({post, refetch}: { post: PostsWithNavigation|PostsWithNavigationAndRevision, refetch: any, }) => { const currentUser = useCurrentUser(); const { AnswersList, NewAnswerCommentQuestionForm, CantCommentExplanation, RelatedQuestionsList } = Components return ( <div> {(!currentUser || Users.isAllowedToComment(currentUser, post)) && <NewAnswerCommentQuestionForm post={post} refetch={refetch} />} {currentUser && !Users.isAllowedToComment(currentUser, post) && <CantCommentExplanation post={post}/> } <AnswersList terms={{view: "questionAnswers", postId: post._id, limit: MAX_ANSWERS_QUERIED}} post={post}/> <RelatedQuestionsList post={post} /> </div> ) }; const PostsPageQuestionContentComponent = registerComponent('PostsPageQuestionContent', PostsPageQuestionContent, { hocs: [withErrorBoundary] }); declare global { interface ComponentTypes { PostsPageQuestionContent: typeof PostsPageQuestionContentComponent } }
import { Components, registerComponent } from '../../lib/vulcan-lib'; import React from 'react'; import { useCurrentUser } from '../common/withUser' import Users from '../../lib/collections/users/collection'; import withErrorBoundary from '../common/withErrorBoundary'; const MAX_ANSWERS_QUERIED = 100 const PostsPageQuestionContent = ({post, refetch}: { post: PostsWithNavigation|PostsWithNavigationAndRevision, refetch: any, }) => { const currentUser = useCurrentUser(); const { AnswersList, NewAnswerCommentQuestionForm, CantCommentExplanation, RelatedQuestionsList } = Components return ( <div> {(!currentUser || Users.isAllowedToComment(currentUser, post)) && !post.draft && <NewAnswerCommentQuestionForm post={post} refetch={refetch} />} {currentUser && !Users.isAllowedToComment(currentUser, post) && <CantCommentExplanation post={post}/> } <AnswersList terms={{view: "questionAnswers", postId: post._id, limit: MAX_ANSWERS_QUERIED}} post={post}/> <RelatedQuestionsList post={post} /> </div> ) }; const PostsPageQuestionContentComponent = registerComponent('PostsPageQuestionContent', PostsPageQuestionContent, { hocs: [withErrorBoundary] }); declare global { interface ComponentTypes { PostsPageQuestionContent: typeof PostsPageQuestionContentComponent } }
Hide new comment/answer box on draft questions
Hide new comment/answer box on draft questions
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -14,7 +14,7 @@ const { AnswersList, NewAnswerCommentQuestionForm, CantCommentExplanation, RelatedQuestionsList } = Components return ( <div> - {(!currentUser || Users.isAllowedToComment(currentUser, post)) && <NewAnswerCommentQuestionForm post={post} refetch={refetch} />} + {(!currentUser || Users.isAllowedToComment(currentUser, post)) && !post.draft && <NewAnswerCommentQuestionForm post={post} refetch={refetch} />} {currentUser && !Users.isAllowedToComment(currentUser, post) && <CantCommentExplanation post={post}/> }
da74d3ac15ac83672f95792838bb1eeeb529aa32
src/component/feature/FeatureView2/FeatureMetrics/FeatureMetrics.tsx
src/component/feature/FeatureView2/FeatureMetrics/FeatureMetrics.tsx
import { useParams } from 'react-router'; import useFeature from '../../../../hooks/api/getters/useFeature/useFeature'; import MetricComponent from '../../view/metric-container'; import { useStyles } from './FeatureMetrics.styles'; import { IFeatureViewParams } from '../../../../interfaces/params'; import useUiConfig from '../../../../hooks/api/getters/useUiConfig/useUiConfig'; import ConditionallyRender from '../../../common/ConditionallyRender'; import EnvironmentMetricComponent from '../EnvironmentMetricComponent/EnvironmentMetricComponent'; const FeatureMetrics = () => { const styles = useStyles(); const { projectId, featureId } = useParams<IFeatureViewParams>(); const { feature } = useFeature(projectId, featureId); const { uiConfig } = useUiConfig(); const isNewMetricsEnabled = uiConfig.flags.V; return ( <div className={styles.container}> <ConditionallyRender condition={isNewMetricsEnabled} show={<EnvironmentMetricComponent />} elseShow={<MetricComponent featureToggle={feature} />} /> </div> ); }; export default FeatureMetrics;
import { useParams } from 'react-router'; import useFeature from '../../../../hooks/api/getters/useFeature/useFeature'; import MetricComponent from '../../view/metric-container'; import { useStyles } from './FeatureMetrics.styles'; import { IFeatureViewParams } from '../../../../interfaces/params'; import useUiConfig from '../../../../hooks/api/getters/useUiConfig/useUiConfig'; import ConditionallyRender from '../../../common/ConditionallyRender'; import EnvironmentMetricComponent from '../EnvironmentMetricComponent/EnvironmentMetricComponent'; const FeatureMetrics = () => { const styles = useStyles(); const { projectId, featureId } = useParams<IFeatureViewParams>(); const { feature } = useFeature(projectId, featureId); const { uiConfig } = useUiConfig(); const isEnterprise = uiConfig.flags.E; return ( <div className={styles.container}> <ConditionallyRender condition={isEnterprise} show={<EnvironmentMetricComponent />} elseShow={<MetricComponent featureToggle={feature} />} /> </div> ); }; export default FeatureMetrics;
Revert "Use V flag for new metrics component"
Revert "Use V flag for new metrics component" This reverts commit e1b67a49111cdb67c6b4a6b2ea15c4d3736e6dbb.
TypeScript
apache-2.0
Unleash/unleash-frontend,Unleash/unleash-frontend,Unleash/unleash-frontend,Unleash/unleash-frontend
--- +++ @@ -12,11 +12,11 @@ const { projectId, featureId } = useParams<IFeatureViewParams>(); const { feature } = useFeature(projectId, featureId); const { uiConfig } = useUiConfig(); - const isNewMetricsEnabled = uiConfig.flags.V; + const isEnterprise = uiConfig.flags.E; return ( <div className={styles.container}> - <ConditionallyRender condition={isNewMetricsEnabled} + <ConditionallyRender condition={isEnterprise} show={<EnvironmentMetricComponent />} elseShow={<MetricComponent featureToggle={feature} />} />
98105cc7e1ea55bdc5ee98178ab0f1970310e3eb
src/v2/pages/about/PricingPage/components/PricingQuestions/index.tsx
src/v2/pages/about/PricingPage/components/PricingQuestions/index.tsx
import React from 'react' import { useQuery } from '@apollo/client' import { PricingQuestionsQuery } from './contentfulQueries/pricingQuestions' import { PricingQuestions as PricingQuestionsType } from '__generated__/contentful/PricingQuestions' import { P } from 'v2/pages/home/components/Common' import Box from 'v2/components/UI/Box' import Text from 'v2/components/UI/Text' export const PricingQuestions: React.FC = () => { const { data } = useQuery<PricingQuestionsType>(PricingQuestionsQuery, { context: { clientName: 'contentful' }, ssr: false, }) if (!data) return null return ( <> {data.pricingQuestionsCollection.items.map((q, index) => { return ( <Box key={index} mb={8}> <Text f={4} color="gray.block" pb={5}> {q.question} </Text> <P>{q.answer}</P> </Box> ) })} </> ) }
import React from 'react' import { useQuery } from '@apollo/client' import { PricingQuestionsQuery } from './contentfulQueries/pricingQuestions' import { PricingQuestions as PricingQuestionsType } from '__generated__/contentful/PricingQuestions' import Box from 'v2/components/UI/Box' import Text from 'v2/components/UI/Text' import { FONT_SIZES } from 'v2/styles/text' export const PricingQuestions: React.FC = () => { const { data } = useQuery<PricingQuestionsType>(PricingQuestionsQuery, { context: { clientName: 'contentful' }, ssr: false, }) if (!data) return null return ( <> {data.pricingQuestionsCollection.items.map((q, index) => { return ( <Box key={index} mb={8}> <Text f={FONT_SIZES.home.lg} color="gray.block" pb={5}> {q.question} </Text> <Text f={FONT_SIZES.home.md} color="gray.block" pb={5}> {q.answer} </Text> </Box> ) })} </> ) }
Fix sizing on pricing questions
Fix sizing on pricing questions
TypeScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -3,10 +3,10 @@ import { PricingQuestionsQuery } from './contentfulQueries/pricingQuestions' import { PricingQuestions as PricingQuestionsType } from '__generated__/contentful/PricingQuestions' -import { P } from 'v2/pages/home/components/Common' import Box from 'v2/components/UI/Box' import Text from 'v2/components/UI/Text' +import { FONT_SIZES } from 'v2/styles/text' export const PricingQuestions: React.FC = () => { const { data } = useQuery<PricingQuestionsType>(PricingQuestionsQuery, { @@ -21,10 +21,12 @@ {data.pricingQuestionsCollection.items.map((q, index) => { return ( <Box key={index} mb={8}> - <Text f={4} color="gray.block" pb={5}> + <Text f={FONT_SIZES.home.lg} color="gray.block" pb={5}> {q.question} </Text> - <P>{q.answer}</P> + <Text f={FONT_SIZES.home.md} color="gray.block" pb={5}> + {q.answer} + </Text> </Box> ) })}
2d926ba2e48b6478a1057298109b895108f9389b
src/app/app.component.ts
src/app/app.component.ts
import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { BeerService } from '../providers/beer-service'; import { TabsPage } from '../pages/tabs/tabs'; @Component({ templateUrl: 'app.html', providers: [BeerService] }) export class MyApp { rootPage = TabsPage; constructor(platform: Platform) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); Splashscreen.hide(); }); } }
import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { BeerService } from '../providers/beer-service'; import { AuthService } from '../providers/auth-service'; import { LoginPage } from '../pages/login/login'; @Component({ templateUrl: 'app.html', providers: [BeerService, AuthService] }) export class MyApp { rootPage = LoginPage; constructor(platform: Platform) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); Splashscreen.hide(); }); } }
Change rootPage to the LoginPage
Change rootPage to the LoginPage
TypeScript
mit
j-West/Capstone,j-West/Capstone,j-West/Capstone
--- +++ @@ -2,16 +2,18 @@ import { Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { BeerService } from '../providers/beer-service'; +import { AuthService } from '../providers/auth-service'; -import { TabsPage } from '../pages/tabs/tabs'; + +import { LoginPage } from '../pages/login/login'; @Component({ templateUrl: 'app.html', - providers: [BeerService] + providers: [BeerService, AuthService] }) export class MyApp { - rootPage = TabsPage; + rootPage = LoginPage; constructor(platform: Platform) { platform.ready().then(() => { @@ -21,4 +23,7 @@ Splashscreen.hide(); }); } + + + }
0ca34675c92e9b7e641baaab90e74cdfb71f7fc8
src/app/routes/index.tsx
src/app/routes/index.tsx
import * as React from 'react' import { IndexRoute, Route } from 'react-router' import { IRouteConfig } from '~/models/route-config' import { App } from '~/components/App' import { Experiments } from './Experiments' import { Styleguide } from './Styleguide' const config: IRouteConfig[] = [ { path: '/', title: 'Experiments', component: Experiments }, { path: 'style', title: 'Styleguide', component: Styleguide }, ] const buildRoute = (route: IRouteConfig, i: number) => ( (route.path === '/') ? <IndexRoute component={route.component} key={i} /> : <Route path={route.path} component={route.component} key={i} /> ) export default ( <Route path='/' component={App(config)}> {config.map(buildRoute)} </Route> )
import * as React from 'react' import { IndexRoute, Route } from 'react-router' import { IRouteConfig } from '~/models/route-config' import { App } from '~/components/App' import { Experiments } from './Experiments' import { Styleguide } from './Styleguide' const config: IRouteConfig[] = [ { path: 'experiment', title: 'Experiments', component: Experiments }, { path: 'style', title: 'Styleguide', component: Styleguide }, ] const buildRoute = (route: IRouteConfig, i: number) => ( (route.path === '/') ? <IndexRoute component={route.component} key={i} /> : <Route path={route.path} component={route.component} key={i} /> ) export default ( <Route path='/' component={App(config)}> {config.map(buildRoute)} </Route> )
Move Experiments to /experiment route
Move Experiments to /experiment route
TypeScript
mit
devonzuegel/aldine,devonzuegel/aldine,devonzuegel/aldine,devonzuegel/aldine
--- +++ @@ -6,8 +6,8 @@ import { Styleguide } from './Styleguide' const config: IRouteConfig[] = [ - { path: '/', title: 'Experiments', component: Experiments }, - { path: 'style', title: 'Styleguide', component: Styleguide }, + { path: 'experiment', title: 'Experiments', component: Experiments }, + { path: 'style', title: 'Styleguide', component: Styleguide }, ] const buildRoute = (route: IRouteConfig, i: number) => (
34947b836fe1cfc5cfba9dc58392c913ec643eb1
src/components/Login.tsx
src/components/Login.tsx
import * as AWS from 'aws-sdk'; import * as React from 'react'; import GoogleLogin, {GoogleLoginResponse} from 'react-google-login'; interface LoginProps { onSuccessfulLogin: () => void } export default class extends React.Component<LoginProps, {}> { onSuccessfulGoogleLogin = (res: GoogleLoginResponse) => { AWS.config.credentials = new AWS.WebIdentityCredentials({ RoleArn: 'arn:aws:iam::762636538502:role/number-switcher-4000', RoleSessionName: 'number-switcher-4000-web', WebIdentityToken: res.getAuthResponse().id_token }); this.props.onSuccessfulLogin(); } onFailedGoogleLogin = (err: any) => { console.error(err); } render() { return ( <GoogleLogin clientId="721076834592-7iidl9sk4jfc09npct0c4ip8cnmtuknm.apps.googleusercontent.com" buttonText="Login" onSuccess={this.onSuccessfulGoogleLogin} onFailure={this.onFailedGoogleLogin} /> ); } }
import * as AWS from 'aws-sdk'; import * as React from 'react'; import GoogleLogin, {GoogleLoginResponse} from 'react-google-login'; interface LoginProps { onSuccessfulLogin: () => void } interface LoginState { errorMessage: string | null } export default class extends React.Component<LoginProps, LoginState> { constructor() { super(); this.state = { errorMessage: null }; } onSuccessfulGoogleLogin = async (res: GoogleLoginResponse) => { AWS.config.credentials = new AWS.WebIdentityCredentials({ RoleArn: 'arn:aws:iam::762636538502:role/number-switcher-4000', RoleSessionName: 'number-switcher-4000-web', WebIdentityToken: res.getAuthResponse().id_token }); const sts = new AWS.STS(); try { await sts.getCallerIdentity().promise(); this.props.onSuccessfulLogin(); } catch (err) { this.setState({ errorMessage: 'Account not permitted access' }); } } onFailedGoogleLogin = (err: any) => { this.setState({ errorMessage: err }); } render() { return ( <div> <GoogleLogin clientId="721076834592-7iidl9sk4jfc09npct0c4ip8cnmtuknm.apps.googleusercontent.com" buttonText="Login" onSuccess={this.onSuccessfulGoogleLogin} onFailure={this.onFailedGoogleLogin} /> <p style={{color: 'red'}}>{this.state.errorMessage}</p> </div> ); } }
Add error messages when failing to login
Add error messages when failing to login
TypeScript
mit
jeffcharles/number-switcher-4000,jeffcharles/number-switcher-4000,jeffcharles/number-switcher-4000
--- +++ @@ -6,27 +6,45 @@ onSuccessfulLogin: () => void } -export default class extends React.Component<LoginProps, {}> { - onSuccessfulGoogleLogin = (res: GoogleLoginResponse) => { +interface LoginState { + errorMessage: string | null +} + +export default class extends React.Component<LoginProps, LoginState> { + constructor() { + super(); + this.state = { errorMessage: null }; + } + + onSuccessfulGoogleLogin = async (res: GoogleLoginResponse) => { AWS.config.credentials = new AWS.WebIdentityCredentials({ RoleArn: 'arn:aws:iam::762636538502:role/number-switcher-4000', RoleSessionName: 'number-switcher-4000-web', WebIdentityToken: res.getAuthResponse().id_token }); - this.props.onSuccessfulLogin(); + const sts = new AWS.STS(); + try { + await sts.getCallerIdentity().promise(); + this.props.onSuccessfulLogin(); + } catch (err) { + this.setState({ errorMessage: 'Account not permitted access' }); + } } onFailedGoogleLogin = (err: any) => { - console.error(err); + this.setState({ errorMessage: err }); } render() { return ( - <GoogleLogin - clientId="721076834592-7iidl9sk4jfc09npct0c4ip8cnmtuknm.apps.googleusercontent.com" - buttonText="Login" - onSuccess={this.onSuccessfulGoogleLogin} - onFailure={this.onFailedGoogleLogin} /> + <div> + <GoogleLogin + clientId="721076834592-7iidl9sk4jfc09npct0c4ip8cnmtuknm.apps.googleusercontent.com" + buttonText="Login" + onSuccess={this.onSuccessfulGoogleLogin} + onFailure={this.onFailedGoogleLogin} /> + <p style={{color: 'red'}}>{this.state.errorMessage}</p> + </div> ); } }
f8186b3c992327261d5d42e0277f788cc7afe7b6
server/lib/network/redirect-to-canonical.ts
server/lib/network/redirect-to-canonical.ts
import Koa from 'koa' /** Redirects any requests coming to a non-canonical host to the canonical one. */ export function redirectToCanonical(canonicalHost: string) { const asUrl = new URL(canonicalHost) const toCompare = asUrl.host.toLowerCase() return async function redirectToCanonicalMiddleware(ctx: Koa.Context, next: Koa.Next) { const host = ctx.get('Host') ?? '' if (host.toLowerCase() !== toCompare) { ctx.redirect(`${canonicalHost}${ctx.url}`) ctx.status = 308 } else { await next() } } }
import Koa from 'koa' /** Redirects any requests coming to a non-canonical host to the canonical one. */ export function redirectToCanonical(canonicalHost: string) { const asUrl = new URL(canonicalHost) const toCompare = asUrl.host.toLowerCase() return async function redirectToCanonicalMiddleware(ctx: Koa.Context, next: Koa.Next) { const host = ctx.request.host if (host.toLowerCase() !== toCompare) { ctx.redirect(`${canonicalHost}${ctx.url}`) ctx.status = 308 } else { await next() } } }
Use a better way of getting the host so that it deals with proxied requests properly.
Use a better way of getting the host so that it deals with proxied requests properly.
TypeScript
mit
ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery
--- +++ @@ -6,7 +6,7 @@ const toCompare = asUrl.host.toLowerCase() return async function redirectToCanonicalMiddleware(ctx: Koa.Context, next: Koa.Next) { - const host = ctx.get('Host') ?? '' + const host = ctx.request.host if (host.toLowerCase() !== toCompare) { ctx.redirect(`${canonicalHost}${ctx.url}`) ctx.status = 308
f20d1d9810810fdcab385690722acd2de35baf20
projects/igniteui-angular/src/lib/grids/common/column.interface.ts
projects/igniteui-angular/src/lib/grids/common/column.interface.ts
import { TemplateRef } from '@angular/core'; import { DataType } from '../../data-operations/data-util'; import { ISortingStrategy } from '../../data-operations/sorting-strategy'; import { FilteringExpressionsTree } from '../../data-operations/filtering-expressions-tree'; /** * @hidden * @internal */ export interface ColumnType { field: string; index: number; dataType: DataType; inlineEditorTemplate: TemplateRef<any>; visibleIndex: number; editable: boolean; resizable: boolean; searchable: boolean; columnGroup: boolean; movable: boolean; groupable: boolean; sortable: boolean; filterable: boolean; hidden: boolean; disablePinning: boolean; sortStrategy: ISortingStrategy; filteringIgnoreCase: boolean; filteringExpressionsTree: FilteringExpressionsTree; hasSummary: boolean; summaries: any; pinned: boolean; selected: boolean; selectable: boolean; level: number; rowStart: number; rowEnd: number; colStart: number; colEnd: number; gridRowSpan: number; gridColumnSpan: number; columnLayoutChild: boolean; width: string; topLevelParent?: ColumnType; parent?: ColumnType; hasLastPinnedChildColumn: boolean; getGridTemplate(isRow: boolean, isIE: boolean): string; }
import { TemplateRef } from '@angular/core'; import { DataType } from '../../data-operations/data-util'; import { ISortingStrategy } from '../../data-operations/sorting-strategy'; import { FilteringExpressionsTree } from '../../data-operations/filtering-expressions-tree'; /** * @hidden * @internal */ export interface ColumnType { field: string; header?: string; index: number; dataType: DataType; inlineEditorTemplate: TemplateRef<any>; visibleIndex: number; editable: boolean; resizable: boolean; searchable: boolean; columnGroup: boolean; movable: boolean; groupable: boolean; sortable: boolean; filterable: boolean; hidden: boolean; disablePinning: boolean; sortStrategy: ISortingStrategy; filteringIgnoreCase: boolean; filteringExpressionsTree: FilteringExpressionsTree; hasSummary: boolean; summaries: any; pinned: boolean; selected: boolean; selectable: boolean; level: number; rowStart: number; rowEnd: number; colStart: number; colEnd: number; gridRowSpan: number; gridColumnSpan: number; columnLayoutChild: boolean; width: string; topLevelParent?: ColumnType; parent?: ColumnType; hasLastPinnedChildColumn: boolean; getGridTemplate(isRow: boolean, isIE: boolean): string; }
Include missing prop from ColumnType.
chore(*): Include missing prop from ColumnType.
TypeScript
mit
Infragistics/zero-blocks,Infragistics/zero-blocks,Infragistics/zero-blocks
--- +++ @@ -9,6 +9,7 @@ */ export interface ColumnType { field: string; + header?: string; index: number; dataType: DataType; inlineEditorTemplate: TemplateRef<any>;
5e989e873a5f547e45b2cc55cea51f487e730697
src/app/homepage/slides/slides.component.ts
src/app/homepage/slides/slides.component.ts
import {Component, OnInit, OnDestroy} from '@angular/core'; declare var $: any; @Component({ selector: 'app-slides', templateUrl: './slides.component.html', styleUrls: ['./slides.component.sass'] }) export class SlidesComponent implements OnInit, OnDestroy { constructor() { } ngOnInit() { $('#fullpage').fullpage({ anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage'], navigation: true, navigationPosition: 'left', showActiveTooltip: true, slidesNavigation: true, slidesNavPosition: 'bottom', controlArrows: false, onLeave: function (index, nextIndex, direction) { if (index == 1) { $('#floating-nav').fadeIn("fast"); } else if (nextIndex == 1) { $('#floating-nav').fadeOut("fast"); } } }); $(".typed-text").typed({ strings: ["text", "snippets", "code", "images"], typeSpeed: 100, loop: true }); $('.slider').slider({full_width: true}); $('.carousel.carousel-slider').carousel({full_width: true}); $(".button-collapse").sideNav(); } ngOnDestroy() { $.fn.fullpage.destroy('all'); } }
import {Component, OnInit, OnDestroy} from '@angular/core'; declare var $: any; @Component({ selector: 'app-slides', templateUrl: './slides.component.html', styleUrls: ['./slides.component.sass'] }) export class SlidesComponent implements OnInit, OnDestroy { constructor() { } ngOnInit() { $('#fullpage').fullpage({ anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage'], navigation: true, navigationPosition: 'left', showActiveTooltip: true, slidesNavigation: true, slidesNavPosition: 'bottom', controlArrows: false, onLeave: function (index, nextIndex, direction) { if (index == 1) { $('#floating-nav').fadeIn("fast"); } else if (nextIndex == 1) { $('#floating-nav').fadeOut("fast"); } } }); $(".typed-text").typed({ strings: ["text", "snippets", "code", "images"], typeSpeed: 100, loop: true }); $('.carousel.carousel-slider').carousel({full_width: true}); var interval = window.setInterval(function () { $('.carousel').carousel('next') }, 3000); $('#carousel-section').click( function () { clearInterval(interval); }); $('.slider').slider({full_width: true}); $(".button-collapse").sideNav(); } ngOnDestroy() { $.fn.fullpage.destroy('all'); } }
Add autoslide section with clear interval onclick
Add autoslide section with clear interval onclick
TypeScript
apache-2.0
SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend
--- +++ @@ -36,10 +36,17 @@ loop: true }); + $('.carousel.carousel-slider').carousel({full_width: true}); + var interval = window.setInterval(function () { + $('.carousel').carousel('next') + }, 3000); + + $('#carousel-section').click( function () { + clearInterval(interval); + }); + $('.slider').slider({full_width: true}); - $('.carousel.carousel-slider').carousel({full_width: true}); $(".button-collapse").sideNav(); - }
376913f2226407351f844168e9b0282aba7a9267
src/translate-message-format-compiler.ts
src/translate-message-format-compiler.ts
import { TranslateCompiler } from '@ngx-translate/core'; import * as MessageFormatStatic from 'messageformat'; /** * This compiler expects ICU syntax and compiles the expressions with messageformat.js */ export class TranslateMessageFormatCompiler extends TranslateCompiler { private messageFormat: MessageFormat; constructor() { super(); this.messageFormat = new MessageFormatStatic(); } public compile(value: string, lang: string): string | Function { return this.messageFormat.compile(value, lang); } public compileTranslations(translations: any, lang: string): any { return this.messageFormat.compile(translations, lang); } }
import { TranslateCompiler } from '@ngx-translate/core'; import * as MessageFormatStatic from 'messageformat'; /** * This compiler expects ICU syntax and compiles the expressions with messageformat.js */ export class TranslateMessageFormatCompiler extends TranslateCompiler { private messageFormat: MessageFormat; constructor() { super(); this.messageFormat = new MessageFormatStatic(); } public compile(value: string, lang: string): Function { return this.messageFormat.compile(value, lang); } public compileTranslations(translations: any, lang: string): any { return this.messageFormat.compile(translations, lang); } }
Improve signature of compile method
Improve signature of compile method We always return a function, and `Function` is still compatible with `string | Function` of the superclass
TypeScript
mit
lephyrus/ngx-translate-messageformat-compiler,lephyrus/ngx-translate-messageformat-compiler
--- +++ @@ -12,7 +12,7 @@ this.messageFormat = new MessageFormatStatic(); } - public compile(value: string, lang: string): string | Function { + public compile(value: string, lang: string): Function { return this.messageFormat.compile(value, lang); }
df57bff7e147d12d3ded17e40c873e21a7cbddb5
packages/skin-database/api/graphql/defaultQuery.ts
packages/skin-database/api/graphql/defaultQuery.ts
const DEFAULT_QUERY = `# Winamp Skins GraphQL API # # https://skins.webamp.org # # This is a GraphQL API for the Winamp Skin Museum's database. # It's mostly intended for exploring the data set. Please feel # free to have a look around and see what you can find! # # The GraphiQL environment has many helpful features to help # you discover what fields exist and what they mean, so be bold! # # If you have any questions or feedback, please get in touch: # - Twitter: @captbaritone # - Email: [email protected] # - Discord: https://webamp.org/chat # An example query to get you started... query MyQuery { # Search for a skin made by LuigiHann search_skins(query: "luigihann zelda", first: 1) { # The filename of the skin filename download_url museum_url # Try hovering the returned url # for a preview of the skin --> screenshot_url # All the tweets that shared this skin tweets { likes retweets url } # Information about the files contained within the skin archive_files { filename # For image files, try hovering the # returned url ---> url # Date the file was created according to the zip file date } } }`; export default DEFAULT_QUERY;
const DEFAULT_QUERY = `# Winamp Skins GraphQL API # # https://skins.webamp.org # # This is a GraphQL API for the Winamp Skin Museum's database. # It's mostly intended for exploring the data set. Please feel # free to have a look around and see what you can find! # # The GraphiQL environment has many helpful features to help # you discover what fields exist and what they mean, so be bold! # # If you have any questions or feedback, please get in touch: # - Twitter: @captbaritone # - Email: [email protected] # - Discord: https://webamp.org/chat # An example query to get you started... query MyQuery { # Search for a skin made by LuigiHann search_skins(query: "luigihann zelda", first: 1) { # The filename of the skin filename download_url museum_url # Try hovering the returned url # for a preview of the skin --> screenshot_url # All the tweets that shared this skin tweets { likes retweets url } # Information about the files contained within the skin archive_files { filename # For image files, try hovering the # returned url ---> url # Date the file was created according to the zip file date } } }`; export default DEFAULT_QUERY;
Fix formatting in default query
Fix formatting in default query
TypeScript
mit
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
--- +++ @@ -43,7 +43,7 @@ # returned url ---> url # Date the file was created according to the zip file - date + date } } }`;
619e6d38634253ad6e29077729f68296678c3549
source/CroquetAustralia.Website/app/tournaments/scripts/TournamentPlayer.ts
source/CroquetAustralia.Website/app/tournaments/scripts/TournamentPlayer.ts
'use strict'; module App { export class TournamentPlayer { firstName: string; lastName: string; email: string; phone: string; handicap: number; under21: boolean; fullTimeStudentUnder25: boolean; dateOfBirth: /* nullable */ number; nonResident: /* nullable */ boolean; constructor() { this.dateOfBirth = null; this.nonResident = null; } } }
'use strict'; module App { export class TournamentPlayer { firstName: string; lastName: string; email: string; phone: string; handicap: number; under21: boolean; fullTimeStudentUnder25: boolean; dateOfBirth: /* nullable */ Date; nonResident: /* nullable */ boolean; constructor() { this.dateOfBirth = null; this.nonResident = null; } } }
Change dateOfBirth type to date
Change dateOfBirth type to date
TypeScript
mit
croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application
--- +++ @@ -9,7 +9,7 @@ handicap: number; under21: boolean; fullTimeStudentUnder25: boolean; - dateOfBirth: /* nullable */ number; + dateOfBirth: /* nullable */ Date; nonResident: /* nullable */ boolean; constructor() {
1b0400af8c53683f57b8bb5a727ac47fff69408e
demo/app/app.ts
demo/app/app.ts
/* In NativeScript, the app.ts file is the entry point to your application. You can use this file to perform app-level initialization, but the primary purpose of the file is to pass control to the app’s first module. */ import * as app from "application"; import * as frescoModule from "nativescript-fresco"; if (app.android) { app.on("launch", () => { frescoModule.initialize({ isDownsampleEnabled: true }); }); } app.run({ moduleName: "app-root" }); /* Do not place any code after the application has been started as it will not be executed on iOS. */
import * as app from "application"; import * as frescoModule from "nativescript-fresco"; if (app.android) { app.on(app.launchEvent, () => { frescoModule.initialize({ isDownsampleEnabled: true }); }); app.on(app.exitEvent, (args) => { if (args.android) { console.log("dev-log: Manually shutting down Fresco"); frescoModule.shutDown(); } }); } app.run({ moduleName: "app-root" });
Add "exit" event handler and call shut down for the nativescript-fresco plugin
chore: Add "exit" event handler and call shut down for the nativescript-fresco plugin
TypeScript
apache-2.0
NativeScript/nativescript-fresco,NativeScript/nativescript-fresco,NativeScript/nativescript-fresco
--- +++ @@ -1,22 +1,18 @@ -/* -In NativeScript, the app.ts file is the entry point to your application. -You can use this file to perform app-level initialization, but the primary -purpose of the file is to pass control to the app’s first module. -*/ - import * as app from "application"; import * as frescoModule from "nativescript-fresco"; if (app.android) { - app.on("launch", () => { + app.on(app.launchEvent, () => { frescoModule.initialize({ isDownsampleEnabled: true }); + }); + + app.on(app.exitEvent, (args) => { + if (args.android) { + console.log("dev-log: Manually shutting down Fresco"); + frescoModule.shutDown(); + } }); } app.run({ moduleName: "app-root" }); - -/* -Do not place any code after the application has been started as it will not -be executed on iOS. -*/
5e300fce99e6b5130564435edeb2bb846b857270
src/app/app-routing.module.ts
src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; import { RmsPage } from './rms'; import { SettingsPage, ColorsPage, DriversPage, AboutPage, LoggingPage , LicensesPage, ConnectionPage, NotificationsPage } from './settings'; import { TuningPage } from './tuning'; const routes: Routes = [ { path: '', redirectTo: 'rms/practice', pathMatch: 'full' }, { path: 'rms/:mode', component: RmsPage }, { path: 'settings', component: SettingsPage }, { path: 'colors', component: ColorsPage }, { path: 'drivers', component: DriversPage }, { path: 'about', component: AboutPage }, { path: 'logging', component: LoggingPage }, { path: 'licenses', component: LicensesPage }, { path: 'connection', component: ConnectionPage }, { path: 'notifications', component: NotificationsPage }, { path: 'tuning', component: TuningPage }, { path: '**', component: RmsPage } ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload', preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule {}
import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; import { RmsPage } from './rms'; import { SettingsPage, ColorsPage, DriversPage, AboutPage, LoggingPage , LicensesPage, ConnectionPage, NotificationsPage } from './settings'; import { TuningPage } from './tuning'; const routes: Routes = [ { path: '', redirectTo: 'rms/practice', pathMatch: 'full' }, { path: 'rms/:mode', component: RmsPage }, { path: 'settings', component: SettingsPage }, { path: 'colors', component: ColorsPage }, { path: 'drivers', component: DriversPage }, { path: 'about', component: AboutPage }, { path: 'logging', component: LoggingPage }, { path: 'licenses', component: LicensesPage }, { path: 'connection', component: ConnectionPage }, { path: 'notifications', component: NotificationsPage }, { path: 'tuning', component: TuningPage }, { path: '**', component: RmsPage } ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, useHash: true }) ], exports: [RouterModule] }) export class AppRoutingModule {}
Use hash location strategy (for now).
Use hash location strategy (for now).
TypeScript
apache-2.0
tkem/openlap,tkem/openlap,tkem/openlap
--- +++ @@ -60,8 +60,8 @@ @NgModule({ imports: [ RouterModule.forRoot(routes, { - onSameUrlNavigation: 'reload', - preloadingStrategy: PreloadAllModules + preloadingStrategy: PreloadAllModules, + useHash: true }) ], exports: [RouterModule]
92c3ff56ad41e66108e0185864b7ec9f5e79146d
app/src/ui/welcome/sign-in-enterprise.tsx
app/src/ui/welcome/sign-in-enterprise.tsx
import * as React from 'react' import { WelcomeStep } from './welcome' import { Button } from '../lib/button' import { SignIn } from '../lib/sign-in' import { Dispatcher } from '../dispatcher' import { SignInState } from '../../lib/stores' interface ISignInEnterpriseProps { readonly dispatcher: Dispatcher readonly advance: (step: WelcomeStep) => void readonly signInState: SignInState | null } /** The Welcome flow step to login to an Enterprise instance. */ export class SignInEnterprise extends React.Component< ISignInEnterpriseProps, {} > { public render() { const state = this.props.signInState if (!state) { return null } return ( <div id="sign-in-enterprise"> <h1 className="welcome-title"> Sign in to your GitHub Enterprise server </h1> <SignIn signInState={state} dispatcher={this.props.dispatcher}> <Button onClick={this.cancel}>Cancel</Button> </SignIn> </div> ) } private cancel = () => { this.props.advance(WelcomeStep.Start) } }
import * as React from 'react' import { WelcomeStep } from './welcome' import { Button } from '../lib/button' import { SignIn } from '../lib/sign-in' import { Dispatcher } from '../dispatcher' import { SignInState } from '../../lib/stores' interface ISignInEnterpriseProps { readonly dispatcher: Dispatcher readonly advance: (step: WelcomeStep) => void readonly signInState: SignInState | null } /** The Welcome flow step to login to an Enterprise instance. */ export class SignInEnterprise extends React.Component< ISignInEnterpriseProps, {} > { public render() { const state = this.props.signInState if (!state) { return null } return ( <div id="sign-in-enterprise"> <h1 className="welcome-title"> Sign in to your GitHub Enterprise Server </h1> <SignIn signInState={state} dispatcher={this.props.dispatcher}> <Button onClick={this.cancel}>Cancel</Button> </SignIn> </div> ) } private cancel = () => { this.props.advance(WelcomeStep.Start) } }
Update Enterprise sign-in UI for 'Enterprise Server'
Update Enterprise sign-in UI for 'Enterprise Server'
TypeScript
mit
desktop/desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,kactus-io/kactus,say25/desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,kactus-io/kactus,kactus-io/kactus
--- +++ @@ -26,7 +26,7 @@ return ( <div id="sign-in-enterprise"> <h1 className="welcome-title"> - Sign in to your GitHub Enterprise server + Sign in to your GitHub Enterprise Server </h1> <SignIn signInState={state} dispatcher={this.props.dispatcher}>
deb3d110a5ada96712889e0b93c7b7eb1bacce63
packages/hub/services/health-check.ts
packages/hub/services/health-check.ts
import Router from '@koa/router'; import Koa from 'koa'; import { inject } from '@cardstack/di'; import DatabaseManager from '@cardstack/db'; export default class HealthCheck { databaseManager: DatabaseManager = inject('database-manager', { as: 'databaseManager' }); routes() { let healthCheckRouter = new Router(); healthCheckRouter.all('/', async (ctx: Koa.Context) => { let db = await this.databaseManager.getClient(); await db.query('SELECT 1'); ctx.status = 200; ctx.body = `Cardstack Hub is up and running at ${new Date().toISOString()}`; }); return healthCheckRouter.routes(); } } declare module '@cardstack/hub/services' { interface HubServices { 'health-check': HealthCheck; } }
import Router from '@koa/router'; import Koa from 'koa'; import { inject } from '@cardstack/di'; import DatabaseManager from '@cardstack/db'; export default class HealthCheck { databaseManager: DatabaseManager = inject('database-manager', { as: 'databaseManager' }); routes() { let healthCheckRouter = new Router(); healthCheckRouter.all('/', async (ctx: Koa.Context) => { let db = await this.databaseManager.getClient(); await db.query('SELECT 1'); ctx.status = 200; let body = ` Cardstack Hub ------------- Up and running at ${new Date().toISOString()} ${ process.env.WAYPOINT_DEPLOYMENT_ID ? `Deployment ID: ${process.env.WAYPOINT_DEPLOYMENT_ID}` : 'Running outside of Waypoint' } `; ctx.body = body; }); return healthCheckRouter.routes(); } } declare module '@cardstack/hub/services' { interface HubServices { 'health-check': HealthCheck; } }
Improve health check response to include WAYPOINT_DEPLOYMENT_ID
Improve health check response to include WAYPOINT_DEPLOYMENT_ID - so that it is easier to see when deployments are live
TypeScript
mit
cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack
--- +++ @@ -11,7 +11,17 @@ let db = await this.databaseManager.getClient(); await db.query('SELECT 1'); ctx.status = 200; - ctx.body = `Cardstack Hub is up and running at ${new Date().toISOString()}`; + let body = ` +Cardstack Hub +------------- +Up and running at ${new Date().toISOString()} +${ + process.env.WAYPOINT_DEPLOYMENT_ID + ? `Deployment ID: ${process.env.WAYPOINT_DEPLOYMENT_ID}` + : 'Running outside of Waypoint' +} +`; + ctx.body = body; }); return healthCheckRouter.routes();
f571525abf258630811b9c0aa0ecef4462f354af
test/e2e/grid-pager-info.e2e-spec.ts
test/e2e/grid-pager-info.e2e-spec.ts
ο»Ώimport { browser, element, by } from '../../node_modules/protractor/built'; describe('grid pager info', () => { let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'), gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'), pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select'); gridSearchInput = element(by.tagName('grid-search')).$('div').$('div').$('input'); beforeEach(() => { browser.get('/'); pageSizeSelector.$('[value="10"]').click(); }); it('should show text in accordance to numbered of filter rows and current results-page',() => { expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records'); paginator.get(7).$$('a').click(); pageSizeSelector.$('[value="20"]').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records'); paginator.get(5).$$('a').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records'); }); it('should show count in footer', () => { gridSearchInput.sendKeys('a'); expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)'); }); });
ο»Ώimport { browser, element, by } from '../../node_modules/protractor/built'; describe('grid pager info', () => { let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'), gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'), pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select'), gridSearchInput = element(by.tagName('grid-search')).$('div').$('div').$('input'); beforeEach(() => { browser.get('/'); pageSizeSelector.$('[value="10"]').click(); }); it('should show text in accordance to numbered of filter rows and current results-page',() => { expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records'); paginator.get(7).$$('a').click(); pageSizeSelector.$('[value="20"]').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records'); paginator.get(5).$$('a').click(); expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records'); }); it('should show count in footer', () => { gridSearchInput.sendKeys('a'); expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)'); }); });
Fix issues with e2e testing
Fix issues with e2e testing
TypeScript
mit
unosquare/tubular2,unosquare/tubular2,unosquare/tubular2,unosquare/tubular2
--- +++ @@ -4,7 +4,7 @@ let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'), gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'), - pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select'); + pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select'), gridSearchInput = element(by.tagName('grid-search')).$('div').$('div').$('input'); beforeEach(() => {
671a27c1e729b8873718d801348cf1ee9cb34626
src/Patterns.ts
src/Patterns.ts
import { Model, Utils } from "./Model" export { Model as ConsumersModel } export { Utils as Utils } export class ScheduledProductionThread<JOB_TYPE>{ private model : Model<JOB_TYPE> constructor( public productionFunc: (model: Model<JOB_TYPE>)=>Promise<void>, public consumerNum: number, public consumer: (job: JOB_TYPE)=>Promise<void> ){ this.model = new Model<JOB_TYPE>(consumerNum, consumer) } async start(interval_millis=1000){ while (this.model.isRunning){ try{ await this.productionFunc(this.model) } catch (err) { console.error(err) } await Utils.sleep(1000) } } stop(){ this.model.shutdown() } } export class Scheduler{ public isRunning = true constructor(private func: ()=>Promise<void>){} async start(interval_millis = 1000){ while (this.isRunning){ try { await this.func() } catch(err){ console.error(err) } await Utils.sleep(interval_millis) } } stop(){ this.isRunning = false } static start(func: ()=>Promise<void>, interval_millis = 1000){ const s = new Scheduler(func) s.start() return s } }
import { Model, Utils } from "./Model" export { Model as ConsumersModel } export { Utils as Utils } export class ScheduledProductionThread<JOB_TYPE>{ private model : Model<JOB_TYPE> constructor( public productionFunc: (model: Model<JOB_TYPE>)=>Promise<void>, public consumerNum: number, public consumer: (job: JOB_TYPE)=>Promise<void> ){ this.model = new Model<JOB_TYPE>(consumerNum, consumer) } async start(interval_millis=1000){ while (this.model.isRunning){ try{ await this.productionFunc(this.model) } catch (err) { console.error(err) } await Utils.sleep(interval_millis) } } stop(){ this.model.shutdown() } } export class Scheduler{ public isRunning = true constructor(private func: ()=>Promise<void>){} async start(interval_millis = 1000){ while (this.isRunning){ try { await this.func() } catch(err){ console.error(err) } await Utils.sleep(interval_millis) } } stop(){ this.isRunning = false } static start(func: ()=>Promise<void>, interval_millis = 1000){ const s = new Scheduler(func) s.start() return s } }
Fix a bug about argument.
Fix a bug about argument.
TypeScript
apache-2.0
D-Y-Innovations/producer-consumer,D-Y-Innovations/producer-consumer
--- +++ @@ -22,7 +22,7 @@ } catch (err) { console.error(err) } - await Utils.sleep(1000) + await Utils.sleep(interval_millis) } }
8edc9d2a7913a18146e911a0f504caf5e8eaa332
client/imports/app/app.routes.ts
client/imports/app/app.routes.ts
import { Route } from '@angular/router'; import { StoresListComponent } from './stores/stores-list.component'; import { StoreDetailsComponent } from './stores/store-details.component'; import {StoresFormComponent} from './stores/stores-form.component'; import {LoginComponent} from "./auth/login.component"; import {SignupComponent} from "./auth/signup.component"; import {RecoverComponent} from "./auth/recover.component"; import {HomeComponent} from "./home/home.component"; export const routes: Route[] = [ { path: '', component: HomeComponent }, { path: 'stores/:lng/:lat', component: StoresListComponent }, { path: 'store/:storeId', component: StoreDetailsComponent , canActivate: ['canActivateForLoggedIn']},// for action on loggin only { path: 'update/:storeId', component: StoresFormComponent , canActivate: ['canActivateForLoggedIn']}, { path: 'add', component: StoresFormComponent, canActivate: ['canActivateForLoggedIn']}, { path: 'login', component: LoginComponent }, { path: 'signup', component: SignupComponent }, { path: 'recover', component: RecoverComponent } ]; export const ROUTES_PROVIDERS = [{ provide: 'canActivateForLoggedIn', useValue: () => !! Meteor.userId() }];
import { Route } from '@angular/router'; import { StoresListComponent } from './stores/stores-list.component'; import { StoreDetailsComponent } from './stores/store-details.component'; import {StoresFormComponent} from './stores/stores-form.component'; import {LoginComponent} from "./auth/login.component"; import {SignupComponent} from "./auth/signup.component"; import {RecoverComponent} from "./auth/recover.component"; import {HomeComponent} from "./home/home.component"; export const routes: Route[] = [ { path: '', component: HomeComponent }, { path: 'stores/:lng/:lat/:search', component: StoresListComponent }, { path: 'stores/:lng/:lat', component: StoresListComponent }, { path: 'store/:storeId', component: StoreDetailsComponent , canActivate: ['canActivateForLoggedIn']},// for action on loggin only { path: 'update/:storeId', component: StoresFormComponent , canActivate: ['canActivateForLoggedIn']}, { path: 'add', component: StoresFormComponent, canActivate: ['canActivateForLoggedIn']}, { path: 'login', component: LoginComponent }, { path: 'signup', component: SignupComponent }, { path: 'recover', component: RecoverComponent } ]; export const ROUTES_PROVIDERS = [{ provide: 'canActivateForLoggedIn', useValue: () => !! Meteor.userId() }];
Allow stores route with 2 and 3 params
Allow stores route with 2 and 3 params
TypeScript
mit
DarkChopper/yssi,DarkChopper/yssi,DarkChopper/yssi
--- +++ @@ -10,6 +10,7 @@ export const routes: Route[] = [ { path: '', component: HomeComponent }, + { path: 'stores/:lng/:lat/:search', component: StoresListComponent }, { path: 'stores/:lng/:lat', component: StoresListComponent }, { path: 'store/:storeId', component: StoreDetailsComponent , canActivate: ['canActivateForLoggedIn']},// for action on loggin only { path: 'update/:storeId', component: StoresFormComponent , canActivate: ['canActivateForLoggedIn']},
a283e878609247fccf23f9bc7c181bdf2c9d08f5
source/danger/danger_runner.ts
source/danger/danger_runner.ts
/* tslint:disable: no-var-requires */ import { GitHubIntegration } from "../db/mongo" import { PullRequestJSON } from "../github/types/pull_request" import { getCISourceForEnv } from "danger/distribution/ci_source/ci_source" import { GitHub } from "danger/distribution/platforms/GitHub" import Executor from "danger/distribution/runner/Executor" import { writeFileSync } from "fs" import { tmpdir } from "os" export async function runDangerAgainstInstallation(pullRequest: PullRequestJSON, installation: GitHubIntegration) { // We need this for things like repo slugs, PR IDs etc // https://github.com/danger/danger-js/blob/master/source/ci_source/ci_source.js const source = { env: process.env, isCI: true, isPR: true, name: "Peril", pullRequestID: String(pullRequest.pull_request.id), repoSlug: pullRequest.repository.full_name, supportedPlatforms: [], } const gh = new GitHub(installation.accessToken, source) gh.additionalHeaders = { Accept: "application/vnd.github.machine-man-preview+json" } const exec = new Executor(source, gh) const dangerfile = await gh.fileContents("dangerfile.js") const localDangerfile = tmpdir() + "/dangerfile.js" writeFileSync(localDangerfile, dangerfile) exec.runDanger(localDangerfile) }
/* tslint:disable: no-var-requires */ const config = require("config") import { GitHubIntegration } from "../db/mongo" import { PullRequestJSON } from "../github/types/pull_request" import { getCISourceForEnv } from "danger/distribution/ci_source/ci_source" import { GitHub } from "danger/distribution/platforms/GitHub" import Executor from "danger/distribution/runner/Executor" import { writeFileSync } from "fs" import { tmpdir } from "os" export async function runDangerAgainstInstallation(pullRequest: PullRequestJSON, installation: GitHubIntegration) { // We need this for things like repo slugs, PR IDs etc // https://github.com/danger/danger-js/blob/master/source/ci_source/ci_source.js const source = { env: process.env, isCI: true, isPR: true, name: "Peril", pullRequestID: String(pullRequest.pull_request.number), repoSlug: pullRequest.repository.full_name, supportedPlatforms: [], } if (config.has("LOG_FETCH_REQUESTS")) { global["verbose"] = true } console.log("OK") const gh = new GitHub(installation.accessToken, source) gh.additionalHeaders = { Accept: "application/vnd.github.machine-man-preview+json" } const exec = new Executor(source, gh) const dangerfile = await gh.fileContents("dangerfile.js") const localDangerfile = tmpdir() + "/dangerfile.js" writeFileSync(localDangerfile, dangerfile) exec.runDanger(localDangerfile) }
Hide verbose behind the config
Hide verbose behind the config
TypeScript
mit
danger/peril,danger/peril,danger/peril,danger/peril,danger/peril
--- +++ @@ -1,4 +1,5 @@ /* tslint:disable: no-var-requires */ +const config = require("config") import { GitHubIntegration } from "../db/mongo" import { PullRequestJSON } from "../github/types/pull_request" @@ -19,14 +20,19 @@ isCI: true, isPR: true, name: "Peril", - pullRequestID: String(pullRequest.pull_request.id), + pullRequestID: String(pullRequest.pull_request.number), repoSlug: pullRequest.repository.full_name, supportedPlatforms: [], } + + if (config.has("LOG_FETCH_REQUESTS")) { + global["verbose"] = true + } + console.log("OK") const gh = new GitHub(installation.accessToken, source) gh.additionalHeaders = { Accept: "application/vnd.github.machine-man-preview+json" } - + const exec = new Executor(source, gh) const dangerfile = await gh.fileContents("dangerfile.js") const localDangerfile = tmpdir() + "/dangerfile.js"
6da4331db1e5644fd9c452ad03b570bfd7442b7a
src/bot/core/LibraryFactory.ts
src/bot/core/LibraryFactory.ts
import { DialogReady, LibModuleReady, } from './../../interfaces/dialog_interfaces'; import { Dialog, WaterfallDialog, Library, } from 'botbuilder'; import * as _ from 'lodash'; class LibraryFactory { private static _instance:LibraryFactory; private _knowledge:Library[] = []; public createLibs(libModules:LibModuleReady[]) { _.forEach(libModules, (libModule) => { const lib = new Library(libModule.moduleName); _.forEach(libModule.dialogs, (component) => { const waterDialog = new WaterfallDialog(component.waterFall); const dialog = waterDialog.triggerAction(component.actions.triggerAction); this.attachAdditionalAction(dialog); lib.dialog(component.name, dialog); }); this._knowledge.push(lib); }); } private attachAdditionalAction(waterDialog:Dialog) { return; } public getRootLib() { if (this._knowledge.length === 0) throw new Error('Not found any sub lib inside Factory'); const rootLib = new Library('/'); _.forEach(this._knowledge, (lib) => { rootLib.library(lib); }); return rootLib; } public static getInstance() { LibraryFactory._instance = LibraryFactory._instance || new LibraryFactory(); return LibraryFactory._instance; } } export const LibFactory = LibraryFactory.getInstance();
import { DialogReady, LibModuleReady, } from './../../interfaces/dialog_interfaces'; import { Dialog, WaterfallDialog, Library, } from 'botbuilder'; import * as _ from 'lodash'; class LibraryFactory { private static _instance:LibraryFactory; private _knowledge:Library[] = []; public createLibs(libModules:LibModuleReady[]) { _.forEach(libModules, ({ moduleName, dialogs }) => { const lib = new Library(moduleName); _.forEach(dialogs, ({ name, waterFall, actions }) => { if (!name) throw new Error('Dialog must have a name'); if (!waterFall) throw new Error('Dialog must contain steps!'); if (!actions) throw new Error('Dialog must at least contain triggerAction'); const waterDialog = new WaterfallDialog(waterFall); const dialog = waterDialog.triggerAction(actions.triggerAction); this.attachAdditionalAction(dialog); lib.dialog(name, dialog); }); this._knowledge.push(lib); }); } private attachAdditionalAction(dialog:Dialog) { // TODO: it can attach different type of actions into dialog return; } public getRootLib() { if (this._knowledge.length === 0) throw new Error('Not found any sub lib inside Factory'); const rootLib = new Library('/'); _.forEach(this._knowledge, (lib) => { rootLib.library(lib); }); return rootLib; } public static getInstance() { LibraryFactory._instance = LibraryFactory._instance || new LibraryFactory(); return LibraryFactory._instance; } } export const LibFactory = LibraryFactory.getInstance();
Use destruct syntax to clean code
Use destruct syntax to clean code
TypeScript
mit
yujiahaol68/alfred
--- +++ @@ -16,15 +16,19 @@ private _knowledge:Library[] = []; public createLibs(libModules:LibModuleReady[]) { - _.forEach(libModules, (libModule) => { - const lib = new Library(libModule.moduleName); + _.forEach(libModules, ({ moduleName, dialogs }) => { + const lib = new Library(moduleName); - _.forEach(libModule.dialogs, (component) => { - const waterDialog = new WaterfallDialog(component.waterFall); - const dialog = waterDialog.triggerAction(component.actions.triggerAction); + _.forEach(dialogs, ({ name, waterFall, actions }) => { + if (!name) throw new Error('Dialog must have a name'); + if (!waterFall) throw new Error('Dialog must contain steps!'); + if (!actions) throw new Error('Dialog must at least contain triggerAction'); + + const waterDialog = new WaterfallDialog(waterFall); + const dialog = waterDialog.triggerAction(actions.triggerAction); this.attachAdditionalAction(dialog); - lib.dialog(component.name, dialog); + lib.dialog(name, dialog); }); this._knowledge.push(lib); @@ -32,7 +36,8 @@ } - private attachAdditionalAction(waterDialog:Dialog) { + private attachAdditionalAction(dialog:Dialog) { + // TODO: it can attach different type of actions into dialog return; }
899386089a4c75dcf520be1da09a64d3e8632f3a
packages/celltags-extension/src/index.ts
packages/celltags-extension/src/index.ts
import { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { INotebookTools, INotebookTracker } from '@jupyterlab/notebook'; import { TagTool } from '@jupyterlab/celltags'; /** * Initialization data for the celltags extension. */ const celltags: JupyterFrontEndPlugin<void> = { id: 'celltags', autoStart: true, requires: [INotebookTools, INotebookTracker], activate: ( app: JupyterFrontEnd, tools: INotebookTools, tracker: INotebookTracker ) => { const tool = new TagTool(tracker, app); tools.addItem({ tool: tool, rank: 1.6 }); } }; export default celltags;
import { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { INotebookTools, INotebookTracker } from '@jupyterlab/notebook'; import { TagTool } from '@jupyterlab/celltags'; /** * Initialization data for the celltags extension. */ const celltags: JupyterFrontEndPlugin<void> = { id: '@jupyterlab/celltags', autoStart: true, requires: [INotebookTools, INotebookTracker], activate: ( app: JupyterFrontEnd, tools: INotebookTools, tracker: INotebookTracker ) => { const tool = new TagTool(tracker, app); tools.addItem({ tool: tool, rank: 1.6 }); } }; export default celltags;
Rename the celltags plugin id
Rename the celltags plugin id
TypeScript
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -11,7 +11,7 @@ * Initialization data for the celltags extension. */ const celltags: JupyterFrontEndPlugin<void> = { - id: 'celltags', + id: '@jupyterlab/celltags', autoStart: true, requires: [INotebookTools, INotebookTracker], activate: (
6a1e363137c921caf3af563a608eae854ae29ac3
test/e2e/media/media-tab_test.ts
test/e2e/media/media-tab_test.ts
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert} from 'chai'; import {describe, it} from 'mocha'; import {enableExperiment} from '../../shared/helper.js'; import {getPlayerButtonText, playMediaFile} from '../helpers/media-helpers.js'; import {openPanelViaMoreTools} from '../helpers/settings-helpers.js'; function shouldRunTest() { const features = process.env['CHROME_FEATURES']; return features !== undefined && features.includes('MediaInspectorLogging'); } describe('Media Tab', () => { beforeEach(async () => { await enableExperiment('mediaInspector'); }); it('ensures video playback adds entry', async () => { if (!shouldRunTest()) { return; } await openPanelViaMoreTools('Media'); await playMediaFile('fisch.webm'); const entryName = await getPlayerButtonText(); // Names are glitched right now, and display 32-character unguessable tokens. assert.strictEqual(entryName.length, 32); }); });
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assert} from 'chai'; import {describe, it} from 'mocha'; import {getPlayerButtonText, playMediaFile} from '../helpers/media-helpers.js'; import {openPanelViaMoreTools} from '../helpers/settings-helpers.js'; describe('Media Tab', () => { it('ensures video playback adds entry', async () => { await openPanelViaMoreTools('Media'); await playMediaFile('fisch.webm'); const entryName = await getPlayerButtonText(); // Names are glitched right now, and display 32-character unguessable tokens. assert.strictEqual(entryName.length, 32); }); });
Remove need for media flag for media e2e tests
Remove need for media flag for media e2e tests When I wrote the test, the chrome feature was still behind a flag. It isn't behind a flag anymore, so it should run always. Change-Id: Ide674bb7adf94cd5c0b194ede310c7452d96d0fe Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2290578 Commit-Queue: Tim van der Lippe <[email protected]> Auto-Submit: Ted Meyer <[email protected]> Reviewed-by: Tim van der Lippe <[email protected]>
TypeScript
bsd-3-clause
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
--- +++ @@ -5,25 +5,11 @@ import {assert} from 'chai'; import {describe, it} from 'mocha'; -import {enableExperiment} from '../../shared/helper.js'; import {getPlayerButtonText, playMediaFile} from '../helpers/media-helpers.js'; import {openPanelViaMoreTools} from '../helpers/settings-helpers.js'; -function shouldRunTest() { - const features = process.env['CHROME_FEATURES']; - return features !== undefined && features.includes('MediaInspectorLogging'); -} - describe('Media Tab', () => { - beforeEach(async () => { - await enableExperiment('mediaInspector'); - }); - it('ensures video playback adds entry', async () => { - if (!shouldRunTest()) { - return; - } - await openPanelViaMoreTools('Media'); await playMediaFile('fisch.webm'); const entryName = await getPlayerButtonText();
9de337d811cdb6fbba4c9bddc36e1d8a9f82473a
bot/app.ts
bot/app.ts
import * as restify from 'restify'; import * as builder from 'botbuilder'; const connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); const server = restify.createServer(); server.post('/api/messages', connector.listen()); server.get('/healthz', (request, response) => { response.send(200); }) server.listen(3978, () => console.log(`${server.name} listening to ${server.url}`)); var bot = new builder.UniversalBot(connector, (session: builder.Session) => { session.send(`I think you said: ${session.message.text}`) });
import * as restify from 'restify'; import * as builder from 'botbuilder'; import * as os from 'os'; const connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); const server = restify.createServer(); server.post('/api/messages', connector.listen()); server.get('/healthz', (request, response) => { response.send(200); }) server.listen(3978, () => console.log(`${server.name} listening to ${server.url}`)); var bot = new builder.UniversalBot(connector, (session: builder.Session) => { session.send(`I am ${os.hostname}. You said: ${session.message.text}`) });
Add hostname in bot reply
Add hostname in bot reply Signed-off-by: radu-matei <[email protected]>
TypeScript
mit
radu-matei/kube-bot,radu-matei/kube-bot
--- +++ @@ -1,5 +1,6 @@ import * as restify from 'restify'; import * as builder from 'botbuilder'; +import * as os from 'os'; const connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, @@ -15,5 +16,5 @@ server.listen(3978, () => console.log(`${server.name} listening to ${server.url}`)); var bot = new builder.UniversalBot(connector, (session: builder.Session) => { - session.send(`I think you said: ${session.message.text}`) + session.send(`I am ${os.hostname}. You said: ${session.message.text}`) });
27d70504fc4bf3c250002ca0f25a7f8f00cbd50a
ui/src/flux/components/BodyDelete.tsx
ui/src/flux/components/BodyDelete.tsx
import React, {PureComponent} from 'react' import ConfirmButton from 'src/shared/components/ConfirmButton' interface Props { bodyID: string onDeleteBody: (bodyID: string) => void } class BodyDelete extends PureComponent<Props> { public render() { return ( <ConfirmButton icon="trash" type="btn-danger" confirmText="Delete this query" square={true} confirmAction={this.handleDelete} position="right" /> ) } private handleDelete = (): void => { this.props.onDeleteBody(this.props.bodyID) } } export default BodyDelete
import React, {PureComponent} from 'react' import ConfirmButton from 'src/shared/components/ConfirmButton' type BodyType = 'variable' | 'query' interface Props { bodyID: string type?: BodyType onDeleteBody: (bodyID: string) => void } class BodyDelete extends PureComponent<Props> { public static defaultProps: Partial<Props> = { type: 'query', } public render() { return ( <ConfirmButton icon="trash" type="btn-danger" confirmText={this.confirmText} square={true} confirmAction={this.handleDelete} position="right" /> ) } private handleDelete = (): void => { this.props.onDeleteBody(this.props.bodyID) } private get confirmText(): string { const {type} = this.props return `Delete this ${type}` } } export default BodyDelete
Allow for optional "type" for body delete
Allow for optional "type" for body delete Used in the confirmation dialog to refer correctly to the object being deleted
TypeScript
mit
nooproblem/influxdb,influxdata/influxdb,influxdata/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,li-ang/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb
--- +++ @@ -1,18 +1,25 @@ import React, {PureComponent} from 'react' import ConfirmButton from 'src/shared/components/ConfirmButton' +type BodyType = 'variable' | 'query' + interface Props { bodyID: string + type?: BodyType onDeleteBody: (bodyID: string) => void } class BodyDelete extends PureComponent<Props> { + public static defaultProps: Partial<Props> = { + type: 'query', + } + public render() { return ( <ConfirmButton icon="trash" type="btn-danger" - confirmText="Delete this query" + confirmText={this.confirmText} square={true} confirmAction={this.handleDelete} position="right" @@ -23,6 +30,12 @@ private handleDelete = (): void => { this.props.onDeleteBody(this.props.bodyID) } + + private get confirmText(): string { + const {type} = this.props + + return `Delete this ${type}` + } } export default BodyDelete
dedd2fd7f3c49c36e0d4ad3b21b0546c2bc4a429
ui/src/shared/components/FeatureFlag.tsx
ui/src/shared/components/FeatureFlag.tsx
import {SFC} from 'react' interface Props { children?: any } const FeatureFlag: SFC<Props> = props => { if (process.env.NODE_ENV === 'development') { return props.children } return null } export default FeatureFlag
import {SFC} from 'react' interface Props { name?: string children?: any } const FeatureFlag: SFC<Props> = props => { if (process.env.NODE_ENV === 'development') { return props.children } return null } export default FeatureFlag
Define name type for feature flag
Define name type for feature flag
TypeScript
mit
mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb
--- +++ @@ -1,6 +1,7 @@ import {SFC} from 'react' interface Props { + name?: string children?: any }
7082d226070163abd603e391f638f987ef0ecebb
src/Misc/index.ts
src/Misc/index.ts
export * from "./andOrNotEvaluator"; export * from "./assetsManager"; export * from "./dds"; export * from "./decorators"; export * from "./deferred"; export * from "./environmentTextureTools"; export * from "./meshExploder"; export * from "./filesInput"; export * from "./HighDynamicRange/index"; export * from "./khronosTextureContainer"; export * from "./observable"; export * from "./performanceMonitor"; export * from "./promise"; export * from "./sceneOptimizer"; export * from "./sceneSerializer"; export * from "./smartArray"; export * from "./stringDictionary"; export * from "./tags"; export * from "./textureTools"; export * from "./tga"; export * from "./tools"; export * from "./videoRecorder"; export * from "./virtualJoystick"; export * from "./workerPool"; export * from "./logger"; export * from "./typeStore"; export * from "./filesInputStore"; export * from "./deepCopier"; export * from "./pivotTools"; export * from "./precisionDate"; export * from "./screenshotTools"; export * from "./typeStore"; export * from "./webRequest"; export * from "./iInspectable";
export * from "./andOrNotEvaluator"; export * from "./assetsManager"; export * from "./dds"; export * from "./decorators"; export * from "./deferred"; export * from "./environmentTextureTools"; export * from "./meshExploder"; export * from "./filesInput"; export * from "./HighDynamicRange/index"; export * from "./khronosTextureContainer"; export * from "./observable"; export * from "./performanceMonitor"; export * from "./promise"; export * from "./sceneOptimizer"; export * from "./sceneSerializer"; export * from "./smartArray"; export * from "./stringDictionary"; export * from "./tags"; export * from "./textureTools"; export * from "./tga"; export * from "./tools"; export * from "./videoRecorder"; export * from "./virtualJoystick"; export * from "./workerPool"; export * from "./logger"; export * from "./typeStore"; export * from "./filesInputStore"; export * from "./deepCopier"; export * from "./pivotTools"; export * from "./precisionDate"; export * from "./screenshotTools"; export * from "./typeStore"; export * from "./webRequest"; export * from "./iInspectable"; export * from "./brdfTextureTools";
Add brdfTextureTools to the main export
Add brdfTextureTools to the main export
TypeScript
apache-2.0
sebavan/Babylon.js,NicolasBuecher/Babylon.js,BabylonJS/Babylon.js,Kesshi/Babylon.js,RaananW/Babylon.js,sebavan/Babylon.js,jbousquie/Babylon.js,NicolasBuecher/Babylon.js,jbousquie/Babylon.js,Kesshi/Babylon.js,RaananW/Babylon.js,NicolasBuecher/Babylon.js,sebavan/Babylon.js,BabylonJS/Babylon.js,Kesshi/Babylon.js,jbousquie/Babylon.js,RaananW/Babylon.js,BabylonJS/Babylon.js
--- +++ @@ -32,3 +32,4 @@ export * from "./typeStore"; export * from "./webRequest"; export * from "./iInspectable"; +export * from "./brdfTextureTools";
3075ae87cf7fd2edcd81dcd51364ae8cfaf4ddca
code-sample-angular-java/hello-world/src/app/heroes/heroes.component.ts
code-sample-angular-java/hello-world/src/app/heroes/heroes.component.ts
import { Component, OnInit } from '@angular/core'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] }) export class HeroesComponent implements OnInit { constructor(private heroService: HeroService) { } heroes: Hero[]; selectedHero: Hero; ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } onSelect(hero: Hero): void { this.selectedHero = hero; } }
import { Component, OnInit } from '@angular/core'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; import {MessageService} from "../message.service"; @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] }) export class HeroesComponent implements OnInit { constructor(private heroService: HeroService, private messageService: MessageService) { } heroes: Hero[]; selectedHero: Hero; ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } onSelect(hero: Hero): void { this.messageService.add("Hero " + hero.name + " choosen"); this.selectedHero = hero; } }
Add messaging when hero is selected
Add messaging when hero is selected
TypeScript
mit
aquatir/remember_java_api,aquatir/remember_java_api,aquatir/remember_java_api,aquatir/remember_java_api
--- +++ @@ -1,6 +1,7 @@ import { Component, OnInit } from '@angular/core'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; +import {MessageService} from "../message.service"; @Component({ selector: 'app-heroes', @@ -9,7 +10,7 @@ }) export class HeroesComponent implements OnInit { - constructor(private heroService: HeroService) { } + constructor(private heroService: HeroService, private messageService: MessageService) { } heroes: Hero[]; selectedHero: Hero; @@ -27,6 +28,7 @@ onSelect(hero: Hero): void { + this.messageService.add("Hero " + hero.name + " choosen"); this.selectedHero = hero; }
3a62d8506bf196a46382566043023d92531b442f
src/index.spec.ts
src/index.spec.ts
import { parse, http } from './index' import { expect } from 'chai' import { get, createServer } from 'http' describe('get headers', () => { it('should parse headers', () => { const headers = parse([ 'Content-Type: application/json', 'Cookie: foo', 'Cookie: bar', 'Cookie: baz' ].join('\n')) expect(headers).to.deep.equal({ 'Content-Type': 'application/json', 'Cookie': ['foo', 'bar', 'baz'] }) }) it('should parse http', (done) => { const server = createServer((req, res) => { res.setHeader('Content-Type', 'application/json') res.setHeader('Cookie', <any> ['foo', 'bar', 'baz']) res.end('hello world') }) server.on('listening', () => { get('http://localhost:' + server.address().port, (res) => { const headers = http(res) if (res.rawHeaders) { expect(headers['Content-Type']).to.equal('application/json') expect(headers['Cookie']).to.deep.equal(['foo', 'bar', 'baz']) } else { expect(headers['content-type']).to.equal('application/json') expect(headers['cookie']).to.deep.equal(['foo', 'bar', 'baz']) } server.close() return done() }) }) server.listen(0) }) })
import { parse, http } from './index' import { expect } from 'chai' import { get, createServer } from 'http' describe('get headers', () => { it('should parse headers', () => { const headers = parse([ 'Content-Type: application/json', 'Cookie: foo', 'Cookie: bar', 'Cookie: baz' ].join('\n')) expect(headers).to.deep.equal({ 'Content-Type': 'application/json', 'Cookie': ['foo', 'bar', 'baz'] }) }) it('should parse http', (done) => { const server = createServer((req, res) => { res.setHeader('Content-Type', 'application/json') res.setHeader('Cookie', <any> ['foo', 'bar', 'baz']) res.end('hello world') }) server.on('listening', () => { get('http://localhost:' + server.address().port, (res) => { const headers = http(res) if (res.rawHeaders) { expect(headers['Content-Type']).to.equal('application/json') expect(headers['Cookie']).to.deep.equal(['foo', 'bar', 'baz']) } else { expect(headers['content-type']).to.equal('application/json') expect(headers['cookie']).to.deep.equal('foo, bar, baz') } server.close() return done() }) }) server.listen(0) }) })
Fix tests under node 0.10
Fix tests under node 0.10
TypeScript
mit
blakeembrey/get-headers
--- +++ @@ -33,7 +33,7 @@ expect(headers['Cookie']).to.deep.equal(['foo', 'bar', 'baz']) } else { expect(headers['content-type']).to.equal('application/json') - expect(headers['cookie']).to.deep.equal(['foo', 'bar', 'baz']) + expect(headers['cookie']).to.deep.equal('foo, bar, baz') } server.close()
b392ae10bafb770cc87ca45c52e642b04d8af493
src/helpers/export.ts
src/helpers/export.ts
import { VERSION } from "../constants" import type { CommandType } from "../data/templates" import type { Snippet } from "../classes/Snippets/SnippetTypes/Snippet" import { duplicate_snippet } from "./duplicate_snippet" function strip_id(snippet: Snippet): Snippet { delete snippet.id; snippet.hover_event_children = snippet.hover_event_children.map(child => strip_id(child)); return snippet; } export function export_snippets(snippets: Array<Snippet>, command: string, type: CommandType): string { const snippets_stripped = snippets .map(snippet => duplicate_snippet(snippet)) .map(snippet => strip_id(snippet)); const data = { "jformat": VERSION, "jobject": snippets_stripped, "command": command, "jtemplate": type } return JSON.stringify(data) }
import { VERSION } from "../constants" import type { CommandType } from "../data/templates" import type { Snippet } from "../classes/Snippets/SnippetTypes/Snippet" import { duplicate_snippet } from "./duplicate_snippet" import { GroupSnippet } from "../classes/Snippets/SnippetTypes/GroupSnippet"; function strip_id(snippet: Snippet): Snippet { delete snippet.id; snippet.hover_event_children = snippet.hover_event_children.map(child => strip_id(child)); if (snippet instanceof GroupSnippet) { snippet.children = snippet.children.map(child => strip_id(child)); } return snippet; } export function export_snippets(snippets: Array<Snippet>, command: string, type: CommandType): string { const snippets_stripped = snippets .map(snippet => duplicate_snippet(snippet)) .map(snippet => strip_id(snippet)); const data = { "jformat": VERSION, "jobject": snippets_stripped, "command": command, "jtemplate": type } return JSON.stringify(data) }
Remove IDs from group children
Remove IDs from group children
TypeScript
mit
ezfe/tellraw,ezfe/tellraw,ezfe/tellraw
--- +++ @@ -2,10 +2,14 @@ import type { CommandType } from "../data/templates" import type { Snippet } from "../classes/Snippets/SnippetTypes/Snippet" import { duplicate_snippet } from "./duplicate_snippet" +import { GroupSnippet } from "../classes/Snippets/SnippetTypes/GroupSnippet"; function strip_id(snippet: Snippet): Snippet { delete snippet.id; snippet.hover_event_children = snippet.hover_event_children.map(child => strip_id(child)); + if (snippet instanceof GroupSnippet) { + snippet.children = snippet.children.map(child => strip_id(child)); + } return snippet; }
4349d7cf75ad2ad6cc0ee3c6cd44fe7c8ccba137
frontend/src/app/services/unauthorized.interceptor.ts
frontend/src/app/services/unauthorized.interceptor.ts
import { Injectable } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/empty'; @Injectable() export class UnauthorizedInterceptor implements HttpInterceptor { constructor( private router: Router, private route: ActivatedRoute, ) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).catch((err: any) => { if (err instanceof HttpErrorResponse && err.status === 401) { this.router.navigate(['/login'], { // TODO: put in config! queryParams: { route: this.router.url, } }); // this response is handled // stop the chain of handlers by returning empty return Observable.empty(); } // rethrow so other error handlers may pick this up return Observable.throw(err); }); } }
import { Injectable } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/empty'; @Injectable() export class UnauthorizedInterceptor implements HttpInterceptor { constructor( private router: Router, private route: ActivatedRoute, ) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).catch((err: any) => { if (err instanceof HttpErrorResponse && err.status === 401 && this.router.url != '/') { this.router.navigate(['/login'], { // TODO: put in config! queryParams: { route: this.router.url, } }); // this response is handled // stop the chain of handlers by returning empty return Observable.empty(); } // rethrow so other error handlers may pick this up return Observable.throw(err); }); } }
Revert "fix frontend redirection after token expires"
Revert "fix frontend redirection after token expires" This reverts commit ef82d0dc3e4a762edcb843ee20e70132b8b9c01a.
TypeScript
bsd-2-clause
PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature
--- +++ @@ -15,7 +15,8 @@ intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).catch((err: any) => { if (err instanceof HttpErrorResponse - && err.status === 401) { + && err.status === 401 + && this.router.url != '/') { this.router.navigate(['/login'], { // TODO: put in config! queryParams: { route: this.router.url, } });
0097ea9fce99d41151eb0d1c30026b207e749634
src/services/index.ts
src/services/index.ts
import * as vscode from 'vscode'; import DocumentTracker from './documentTracker'; import CodeLensProvider from './codeLensProvider'; import CommandHandler from './commandHandler'; import Decorator from './mergeDecorator'; const ConfigurationSectionName = 'better-merge'; export default class ServiceWrapper implements vscode.Disposable { private services: vscode.Disposable[] = []; constructor(private context: vscode.ExtensionContext) { } begin() { let configuration = vscode.workspace.getConfiguration(ConfigurationSectionName); const documentTracker = new DocumentTracker(); this.services.push( documentTracker, new CommandHandler(this.context, documentTracker), new CodeLensProvider(this.context, documentTracker), new Decorator(this.context, documentTracker), ); this.services.forEach((service: any) => { if (service.begin && service.begin instanceof Function) { service.begin(configuration); } }); vscode.workspace.onDidChangeConfiguration(() => { this.services.forEach((service: any) => { if (service.configurationUpdated && service.configurationUpdated instanceof Function) { service.configurationUpdated(vscode.workspace.getConfiguration(ConfigurationSectionName)); } }); }); } dispose() { if (this.services) { this.services.forEach(disposable => disposable.dispose()); this.services = null; } } }
import * as vscode from 'vscode'; import DocumentTracker from './documentTracker'; import CodeLensProvider from './codelensProvider'; import CommandHandler from './commandHandler'; import Decorator from './mergeDecorator'; const ConfigurationSectionName = 'better-merge'; export default class ServiceWrapper implements vscode.Disposable { private services: vscode.Disposable[] = []; constructor(private context: vscode.ExtensionContext) { } begin() { let configuration = vscode.workspace.getConfiguration(ConfigurationSectionName); const documentTracker = new DocumentTracker(); this.services.push( documentTracker, new CommandHandler(this.context, documentTracker), new CodeLensProvider(this.context, documentTracker), new Decorator(this.context, documentTracker), ); this.services.forEach((service: any) => { if (service.begin && service.begin instanceof Function) { service.begin(configuration); } }); vscode.workspace.onDidChangeConfiguration(() => { this.services.forEach((service: any) => { if (service.configurationUpdated && service.configurationUpdated instanceof Function) { service.configurationUpdated(vscode.workspace.getConfiguration(ConfigurationSectionName)); } }); }); } dispose() { if (this.services) { this.services.forEach(disposable => disposable.dispose()); this.services = null; } } }
Fix codelensProvider import to use correct casing
Fix codelensProvider import to use correct casing
TypeScript
mit
pprice/vscode-better-merge
--- +++ @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; import DocumentTracker from './documentTracker'; -import CodeLensProvider from './codeLensProvider'; +import CodeLensProvider from './codelensProvider'; import CommandHandler from './commandHandler'; import Decorator from './mergeDecorator';
9b35379fd92eef5ff274d5fe7254798508b9b566
packages/http-transport/ts/lsRemote.ts
packages/http-transport/ts/lsRemote.ts
import parseRefsResponse from './parseRefsResponse'; import { Ref } from './types'; export interface Result { readonly capabilities : Map<string, string | boolean>, readonly remoteRefs : Ref[] } export type Fetch = (url : string) => Promise<FetchResponse> export interface FetchResponse { text() : Promise<string> readonly status : number readonly statusText : string } export default async function lsRemote(url : string, fetch : Fetch, service : string = 'git-upload-pack') : Promise<Result> { const res = await fetch(`${url}/info/refs?service=${service}`); if(res.status !== 200) throw new Error(`ls-remote failed with ${res.status} ${res.statusText}`); const refs = await res.text(); const capabilities = new Map<string, string | boolean>(); const remoteRefs = [...parseRefsResponse(refs, service, capabilities)]; return { remoteRefs, capabilities }; }
import parseRefsResponse from './parseRefsResponse'; import { Ref } from './types'; export interface Result { readonly capabilities : Map<string, string | boolean>, readonly remoteRefs : Ref[] } export type Fetch = (url : string) => Promise<FetchResponse> export interface FetchResponse { text() : Promise<string> readonly status : number readonly statusText : string } export default async function lsRemote(url : string, fetch : Fetch, service : string = 'git-upload-pack') : Promise<Result> { const res = await fetch(`${url}/info/refs?service=${service}`); if(res.status !== 200) throw new Error(`ls-remote failed with ${res.status} ${res.statusText}\n${await res.text()}`); const refs = await res.text(); const capabilities = new Map<string, string | boolean>(); const remoteRefs = [...parseRefsResponse(refs, service, capabilities)]; return { remoteRefs, capabilities }; }
Include message from the server when the response is not a success
Include message from the server when the response is not a success
TypeScript
mit
es-git/es-git,es-git/es-git,es-git/es-git
--- +++ @@ -16,7 +16,7 @@ export default async function lsRemote(url : string, fetch : Fetch, service : string = 'git-upload-pack') : Promise<Result> { const res = await fetch(`${url}/info/refs?service=${service}`); - if(res.status !== 200) throw new Error(`ls-remote failed with ${res.status} ${res.statusText}`); + if(res.status !== 200) throw new Error(`ls-remote failed with ${res.status} ${res.statusText}\n${await res.text()}`); const refs = await res.text(); const capabilities = new Map<string, string | boolean>(); const remoteRefs = [...parseRefsResponse(refs, service, capabilities)];
30e8954d807fee0e35925c189439cb36fc21064c
packages/shared/lib/interfaces/User.ts
packages/shared/lib/interfaces/User.ts
import { Key } from './Key'; import { USER_ROLES } from '../constants'; export enum MNEMONIC_STATUS { DISABLED = 0, ENABLED = 1, OUTDATED = 2, SET = 3, PROMPT = 4, } export enum UserType { PROTON = 1, MANAGED = 2, EXTERNAL = 3, } export interface User { ID: string; Name: string; UsedSpace: number; Currency: string; Credit: number; MaxSpace: number; MaxUpload: number; Role: USER_ROLES; Private: number; Type: UserType; Subscribed: number; Services: number; Delinquent: number; Email: string; DisplayName: string; OrganizationPrivateKey?: string; Keys: Key[]; DriveEarlyAccess: number; ToMigrate: 0 | 1; MnemonicStatus: MNEMONIC_STATUS; } export interface UserModel extends User { isAdmin: boolean; isMember: boolean; isFree: boolean; isPaid: boolean; isPrivate: boolean; isSubUser: boolean; isDelinquent: boolean; hasNonDelinquentScope: boolean; hasPaidMail: boolean; hasPaidVpn: boolean; canPay: boolean; }
import { Key } from './Key'; import { USER_ROLES } from '../constants'; export enum MNEMONIC_STATUS { DISABLED = 0, ENABLED = 1, OUTDATED = 2, SET = 3, PROMPT = 4, } export enum UserType { PROTON = 1, MANAGED = 2, EXTERNAL = 3, } export interface User { ID: string; Name: string; UsedSpace: number; Currency: string; Credit: number; MaxSpace: number; MaxUpload: number; Role: USER_ROLES; Private: number; Type: UserType; Subscribed: number; Services: number; Delinquent: number; Email: string; DisplayName: string; OrganizationPrivateKey?: string; Keys: Key[]; DriveEarlyAccess: number; ToMigrate: 0 | 1; MnemonicStatus: MNEMONIC_STATUS; Idle: 0 | 1; } export interface UserModel extends User { isAdmin: boolean; isMember: boolean; isFree: boolean; isPaid: boolean; isPrivate: boolean; isSubUser: boolean; isDelinquent: boolean; hasNonDelinquentScope: boolean; hasPaidMail: boolean; hasPaidVpn: boolean; canPay: boolean; }
Add IdleBadge to StatusAndPrivileges section
Add IdleBadge to StatusAndPrivileges section CP-3568
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -36,6 +36,7 @@ DriveEarlyAccess: number; ToMigrate: 0 | 1; MnemonicStatus: MNEMONIC_STATUS; + Idle: 0 | 1; } export interface UserModel extends User {