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
cdc06ec8c611156a879deee78768ce3b1ec93d37
app/src/lib/progress/fetch-progress-parser.ts
app/src/lib/progress/fetch-progress-parser.ts
import { StepProgressParser } from './step-progress' /** * Highly approximate (some would say outright inaccurate) division * of the individual progress reporting steps in a fetch operation */ const steps = [ { title: 'remote: Compressing objects', weight: 0.1 }, { title: 'Receiving objects', weight: 0.7 }, { title: 'Resolving deltas', weight: 0.2 }, ] /** * A utility class for interpreting the output from `git push --progress` * and turning that into a percentage value estimating the overall progress * of the clone. */ export class PushProgressParser extends StepProgressParser { public constructor() { super(steps) } }
Add a fetch progress parser
Add a fetch progress parser
TypeScript
mit
say25/desktop,artivilla/desktop,hjobrien/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,BugTesterTest/desktops,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,BugTesterTest/desktops,artivilla/desktop,shiftkey/desktop,gengjiawen/desktop,j-f1/forked-desktop,j-f1/forked-desktop,gengjiawen/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,say25/desktop,hjobrien/desktop,gengjiawen/desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,gengjiawen/desktop,kactus-io/kactus,BugTesterTest/desktops,hjobrien/desktop,kactus-io/kactus,say25/desktop,desktop/desktop,hjobrien/desktop,BugTesterTest/desktops
--- +++ @@ -0,0 +1,22 @@ +import { StepProgressParser } from './step-progress' + +/** + * Highly approximate (some would say outright inaccurate) division + * of the individual progress reporting steps in a fetch operation + */ +const steps = [ + { title: 'remote: Compressing objects', weight: 0.1 }, + { title: 'Receiving objects', weight: 0.7 }, + { title: 'Resolving deltas', weight: 0.2 }, +] + +/** + * A utility class for interpreting the output from `git push --progress` + * and turning that into a percentage value estimating the overall progress + * of the clone. + */ +export class PushProgressParser extends StepProgressParser { + public constructor() { + super(steps) + } +}
e0e03a2a792c2f36b268d4d9cdcd95988fcb70e6
app/modules/OptionsBar/FontSize/FontSize.tsx
app/modules/OptionsBar/FontSize/FontSize.tsx
import * as React from 'react'; import { Menu, MenuDivider, MenuItem, Popover, Position } from "@blueprintjs/core"; interface FontSizeProps { pluginState: any; updateCurrentPlugin: Function; } const FontSize = ({ pluginState, updateCurrentPlugin }: FontSizeProps) => { const DEFAULT_SIZE = 100; const MAGNIFIER = 3; const fontSizes = [50, 75, 90, 100, 125, 150, 175, 200, 250, 275, 300]; const fontSelection = ( <Menu> { fontSizes.map((fontSize, key) => ( <MenuItem key={ key } text={`${fontSize}%`} onClick={() => updateCurrentPlugin({ fontSize: fontSize * MAGNIFIER })} /> )) } </Menu> ); return ( <Popover content={ fontSelection } position={ Position.RIGHT_TOP }> <button className="pt-button" type="button"> { pluginState.fontSize ? `${ pluginState.fontSize / MAGNIFIER }%` : `${ DEFAULT_SIZE }%` } </button> </Popover> ); } export default FontSize;
Add ability to change font size
feat: Add ability to change font size
TypeScript
mit
chengsieuly/devdecks,chengsieuly/devdecks,chengsieuly/devdecks,DevDecks/devdecks,Team-CHAD/DevDecks,DevDecks/devdecks,DevDecks/devdecks,Team-CHAD/DevDecks,Team-CHAD/DevDecks
--- +++ @@ -0,0 +1,36 @@ +import * as React from 'react'; +import { Menu, MenuDivider, MenuItem, Popover, Position } from "@blueprintjs/core"; + +interface FontSizeProps { + pluginState: any; + updateCurrentPlugin: Function; +} + +const FontSize = ({ pluginState, updateCurrentPlugin }: FontSizeProps) => { + const DEFAULT_SIZE = 100; + const MAGNIFIER = 3; + + const fontSizes = [50, 75, 90, 100, 125, 150, 175, 200, 250, 275, 300]; + const fontSelection = ( + <Menu> + { + fontSizes.map((fontSize, key) => ( + <MenuItem + key={ key } + text={`${fontSize}%`} + onClick={() => updateCurrentPlugin({ fontSize: fontSize * MAGNIFIER })} /> + )) + } + </Menu> + ); + + return ( + <Popover content={ fontSelection } position={ Position.RIGHT_TOP }> + <button className="pt-button" type="button"> + { pluginState.fontSize ? `${ pluginState.fontSize / MAGNIFIER }%` : `${ DEFAULT_SIZE }%` } + </button> + </Popover> + ); +} + +export default FontSize;
9835651432a733c4b18f2d452ab8a00a07f8ac23
app/src/lib/stores/helpers/pull-request-updater.ts
app/src/lib/stores/helpers/pull-request-updater.ts
import { PullRequestStore } from '../pull-request-store' import { Repository } from '../../../models/repository' import { Account } from '../../../models/account' import { fatalError } from '../../fatal-error' const PullRequestInterval = 1000 * 60 * 3 const StatusInterval = 1000 * 60 enum TimeoutHandles { PullRequest = 'PullRequestHandle', Status = 'StatusHandle', } export class PullRequestUpdater { private readonly repository: Repository private readonly account: Account private readonly store: PullRequestStore private readonly timeoutHandles = new Map<TimeoutHandles, number>() private isStopped: boolean = true public constructor( repository: Repository, account: Account, pullRequestStore: PullRequestStore ) { this.repository = repository this.account = account this.store = pullRequestStore } public start() { if (this.isStopped) { fatalError('Cannot start the Pull Request Updater that has been stopped.') return } const gitHubRepository = this.repository.gitHubRepository if (!gitHubRepository) { return } this.timeoutHandles.set( TimeoutHandles.PullRequest, window.setTimeout(() => { this.store.refreshPullRequests(gitHubRepository, this.account) }, PullRequestInterval) ) this.timeoutHandles.set( TimeoutHandles.Status, window.setTimeout(() => { this.store.refreshPullRequestStatuses(gitHubRepository, this.account) }, StatusInterval) ) } public stop() { this.isStopped = true for (const timeoutHandle of this.timeoutHandles.values()) { window.clearTimeout(timeoutHandle) } this.timeoutHandles.clear() } }
Add service to handle updating PRs
Add service to handle updating PRs
TypeScript
mit
say25/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,desktop/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,say25/desktop,shiftkey/desktop,artivilla/desktop,kactus-io/kactus
--- +++ @@ -0,0 +1,69 @@ +import { PullRequestStore } from '../pull-request-store' +import { Repository } from '../../../models/repository' +import { Account } from '../../../models/account' +import { fatalError } from '../../fatal-error' + +const PullRequestInterval = 1000 * 60 * 3 +const StatusInterval = 1000 * 60 + +enum TimeoutHandles { + PullRequest = 'PullRequestHandle', + Status = 'StatusHandle', +} + +export class PullRequestUpdater { + private readonly repository: Repository + private readonly account: Account + private readonly store: PullRequestStore + + private readonly timeoutHandles = new Map<TimeoutHandles, number>() + private isStopped: boolean = true + + public constructor( + repository: Repository, + account: Account, + pullRequestStore: PullRequestStore + ) { + this.repository = repository + this.account = account + this.store = pullRequestStore + } + + public start() { + if (this.isStopped) { + fatalError('Cannot start the Pull Request Updater that has been stopped.') + + return + } + const gitHubRepository = this.repository.gitHubRepository + + if (!gitHubRepository) { + return + } + + this.timeoutHandles.set( + TimeoutHandles.PullRequest, + + window.setTimeout(() => { + this.store.refreshPullRequests(gitHubRepository, this.account) + }, PullRequestInterval) + ) + + this.timeoutHandles.set( + TimeoutHandles.Status, + window.setTimeout(() => { + this.store.refreshPullRequestStatuses(gitHubRepository, this.account) + }, StatusInterval) + ) + } + + public stop() { + this.isStopped = true + + for (const timeoutHandle of this.timeoutHandles.values()) { + window.clearTimeout(timeoutHandle) + } + + this.timeoutHandles.clear() + } +}
e4fe82d63f9a23d98f4952611fa7ae082645f8b5
dom_hr.ts
dom_hr.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="hr_HR"> <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 type="unfinished">Svojstvo</translation> </message> <message> <location filename="../treewindow.ui" line="68"/> <source>Value</source> <translation type="unfinished">Vrijednost</translation> </message> <message> <location filename="../treewindow.ui" line="76"/> <source>All properties</source> <translation type="unfinished">Sva svojstva</translation> </message> <message> <location filename="../treewindow.ui" line="101"/> <source>Type</source> <translation type="unfinished">Vrsta</translation> </message> <message> <location filename="../treewindow.ui" line="106"/> <source>String value</source> <translation type="unfinished"></translation> </message> </context> </TS>
Create HR translations for panel and plugins
Create HR translations for panel and plugins
TypeScript
lgpl-2.1
lxde/lxqt-l10n
--- +++ @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE TS> +<TS version="2.0" language="hr_HR"> +<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 type="unfinished">Svojstvo</translation> + </message> + <message> + <location filename="../treewindow.ui" line="68"/> + <source>Value</source> + <translation type="unfinished">Vrijednost</translation> + </message> + <message> + <location filename="../treewindow.ui" line="76"/> + <source>All properties</source> + <translation type="unfinished">Sva svojstva</translation> + </message> + <message> + <location filename="../treewindow.ui" line="101"/> + <source>Type</source> + <translation type="unfinished">Vrsta</translation> + </message> + <message> + <location filename="../treewindow.ui" line="106"/> + <source>String value</source> + <translation type="unfinished"></translation> + </message> +</context> +</TS>
f9639d2f3809b7ca165f90d21e602789ef285708
src/resources/qna.ts
src/resources/qna.ts
import * as request from "request"; let qnaSubKey = process.env["qnaSubKey"]; /** * Returns an answer to a question. */ export const ask = function (questionText: string, kb: string): Promise<string> { return new Promise(resolve => { try { request.post({ headers: { "content-type": "application/json", "Ocp-Apim-Subscription-Key": qnaSubKey }, url: `https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/${kb}/generateAnswer`, body: JSON.stringify({question: questionText}) }, function (error, response, body) { console.log("Response: " + body); if (response.statusCode === 200) { let answer = JSON.parse(body); resolve(answer["answers"][0]); } else { resolve(""); } }); } catch (e) { console.log("EXCEPTION " + e); resolve(""); } }); };
Add helper for Microsoft QnA service.
Add helper for Microsoft QnA service.
TypeScript
agpl-3.0
deegles/cookietime,deegles/cookietime
--- +++ @@ -0,0 +1,32 @@ +import * as request from "request"; + +let qnaSubKey = process.env["qnaSubKey"]; + +/** + * Returns an answer to a question. + */ +export const ask = function (questionText: string, kb: string): Promise<string> { + return new Promise(resolve => { + try { + request.post({ + headers: { + "content-type": "application/json", + "Ocp-Apim-Subscription-Key": qnaSubKey + }, + url: `https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/${kb}/generateAnswer`, + body: JSON.stringify({question: questionText}) + }, function (error, response, body) { + console.log("Response: " + body); + if (response.statusCode === 200) { + let answer = JSON.parse(body); + resolve(answer["answers"][0]); + } else { + resolve(""); + } + }); + } catch (e) { + console.log("EXCEPTION " + e); + resolve(""); + } + }); +};
a538358862e0f4f0187a44a6227d6d092f5afe50
types/iopipe__iopipe/index.d.ts
types/iopipe__iopipe/index.d.ts
// Type definitions for iopipe__iopipe 1.12 // Project: https://github.com/iopipe/iopipe (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) // Definitions by: Javon Harper <https://github.com/javonharper> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface LibraryConfig { debug?: boolean; token?: string; networkTimeout?: number; timeoutWindow?: number; } type FunctionWrapper = (handler: any) => void; declare function iopipe(config?: LibraryConfig): FunctionWrapper; declare namespace iopipe { function label(label: string): void; function metric(label: string, value: number): void; namespace mark { function start(label: string): void; function end(label: string): void; } } export = iopipe;
// Type definitions for iopipe__iopipe 1.12 // Project: https://github.com/iopipe/iopipe (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) // Definitions by: Javon Harper <https://github.com/javonharper> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function iopipe(config?: iopipe.LibraryConfig): iopipe.FunctionWrapper; declare namespace iopipe { function label(label: string): void; function metric(label: string, value: number): void; namespace mark { function start(label: string): void; function end(label: string): void; } interface LibraryConfig { debug?: boolean; token?: string; networkTimeout?: number; timeoutWindow?: number; } type FunctionWrapper = (handler: any) => void; } export = iopipe;
Move implicit exports into the namespace.
Move implicit exports into the namespace.
TypeScript
mit
dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,borisyankov/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped
--- +++ @@ -3,16 +3,7 @@ // Definitions by: Javon Harper <https://github.com/javonharper> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface LibraryConfig { - debug?: boolean; - token?: string; - networkTimeout?: number; - timeoutWindow?: number; -} - -type FunctionWrapper = (handler: any) => void; - -declare function iopipe(config?: LibraryConfig): FunctionWrapper; +declare function iopipe(config?: iopipe.LibraryConfig): iopipe.FunctionWrapper; declare namespace iopipe { function label(label: string): void; @@ -23,6 +14,15 @@ function start(label: string): void; function end(label: string): void; } + + interface LibraryConfig { + debug?: boolean; + token?: string; + networkTimeout?: number; + timeoutWindow?: number; + } + + type FunctionWrapper = (handler: any) => void; } export = iopipe;
9dfface8db1a19d367f1efc925590e7c754cadec
src/utils/hots-commons.ts
src/utils/hots-commons.ts
export enum HeroRoles { Assassin, Warrior, Specialist, Support } export interface Skill{ name: string; level: number; description: string; } export interface Build{ name: string; skills: Array<Skill>; } export interface Hero{ name: string; role: HeroRoles|Array<HeroRoles>; builds: Array<Build> }
Add basic interfaces about HotS elements (Hero, Build, Role, Skill)
Add basic interfaces about HotS elements (Hero, Build, Role, Skill)
TypeScript
mit
jchakra/hots-parser
--- +++ @@ -0,0 +1,23 @@ +export enum HeroRoles { + Assassin, + Warrior, + Specialist, + Support +} + +export interface Skill{ + name: string; + level: number; + description: string; +} + +export interface Build{ + name: string; + skills: Array<Skill>; +} + +export interface Hero{ + name: string; + role: HeroRoles|Array<HeroRoles>; + builds: Array<Build> +}
4718ce3c11aef0c4858b52fd4d5a59b39e56af79
ui/src/tempVars/components/TemplatePreviewListItem.tsx
ui/src/tempVars/components/TemplatePreviewListItem.tsx
import React, {PureComponent} from 'react' import classNames from 'classnames' import {TemplateValue} from 'src/types' interface Props { item: TemplateValue onClick: (item: TemplateValue) => void style: { height: string marginBottom: string } } class TemplatePreviewListItem extends PureComponent<Props> { public render() { const {item, style} = this.props return ( <li onClick={this.handleClick} style={style} className={classNames('temp-builder-results--list-item', { active: this.isSelected, })} > {item.value} </li> ) } private get isSelected() { return this.props.item.selected } private handleClick = (): void => { this.props.onClick(this.props.item) } } export default TemplatePreviewListItem
import React, {PureComponent} from 'react' import classNames from 'classnames' import {TemplateValue} from 'src/types' interface Props { item: TemplateValue onClick: (item: TemplateValue) => void style: React.CSSProperties } class TemplatePreviewListItem extends PureComponent<Props> { public render() { const {item, style} = this.props return ( <li onClick={this.handleClick} style={style} className={classNames('temp-builder-results--list-item', { active: this.isSelected, })} > {item.value} </li> ) } private get isSelected() { return this.props.item.selected } private handleClick = (): void => { this.props.onClick(this.props.item) } } export default TemplatePreviewListItem
Update tempvar preview list to accept CSSProperties for style
Update tempvar preview list to accept CSSProperties for style
TypeScript
mit
mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb
--- +++ @@ -6,10 +6,7 @@ interface Props { item: TemplateValue onClick: (item: TemplateValue) => void - style: { - height: string - marginBottom: string - } + style: React.CSSProperties } class TemplatePreviewListItem extends PureComponent<Props> {
dd81f4381de8e663c17e12595b33b46020c153cf
public/app/plugins/datasource/influxdb/specs/datasource.jest.ts
public/app/plugins/datasource/influxdb/specs/datasource.jest.ts
import InfluxDatasource from '../datasource'; import $q from 'q'; import { TemplateSrvStub } from 'test/specs/helpers'; describe('InfluxDataSource', () => { let ctx: any = { backendSrv: {}, $q: $q, templateSrv: new TemplateSrvStub(), instanceSettings: { url: 'url', name: 'influxDb', jsonData: {} }, }; beforeEach(function() { ctx.instanceSettings.url = '/api/datasources/proxy/1'; ctx.ds = new InfluxDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); }); describe('When issuing metricFindQuery', () => { let query = 'SELECT max(value) FROM measurement WHERE $timeFilter'; let queryOptions: any = { range: { from: '2018-01-01 00:00:00', to: '2018-01-02 00:00:00', }, }; let requestQuery; beforeEach(async () => { ctx.backendSrv.datasourceRequest = function(req) { requestQuery = req.params.q; return ctx.$q.when({ results: [ { series: [ { name: 'measurement', columns: ['max'], values: [[1]], }, ], }, ], }); }; await ctx.ds.metricFindQuery(query, queryOptions).then(function(_) {}); }); it('should replace $timefilter', () => { expect(requestQuery).toMatch('time >= 1514761200000ms and time <= 1514847600000ms'); }); }); });
Add unit test for InfluxDB datasource
Add unit test for InfluxDB datasource
TypeScript
agpl-3.0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
--- +++ @@ -0,0 +1,53 @@ +import InfluxDatasource from '../datasource'; +import $q from 'q'; +import { TemplateSrvStub } from 'test/specs/helpers'; + +describe('InfluxDataSource', () => { + let ctx: any = { + backendSrv: {}, + $q: $q, + templateSrv: new TemplateSrvStub(), + instanceSettings: { url: 'url', name: 'influxDb', jsonData: {} }, + }; + + beforeEach(function() { + ctx.instanceSettings.url = '/api/datasources/proxy/1'; + ctx.ds = new InfluxDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); + }); + + describe('When issuing metricFindQuery', () => { + let query = 'SELECT max(value) FROM measurement WHERE $timeFilter'; + let queryOptions: any = { + range: { + from: '2018-01-01 00:00:00', + to: '2018-01-02 00:00:00', + }, + }; + let requestQuery; + + beforeEach(async () => { + ctx.backendSrv.datasourceRequest = function(req) { + requestQuery = req.params.q; + return ctx.$q.when({ + results: [ + { + series: [ + { + name: 'measurement', + columns: ['max'], + values: [[1]], + }, + ], + }, + ], + }); + }; + + await ctx.ds.metricFindQuery(query, queryOptions).then(function(_) {}); + }); + + it('should replace $timefilter', () => { + expect(requestQuery).toMatch('time >= 1514761200000ms and time <= 1514847600000ms'); + }); + }); +});
8d8ed5e2ed383bda78866593b116e947a71732e5
desktop/app/src/ui/components/__tests__/ToolbarIcon.node.tsx
desktop/app/src/ui/components/__tests__/ToolbarIcon.node.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import {render, fireEvent} from '@testing-library/react'; import ToolbarIcon from '../ToolbarIcon'; import TooltipProvider from '../TooltipProvider'; const TITLE_STRING = 'This is for testing'; test('rendering element icon without hovering', () => { const res = render( <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} />, ); expect(res.queryAllByText(TITLE_STRING).length).toBe(0); }); test('trigger active for coverage(?)', () => { const res = render( <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} />, ); res.rerender( <ToolbarIcon active title={TITLE_STRING} icon="target" onClick={() => {}} />, ); res.rerender( <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} />, ); }); test('test on hover and unhover', () => { const res = render( <TooltipProvider> <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} /> </TooltipProvider>, ); expect(res.queryAllByText(TITLE_STRING).length).toBe(0); const comp = res.container.firstChild?.childNodes[0]; expect(comp).not.toBeNull(); // hover fireEvent.mouseEnter(comp!); expect(res.queryAllByText(TITLE_STRING).length).toBe(1); // unhover fireEvent.mouseLeave(comp!); expect(res.queryAllByText(TITLE_STRING).length).toBe(0); }); test('test on click', () => { const mockOnClick = jest.fn(() => {}); const res = render( <TooltipProvider> <ToolbarIcon title={TITLE_STRING} icon="target" onClick={mockOnClick} /> </TooltipProvider>, ); const comp = res.container.firstChild?.childNodes[0]; expect(comp).not.toBeNull(); // click fireEvent.click(comp!); expect(mockOnClick.mock.calls.length).toBe(1); });
Add Unit Test to ToolbarIcon
Add Unit Test to ToolbarIcon Summary: per title Reviewed By: mweststrate Differential Revision: D21663253 fbshipit-source-id: de1eff5a3500473082973a27d0b72479407cbebe
TypeScript
mit
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
--- +++ @@ -0,0 +1,74 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import React from 'react'; +import {render, fireEvent} from '@testing-library/react'; + +import ToolbarIcon from '../ToolbarIcon'; +import TooltipProvider from '../TooltipProvider'; + +const TITLE_STRING = 'This is for testing'; + +test('rendering element icon without hovering', () => { + const res = render( + <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} />, + ); + expect(res.queryAllByText(TITLE_STRING).length).toBe(0); +}); + +test('trigger active for coverage(?)', () => { + const res = render( + <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} />, + ); + res.rerender( + <ToolbarIcon + active + title={TITLE_STRING} + icon="target" + onClick={() => {}} + />, + ); + res.rerender( + <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} />, + ); +}); + +test('test on hover and unhover', () => { + const res = render( + <TooltipProvider> + <ToolbarIcon title={TITLE_STRING} icon="target" onClick={() => {}} /> + </TooltipProvider>, + ); + expect(res.queryAllByText(TITLE_STRING).length).toBe(0); + + const comp = res.container.firstChild?.childNodes[0]; + expect(comp).not.toBeNull(); + + // hover + fireEvent.mouseEnter(comp!); + expect(res.queryAllByText(TITLE_STRING).length).toBe(1); + // unhover + fireEvent.mouseLeave(comp!); + expect(res.queryAllByText(TITLE_STRING).length).toBe(0); +}); + +test('test on click', () => { + const mockOnClick = jest.fn(() => {}); + const res = render( + <TooltipProvider> + <ToolbarIcon title={TITLE_STRING} icon="target" onClick={mockOnClick} /> + </TooltipProvider>, + ); + const comp = res.container.firstChild?.childNodes[0]; + expect(comp).not.toBeNull(); + + // click + fireEvent.click(comp!); + expect(mockOnClick.mock.calls.length).toBe(1); +});
7a02938e5bdb3566e8777a258f084b94b4000286
src/Zombie.ts
src/Zombie.ts
module Lowrezjam { export class Zombie extends Phaser.Sprite { game: Lowrezjam.Game; constructor() { this.game = window["game"]; super(this.game, 1, 1, 'player'); this.game.add.existing(this); this.smoothed = false; this.scale.x = this.game.gameScale; this.scale.y = this.game.gameScale; } } }
Add zombie, copied from player.
Add zombie, copied from player.
TypeScript
mit
bbqcode/lowrezjam-2014,bbqcode/lowrezjam-2014
--- +++ @@ -0,0 +1,19 @@ +module Lowrezjam { + + export class Zombie extends Phaser.Sprite { + game: Lowrezjam.Game; + + + constructor() { + this.game = window["game"]; + super(this.game, 1, 1, 'player'); + this.game.add.existing(this); + this.smoothed = false; + + this.scale.x = this.game.gameScale; + this.scale.y = this.game.gameScale; + + } + } + +}
580245e33060fb3c93a0bf16c34ec3318bf06fa2
src/app/shared/mrs.service.spec.ts
src/app/shared/mrs.service.spec.ts
'use strict'; import { it, describe, expect, inject, beforeEachProviders, beforeEach, fakeAsync, tick } from '@angular/core/testing'; import { MRSService } from './mrs.service'; import { StorageService } from './storage.service'; describe('MRS Service', () => { beforeEachProviders(() => [ StorageService, MRSService ]); beforeEach(inject([StorageService], (storageService: StorageService) => { storageService.initStorage(); })); describe('userHasCollection', () => { it('should be false at first', inject([MRSService], (mrsService: MRSService) => { expect(mrsService.userHasCollection).toBe(false); })); it('should be true if user has 1 or more comics', inject([MRSService], fakeAsync((mrsService: MRSService) => { mrsService.addComic({id: 'test'}); tick(); expect(mrsService.userHasCollection).toBe(true); }))); it('should be false if user delete all his comics', inject([MRSService], fakeAsync((mrsService: MRSService) => { mrsService.addComic({id: 'test'}); expect(mrsService.userHasCollection).toBe(true); mrsService.removeComic({id: 'test'}); expect(mrsService.userHasCollection).toBe(false); tick(); }))); }); describe('addComic', () => { it('should add a comic to storage', inject([MRSService, StorageService], fakeAsync((mrsService: MRSService, storageService: StorageService) => { let counter; storageService.initStorage(); mrsService.userData.subscribe(data => counter = data.comics.size); expect(counter).toBe(0); mrsService.addComic({id: 'test'}); expect(counter).toBe(1); tick(); }))); }); describe('removeComic', () => { it('should remove a comic from storage', inject([MRSService, StorageService], fakeAsync((mrsService: MRSService, storageService: StorageService) => { let counter; storageService.initStorage(); mrsService.userData.subscribe(data => counter = data.comics.size); mrsService.addComic({id: 'test'}); expect(counter).toBe(1); mrsService.removeComic({id: 'test'}); expect(counter).toBe(0); tick(); }))); }); });
Add unit tests for MRS Service
Add unit tests for MRS Service
TypeScript
mit
SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend
--- +++ @@ -0,0 +1,78 @@ +'use strict'; + +import { + it, + describe, + expect, + inject, + beforeEachProviders, + beforeEach, + fakeAsync, + tick +} from '@angular/core/testing'; + +import { MRSService } from './mrs.service'; +import { StorageService } from './storage.service'; + +describe('MRS Service', () => { + + beforeEachProviders(() => [ + StorageService, + MRSService + ]); + + beforeEach(inject([StorageService], (storageService: StorageService) => { + storageService.initStorage(); + })); + + describe('userHasCollection', () => { + it('should be false at first', + inject([MRSService], (mrsService: MRSService) => { + expect(mrsService.userHasCollection).toBe(false); + })); + + it('should be true if user has 1 or more comics', + inject([MRSService], fakeAsync((mrsService: MRSService) => { + mrsService.addComic({id: 'test'}); + tick(); + expect(mrsService.userHasCollection).toBe(true); + }))); + + it('should be false if user delete all his comics', + inject([MRSService], fakeAsync((mrsService: MRSService) => { + mrsService.addComic({id: 'test'}); + expect(mrsService.userHasCollection).toBe(true); + mrsService.removeComic({id: 'test'}); + expect(mrsService.userHasCollection).toBe(false); + tick(); + }))); + }); + + describe('addComic', () => { + it('should add a comic to storage', + inject([MRSService, StorageService], fakeAsync((mrsService: MRSService, storageService: StorageService) => { + let counter; + storageService.initStorage(); + mrsService.userData.subscribe(data => counter = data.comics.size); + expect(counter).toBe(0); + mrsService.addComic({id: 'test'}); + expect(counter).toBe(1); + tick(); + }))); + }); + + describe('removeComic', () => { + it('should remove a comic from storage', + inject([MRSService, StorageService], fakeAsync((mrsService: MRSService, storageService: StorageService) => { + let counter; + storageService.initStorage(); + mrsService.userData.subscribe(data => counter = data.comics.size); + mrsService.addComic({id: 'test'}); + expect(counter).toBe(1); + mrsService.removeComic({id: 'test'}); + expect(counter).toBe(0); + tick(); + }))); + }); + +});
e5973b8daa325344cf55b4c2840dd235e5e4e4f4
tests/cases/fourslash/completionForStringLiteral4.ts
tests/cases/fourslash/completionForStringLiteral4.ts
/// <reference path='fourslash.ts'/> // @allowJs: true // @Filename: in.js /////** I am documentation //// * @param {'literal'} p1 //// * @param {"literal"} p2 //// * @param {'other1' | 'other2'} p3 //// * @param {'literal' | number} p4 //// */ ////function f(p1, p2, p3, p4) { //// return p1 + p2 + p3 + p4 + '.'; ////} ////f/*1*/('literal', 'literal', "o/*2*/ther1", 12); goTo.marker('1'); verify.quickInfoExists(); verify.quickInfoIs('function f(p1: "literal", p2: "literal", p3: "other1" | "other2", p4: "literal" | number): string', 'I am documentation'); goTo.marker('2'); verify.completionListContains("other1"); verify.completionListContains("other2"); verify.memberListCount(2);
Add string-literal completion test for jsdoc
Add string-literal completion test for jsdoc
TypeScript
apache-2.0
chuckjaz/TypeScript,weswigham/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,synaptek/TypeScript,erikmcc/TypeScript,mihailik/TypeScript,synaptek/TypeScript,thr0w/Thr0wScript,Eyas/TypeScript,minestarks/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,erikmcc/TypeScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,DLehenbauer/TypeScript,jeremyepling/TypeScript,chuckjaz/TypeScript,DLehenbauer/TypeScript,vilic/TypeScript,vilic/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,kitsonk/TypeScript,thr0w/Thr0wScript,kpreisser/TypeScript,DLehenbauer/TypeScript,basarat/TypeScript,mihailik/TypeScript,mihailik/TypeScript,vilic/TypeScript,Eyas/TypeScript,jwbay/TypeScript,minestarks/TypeScript,jeremyepling/TypeScript,DLehenbauer/TypeScript,SaschaNaz/TypeScript,TukekeSoft/TypeScript,minestarks/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,nojvek/TypeScript,Microsoft/TypeScript,jwbay/TypeScript,RyanCavanaugh/TypeScript,erikmcc/TypeScript,Eyas/TypeScript,vilic/TypeScript,RyanCavanaugh/TypeScript,weswigham/TypeScript,mihailik/TypeScript,Microsoft/TypeScript,basarat/TypeScript,jeremyepling/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,thr0w/Thr0wScript,alexeagle/TypeScript,basarat/TypeScript,weswigham/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,thr0w/Thr0wScript,TukekeSoft/TypeScript,microsoft/TypeScript,chuckjaz/TypeScript,basarat/TypeScript,synaptek/TypeScript,kpreisser/TypeScript,erikmcc/TypeScript,chuckjaz/TypeScript,Eyas/TypeScript,microsoft/TypeScript,TukekeSoft/TypeScript,donaldpipowitch/TypeScript,alexeagle/TypeScript,alexeagle/TypeScript,jwbay/TypeScript,jwbay/TypeScript,synaptek/TypeScript
--- +++ @@ -0,0 +1,22 @@ +/// <reference path='fourslash.ts'/> +// @allowJs: true +// @Filename: in.js +/////** I am documentation +//// * @param {'literal'} p1 +//// * @param {"literal"} p2 +//// * @param {'other1' | 'other2'} p3 +//// * @param {'literal' | number} p4 +//// */ +////function f(p1, p2, p3, p4) { +//// return p1 + p2 + p3 + p4 + '.'; +////} +////f/*1*/('literal', 'literal', "o/*2*/ther1", 12); + +goTo.marker('1'); +verify.quickInfoExists(); +verify.quickInfoIs('function f(p1: "literal", p2: "literal", p3: "other1" | "other2", p4: "literal" | number): string', 'I am documentation'); + +goTo.marker('2'); +verify.completionListContains("other1"); +verify.completionListContains("other2"); +verify.memberListCount(2);
7cfe7f8a0aaf5e3c1d42d5ca7766c1e3a0983780
lib/item_store_test.ts
lib/item_store_test.ts
import item_store = require('./item_store'); import testLib = require('./test'); testLib.addTest('default item properties', (assert) => { var item = new item_store.Item(); assert.notEqual(item.uuid.match(/^[0-9A-F]{32}$/), null); assert.ok(!item.isSaved()); assert.equal(item.primaryLocation(), ''); }); testLib.addAsyncTest('default item content', (assert) => { var item = new item_store.Item(); return item.getContent().then((content) => { assert.equal(content.urls.length, 0); assert.equal(content.sections.length, 0); assert.equal(content.formFields.length, 0); }); });
Add basic test case for default item_store.Item properties
Add basic test case for default item_store.Item properties
TypeScript
bsd-3-clause
robertknight/passcards,robertknight/passcards,robertknight/passcards,robertknight/passcards
--- +++ @@ -0,0 +1,19 @@ +import item_store = require('./item_store'); +import testLib = require('./test'); + +testLib.addTest('default item properties', (assert) => { + var item = new item_store.Item(); + assert.notEqual(item.uuid.match(/^[0-9A-F]{32}$/), null); + assert.ok(!item.isSaved()); + assert.equal(item.primaryLocation(), ''); +}); + +testLib.addAsyncTest('default item content', (assert) => { + var item = new item_store.Item(); + return item.getContent().then((content) => { + assert.equal(content.urls.length, 0); + assert.equal(content.sections.length, 0); + assert.equal(content.formFields.length, 0); + }); +}); +
2af7ccae6b0aff481100609dfd09f4a7776fab49
saleor/static/dashboard-next/components/DebounceForm.tsx
saleor/static/dashboard-next/components/DebounceForm.tsx
import * as React from "react"; import Debounce from "./Debounce"; export interface DebounceFormProps { change: (event: React.ChangeEvent<any>) => void; children: (( props: (event: React.ChangeEvent<any>) => void ) => React.ReactNode); submit: (event: React.FormEvent<any>) => void; time?: number; } export const DebounceForm: React.StatelessComponent<DebounceFormProps> = ({ change, children, submit, time }) => ( <Debounce debounceFn={submit} time={time}> {debounceFn => children(event => { change(event); debounceFn(); }) } </Debounce> );
import * as React from "react"; import Debounce from "./Debounce"; export interface DebounceFormProps { change: (event: React.ChangeEvent<any>, cb?: () => void) => void; children: (( props: (event: React.ChangeEvent<any>) => void ) => React.ReactNode); submit: (event: React.FormEvent<any>) => void; time?: number; } export const DebounceForm: React.StatelessComponent<DebounceFormProps> = ({ change, children, submit, time }) => ( <Debounce debounceFn={submit} time={time}> {debounceFn => children(event => { change(event, debounceFn); }) } </Debounce> );
Use callback after form's setState
Use callback after form's setState
TypeScript
bsd-3-clause
UITools/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor
--- +++ @@ -2,7 +2,7 @@ import Debounce from "./Debounce"; export interface DebounceFormProps { - change: (event: React.ChangeEvent<any>) => void; + change: (event: React.ChangeEvent<any>, cb?: () => void) => void; children: (( props: (event: React.ChangeEvent<any>) => void ) => React.ReactNode); @@ -19,8 +19,7 @@ <Debounce debounceFn={submit} time={time}> {debounceFn => children(event => { - change(event); - debounceFn(); + change(event, debounceFn); }) } </Debounce>
da208c9e6da278ce358bdb779fbfbfe727367143
data_structures/Queue/ts/queue.ts
data_structures/Queue/ts/queue.ts
interface Queue<T> { readonly length: number; enqueue(value: T): number; dequeue(): T | undefined; peek(): T | undefined; isEmpty(): boolean; [Symbol.iterator](): IterableIterator<T>; } class QueueImpl<T> implements Queue<T> { private _store: Array<T> = []; get length(): number { return this._store.length; } public enqueue(value: T): number { this._store.push(value); return this._store.length; } public dequeue(): T | undefined { if (this.isEmpty()) return undefined; return this._store.shift(); } public peek(): T | undefined { if (this.isEmpty()) return undefined; return this._store[0]; } public isEmpty() { return this._store.length === 0; } public next(): IteratorResult<T> { if (!this.isEmpty()) { return { done: false, value: this.dequeue() as any as T } } return { done: true, value: undefined }; } [Symbol.iterator](): IterableIterator<T> { return this; } } let testQueue: Queue<number> = new QueueImpl(); console.log(`The queue is currently ${testQueue.length} items long`); testQueue.enqueue(3); testQueue.enqueue(4); testQueue.enqueue(5); console.log(`The queue is currently ${testQueue.length} items long`); console.log('\nThe items in the queue are:'); for (let item of testQueue) { console.log(item); } console.log(`\nThe queue is now ${testQueue.isEmpty() ? "empty" : "not empty"}`);
Add implementation of Queue in TypeScript
Add implementation of Queue in TypeScript
TypeScript
cc0-1.0
ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms
--- +++ @@ -0,0 +1,63 @@ +interface Queue<T> { + readonly length: number; + enqueue(value: T): number; + dequeue(): T | undefined; + peek(): T | undefined; + isEmpty(): boolean; + [Symbol.iterator](): IterableIterator<T>; +} + +class QueueImpl<T> implements Queue<T> { + private _store: Array<T> = []; + + get length(): number { + return this._store.length; + } + + public enqueue(value: T): number { + this._store.push(value); + + return this._store.length; + } + + public dequeue(): T | undefined { + if (this.isEmpty()) return undefined; + + return this._store.shift(); + } + + public peek(): T | undefined { + if (this.isEmpty()) return undefined; + + return this._store[0]; + } + + public isEmpty() { + return this._store.length === 0; + } + + public next(): IteratorResult<T> { + + if (!this.isEmpty()) { + return { done: false, value: this.dequeue() as any as T } + } + + return { done: true, value: undefined }; + } + + [Symbol.iterator](): IterableIterator<T> { + return this; + } +} + +let testQueue: Queue<number> = new QueueImpl(); +console.log(`The queue is currently ${testQueue.length} items long`); +testQueue.enqueue(3); +testQueue.enqueue(4); +testQueue.enqueue(5); +console.log(`The queue is currently ${testQueue.length} items long`); +console.log('\nThe items in the queue are:'); +for (let item of testQueue) { + console.log(item); +} +console.log(`\nThe queue is now ${testQueue.isEmpty() ? "empty" : "not empty"}`);
d9fbf2fe9e0c2be51976539b393302729f15c58a
application/confagrid-frontend/src/main/frontend/root/modules/main/models/mex/word-grid-update-request.ts
application/confagrid-frontend/src/main/frontend/root/modules/main/models/mex/word-grid-update-request.ts
/* * word-grid-update-request.ts * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ import { BaseRequest } from './base-request'; export interface WordGridUpdateRequest extends BaseRequest { id: string; phrase: string; }
Add simple update request for adding phrase to word-grid
Add simple update request for adding phrase to word-grid
TypeScript
mit
ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid
--- +++ @@ -0,0 +1,15 @@ +/* + * word-grid-update-request.ts + * + * Copyright (C) 2018 [ A Legge Up ] + * + * This software may be modified and distributed under the terms + * of the MIT license. See the LICENSE file for details. + */ + +import { BaseRequest } from './base-request'; + +export interface WordGridUpdateRequest extends BaseRequest { + id: string; + phrase: string; +}
e5261df82d291449d95de3d9de6a914e2bae4bc9
src/Parsing/Outline/ParseInlineOnlyIfParagraph.ts
src/Parsing/Outline/ParseInlineOnlyIfParagraph.ts
import { TextConsumer } from '../TextConsumer' import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode' import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode' import { getOutlineNodes } from './GetOutlineNodes' import { NON_BLANK } from './Patterns' import { OutlineParser, OutlineParserArgs, } from './OutlineParser' interface ParseInlineOnlyIfParagraphArgs { text: string, then: OnSuccess } interface OnSuccess { (resultNodes: SyntaxNode[]): void } const NON_BLANK_PATTERN = new RegExp( NON_BLANK ) // `parseInlineOnlyIfParagraph` only succeeds if the text would otherwise be parsed as a plain paragraph. // // The following three inputs would fail: // // 1) Buy milk // // =-=-=-=-=-= // // * Drink milk export function parseInlineOnlyIfParagraph(args: ParseInlineOnlyIfParagraphArgs): boolean { const outlineNodeFromContent = getOutlineNodes(args.text)[0] if (outlineNodeFromContent instanceof ParagraphNode) { args.then(outlineNodeFromContent.children) return true } return false }
Add helper for excluding fancy outline lines
Add helper for excluding fancy outline lines
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,39 @@ +import { TextConsumer } from '../TextConsumer' +import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode' +import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode' +import { getOutlineNodes } from './GetOutlineNodes' +import { NON_BLANK } from './Patterns' +import { OutlineParser, OutlineParserArgs, } from './OutlineParser' + +interface ParseInlineOnlyIfParagraphArgs { + text: string, + then: OnSuccess +} + +interface OnSuccess { + (resultNodes: SyntaxNode[]): void +} + +const NON_BLANK_PATTERN = new RegExp( + NON_BLANK +) + +// `parseInlineOnlyIfParagraph` only succeeds if the text would otherwise be parsed as a plain paragraph. +// +// The following three inputs would fail: +// +// 1) Buy milk +// +// =-=-=-=-=-= +// +// * Drink milk +export function parseInlineOnlyIfParagraph(args: ParseInlineOnlyIfParagraphArgs): boolean { + const outlineNodeFromContent = getOutlineNodes(args.text)[0] + + if (outlineNodeFromContent instanceof ParagraphNode) { + args.then(outlineNodeFromContent.children) + return true + } + + return false +}
4b2cf4df1a1d1cef2fe14b9a48d8529f331185cc
src/utils/outputSvg.ts
src/utils/outputSvg.ts
import { select } from 'd3-selection'; export type TOutputType = 'png' | 'blob'; // Method to combine an svg specified by id with the InfoSum watermark and // produce a blob or png output that can be used for download export const outputSvg = ( svgId: string, width: number, height: number, callback: (outpuData: string | Blob | null) => void, type: TOutputType = 'blob', ) => { // Select the first svg element const svg: any = select(`svg#${svgId}`); const serializer = new XMLSerializer(); // generate IMG in new tab const svgStr = serializer.serializeToString(svg.node()); const watermark = require('../assets/Powered-By-InfoSum_DARK.svg') as string; const svgData = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgStr))); // create canvas in memory(not in DOM) const canvas = document.createElement('canvas'); // set canvas size canvas.width = width + 200; canvas.height = height; // get canvas context for drawing on canvas const context = canvas.getContext('2d'); // create images in memory(not DOM) var image = new Image(); const watermarkImage = new Image(); // when watermark loaded create main image watermarkImage.onload = () => { // later when image loads run this image.onload = () => { // clear canvas context!.clearRect(0, 0, width + 20, height + 20); // draw image with SVG data to canvas context!.drawImage(image, 0, 0, width, height); context!.drawImage(watermarkImage, canvas.width - 200, 0, 200, 62); // add a background context!.globalCompositeOperation = 'destination-over' context!.fillStyle = "#FFF"; context!.fillRect(0, 0, canvas.width, canvas.height); // snapshot canvas as png or blob depending on type if (type === 'blob') { canvas.toBlob(callback); } else if (type === 'png') { const pngData = canvas.toDataURL('image/png'); callback(pngData); } }; // start loading SVG data into in memory image image.src = svgData; } // start loading watermark SVG data into memory watermarkImage.src = watermark; }; /* Alternate method for downloading image in new tab kept for reference const downloadImage = (pngData) => { let w = window.open('about:blank'); let image = new Image(); image.src = pngData; setTimeout(function () { w!.document.write(image.outerHTML); }, 0); } */
Add svgOutput utility to combine svgs and output to blob or png
Add svgOutput utility to combine svgs and output to blob or png
TypeScript
mit
cognitivelogic/cl-react-graph,cognitivelogic/cl-react-graph,cognitivelogic/cl-react-graph
--- +++ @@ -0,0 +1,67 @@ +import { select } from 'd3-selection'; + +export type TOutputType = 'png' | 'blob'; + +// Method to combine an svg specified by id with the InfoSum watermark and +// produce a blob or png output that can be used for download +export const outputSvg = ( + svgId: string, + width: number, + height: number, + callback: (outpuData: string | Blob | null) => void, + type: TOutputType = 'blob', +) => { + // Select the first svg element + const svg: any = select(`svg#${svgId}`); + const serializer = new XMLSerializer(); + // generate IMG in new tab + const svgStr = serializer.serializeToString(svg.node()); + const watermark = require('../assets/Powered-By-InfoSum_DARK.svg') as string; + const svgData = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgStr))); + // create canvas in memory(not in DOM) + const canvas = document.createElement('canvas'); + // set canvas size + canvas.width = width + 200; + canvas.height = height; + // get canvas context for drawing on canvas + const context = canvas.getContext('2d'); + // create images in memory(not DOM) + var image = new Image(); + const watermarkImage = new Image(); + // when watermark loaded create main image + watermarkImage.onload = () => { + // later when image loads run this + image.onload = () => { + // clear canvas + context!.clearRect(0, 0, width + 20, height + 20); + // draw image with SVG data to canvas + context!.drawImage(image, 0, 0, width, height); + context!.drawImage(watermarkImage, canvas.width - 200, 0, 200, 62); + // add a background + context!.globalCompositeOperation = 'destination-over' + context!.fillStyle = "#FFF"; + context!.fillRect(0, 0, canvas.width, canvas.height); + // snapshot canvas as png or blob depending on type + if (type === 'blob') { + canvas.toBlob(callback); + } else if (type === 'png') { + const pngData = canvas.toDataURL('image/png'); + callback(pngData); + } + }; + // start loading SVG data into in memory image + image.src = svgData; + } + // start loading watermark SVG data into memory + watermarkImage.src = watermark; +}; +/* Alternate method for downloading image in new tab kept for reference +const downloadImage = (pngData) => { + let w = window.open('about:blank'); + let image = new Image(); + image.src = pngData; + setTimeout(function () { + w!.document.write(image.outerHTML); + }, 0); +} +*/
dddc76b15675621d6996a45549f386a5a8630831
tests/cases/fourslash/quickInfoDisplayPartsTypeParameterInTypeAlias.ts
tests/cases/fourslash/quickInfoDisplayPartsTypeParameterInTypeAlias.ts
/// <reference path='fourslash.ts'/> ////type /*0*/List</*1*/T> = /*2*/T[] type L<T> = T[] let typeAliashDisplayParts = [{ text: "type", kind: "keyword" }, { text: " ", kind: "space" }, { text: "List", kind: "aliasName" }, { text: "<", kind: "punctuation" }, { text: "T", kind: "typeParameterName" }, { text: ">", kind: "punctuation" }]; let typeParameterDisplayParts = [{ text: "(", kind: "punctuation" }, { text: "type parameter", kind: "text" }, { text: ")", kind: "punctuation" }, { text: " ", kind: "space" }, { text: "T", kind: "typeParameterName" }, { text: " ", kind: "space" }, { text: "in", kind: "keyword" }, { text: " ", kind: "space" } ] goTo.marker('0'); verify.verifyQuickInfoDisplayParts("type", "", { start: test.markerByName("0").position, length: "List".length }, typeAliashDisplayParts.concat([{ text: " ", kind: "space" }, { text: "=", kind: "operator" }, { "text": " ", "kind": "space" }, { text: "T", kind: "typeParameterName" }, { text: "[", kind: "punctuation" }, { text: "]", kind: "punctuation" }]), []); goTo.marker('1'); verify.verifyQuickInfoDisplayParts("type parameter", "", { start: test.markerByName("1").position, length: "T".length }, typeParameterDisplayParts.concat(typeAliashDisplayParts), []); goTo.marker('2'); verify.verifyQuickInfoDisplayParts("type parameter", "", { start: test.markerByName("2").position, length: "T".length }, typeParameterDisplayParts.concat(typeAliashDisplayParts), []);
Add quick info test for type parameter in type alias
Add quick info test for type parameter in type alias
TypeScript
apache-2.0
Mqgh2013/TypeScript,kimamula/TypeScript,DanielRosenwasser/TypeScript,fabioparra/TypeScript,Eyas/TypeScript,kimamula/TypeScript,fabioparra/TypeScript,nojvek/TypeScript,mcanthony/TypeScript,evgrud/TypeScript,chuckjaz/TypeScript,mmoskal/TypeScript,basarat/TypeScript,nojvek/TypeScript,moander/TypeScript,kimamula/TypeScript,ionux/TypeScript,DanielRosenwasser/TypeScript,blakeembrey/TypeScript,germ13/TypeScript,mihailik/TypeScript,weswigham/TypeScript,jbondc/TypeScript,kitsonk/TypeScript,mmoskal/TypeScript,microsoft/TypeScript,jwbay/TypeScript,nycdotnet/TypeScript,kitsonk/TypeScript,SmallAiTT/TypeScript,basarat/TypeScript,bpowers/TypeScript,suto/TypeScript,JohnZ622/TypeScript,moander/TypeScript,SmallAiTT/TypeScript,nycdotnet/TypeScript,OlegDokuka/TypeScript,alexeagle/TypeScript,suto/TypeScript,suto/TypeScript,SimoneGianni/TypeScript,mszczepaniak/TypeScript,nagyistoce/TypeScript,microsoft/TypeScript,vilic/TypeScript,mszczepaniak/TypeScript,shanexu/TypeScript,erikmcc/TypeScript,MartyIX/TypeScript,mszczepaniak/TypeScript,fearthecowboy/TypeScript,donaldpipowitch/TypeScript,germ13/TypeScript,samuelhorwitz/typescript,evgrud/TypeScript,jeremyepling/TypeScript,TukekeSoft/TypeScript,yortus/TypeScript,JohnZ622/TypeScript,enginekit/TypeScript,ionux/TypeScript,plantain-00/TypeScript,tempbottle/TypeScript,progre/TypeScript,rodrigues-daniel/TypeScript,tempbottle/TypeScript,AbubakerB/TypeScript,progre/TypeScript,shanexu/TypeScript,enginekit/TypeScript,jwbay/TypeScript,donaldpipowitch/TypeScript,OlegDokuka/TypeScript,rodrigues-daniel/TypeScript,chuckjaz/TypeScript,weswigham/TypeScript,shovon/TypeScript,Microsoft/TypeScript,jwbay/TypeScript,thr0w/Thr0wScript,DLehenbauer/TypeScript,jeremyepling/TypeScript,mcanthony/TypeScript,moander/TypeScript,hoanhtien/TypeScript,hitesh97/TypeScript,DLehenbauer/TypeScript,nagyistoce/TypeScript,basarat/TypeScript,evgrud/TypeScript,impinball/TypeScript,enginekit/TypeScript,ziacik/TypeScript,DLehenbauer/TypeScript,fearthecowboy/TypeScript,shovon/TypeScript,impinball/TypeScript,DLehenbauer/TypeScript,DanielRosenwasser/TypeScript,synaptek/TypeScript,shovon/TypeScript,sassson/TypeScript,erikmcc/TypeScript,samuelhorwitz/typescript,vilic/TypeScript,SaschaNaz/TypeScript,tempbottle/TypeScript,Eyas/TypeScript,rodrigues-daniel/TypeScript,kimamula/TypeScript,progre/TypeScript,SimoneGianni/TypeScript,bpowers/TypeScript,thr0w/Thr0wScript,MartyIX/TypeScript,weswigham/TypeScript,thr0w/Thr0wScript,Eyas/TypeScript,Microsoft/TypeScript,gonifade/TypeScript,plantain-00/TypeScript,kpreisser/TypeScript,fabioparra/TypeScript,Viromo/TypeScript,ziacik/TypeScript,jbondc/TypeScript,donaldpipowitch/TypeScript,yortus/TypeScript,AbubakerB/TypeScript,mmoskal/TypeScript,erikmcc/TypeScript,Viromo/TypeScript,hoanhtien/TypeScript,impinball/TypeScript,fearthecowboy/TypeScript,yortus/TypeScript,Microsoft/TypeScript,microsoft/TypeScript,samuelhorwitz/typescript,JohnZ622/TypeScript,ziacik/TypeScript,mihailik/TypeScript,blakeembrey/TypeScript,blakeembrey/TypeScript,vilic/TypeScript,RyanCavanaugh/TypeScript,gonifade/TypeScript,SaschaNaz/TypeScript,hitesh97/TypeScript,alexeagle/TypeScript,synaptek/TypeScript,plantain-00/TypeScript,gonifade/TypeScript,Eyas/TypeScript,shanexu/TypeScript,mihailik/TypeScript,thr0w/Thr0wScript,MartyIX/TypeScript,minestarks/TypeScript,vilic/TypeScript,yortus/TypeScript,Mqgh2013/TypeScript,plantain-00/TypeScript,donaldpipowitch/TypeScript,mihailik/TypeScript,ziacik/TypeScript,nycdotnet/TypeScript,sassson/TypeScript,MartyIX/TypeScript,basarat/TypeScript,blakeembrey/TypeScript,bpowers/TypeScript,synaptek/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,mmoskal/TypeScript,chuckjaz/TypeScript,ionux/TypeScript,nojvek/TypeScript,synaptek/TypeScript,shanexu/TypeScript,samuelhorwitz/typescript,moander/TypeScript,rodrigues-daniel/TypeScript,mcanthony/TypeScript,alexeagle/TypeScript,chuckjaz/TypeScript,kpreisser/TypeScript,nycdotnet/TypeScript,SmallAiTT/TypeScript,nagyistoce/TypeScript,TukekeSoft/TypeScript,jeremyepling/TypeScript,fabioparra/TypeScript,minestarks/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,jwbay/TypeScript,TukekeSoft/TypeScript,mcanthony/TypeScript,germ13/TypeScript,Mqgh2013/TypeScript,DanielRosenwasser/TypeScript,evgrud/TypeScript,JohnZ622/TypeScript,SimoneGianni/TypeScript,Viromo/TypeScript,ionux/TypeScript,hitesh97/TypeScript,kitsonk/TypeScript,AbubakerB/TypeScript,erikmcc/TypeScript,jbondc/TypeScript,RyanCavanaugh/TypeScript,hoanhtien/TypeScript,Viromo/TypeScript,OlegDokuka/TypeScript,AbubakerB/TypeScript,sassson/TypeScript
--- +++ @@ -0,0 +1,22 @@ +/// <reference path='fourslash.ts'/> + +////type /*0*/List</*1*/T> = /*2*/T[] + +type L<T> = T[] +let typeAliashDisplayParts = [{ text: "type", kind: "keyword" }, { text: " ", kind: "space" }, { text: "List", kind: "aliasName" }, + { text: "<", kind: "punctuation" }, { text: "T", kind: "typeParameterName" }, { text: ">", kind: "punctuation" }]; +let typeParameterDisplayParts = [{ text: "(", kind: "punctuation" }, { text: "type parameter", kind: "text" }, { text: ")", kind: "punctuation" }, { text: " ", kind: "space" }, + { text: "T", kind: "typeParameterName" }, { text: " ", kind: "space" }, { text: "in", kind: "keyword" }, { text: " ", kind: "space" } ] + +goTo.marker('0'); +verify.verifyQuickInfoDisplayParts("type", "", { start: test.markerByName("0").position, length: "List".length }, + typeAliashDisplayParts.concat([{ text: " ", kind: "space" }, { text: "=", kind: "operator" }, { "text": " ", "kind": "space" }, { text: "T", kind: "typeParameterName" }, + { text: "[", kind: "punctuation" }, { text: "]", kind: "punctuation" }]), []); + +goTo.marker('1'); +verify.verifyQuickInfoDisplayParts("type parameter", "", { start: test.markerByName("1").position, length: "T".length }, + typeParameterDisplayParts.concat(typeAliashDisplayParts), []); + +goTo.marker('2'); +verify.verifyQuickInfoDisplayParts("type parameter", "", { start: test.markerByName("2").position, length: "T".length }, + typeParameterDisplayParts.concat(typeAliashDisplayParts), []);
187332e26777bbd1e08c7c96c365c0b3e1f88482
src/channel-members-view.tsx
src/channel-members-view.tsx
// tslint:disable-next-line:no-unused-variable import * as React from 'react'; import { Api } from './lib/models/api-call'; import { UserViewModel, UserListItem } from './user-list-item'; import { CollectionView } from './lib/collection-view'; import { Model } from './lib/model'; import { Store } from './store'; export class ChannelMembersViewModel extends Model { constructor( public readonly store: Store, public readonly api: Api, public readonly members: Array<string> ) { super(); } } export class ChannelMembersView extends CollectionView<ChannelMembersViewModel, UserViewModel> { viewModelFactory(index: number) { return new UserViewModel( this.viewModel.store, this.viewModel.members[index], this.viewModel.api ); } renderItem(viewModel: UserViewModel) { return <UserListItem viewModel={viewModel} />; } rowCount() { return this.viewModel.members.length; } }
Add a ChannelMembersView that's just a collection of users.
Add a ChannelMembersView that's just a collection of users.
TypeScript
bsd-3-clause
paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline
--- +++ @@ -0,0 +1,36 @@ +// tslint:disable-next-line:no-unused-variable +import * as React from 'react'; + +import { Api } from './lib/models/api-call'; +import { UserViewModel, UserListItem } from './user-list-item'; +import { CollectionView } from './lib/collection-view'; +import { Model } from './lib/model'; +import { Store } from './store'; + +export class ChannelMembersViewModel extends Model { + constructor( + public readonly store: Store, + public readonly api: Api, + public readonly members: Array<string> + ) { + super(); + } +} + +export class ChannelMembersView extends CollectionView<ChannelMembersViewModel, UserViewModel> { + viewModelFactory(index: number) { + return new UserViewModel( + this.viewModel.store, + this.viewModel.members[index], + this.viewModel.api + ); + } + + renderItem(viewModel: UserViewModel) { + return <UserListItem viewModel={viewModel} />; + } + + rowCount() { + return this.viewModel.members.length; + } +}
e563a663d95e499ccdc03c615722d530c7c7a2db
test/routes/dslRouterTest.ts
test/routes/dslRouterTest.ts
import * as DSLRouter from "../../src/routes/dslRouter"; import * as express from "express"; import * as Chai from "chai"; /** * This is the test for DatabaseRouter class * * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | * * @author Emanuele Carraro * @copyright MIT * */ describe("DSLRouter", () => { /* nothing to test for now let toTest : DSLRouter; let dummyExpress : express.Express = express(); beforeEach(function () : void { toTest = new DSLRouter(dummyExpress); }); describe("#nameOfWhatYouAreTesting", () => { it ("should <say what it should do>", () => { // Your code here }); }); */ });
Add test file (to be implemented)
Add test file (to be implemented)
TypeScript
mit
BugBusterSWE/MaaS,BugBusterSWE/MaaS,BugBusterSWE/MaaS,BugBusterSWE/MaaS
--- +++ @@ -0,0 +1,32 @@ +import * as DSLRouter from "../../src/routes/dslRouter"; +import * as express from "express"; +import * as Chai from "chai"; + +/** + * This is the test for DatabaseRouter class + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | + * + * @author Emanuele Carraro + * @copyright MIT + * + */ +describe("DSLRouter", () => { + + /* nothing to test for now + let toTest : DSLRouter; + let dummyExpress : express.Express = express(); + beforeEach(function () : void { + toTest = new DSLRouter(dummyExpress); + }); + describe("#nameOfWhatYouAreTesting", () => { + it ("should <say what it should do>", () => { + // Your code here + }); + }); + */ + +});
aa0c43fed16b610195a351b8fab973d7b9575325
src/app/tech-list.ts
src/app/tech-list.ts
import { Tech } from './tech'; export const techs: Tech[] = [ { id: 1, name: 'Angular' }, { id: 2, name: 'EcmaScript' }, { id: 3, name: 'TypeScript' }, { id: 4, name: 'Java' }, { id: 5, name: 'Spring' }, { id: 6, name: 'JQuery' }, { id: 7, name: 'Node.js' }, { id: 8, name: 'Hibernate' }, { id: 9, name: 'Sass' }, { id: 10, name: 'Swift' } ];
Create a list of technologies.
Create a list of technologies.
TypeScript
mit
EtienneMiret/angular-quickstart,EtienneMiret/angular-quickstart,EtienneMiret/angular-quickstart
--- +++ @@ -0,0 +1,44 @@ +import { Tech } from './tech'; + +export const techs: Tech[] = [ + { + id: 1, + name: 'Angular' + }, + { + id: 2, + name: 'EcmaScript' + }, + { + id: 3, + name: 'TypeScript' + }, + { + id: 4, + name: 'Java' + }, + { + id: 5, + name: 'Spring' + }, + { + id: 6, + name: 'JQuery' + }, + { + id: 7, + name: 'Node.js' + }, + { + id: 8, + name: 'Hibernate' + }, + { + id: 9, + name: 'Sass' + }, + { + id: 10, + name: 'Swift' + } +];
8613f648bb75b234864c798064cbb93042263c7f
app/ui/pages/crumpet-page.ts
app/ui/pages/crumpet-page.ts
/** * Created by lthompson on 28/05/2016. */ import {Component} from "@angular/core"; import {AppStore} from "angular2-redux"; import {Crumpet} from "../../data/Crumpet"; import {Observable} from "rxjs/Rx"; import {CrumpetListView} from "../views/crumpet-list-view"; import {CrumpetActions} from "../../actions/crumpet-actions"; import {crumpetListSelector} from "../../reducers/crumpet-reducer"; @Component({ selector: "crumpet-page", directives: [CrumpetListView], providers: [CrumpetActions], template: `<TabView #tabView selectedIndex="0"> <StackLayout *tabItem="{title: 'Crumpets'}"> <crumpet-list-view [list]="(crumpetList$ | async)" (clicked)="clicked($event)"></crumpet-list-view> </StackLayout> <StackLayout *tabItem="{title: 'About'}"> <Label text="About"></Label> </StackLayout> </TabView> `, styles: [``] }) export class CrumpetPage { crumpetList$:Observable<Crumpet[]>; constructor(private crumpetActions:CrumpetActions, private appStore:AppStore) { this.crumpetList$ = appStore.select(crumpetListSelector); appStore.dispatch(crumpetActions.loadCrumpets()); } clicked(crumpet:Crumpet) { alert('Clicked on ' + crumpet.name); } }
Create a routable page view for the main application page, which hosts the crumpet list view and an about page.
Create a routable page view for the main application page, which hosts the crumpet list view and an about page.
TypeScript
unlicense
luketn/WonderCrumpet
--- +++ @@ -0,0 +1,39 @@ +/** + * Created by lthompson on 28/05/2016. + */ +import {Component} from "@angular/core"; +import {AppStore} from "angular2-redux"; +import {Crumpet} from "../../data/Crumpet"; +import {Observable} from "rxjs/Rx"; +import {CrumpetListView} from "../views/crumpet-list-view"; +import {CrumpetActions} from "../../actions/crumpet-actions"; +import {crumpetListSelector} from "../../reducers/crumpet-reducer"; + +@Component({ + selector: "crumpet-page", + directives: [CrumpetListView], + providers: [CrumpetActions], + template: `<TabView #tabView selectedIndex="0"> + <StackLayout *tabItem="{title: 'Crumpets'}"> + <crumpet-list-view [list]="(crumpetList$ | async)" (clicked)="clicked($event)"></crumpet-list-view> + </StackLayout> + <StackLayout *tabItem="{title: 'About'}"> + <Label text="About"></Label> + </StackLayout> + </TabView> + `, + styles: [``] +}) + +export class CrumpetPage { + crumpetList$:Observable<Crumpet[]>; + + constructor(private crumpetActions:CrumpetActions, private appStore:AppStore) { + this.crumpetList$ = appStore.select(crumpetListSelector); + appStore.dispatch(crumpetActions.loadCrumpets()); + } + + clicked(crumpet:Crumpet) { + alert('Clicked on ' + crumpet.name); + } +}
799b78488d95996a67837ace1baf88830d3456c8
saleor/static/dashboard-next/components/DateFormatter/DateProvider.tsx
saleor/static/dashboard-next/components/DateFormatter/DateProvider.tsx
import * as React from "react"; import { Provider } from "./DateContext"; interface DateProviderState { date: number; } export class DateProvider extends React.Component<{}, DateProviderState> { static contextTypes = {}; intervalId: number; state = { date: Date.now() }; componentDidMount() { this.intervalId = window.setInterval( () => this.setState({ date: Date.now() }), 60_000 ); } componentWillUnmount() { window.clearInterval(this.intervalId); } render() { const { children } = this.props; const { date } = this.state; return <Provider value={date}>{children}</Provider>; } }
import * as React from "react"; import { Provider } from "./DateContext"; interface DateProviderState { date: number; } export class DateProvider extends React.Component<{}, DateProviderState> { static contextTypes = {}; intervalId: number; state = { date: Date.now() }; componentDidMount() { this.intervalId = window.setInterval( () => this.setState({ date: Date.now() }), 10_000 ); } componentWillUnmount() { window.clearInterval(this.intervalId); } render() { const { children } = this.props; const { date } = this.state; return <Provider value={date}>{children}</Provider>; } }
Fix bug causing to display in a few seconds instead of few seconds ago
Fix bug causing to display in a few seconds instead of few seconds ago
TypeScript
bsd-3-clause
UITools/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,UITools/saleor
--- +++ @@ -18,7 +18,7 @@ componentDidMount() { this.intervalId = window.setInterval( () => this.setState({ date: Date.now() }), - 60_000 + 10_000 ); }
be2fb5c73379ff3dc7fb6924fa0c0f2fab4621ac
tests/DTMtest.ts
tests/DTMtest.ts
import "should"; import { parseNmeaSentence } from "../index"; describe("DTM", (): void => { it("parser", (): void => { const packet = parseNmeaSentence("$GNDTM,W84,,0.0,N,0.0,E,0.0,W84*71"); packet.should.have.property("sentenceId", "DTM"); packet.should.have.property("sentenceName", "Datum reference"); packet.should.have.property("talkerId", "GN"); packet.should.have.property("datumCode", "W84"); packet.should.have.property("datumSubcode", undefined); packet.should.have.property("offsetLatitude", 0); packet.should.have.property("offsetLongitude", 0); packet.should.have.property("offsetAltitudeMeters", 0); packet.should.have.property("datumName", "W84"); }); });
Add test for DTM packet decoding
Add test for DTM packet decoding
TypeScript
mit
101100/nmea-simple
--- +++ @@ -0,0 +1,22 @@ +import "should"; + +import { parseNmeaSentence } from "../index"; + + +describe("DTM", (): void => { + + it("parser", (): void => { + const packet = parseNmeaSentence("$GNDTM,W84,,0.0,N,0.0,E,0.0,W84*71"); + + packet.should.have.property("sentenceId", "DTM"); + packet.should.have.property("sentenceName", "Datum reference"); + packet.should.have.property("talkerId", "GN"); + packet.should.have.property("datumCode", "W84"); + packet.should.have.property("datumSubcode", undefined); + packet.should.have.property("offsetLatitude", 0); + packet.should.have.property("offsetLongitude", 0); + packet.should.have.property("offsetAltitudeMeters", 0); + packet.should.have.property("datumName", "W84"); + }); + +});
bd6674859cb23500fd24d4cfbdf5503aeef0c831
ui/test/kapacitor/components/KapacitorRulesTable.test.tsx
ui/test/kapacitor/components/KapacitorRulesTable.test.tsx
import React from 'react' import {shallow} from 'enzyme' import KapacitorRulesTable from 'src/kapacitor/components/KapacitorRulesTable' import {source, kapacitorRules} from 'test/resources' const setup = () => { const props = { source, rules: kapacitorRules, onDelete: () => {}, onChangeRuleStatus: () => {} } const wrapper = shallow(<KapacitorRulesTable {...props} />) return { wrapper, props } } describe('Kapacitor.Components.KapacitorRulesTable', () => { describe('rendering', () => { it('renders KapacitorRulesTable', () => { const {wrapper} = setup() expect(wrapper.exists()).toBe(true) }) }) })
import React from 'react' import {shallow} from 'enzyme' import {isUUIDv4} from 'src/utils/stringValidators' import KapacitorRulesTable from 'src/kapacitor/components/KapacitorRulesTable' import {source, kapacitorRules} from 'test/resources' const setup = () => { const props = { source, rules: kapacitorRules, onDelete: () => {}, onChangeRuleStatus: () => {}, } const wrapper = shallow(<KapacitorRulesTable {...props} />) return { wrapper, props, } } describe('Kapacitor.Components.KapacitorRulesTable', () => { describe('rendering', () => { it('renders KapacitorRulesTable', () => { const {wrapper} = setup() expect(wrapper.exists()).toBe(true) }) it('renders each row with key that is a UUIDv4', () => { const {wrapper} = setup() wrapper .find('tbody') .children() .forEach(child => expect(isUUIDv4(child.key())).toEqual(true)) }) }) })
Test KapacitorRulesTable tr keys to be UUIDv4
Test KapacitorRulesTable tr keys to be UUIDv4
TypeScript
mit
influxdb/influxdb,li-ang/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,influxdata/influxdb,influxdb/influxdb
--- +++ @@ -1,5 +1,7 @@ import React from 'react' import {shallow} from 'enzyme' + +import {isUUIDv4} from 'src/utils/stringValidators' import KapacitorRulesTable from 'src/kapacitor/components/KapacitorRulesTable' @@ -10,14 +12,14 @@ source, rules: kapacitorRules, onDelete: () => {}, - onChangeRuleStatus: () => {} + onChangeRuleStatus: () => {}, } const wrapper = shallow(<KapacitorRulesTable {...props} />) return { wrapper, - props + props, } } @@ -27,5 +29,13 @@ const {wrapper} = setup() expect(wrapper.exists()).toBe(true) }) + + it('renders each row with key that is a UUIDv4', () => { + const {wrapper} = setup() + wrapper + .find('tbody') + .children() + .forEach(child => expect(isUUIDv4(child.key())).toEqual(true)) + }) }) })
f75499a7cb363279a2cce55d5fb5296851092259
saleor/static/dashboard-next/components/Tab/Tab.tsx
saleor/static/dashboard-next/components/Tab/Tab.tsx
import { createStyles, Theme, withStyles, WithStyles } from "@material-ui/core/styles"; import Typography from "@material-ui/core/Typography"; import * as classNames from "classnames"; import * as React from "react"; const styles = (theme: Theme) => createStyles({ active: {}, root: { "&$active": { borderBottomColor: theme.palette.primary.main }, "&:focus": { color: "#5AB378" }, "&:hover": { color: "#5AB378" }, borderBottom: "1px solid transparent", cursor: "pointer", display: "inline-block", fontWeight: theme.typography.fontWeightRegular, marginRight: theme.spacing.unit * 4, minWidth: 40, transition: theme.transitions.duration.short + "ms" } }); interface TabProps<T> extends WithStyles<typeof styles> { children?: React.ReactNode; isActive: boolean; changeTab: (index: T) => void; } export function Tab<T>(value: T) { return withStyles(styles, { name: "Tab" })( ({ classes, children, isActive, changeTab }: TabProps<T>) => ( <Typography component="span" className={classNames({ [classes.root]: true, [classes.active]: isActive })} onClick={() => changeTab(value)} > {children} </Typography> ) ); } export default Tab;
import { createStyles, Theme, withStyles, WithStyles } from "@material-ui/core/styles"; import Typography from "@material-ui/core/Typography"; import * as classNames from "classnames"; import * as React from "react"; const styles = (theme: Theme) => createStyles({ active: {}, root: { "&$active": { borderBottomColor: theme.palette.primary.main }, "&:focus": { color: "#5AB378" }, "&:hover": { color: "#5AB378" }, borderBottom: "1px solid transparent", cursor: "pointer", display: "inline-block", fontWeight: theme.typography.fontWeightRegular, marginRight: theme.spacing.unit * 4, minWidth: 40, padding: `0 ${theme.spacing.unit}px`, transition: theme.transitions.duration.short + "ms" } }); interface TabProps<T> extends WithStyles<typeof styles> { children?: React.ReactNode; isActive: boolean; changeTab: (index: T) => void; } export function Tab<T>(value: T) { return withStyles(styles, { name: "Tab" })( ({ classes, children, isActive, changeTab }: TabProps<T>) => ( <Typography component="span" className={classNames({ [classes.root]: true, [classes.active]: isActive })} onClick={() => changeTab(value)} > {children} </Typography> ) ); } export default Tab;
Add some padding to tab
Add some padding to tab
TypeScript
bsd-3-clause
UITools/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,UITools/saleor
--- +++ @@ -27,6 +27,7 @@ fontWeight: theme.typography.fontWeightRegular, marginRight: theme.spacing.unit * 4, minWidth: 40, + padding: `0 ${theme.spacing.unit}px`, transition: theme.transitions.duration.short + "ms" } });
8435bb05c38fa9af4d84a277a9cc86eeaa3ea629
src/resources/MSATokenService.ts
src/resources/MSATokenService.ts
import * as request from "request"; export interface Token { token_type: string; expires_in: number; ext_expires_in: number; access_token: string; } interface CachedToken extends Token { expires_on: number; } let cachedToken: CachedToken; export function getBotframeworkToken(): Promise<Token> { return new Promise((resolve, reject) => { try { if (tokenIsExpired()) { request.post({ url: "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", form: { grant_type: "client_credentials", client_id: process.env["MicrosoftAppId"], client_secret: process.env["MicrosoftAppSecret"], scope: "https://api.botframework.com/.default" } }, function (err, response, body) { if (response.statusCode === 200) { let token = JSON.parse(body) as Token; let now = new Date(); token["expires_on"] = now.getTime() + token.expires_in * 1000; cachedToken = token as CachedToken; resolve(cachedToken); } else { reject(err); } }); } else { resolve(cachedToken); } } catch (error) { console.log("error fetching token: " + error); reject(error); } }); } function tokenIsExpired(): boolean { let now = new Date(); return !cachedToken || now.getTime() > (cachedToken.expires_on - 5 * 1000); } export function validateToken() { // TODO: validate token from bot service // https://docs.microsoft.com/en-us/bot-framework/rest-api/bot-framework-rest-connector-authentication }
Add helper for MSA auth tokens.
Add helper for MSA auth tokens.
TypeScript
agpl-3.0
deegles/cookietime,deegles/cookietime
--- +++ @@ -0,0 +1,59 @@ +import * as request from "request"; + +export interface Token { + token_type: string; + expires_in: number; + ext_expires_in: number; + access_token: string; +} + +interface CachedToken extends Token { + expires_on: number; +} + +let cachedToken: CachedToken; + +export function getBotframeworkToken(): Promise<Token> { + return new Promise((resolve, reject) => { + try { + if (tokenIsExpired()) { + request.post({ + url: "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", + form: { + grant_type: "client_credentials", + client_id: process.env["MicrosoftAppId"], + client_secret: process.env["MicrosoftAppSecret"], + scope: "https://api.botframework.com/.default" + } + }, function (err, response, body) { + if (response.statusCode === 200) { + let token = JSON.parse(body) as Token; + let now = new Date(); + token["expires_on"] = now.getTime() + token.expires_in * 1000; + cachedToken = token as CachedToken; + resolve(cachedToken); + } else { + reject(err); + } + }); + } else { + resolve(cachedToken); + } + } catch (error) { + console.log("error fetching token: " + error); + reject(error); + } + }); +} + +function tokenIsExpired(): boolean { + let now = new Date(); + + return !cachedToken || now.getTime() > (cachedToken.expires_on - 5 * 1000); +} + + +export function validateToken() { + // TODO: validate token from bot service + // https://docs.microsoft.com/en-us/bot-framework/rest-api/bot-framework-rest-connector-authentication +}
663791f844168c13ad2312e63f0923ad65ccca25
ngLabels/App_Script/contenteditable.ts
ngLabels/App_Script/contenteditable.ts
/// <reference path="../scripts/typings/angularjs/angular.d.ts" /> module LabelApplication { class ContentEditable implements ng.IDirective { static factory(): ng.IDirectiveFactory { return () => new ContentEditable();     } restrict = 'A'; require = 'ngModel'; link = (scope: ng.IScope, element: ng.IRootElementService, attrs: any, ngModel: ng.INgModelController) => { function read() { ngModel.$setViewValue(element.html()); } ngModel.$render = function () { element.html(ngModel.$viewValue || ""); }; element.bind("blur keyup change", function () { scope.$apply(read); }); }; } LabelEditor.editorModule.directive('contenteditable', ContentEditable.factory()); } 
Add the content editable typescript file
Add the content editable typescript file
TypeScript
apache-2.0
BillWagner/TypeScriptAngular,BillWagner/TypeScriptAngular,BillWagner/TypeScriptAngular,BillWagner/TypeScriptAngular
--- +++ @@ -0,0 +1,26 @@ +/// <reference path="../scripts/typings/angularjs/angular.d.ts" /> + +module LabelApplication { + class ContentEditable implements ng.IDirective { + static factory(): ng.IDirectiveFactory { + return () => new ContentEditable(); +     } + + restrict = 'A'; + require = 'ngModel'; + link = (scope: ng.IScope, element: ng.IRootElementService, attrs: any, + ngModel: ng.INgModelController) => { + function read() { + ngModel.$setViewValue(element.html()); + } + ngModel.$render = function () { + element.html(ngModel.$viewValue || ""); + }; + element.bind("blur keyup change", function () { + scope.$apply(read); + }); + + }; + } + LabelEditor.editorModule.directive('contenteditable', ContentEditable.factory()); +} 
1eda190dd7136fb387c2b6cccc84f8d42c3088f4
test/whatwgTest.ts
test/whatwgTest.ts
'use strict'; import * as assert from 'power-assert'; import * as url from 'url'; import * as whatwg from '../rules/whatwg'; // describe('whatwg', () => { it('should normalize protocol', () => { const httpURL = 'http://dom.spec.whatwg.org/'; const actual = whatwg.normalize(url.parse(httpURL)); const expected = 'https://dom.spec.whatwg.org/'; assert(actual === expected); }); it('should normalize urls of html standard', () => { const oldURLs = [ 'http://whatwg.org/html/#applicationcache', 'http://whatwg.org/html#2dcontext', 'http://www.whatwg.org/specs/web-apps/current-work/#attr-fe-minlength', 'http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#constraints', 'https://html.spec.whatwg.org/#imagebitmapfactories', ]; const normalizedURLs = [ 'https://html.spec.whatwg.org/multipage/browsers.html#applicationcache', 'https://html.spec.whatwg.org/multipage/scripting.html#2dcontext', 'https://html.spec.whatwg.org/multipage/forms.html#attr-fe-minlength', 'https://html.spec.whatwg.org/multipage/forms.html#constraints', 'https://html.spec.whatwg.org/multipage/webappapis.html#imagebitmapfactories', ]; for (let i = 0; i < oldURLs.length; i++) { const actual = whatwg.normalize(url.parse(oldURLs[i])); const expected = normalizedURLs[i]; assert(actual === expected); } }); });
Add test for whatwg normalizer
Add test for whatwg normalizer
TypeScript
mit
takenspc/ps-url-normalizer
--- +++ @@ -0,0 +1,39 @@ +'use strict'; +import * as assert from 'power-assert'; +import * as url from 'url'; +import * as whatwg from '../rules/whatwg'; + +// +describe('whatwg', () => { + it('should normalize protocol', () => { + const httpURL = 'http://dom.spec.whatwg.org/'; + const actual = whatwg.normalize(url.parse(httpURL)); + const expected = 'https://dom.spec.whatwg.org/'; + assert(actual === expected); + }); + + it('should normalize urls of html standard', () => { + const oldURLs = [ + 'http://whatwg.org/html/#applicationcache', + 'http://whatwg.org/html#2dcontext', + 'http://www.whatwg.org/specs/web-apps/current-work/#attr-fe-minlength', + 'http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#constraints', + 'https://html.spec.whatwg.org/#imagebitmapfactories', + ]; + + const normalizedURLs = [ + 'https://html.spec.whatwg.org/multipage/browsers.html#applicationcache', + 'https://html.spec.whatwg.org/multipage/scripting.html#2dcontext', + 'https://html.spec.whatwg.org/multipage/forms.html#attr-fe-minlength', + 'https://html.spec.whatwg.org/multipage/forms.html#constraints', + 'https://html.spec.whatwg.org/multipage/webappapis.html#imagebitmapfactories', + ]; + + for (let i = 0; i < oldURLs.length; i++) { + const actual = whatwg.normalize(url.parse(oldURLs[i])); + const expected = normalizedURLs[i]; + assert(actual === expected); + } + }); +}); +
6231645016dc4bf46e5db5940be48c9c8802c9c2
tests/ls/fourslash/formattingAfterChainedFatArrow.ts
tests/ls/fourslash/formattingAfterChainedFatArrow.ts
/// <reference path="fourslash.ts" /> ////var x = n => p => { //// while (true) { //// void 0; //// }/**/ ////}; goTo.marker(); format.document(); // Bug 17854: Bad formatting after chained fat arrow // verify.currentLineContentIs(' }'); verify.currentLineContentIs('}');
Test for indent formatting after x => y => z
Test for indent formatting after x => y => z
TypeScript
apache-2.0
vcsjones/typescript,fdecampredon/jsx-typescript-old-version,hippich/typescript,tarruda/typescript,bolinfest/typescript,rbirkby/typescript,mbrowne/typescript-dci,mbebenita/shumway.ts,mbrowne/typescript-dci,hippich/typescript,bolinfest/typescript,mbrowne/typescript-dci,popravich/typescript,turbulenz/typescript,guidobouman/typescript,guidobouman/typescript,rbirkby/typescript,hippich/typescript,bolinfest/typescript,popravich/typescript,mbebenita/shumway.ts,guidobouman/typescript,popravich/typescript,turbulenz/typescript,mbrowne/typescript-dci,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,tarruda/typescript,rbirkby/typescript,tarruda/typescript,turbulenz/typescript
--- +++ @@ -0,0 +1,14 @@ +/// <reference path="fourslash.ts" /> + +////var x = n => p => { +//// while (true) { +//// void 0; +//// }/**/ +////}; + +goTo.marker(); +format.document(); +// Bug 17854: Bad formatting after chained fat arrow +// verify.currentLineContentIs(' }'); +verify.currentLineContentIs('}'); +
dda07d32cd6f7bbf0fd03423354974ed30d25095
src/app/error/error.component.stories.ts
src/app/error/error.component.stories.ts
import { NgModule } from '@angular/core'; import { storiesOf } from '@storybook/angular'; import { TitleService } from '../shared/title.service'; import { ErrorComponent } from './error.component'; const mockTitle = { resetTitle: () => {} }; const moduleMetadata: NgModule = { providers: [{ provide: TitleService, useValue: mockTitle }] }; storiesOf('Core', module).add('Error Page', () => ({ component: ErrorComponent, moduleMetadata }));
Add story for error page
Add story for error page
TypeScript
apache-2.0
jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog
--- +++ @@ -0,0 +1,18 @@ +import { NgModule } from '@angular/core'; +import { storiesOf } from '@storybook/angular'; + +import { TitleService } from '../shared/title.service'; +import { ErrorComponent } from './error.component'; + +const mockTitle = { + resetTitle: () => {} +}; + +const moduleMetadata: NgModule = { + providers: [{ provide: TitleService, useValue: mockTitle }] +}; + +storiesOf('Core', module).add('Error Page', () => ({ + component: ErrorComponent, + moduleMetadata +}));
81aacb0ce7cf9f953590521d16f487cdc48d6ab2
src/test/Apha/Projections/Storage/MemoryVersionStorage.spec.ts
src/test/Apha/Projections/Storage/MemoryVersionStorage.spec.ts
import {expect} from "chai"; import {MemoryVersionStorage} from "../../../../main/Apha/Projections/Storage/MemoryVersionStorage"; describe("MemoryVersionStorage", () => { let storage; beforeEach(() => { storage = new MemoryVersionStorage(); }); describe("findByName", () => { it("should retrieve version by name", () => { storage.upsert("foo", 12); const version = storage.findByName("foo"); expect(version).to.equal(12); }); it("should return NULL if no version is stored", () => { const version = storage.findByName("foo"); expect(version).to.be.null; }); }); describe("upsert", () => { it("should insert a non-existing version", () => { storage.upsert("foo", 1); const version = storage.findByName("foo"); expect(version).to.equal(1); }); it("should update an existing version", () => { storage.upsert("foo", 1); storage.upsert("foo", 2); const version = storage.findByName("foo"); expect(version).to.equal(2); }); }); });
Add test for memory version storage.
Add test for memory version storage.
TypeScript
mit
martyn82/aphajs
--- +++ @@ -0,0 +1,42 @@ + +import {expect} from "chai"; +import {MemoryVersionStorage} from "../../../../main/Apha/Projections/Storage/MemoryVersionStorage"; + +describe("MemoryVersionStorage", () => { + let storage; + + beforeEach(() => { + storage = new MemoryVersionStorage(); + }); + + describe("findByName", () => { + it("should retrieve version by name", () => { + storage.upsert("foo", 12); + + const version = storage.findByName("foo"); + expect(version).to.equal(12); + }); + + it("should return NULL if no version is stored", () => { + const version = storage.findByName("foo"); + expect(version).to.be.null; + }); + }); + + describe("upsert", () => { + it("should insert a non-existing version", () => { + storage.upsert("foo", 1); + + const version = storage.findByName("foo"); + expect(version).to.equal(1); + }); + + it("should update an existing version", () => { + storage.upsert("foo", 1); + storage.upsert("foo", 2); + + const version = storage.findByName("foo"); + expect(version).to.equal(2); + }); + }); +});
1fc65b22c8f2f56025eddffc6a53bc89fa12b812
src/panels/itab.ts
src/panels/itab.ts
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2015, S. Chris Colbert | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ module phosphor.panels { /** * An object which can be used as a tab in a tab bar. */ export interface ITab { /** * The text for the tab. */ text: string; /** * Whether the tab is currently selected. */ selected: boolean; /** * Whether the tab is closable. */ closable: boolean; /** * The DOM node for the tab. */ node: HTMLElement; /** * The DOM node for the close icon, if available. */ closeIconNode: HTMLElement; } } // module phosphor.panels
Move ITab interface to panels.
Move ITab interface to panels.
TypeScript
bsd-3-clause
Carreau/phosphor-notebook-old-orig,dwillmer/phosphor,KesterTong/phoshpor-notebook,blink1073/phosphor,KesterTong/phoshpor-notebook,phosphorjs/phosphor,KesterTong/phoshpor-notebook,dwillmer/phosphor,Carreau/phosphor-notebook-old-orig,Carreau/phosphor-notebook-old-orig,dwillmer/phosphor,phosphorjs/phosphor,blink1073/phosphor,dwillmer/phosphor
--- +++ @@ -0,0 +1,41 @@ +/*----------------------------------------------------------------------------- +| Copyright (c) 2014-2015, S. Chris Colbert +| +| Distributed under the terms of the BSD 3-Clause License. +| +| The full license is in the file LICENSE, distributed with this software. +|----------------------------------------------------------------------------*/ +module phosphor.panels { + +/** + * An object which can be used as a tab in a tab bar. + */ +export +interface ITab { + /** + * The text for the tab. + */ + text: string; + + /** + * Whether the tab is currently selected. + */ + selected: boolean; + + /** + * Whether the tab is closable. + */ + closable: boolean; + + /** + * The DOM node for the tab. + */ + node: HTMLElement; + + /** + * The DOM node for the close icon, if available. + */ + closeIconNode: HTMLElement; +} + +} // module phosphor.panels
5df7cf64f2c0f066fc150d1e0b1dbce726887d61
src/lib/directives/set-element.ts
src/lib/directives/set-element.ts
import { directive } from '../../../node_modules/lit-html/lit-html.js'; /** * Sets the part to a new element of the type selector with the given props, attributes and innerHTML * * @param {string} selector * @param {any} [{ props={}, attributes={}, innerHTML = '' }={}] */ export const setElement = (selector: string, { props={}, attributes={}, innerHTML = '' } = {}) => directive((part: any) => { const elem = document.createElement(selector); for(const prop in props) (elem as any)[prop] = (props as any)[prop]; for(const attr in attributes) elem.setAttribute(attr, (attributes as any)[attr]); elem.innerHTML = innerHTML; part.setValue(elem); })
Add setElement directive (for HOE)
Add setElement directive (for HOE)
TypeScript
apache-2.0
DiiLord/lit-element,DiiLord/lit-element,DiiLord/lit-element
--- +++ @@ -0,0 +1,17 @@ +import { directive } from '../../../node_modules/lit-html/lit-html.js'; + +/** + * Sets the part to a new element of the type selector with the given props, attributes and innerHTML + * + * @param {string} selector + * @param {any} [{ props={}, attributes={}, innerHTML = '' }={}] + */ +export const setElement = (selector: string, { props={}, attributes={}, innerHTML = '' } = {}) => directive((part: any) => { + const elem = document.createElement(selector); + for(const prop in props) + (elem as any)[prop] = (props as any)[prop]; + for(const attr in attributes) + elem.setAttribute(attr, (attributes as any)[attr]); + elem.innerHTML = innerHTML; + part.setValue(elem); +})
2cb45c47a5b22010e0343b515000128f013b6038
client/Library/StatBlockLibrary.test.ts
client/Library/StatBlockLibrary.test.ts
import { StatBlock } from "../../common/StatBlock"; import { AccountClient } from "../Account/AccountClient"; import { Store } from "../Utility/Store"; import { StatBlockLibrary } from "./StatBlockLibrary"; describe("StatBlock Library", () => { test("", async done => { localStorage.clear(); Store.Save(Store.StatBlocks, "creatureId", { ...StatBlock.Default(), Name: "Saved Creature", HP: { Value: 10 } }); const library = new StatBlockLibrary(new AccountClient()); library.AddListings( [ { Name: "Saved Creature", Id: "creatureId", Link: Store.StatBlocks, Path: "", Metadata: {}, SearchHint: "" } ], "localStorage" ); const listing = library.GetStatBlocks()[0]; const statBlockFromLibrary = await listing.GetWithTemplate( StatBlock.Default() ); expect(statBlockFromLibrary.Name).toEqual("Saved Creature"); expect(statBlockFromLibrary.HP.Value).toEqual(10); done(); }); });
Test AddListings and GetWithTemplate on localstorage
Test AddListings and GetWithTemplate on localstorage
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -0,0 +1,41 @@ +import { StatBlock } from "../../common/StatBlock"; +import { AccountClient } from "../Account/AccountClient"; +import { Store } from "../Utility/Store"; +import { StatBlockLibrary } from "./StatBlockLibrary"; + +describe("StatBlock Library", () => { + test("", async done => { + localStorage.clear(); + + Store.Save(Store.StatBlocks, "creatureId", { + ...StatBlock.Default(), + Name: "Saved Creature", + HP: { Value: 10 } + }); + + const library = new StatBlockLibrary(new AccountClient()); + library.AddListings( + [ + { + Name: "Saved Creature", + Id: "creatureId", + Link: Store.StatBlocks, + Path: "", + Metadata: {}, + SearchHint: "" + } + ], + "localStorage" + ); + + const listing = library.GetStatBlocks()[0]; + const statBlockFromLibrary = await listing.GetWithTemplate( + StatBlock.Default() + ); + + expect(statBlockFromLibrary.Name).toEqual("Saved Creature"); + expect(statBlockFromLibrary.HP.Value).toEqual(10); + + done(); + }); +});
f7f9bd1d2431c1b2cc2d80f6344d552f0230fb11
tests/cases/fourslash/parameterWithNestedDestructuring.ts
tests/cases/fourslash/parameterWithNestedDestructuring.ts
/// <reference path='fourslash.ts'/> ////[[{foo: 'hello', bar: [1]}]] //// .map(([{foo, bar: [baz]}]) => /*1*/foo + /*2*/baz); goTo.marker('1'); verify.quickInfoIs('var foo: string'); goTo.marker('2'); verify.quickInfoIs('var baz: number');
Add tests for nested destructuring
Add tests for nested destructuring
TypeScript
apache-2.0
Eyas/TypeScript,fabioparra/TypeScript,kimamula/TypeScript,RyanCavanaugh/TypeScript,mihailik/TypeScript,ziacik/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,ziacik/TypeScript,synaptek/TypeScript,synaptek/TypeScript,SaschaNaz/TypeScript,TukekeSoft/TypeScript,chuckjaz/TypeScript,alexeagle/TypeScript,TukekeSoft/TypeScript,RyanCavanaugh/TypeScript,basarat/TypeScript,nycdotnet/TypeScript,mmoskal/TypeScript,mmoskal/TypeScript,samuelhorwitz/typescript,SaschaNaz/TypeScript,Eyas/TypeScript,basarat/TypeScript,Eyas/TypeScript,ionux/TypeScript,nycdotnet/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,vilic/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,AbubakerB/TypeScript,synaptek/TypeScript,fabioparra/TypeScript,DLehenbauer/TypeScript,plantain-00/TypeScript,kitsonk/TypeScript,samuelhorwitz/typescript,jeremyepling/TypeScript,mihailik/TypeScript,jwbay/TypeScript,synaptek/TypeScript,chuckjaz/TypeScript,AbubakerB/TypeScript,TukekeSoft/TypeScript,evgrud/TypeScript,jwbay/TypeScript,kpreisser/TypeScript,ionux/TypeScript,fabioparra/TypeScript,samuelhorwitz/typescript,ionux/TypeScript,evgrud/TypeScript,vilic/TypeScript,blakeembrey/TypeScript,weswigham/TypeScript,basarat/TypeScript,vilic/TypeScript,blakeembrey/TypeScript,jwbay/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,blakeembrey/TypeScript,donaldpipowitch/TypeScript,nojvek/TypeScript,vilic/TypeScript,jeremyepling/TypeScript,thr0w/Thr0wScript,mmoskal/TypeScript,plantain-00/TypeScript,Microsoft/TypeScript,mihailik/TypeScript,thr0w/Thr0wScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,nojvek/TypeScript,RyanCavanaugh/TypeScript,chuckjaz/TypeScript,microsoft/TypeScript,plantain-00/TypeScript,AbubakerB/TypeScript,DLehenbauer/TypeScript,jeremyepling/TypeScript,nojvek/TypeScript,DLehenbauer/TypeScript,ionux/TypeScript,nycdotnet/TypeScript,yortus/TypeScript,fabioparra/TypeScript,erikmcc/TypeScript,ziacik/TypeScript,thr0w/Thr0wScript,Microsoft/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,Eyas/TypeScript,thr0w/Thr0wScript,mmoskal/TypeScript,chuckjaz/TypeScript,evgrud/TypeScript,samuelhorwitz/typescript,kimamula/TypeScript,alexeagle/TypeScript,AbubakerB/TypeScript,DLehenbauer/TypeScript,yortus/TypeScript,kimamula/TypeScript,jwbay/TypeScript,ziacik/TypeScript,plantain-00/TypeScript,yortus/TypeScript,yortus/TypeScript,mihailik/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,nycdotnet/TypeScript,alexeagle/TypeScript,erikmcc/TypeScript,blakeembrey/TypeScript,erikmcc/TypeScript,minestarks/TypeScript,erikmcc/TypeScript,evgrud/TypeScript,minestarks/TypeScript,microsoft/TypeScript,donaldpipowitch/TypeScript,kimamula/TypeScript
--- +++ @@ -0,0 +1,10 @@ +/// <reference path='fourslash.ts'/> + +////[[{foo: 'hello', bar: [1]}]] +//// .map(([{foo, bar: [baz]}]) => /*1*/foo + /*2*/baz); + +goTo.marker('1'); +verify.quickInfoIs('var foo: string'); + +goTo.marker('2'); +verify.quickInfoIs('var baz: number');
b9f4ae435cdacd83d7af7e21256a0f0c55ba015f
app/components/resources/base-list.ts
app/components/resources/base-list.ts
import {ResourcesComponent} from './resources.component'; import {ViewFacade} from './view/view-facade'; import {Loading} from '../../widgets/loading'; import {NavigationPath} from './navigation-path'; /** * A base class for all lists, e.g. sidebarList and List components * * @author Philipp Gerth */ export class BaseList { public navigationPath: NavigationPath = { elements: [] }; constructor( public resourcesComponent: ResourcesComponent, public viewFacade: ViewFacade, public loading: Loading ) { this.viewFacade.pathToRootDocumentNotifications().subscribe(path => { this.navigationPath = path; }); } public showPlusButton() { return (!this.resourcesComponent.isEditingGeometry && this.resourcesComponent.ready && !this.loading.showIcons && this.viewFacade.getQuery().q == '' && (this.viewFacade.isInOverview() || this.viewFacade.getSelectedMainTypeDocument())); } }
Create new abstract class for lists
Create new abstract class for lists
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -0,0 +1,34 @@ +import {ResourcesComponent} from './resources.component'; +import {ViewFacade} from './view/view-facade'; +import {Loading} from '../../widgets/loading'; +import {NavigationPath} from './navigation-path'; + +/** + * A base class for all lists, e.g. sidebarList and List components + * + * @author Philipp Gerth + */ + +export class BaseList { + + public navigationPath: NavigationPath = { elements: [] }; + + constructor( + public resourcesComponent: ResourcesComponent, + public viewFacade: ViewFacade, + public loading: Loading + ) { + this.viewFacade.pathToRootDocumentNotifications().subscribe(path => { + this.navigationPath = path; + }); + } + + + public showPlusButton() { + + return (!this.resourcesComponent.isEditingGeometry && this.resourcesComponent.ready + && !this.loading.showIcons && this.viewFacade.getQuery().q == '' + && (this.viewFacade.isInOverview() || this.viewFacade.getSelectedMainTypeDocument())); + } + +}
cf969e29d54fe0077c7114df07298ca2605c6b8c
app/ui/views/crumpet-list-view.ts
app/ui/views/crumpet-list-view.ts
import {Component,Input,Output,EventEmitter} from "@angular/core"; import {Crumpet} from "../../data/Crumpet"; @Component({ selector: "crumpet-list-view", template: `<GridLayout rows="auto, *"> <ListView [items]="list" row="1" class="small-spacing"> <template let-item="item"> <GridLayout columns="*, auto" (tap)="clicked.emit(item)"> <Label col="0" [text]="item.name" class="medium-spacing"></Label> </GridLayout> </template> </ListView> </GridLayout> `, styles: [``] }) export class CrumpetListView { @Input() list:Crumpet[]; @Output() clicked = new EventEmitter<Crumpet>(); }
Create a 'dumb view' component which can render a list of crumpets
Create a 'dumb view' component which can render a list of crumpets
TypeScript
unlicense
luketn/WonderCrumpet
--- +++ @@ -0,0 +1,22 @@ +import {Component,Input,Output,EventEmitter} from "@angular/core"; +import {Crumpet} from "../../data/Crumpet"; + +@Component({ + selector: "crumpet-list-view", + template: `<GridLayout rows="auto, *"> + <ListView [items]="list" row="1" class="small-spacing"> + <template let-item="item"> + <GridLayout columns="*, auto" (tap)="clicked.emit(item)"> + <Label col="0" [text]="item.name" class="medium-spacing"></Label> + </GridLayout> + </template> + </ListView> + </GridLayout> + `, + styles: [``] +}) + +export class CrumpetListView { + @Input() list:Crumpet[]; + @Output() clicked = new EventEmitter<Crumpet>(); +}
8f12ad6516c3f9937942a62b50d6b92649c554ac
src/app/editor/components/menu/custom-modal.component.ts
src/app/editor/components/menu/custom-modal.component.ts
import {Modal} from "../../../core/services/jetpad-modal.service"; import {Component, OnInit} from "@angular/core"; @Component({ selector: "my-custom-modal", template: ` <div class="my-custom-modal"> <h1>Modal (todo)</h1> <button (click)="onCancel()">×</button> <ul> <li *ngFor="let snack of snacks">{{snack}}</li> <li *ngFor="let cap of capullo">{{cap.text}}</li> </ul> <div> <button (click)="onCancel()"> <span>Cancel</span> </button> <button class="btn btn-success" (click)="onOk()"> <span>Ok</span> </button> </div> </div> `, styles:[` .my-custom-modal > button { position: absolute; top: 4px; right: 4px; } .my-custom-modal > h1 { text-align: center; } ` ] }) @Modal() export class MyCustomModalComponent implements OnInit { private currentState: string = 'inactive'; ok: Function; destroy: Function; closeModal: Function; parentHeight: number; snacks = ["newyorkers", "mars", "snickers"]; ngOnInit(): void { this.currentState = 'active'; } onCancel(): void{ this.currentState = 'inactive'; //console.log(this.parentHeight); setTimeout(() => { this.closeModal(); }, 150); } onOk(): void{ this.currentState = 'inactive'; setTimeout(() => { this.closeModal(); }, 150); this.ok(this.snacks); } }
Create example of custom modal using modal service
Create example of custom modal using modal service
TypeScript
agpl-3.0
P2Pvalue/jetpad,P2Pvalue/jetpad,P2Pvalue/jetpad
--- +++ @@ -0,0 +1,66 @@ +import {Modal} from "../../../core/services/jetpad-modal.service"; +import {Component, OnInit} from "@angular/core"; +@Component({ + selector: "my-custom-modal", + template: ` + <div class="my-custom-modal"> + <h1>Modal (todo)</h1> + <button (click)="onCancel()">×</button> + <ul> + <li *ngFor="let snack of snacks">{{snack}}</li> + <li *ngFor="let cap of capullo">{{cap.text}}</li> + </ul> + <div> + <button (click)="onCancel()"> + <span>Cancel</span> + </button> + <button class="btn btn-success" (click)="onOk()"> + <span>Ok</span> + </button> + </div> + </div> + `, + styles:[` + .my-custom-modal > button { + position: absolute; + top: 4px; + right: 4px; + } + .my-custom-modal > h1 { + text-align: center; + } + + ` + ] +}) + +@Modal() +export class MyCustomModalComponent implements OnInit { + + private currentState: string = 'inactive'; + ok: Function; + destroy: Function; + closeModal: Function; + parentHeight: number; + snacks = ["newyorkers", "mars", "snickers"]; + + ngOnInit(): void { + this.currentState = 'active'; + } + + onCancel(): void{ + this.currentState = 'inactive'; + //console.log(this.parentHeight); + setTimeout(() => { + this.closeModal(); + }, 150); + } + + onOk(): void{ + this.currentState = 'inactive'; + setTimeout(() => { + this.closeModal(); + }, 150); + this.ok(this.snacks); + } +}
35a78dd7bc018bcae86ee371c67df83a54013ef1
spec/polymorphism-root-abstract-class.spec.ts
spec/polymorphism-root-abstract-class.spec.ts
import { jsonObject, jsonMember, TypedJSON } from "../js/typedjson"; describe('single class', function () { abstract class Person { @jsonMember firstName?: string; @jsonMember lastName?: string; public getFullName() { return this.firstName + " " + this.lastName; } } @jsonObject class Bob extends Person { @jsonMember pounds?: number; public getFullName() { return super.getFullName() + ` weighing ${this.pounds}`; } } // todo we need something better jsonObject({ knownTypes: [Bob]})(Person as any); describe('deserialized', function () { beforeAll(function () { // todo fix types so they accept abstract this.person = TypedJSON.parse('{ "__type": "Bob", "firstName": "John", "lastName": "Doe", "pounds": 40 }', Person as any); }); it('should be of proper type', function () { expect(this.person instanceof Bob).toBeTruthy(); }); it('should have functions', function () { expect(this.person.getFullName).toBeDefined(); expect(this.person.getFullName()).toBe('John Doe weighing 40'); }); }); describe('serialized', function () { it('should contain all data', function () { const person = new Bob; person.firstName = 'John'; person.lastName = 'Doe'; person.pounds = 30 // todo fix types so they accept abstract expect(TypedJSON.stringify(person, Person as any)) .toBe('{"firstName":"John","lastName":"Doe","pounds":30,"__type":"Bob"}'); }); }); });
Add test for a direct deserialization of an abstract class
Add test for a direct deserialization of an abstract class
TypeScript
mit
JohnWhiteTB/TypedJSON,JohnWhiteTB/TypedJSON,JohnWeisz/TypedJSON,JohnWhiteTB/TypedJSON,JohnWeisz/TypedJSON
--- +++ @@ -0,0 +1,57 @@ +import { jsonObject, jsonMember, TypedJSON } from "../js/typedjson"; + +describe('single class', function () { + + abstract class Person { + @jsonMember + firstName?: string; + + @jsonMember + lastName?: string; + + public getFullName() { + return this.firstName + " " + this.lastName; + } + } + + @jsonObject + class Bob extends Person { + @jsonMember + pounds?: number; + + public getFullName() { + return super.getFullName() + ` weighing ${this.pounds}`; + } + } + + // todo we need something better + jsonObject({ knownTypes: [Bob]})(Person as any); + + describe('deserialized', function () { + beforeAll(function () { + // todo fix types so they accept abstract + this.person = TypedJSON.parse('{ "__type": "Bob", "firstName": "John", "lastName": "Doe", "pounds": 40 }', Person as any); + }); + + it('should be of proper type', function () { + expect(this.person instanceof Bob).toBeTruthy(); + }); + + it('should have functions', function () { + expect(this.person.getFullName).toBeDefined(); + expect(this.person.getFullName()).toBe('John Doe weighing 40'); + }); + }); + + describe('serialized', function () { + it('should contain all data', function () { + const person = new Bob; + person.firstName = 'John'; + person.lastName = 'Doe'; + person.pounds = 30 + // todo fix types so they accept abstract + expect(TypedJSON.stringify(person, Person as any)) + .toBe('{"firstName":"John","lastName":"Doe","pounds":30,"__type":"Bob"}'); + }); + }); +});
e440d7355c16d98024190030ed9c93bde8709974
src/lib/textfield/textfield-box.component.ts
src/lib/textfield/textfield-box.component.ts
import { Component, HostBinding, OnInit, } from '@angular/core'; import { Ripple } from '.././ripple/ripple.directive'; import { TextfieldComponent } from './textfield.component'; @Component({ selector: 'mdc-textfield-box', template: ` <input #input class="mdc-textfield__input" [type]="type" [id]="id" [attr.name]="name" [(ngModel)]="value" [tabindex]="tabindex" [maxlength]="maxlength" [disabled]="disabled" [required]="required" (focus)="onFocus($event)" (keydown)="onKeyDown($event)" (blur)="onBlur($event)" (input)="onInput($event)" /> <label #inputlabel [attr.for]="id" class="mdc-textfield__label">{{label}}</label> <div class="mdc-textfield__bottom-line"></div> `, providers: [Ripple] }) export class TextfieldBoxComponent extends TextfieldComponent implements OnInit { @HostBinding('class.mdc-textfield--box') isHostClass = true; ngOnInit() { this.ripple.init(); } }
Implement MDC Text field boxes
feat(textfield): Implement MDC Text field boxes Text field boxes support all of the same features as normal textfields, including help text, validation, and dense UI. Closes #57
TypeScript
mit
trimox/angular-mdc-web,trimox/angular-mdc-web
--- +++ @@ -0,0 +1,37 @@ +import { + Component, + HostBinding, + OnInit, +} from '@angular/core'; +import { Ripple } from '.././ripple/ripple.directive'; +import { TextfieldComponent } from './textfield.component'; + +@Component({ + selector: 'mdc-textfield-box', + template: + ` + <input #input class="mdc-textfield__input" + [type]="type" + [id]="id" + [attr.name]="name" + [(ngModel)]="value" + [tabindex]="tabindex" + [maxlength]="maxlength" + [disabled]="disabled" + [required]="required" + (focus)="onFocus($event)" + (keydown)="onKeyDown($event)" + (blur)="onBlur($event)" + (input)="onInput($event)" /> + <label #inputlabel [attr.for]="id" class="mdc-textfield__label">{{label}}</label> + <div class="mdc-textfield__bottom-line"></div> + `, + providers: [Ripple] +}) +export class TextfieldBoxComponent extends TextfieldComponent implements OnInit { + @HostBinding('class.mdc-textfield--box') isHostClass = true; + + ngOnInit() { + this.ripple.init(); + } +}
565423d192c67bd5ea6477b217eccb43b416ffaa
src/core/Channel.ts
src/core/Channel.ts
/** * Signature for the functions that are called when an event is sent. */ type Listener<TMessage> = (message: TMessage) => void /** * Type-safe event mini-bus, or publisher/subscriber system. It is a useful way to establish communication between * components which are far away in the shared component hierarchy. */ export class Channel<TMessage> { private listeners: Listener<TMessage>[] = [] /** * Subscribe a listener to the event channel. A function is returned which can be called to unsubscribe the same * listener. */ do(listener: Listener<TMessage>) { this.listeners.push(listener) return () => this.stop(listener) } /** * Subscribe a listener to the event channel, and unsubscribe from it once the event has been emitted for the first * time after the subscription. A function is returned which can be called to unsubscribe the listener even before * this happens automatically. */ once(listener: Listener<TMessage>) { const stop = () => this.stop(listener) const listenerWrapper = (message: TMessage) => { listener(message) stop() } this.listeners.push(listenerWrapper) return stop } /** * Unsubscribe a listener from the event channel. */ stop(listener: Listener<TMessage>) { const listenerPos = this.listeners.indexOf(listener) if (listenerPos > -1) { this.listeners.splice(listenerPos, 1) } } /** * Send an event to all listeners, with a payload. */ echo(message: TMessage) { this.listeners.forEach(l => l(message)) } /** * Unsubscribe all listeners from the event channel. */ close() { this.listeners = [] } }
Add communication mechanism for separated components
Add communication mechanism for separated components
TypeScript
agpl-3.0
inad9300/Soil,inad9300/Soil
--- +++ @@ -0,0 +1,65 @@ +/** + * Signature for the functions that are called when an event is sent. + */ +type Listener<TMessage> = (message: TMessage) => void + +/** + * Type-safe event mini-bus, or publisher/subscriber system. It is a useful way to establish communication between + * components which are far away in the shared component hierarchy. + */ +export class Channel<TMessage> { + + private listeners: Listener<TMessage>[] = [] + + /** + * Subscribe a listener to the event channel. A function is returned which can be called to unsubscribe the same + * listener. + */ + do(listener: Listener<TMessage>) { + this.listeners.push(listener) + + return () => this.stop(listener) + } + + /** + * Subscribe a listener to the event channel, and unsubscribe from it once the event has been emitted for the first + * time after the subscription. A function is returned which can be called to unsubscribe the listener even before + * this happens automatically. + */ + once(listener: Listener<TMessage>) { + const stop = () => this.stop(listener) + + const listenerWrapper = (message: TMessage) => { + listener(message) + stop() + } + + this.listeners.push(listenerWrapper) + + return stop + } + + /** + * Unsubscribe a listener from the event channel. + */ + stop(listener: Listener<TMessage>) { + const listenerPos = this.listeners.indexOf(listener) + if (listenerPos > -1) { + this.listeners.splice(listenerPos, 1) + } + } + + /** + * Send an event to all listeners, with a payload. + */ + echo(message: TMessage) { + this.listeners.forEach(l => l(message)) + } + + /** + * Unsubscribe all listeners from the event channel. + */ + close() { + this.listeners = [] + } +}
91900e122bf626e34da7087c452e46a863d7a842
src/app/shared/title.service.spec.ts
src/app/shared/title.service.spec.ts
import { Title } from '@angular/platform-browser'; import { It, IMock, Mock, Times } from 'typemoq'; import { TitleService } from './title.service'; describe('Title Service wrapper', () => { let mockTitle: IMock<Title>; beforeEach(() => { mockTitle = Mock.ofType<Title>(); }); it ('should set and format title if non-empty string is passed', () => { const newTitle = 'my new title'; const expectedTitle = `Jason Browne: ${newTitle}`; mockTitle.setup(s => s.setTitle(It.isAnyString())); const service = new TitleService(mockTitle.object); service.setTitle(newTitle); mockTitle.verify(s => s.setTitle(It.isValue(expectedTitle)), Times.once()); }); it ('should set default title if empty string is passed', () => { const newTitle = ''; const expectedTitle = 'Jason Browne'; mockTitle.setup(s => s.setTitle(It.isAnyString())); const service = new TitleService(mockTitle.object); service.setTitle(newTitle); mockTitle.verify(s => s.setTitle(It.isValue(expectedTitle)), Times.once()); }); it ('should set default title if reset is called', () => { const expectedTitle = 'Jason Browne'; mockTitle.setup(s => s.setTitle(It.isAnyString())); const service = new TitleService(mockTitle.object); service.resetTitle(); mockTitle.verify(s => s.setTitle(It.isValue(expectedTitle)), Times.once()); }); });
Add unit tests for page title service
Add unit tests for page title service
TypeScript
apache-2.0
jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog
--- +++ @@ -0,0 +1,47 @@ +import { Title } from '@angular/platform-browser'; +import { It, IMock, Mock, Times } from 'typemoq'; + +import { TitleService } from './title.service'; + +describe('Title Service wrapper', () => { + let mockTitle: IMock<Title>; + + beforeEach(() => { + mockTitle = Mock.ofType<Title>(); + }); + + it ('should set and format title if non-empty string is passed', () => { + const newTitle = 'my new title'; + const expectedTitle = `Jason Browne: ${newTitle}`; + mockTitle.setup(s => s.setTitle(It.isAnyString())); + + const service = new TitleService(mockTitle.object); + + service.setTitle(newTitle); + + mockTitle.verify(s => s.setTitle(It.isValue(expectedTitle)), Times.once()); + }); + + it ('should set default title if empty string is passed', () => { + const newTitle = ''; + const expectedTitle = 'Jason Browne'; + mockTitle.setup(s => s.setTitle(It.isAnyString())); + + const service = new TitleService(mockTitle.object); + + service.setTitle(newTitle); + + mockTitle.verify(s => s.setTitle(It.isValue(expectedTitle)), Times.once()); + }); + + it ('should set default title if reset is called', () => { + const expectedTitle = 'Jason Browne'; + mockTitle.setup(s => s.setTitle(It.isAnyString())); + + const service = new TitleService(mockTitle.object); + + service.resetTitle(); + + mockTitle.verify(s => s.setTitle(It.isValue(expectedTitle)), Times.once()); + }); +});
0e55ab17fc8eac97d856284c954fba717b5900b3
types/koa-websocket/index.d.ts
types/koa-websocket/index.d.ts
// Type definitions for koa-websocket 2.1 // Project: https://github.com/kudos/koa-websocket // Definitions by: My Self <https://github.com/me> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import Koa = require('koa'); import * as ws from 'ws'; import * as http from 'http'; import * as https from 'https'; type KoaWebsocketConnectionHandler = (socket: ws) => void; type KoaWebsocketMiddleware = (this: KoaWebsocketMiddlewareContext, context: Koa.Context, next: () => Promise<any>) => any; interface KoaWebsocketMiddlewareContext extends Koa.Context { websocket: ws; path: string; } declare class KoaWebsocketServer { app: Koa; middleware: Koa.Middleware[]; constructor(app: Koa); listen(server: http.Server | https.Server): ws.Server; onConnection(handler: KoaWebsocketConnectionHandler): void; use(middleware: KoaWebsocketMiddleware): this; } interface KoaWebsocketApp extends Koa { ws: KoaWebsocketServer; } declare function websockets(app: Koa): KoaWebsocketApp; export = websockets;
// Type definitions for koa-websocket 5.0 // Project: https://github.com/kudos/koa-websocket // Definitions by: Maël Lavault <https://github.com/moimael> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import Koa = require('koa'); import * as ws from 'ws'; import * as http from 'http'; import * as https from 'https'; type KoaWebsocketConnectionHandler = (socket: ws) => void; type KoaWebsocketMiddleware = (this: KoaWebsocketMiddlewareContext, context: Koa.Context, next: () => Promise<any>) => any; interface KoaWebsocketMiddlewareContext extends Koa.Context { websocket: ws; path: string; } declare class KoaWebsocketServer { app: Koa; middleware: Koa.Middleware[]; constructor(app: Koa); listen(options: ws.ServerOptions): ws.Server; onConnection(handler: KoaWebsocketConnectionHandler): void; use(middleware: KoaWebsocketMiddleware): this; } interface KoaWebsocketApp extends Koa { ws: KoaWebsocketServer; } declare function websockets(app: Koa): KoaWebsocketApp; export = websockets;
Support passing ws options to listen.
Support passing ws options to listen. Fix ts breaking when passing anything to listen. Signed-off-by: Maël Lavault <[email protected]>
TypeScript
mit
magny/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,mcliment/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped
--- +++ @@ -1,6 +1,6 @@ -// Type definitions for koa-websocket 2.1 +// Type definitions for koa-websocket 5.0 // Project: https://github.com/kudos/koa-websocket -// Definitions by: My Self <https://github.com/me> +// Definitions by: Maël Lavault <https://github.com/moimael> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -21,7 +21,7 @@ middleware: Koa.Middleware[]; constructor(app: Koa); - listen(server: http.Server | https.Server): ws.Server; + listen(options: ws.ServerOptions): ws.Server; onConnection(handler: KoaWebsocketConnectionHandler): void; use(middleware: KoaWebsocketMiddleware): this; }
e7730542be624cfb569aea201cbdc89101367a9f
client/Library/Components/Listing.tsx
client/Library/Components/Listing.tsx
import * as React from "react"; import { MouseEvent } from "react"; import { Listing, Listable } from "../Listing"; import { Button } from "./Button"; export interface ListingProps<T extends Listable> { name: string; listing: Listing<T>; onAdd: (listing: Listing<T>) => void; onDelete?: (listing: Listing<T>) => void; onEdit?: (listing: Listing<T>) => void; onPreview?: (listing: Listing<T>) => void; } export class ListingViewModel<T extends Listable> extends React.Component<ListingProps<T>> { private addFn = () => this.props.onAdd(this.props.listing); private deleteFn = () => this.props.onDelete(this.props.listing); private editFn = () => this.props.onEdit(this.props.listing); private previewFn = () => this.props.onPreview(this.props.listing); public render() { return <li> <Button text={this.props.name} onClick={this.addFn} /> {this.editFn && <Button faClass="edit" onClick={this.editFn} />} {this.deleteFn && <Button faClass="trash" onClick={this.deleteFn} />} {this.previewFn && <Button faClass="search" onClick={this.previewFn} onMouseOver={this.previewFn} />} </li>; } }
import * as React from "react"; import { MouseEvent } from "react"; import { Listing, Listable } from "../Listing"; import { Button } from "./Button"; export interface ListingProps<T extends Listable> { name: string; listing: Listing<T>; onAdd: (listing: Listing<T>) => void; onDelete?: (listing: Listing<T>) => void; onEdit?: (listing: Listing<T>) => void; onPreview?: (listing: Listing<T>) => void; } export class ListingViewModel<T extends Listable> extends React.Component<ListingProps<T>> { private addFn = () => this.props.onAdd(this.props.listing); private deleteFn = () => this.props.onDelete(this.props.listing); private editFn = () => this.props.onEdit(this.props.listing); private previewFn = () => this.props.onPreview(this.props.listing); public render() { return <li> <Button text={this.props.name} onClick={this.addFn} /> {this.props.onEdit && <Button faClass="edit" onClick={this.editFn} />} {this.props.onDelete && <Button faClass="trash" onClick={this.deleteFn} />} {this.props.onPreview && <Button faClass="search" onClick={this.previewFn} onMouseOver={this.previewFn} />} </li>; } }
Check props to hide unused listing buttons
Check props to hide unused listing buttons
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -21,9 +21,9 @@ public render() { return <li> <Button text={this.props.name} onClick={this.addFn} /> - {this.editFn && <Button faClass="edit" onClick={this.editFn} />} - {this.deleteFn && <Button faClass="trash" onClick={this.deleteFn} />} - {this.previewFn && <Button faClass="search" onClick={this.previewFn} onMouseOver={this.previewFn} />} + {this.props.onEdit && <Button faClass="edit" onClick={this.editFn} />} + {this.props.onDelete && <Button faClass="trash" onClick={this.deleteFn} />} + {this.props.onPreview && <Button faClass="search" onClick={this.previewFn} onMouseOver={this.previewFn} />} </li>; } }
c2dbe1d02ceb9987f9002eedf0cdb21d74de0019
test/reflect-other.ts
test/reflect-other.ts
import * as fs from "fs"; import { assert } from "chai"; describe("Reflect", () => { it("does not overwrite existing implementation", () => { const defineMetadata = Reflect.defineMetadata; const reflectPath = require.resolve("../Reflect.js"); const reflectContent = fs.readFileSync(reflectPath, "utf8"); const reflectFunction = Function(reflectContent); reflectFunction(); assert.strictEqual(Reflect.defineMetadata, defineMetadata); }); });
Add test to verify does not overwrite existing implementation
Add test to verify does not overwrite existing implementation
TypeScript
apache-2.0
rbuckton/ReflectDecorators,rbuckton/ReflectDecorators,rbuckton/ReflectDecorators,rbuckton/reflect-metadata,rbuckton/reflect-metadata,rbuckton/reflect-metadata
--- +++ @@ -0,0 +1,15 @@ +import * as fs from "fs"; +import { assert } from "chai"; + +describe("Reflect", () => { + it("does not overwrite existing implementation", () => { + const defineMetadata = Reflect.defineMetadata; + + const reflectPath = require.resolve("../Reflect.js"); + const reflectContent = fs.readFileSync(reflectPath, "utf8"); + const reflectFunction = Function(reflectContent); + reflectFunction(); + + assert.strictEqual(Reflect.defineMetadata, defineMetadata); + }); +});
524ddf729bbffb8d2295ad91c3b31f3cb5800718
client/Commands/LegacyCommandSettingsKeys.ts
client/Commands/LegacyCommandSettingsKeys.ts
export const LegacyCommandSettingsKeys = { "toggle-menu": "Toggle Menu", "start-encounter": "Start Encounter", "reroll-initiative": "Reroll Initiative", "end-encounter": "End Encounter", "clear-encounter": "Clear Encounter", "open-library": "Open Library", "quick-add": "Quick Add Combatant", "player-window": "Show Player Window", "next-turn": "Next Turn", "previous-turn": "Previous Turn", "save-encounter": "Save Encounter", "settings": "Settings", "apply-damage": "Damage/Heal", "apply-temporary-hp": "Apply Temporary HP", "add-tag": "Add Note", "remove": "Remove from Encounter", "set-alias": "Rename", "edit-statblock": "Edit Statblock", "set-initiative": "Edit Initiative", "link-initiative": "Link Initiative", "move-down": "Move Down", "move-up": "Move Up", "select-next": "Select Next", "select-previous": "Select Previous" };
Add legacy command settings keys
Add legacy command settings keys
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -0,0 +1,26 @@ +export const LegacyCommandSettingsKeys = { + "toggle-menu": "Toggle Menu", + "start-encounter": "Start Encounter", + "reroll-initiative": "Reroll Initiative", + "end-encounter": "End Encounter", + "clear-encounter": "Clear Encounter", + "open-library": "Open Library", + "quick-add": "Quick Add Combatant", + "player-window": "Show Player Window", + "next-turn": "Next Turn", + "previous-turn": "Previous Turn", + "save-encounter": "Save Encounter", + "settings": "Settings", + "apply-damage": "Damage/Heal", + "apply-temporary-hp": "Apply Temporary HP", + "add-tag": "Add Note", + "remove": "Remove from Encounter", + "set-alias": "Rename", + "edit-statblock": "Edit Statblock", + "set-initiative": "Edit Initiative", + "link-initiative": "Link Initiative", + "move-down": "Move Down", + "move-up": "Move Up", + "select-next": "Select Next", + "select-previous": "Select Previous" +};
92ce9af47d45f57bae62f7d7be74ff0a10a9cbfa
src/client/src/apps/MainRoute/widgets/contact-us/ContactUs.stories.tsx
src/client/src/apps/MainRoute/widgets/contact-us/ContactUs.stories.tsx
import { storiesOf } from '@storybook/react' import React from 'react' import { Story } from 'rt-storybook' import { styled } from 'rt-theme' import ContactUsButton from './ContactUsButton' const stories = storiesOf('Contact Us', module) const Centered = styled('div')` height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; ` stories.add('Contact Us', () => ( <Root> <ContactUsButton /> </Root> )) const Root: React.FC = ({ children }) => ( <Story> <Centered>{children}</Centered> </Story> )
Add CTA button to storybook
chore(storybook): Add CTA button to storybook
TypeScript
apache-2.0
AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud
--- +++ @@ -0,0 +1,27 @@ +import { storiesOf } from '@storybook/react' +import React from 'react' +import { Story } from 'rt-storybook' +import { styled } from 'rt-theme' +import ContactUsButton from './ContactUsButton' + +const stories = storiesOf('Contact Us', module) + +const Centered = styled('div')` + height: 100%; + width: 100%; + display: flex; + align-items: center; + justify-content: center; +` + +stories.add('Contact Us', () => ( + <Root> + <ContactUsButton /> + </Root> +)) + +const Root: React.FC = ({ children }) => ( + <Story> + <Centered>{children}</Centered> + </Story> +)
5799667bcac2feaa0d57fb3da2422ee571b52d0c
src/elmTest.ts
src/elmTest.ts
import * as utils from './elmUtils'; import * as vscode from 'vscode'; import * as path from 'path'; export function fileIsTestFile(filename) { const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration( 'elm', ); const elmTestLocationMatcher: string = <string>( config.get('elmTestFileMatcher') ); const [cwd, elmVersion] = utils.detectProjectRootAndElmVersion( filename, vscode.workspace.rootPath, ); if (utils.isElm019(elmVersion) === false) { // we didn't differentiate test/app code for 0.18 return false; } const pathFromRoute = path.relative(vscode.workspace.rootPath, filename); const isTestFile = pathFromRoute.indexOf(elmTestLocationMatcher) > -1; return isTestFile; }
Create funciton to detect elm-test files
Create funciton to detect elm-test files
TypeScript
mit
Krzysztof-Cieslak/vscode-elm,sbrink/vscode-elm
--- +++ @@ -0,0 +1,25 @@ +import * as utils from './elmUtils'; +import * as vscode from 'vscode'; +import * as path from 'path'; + +export function fileIsTestFile(filename) { + const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration( + 'elm', + ); + const elmTestLocationMatcher: string = <string>( + config.get('elmTestFileMatcher') + ); + const [cwd, elmVersion] = utils.detectProjectRootAndElmVersion( + filename, + vscode.workspace.rootPath, + ); + if (utils.isElm019(elmVersion) === false) { + // we didn't differentiate test/app code for 0.18 + return false; + } + + const pathFromRoute = path.relative(vscode.workspace.rootPath, filename); + const isTestFile = pathFromRoute.indexOf(elmTestLocationMatcher) > -1; + + return isTestFile; +}
cdd5ef9644e421a8ee79064beba821ef77de1a0b
src/renderer/matchTimestamps.ts
src/renderer/matchTimestamps.ts
interface Match { index: number length: number } export const matchTimestamps = (inputText: string): Match[] => { const lengthOfDelimiter = 1 // Have to advance past/before the opening/closing brackets let bracketPattern = /\[(\d|:|.)+\]/g let match = bracketPattern.exec(inputText) let matches: Match[] = [] let startingIndex let matchLength while (match !== null) { startingIndex = match.index + lengthOfDelimiter matchLength = bracketPattern.lastIndex - startingIndex - lengthOfDelimiter matches = matches.concat({ index: startingIndex, length: matchLength, }) match = bracketPattern.exec(inputText) } return matches }
Add function to match timestamps
Add function to match timestamps
TypeScript
agpl-3.0
briandk/transcriptase,briandk/transcriptase
--- +++ @@ -0,0 +1,24 @@ +interface Match { + index: number + length: number +} + +export const matchTimestamps = (inputText: string): Match[] => { + const lengthOfDelimiter = 1 // Have to advance past/before the opening/closing brackets + let bracketPattern = /\[(\d|:|.)+\]/g + let match = bracketPattern.exec(inputText) + let matches: Match[] = [] + let startingIndex + let matchLength + + while (match !== null) { + startingIndex = match.index + lengthOfDelimiter + matchLength = bracketPattern.lastIndex - startingIndex - lengthOfDelimiter + matches = matches.concat({ + index: startingIndex, + length: matchLength, + }) + match = bracketPattern.exec(inputText) + } + return matches +}
4380ac0abff9be20252ad105faae616fe5668960
src/migration/1541082619105-AddForeignKeyConstraints.ts
src/migration/1541082619105-AddForeignKeyConstraints.ts
import {MigrationInterface, QueryRunner} from "typeorm"; export class AddForeignKeyConstraints1541082619105 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { // Remove duplicate foreign key await queryRunner.query("ALTER TABLE `datasets` DROP FOREIGN KEY `FK_d717ea97450b05d06316d69501a`") // Add missing foreign key constraints await queryRunner.query("ALTER TABLE `dataset_files` ADD CONSTRAINT `dataset_files_datasetId` FOREIGN KEY (`datasetId`) REFERENCES `datasets`(`id`)") await queryRunner.query("ALTER TABLE `sources` ADD CONSTRAINT `sources_datasetId` FOREIGN KEY (`datasetId`) REFERENCES `datasets`(`id`)") } public async down(queryRunner: QueryRunner): Promise<any> { await queryRunner.query("ALTER TABLE `datasets` ADD CONSTRAINT `FK_d717ea97450b05d06316d69501a` FOREIGN KEY (`createdByUserId`) REFERENCES `users` (`id`)") await queryRunner.query("ALTER TABLE `dataset_files` DROP FOREIGN KEY `dataset_files_datasetId`") await queryRunner.query("ALTER TABLE `sources` DROP FOREIGN KEY `sources_datasetId`") } }
Add & deduplicate foreign key constraints
Add & deduplicate foreign key constraints
TypeScript
mit
OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher
--- +++ @@ -0,0 +1,21 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +export class AddForeignKeyConstraints1541082619105 implements MigrationInterface { + + public async up(queryRunner: QueryRunner): Promise<any> { + // Remove duplicate foreign key + await queryRunner.query("ALTER TABLE `datasets` DROP FOREIGN KEY `FK_d717ea97450b05d06316d69501a`") + // Add missing foreign key constraints + await queryRunner.query("ALTER TABLE `dataset_files` ADD CONSTRAINT `dataset_files_datasetId` FOREIGN KEY (`datasetId`) REFERENCES `datasets`(`id`)") + await queryRunner.query("ALTER TABLE `sources` ADD CONSTRAINT `sources_datasetId` FOREIGN KEY (`datasetId`) REFERENCES `datasets`(`id`)") + } + + public async down(queryRunner: QueryRunner): Promise<any> { + await queryRunner.query("ALTER TABLE `datasets` ADD CONSTRAINT `FK_d717ea97450b05d06316d69501a` FOREIGN KEY (`createdByUserId`) REFERENCES `users` (`id`)") + await queryRunner.query("ALTER TABLE `dataset_files` DROP FOREIGN KEY `dataset_files_datasetId`") + await queryRunner.query("ALTER TABLE `sources` DROP FOREIGN KEY `sources_datasetId`") + } + +} + +
05ff8971e636967219f088bf247de616d897cbab
test/lib/mock-store.ts
test/lib/mock-store.ts
import { RecursiveProxyHandler } from 'electron-remote'; import { Store } from '../../src/lib/store'; import { Updatable } from '../../src/lib/updatable'; import { ChannelBase, User } from '../../src/lib/models/api-shapes'; export function createMockStore(seedData: any): Store { return RecursiveProxyHandler.create('mockStore', (names: Array<string>, params: Array<any>) => { const id = params[0]; const model = seedData[id]; switch (names[1]) { case 'channels': return new Updatable<ChannelBase>(() => Promise.resolve(model)); case 'users': return new Updatable<User>(() => Promise.resolve(model)); default: throw new Error(`${names[1]} not yet implemented in MockStore`); } }); }
Use Proxies to make a Mock store that returns what we tell it.
Use Proxies to make a Mock store that returns what we tell it.
TypeScript
bsd-3-clause
paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline
--- +++ @@ -0,0 +1,21 @@ +import { RecursiveProxyHandler } from 'electron-remote'; + +import { Store } from '../../src/lib/store'; +import { Updatable } from '../../src/lib/updatable'; +import { ChannelBase, User } from '../../src/lib/models/api-shapes'; + +export function createMockStore(seedData: any): Store { + return RecursiveProxyHandler.create('mockStore', (names: Array<string>, params: Array<any>) => { + const id = params[0]; + const model = seedData[id]; + + switch (names[1]) { + case 'channels': + return new Updatable<ChannelBase>(() => Promise.resolve(model)); + case 'users': + return new Updatable<User>(() => Promise.resolve(model)); + default: + throw new Error(`${names[1]} not yet implemented in MockStore`); + } + }); +}
9ec6265a7ac6ead18b802e9413d310202cf1f8aa
lib/router/utils.d.ts
lib/router/utils.d.ts
interface StoryData { viewMode?: string; storyId?: string; } interface SeparatorOptions { rootSeparator: string | RegExp; groupSeparator: string | RegExp; } export declare const knownNonViewModesRegex: RegExp; export declare const sanitize: (string: string) => string; export declare const toId: (kind: string, name: string) => string; export declare const parsePath: (path?: string) => StoryData; interface Query { [key: string]: any; } export declare const queryFromString: (s: string) => Query; export declare const queryFromLocation: (location: { search: string }) => Query; export declare const stringifyQuery: (query: Query) => any; export declare const getMatch: ( current: string, target: string, startsWith?: boolean ) => { path: string; }; export declare const parseKind: ( kind: string, { rootSeparator, groupSeparator }: SeparatorOptions ) => { root: string; groups: string[]; }; export {};
REFACTOR lib/router to make creating themes work for react15
REFACTOR lib/router to make creating themes work for react15
TypeScript
mit
storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook
--- +++ @@ -0,0 +1,33 @@ +interface StoryData { + viewMode?: string; + storyId?: string; +} +interface SeparatorOptions { + rootSeparator: string | RegExp; + groupSeparator: string | RegExp; +} +export declare const knownNonViewModesRegex: RegExp; +export declare const sanitize: (string: string) => string; +export declare const toId: (kind: string, name: string) => string; +export declare const parsePath: (path?: string) => StoryData; +interface Query { + [key: string]: any; +} +export declare const queryFromString: (s: string) => Query; +export declare const queryFromLocation: (location: { search: string }) => Query; +export declare const stringifyQuery: (query: Query) => any; +export declare const getMatch: ( + current: string, + target: string, + startsWith?: boolean +) => { + path: string; +}; +export declare const parseKind: ( + kind: string, + { rootSeparator, groupSeparator }: SeparatorOptions +) => { + root: string; + groups: string[]; +}; +export {};
8fc2bcc5ddc7827afd17262c560b75263dbd0032
src/crystalHover.ts
src/crystalHover.ts
import * as vscode from 'vscode' import { CrystalContext } from './crystalContext' export class CrystalHoverProvider extends CrystalContext implements vscode.HoverProvider { public currentLine public crystalOutput public crystalMessageObject constructor() { super() this.currentLine = -1 this.crystalOutput = '' this.crystalMessageObject = {} } async provideHover(document: vscode.TextDocument, position: vscode.Position, token) { if (this.currentLine != position.line) { try { this.crystalOutput = await this.crystalContext(document, position, 'types') this.crystalMessageObject = JSON.parse(this.crystalOutput.toString()) this.currentLine = position.line } catch (err) { console.error('ERROR: JSON.parse failed to parse crystal context output when hover') throw err } } if (this.crystalMessageObject.status == 'ok') { let range = document.getWordRangeAtPosition(new vscode.Position(position.line, position.character)) if (range) { let word = document.getText(range) for (let element of this.crystalMessageObject.contexts) { let type = element[word] if (type) { return new vscode.Hover(`${word} : ${type}`) } } } } else if (this.crystalMessageObject.status == 'disabled') { console.error('INFO: crystal context on hover is disabled') } } }
Add support to show variable type on Hover.
Add support to show variable type on Hover.
TypeScript
mit
faustinoaq/vscode-crystal-lang,faustinoaq/vscode-crystal-lang
--- +++ @@ -0,0 +1,43 @@ +import * as vscode from 'vscode' +import { CrystalContext } from './crystalContext' + +export class CrystalHoverProvider extends CrystalContext implements vscode.HoverProvider { + + public currentLine + public crystalOutput + public crystalMessageObject + + constructor() { + super() + this.currentLine = -1 + this.crystalOutput = '' + this.crystalMessageObject = {} + } + + async provideHover(document: vscode.TextDocument, position: vscode.Position, token) { + if (this.currentLine != position.line) { + try { + this.crystalOutput = await this.crystalContext(document, position, 'types') + this.crystalMessageObject = JSON.parse(this.crystalOutput.toString()) + this.currentLine = position.line + } catch (err) { + console.error('ERROR: JSON.parse failed to parse crystal context output when hover') + throw err + } + } + if (this.crystalMessageObject.status == 'ok') { + let range = document.getWordRangeAtPosition(new vscode.Position(position.line, position.character)) + if (range) { + let word = document.getText(range) + for (let element of this.crystalMessageObject.contexts) { + let type = element[word] + if (type) { + return new vscode.Hover(`${word} : ${type}`) + } + } + } + } else if (this.crystalMessageObject.status == 'disabled') { + console.error('INFO: crystal context on hover is disabled') + } + } +}
53a7848f4e2e57612e5531037e1fc2bf29d77986
lib/omnisharp-atom/services/apply-changes.ts
lib/omnisharp-atom/services/apply-changes.ts
var Range = require('atom').Range; import {Observable} from "rx"; export function applyChanges(editor: Atom.TextEditor, response: { Changes: OmniSharp.Models.LinePositionSpanTextChange[]; }); export function applyChanges(editor: Atom.TextEditor, response: { Buffer: string }); export function applyChanges(editor: Atom.TextEditor, response: any) { if (response && response.Changes) { var buffer = editor.getBuffer(); var checkpoint = buffer.createCheckpoint(); response.Changes.forEach((change) => { var range = new Range([change.StartLine, change.StartColumn], [change.EndLine, change.EndColumn]); buffer.setTextInRange(range, change.NewText); }); buffer.groupChangesSinceCheckpoint(checkpoint); } else if (response && response.Buffer) { editor.setText(response.Buffer) } } // If you have preview tabs enabled, // they will actually try to close // with changes still. function resetPreviewTab() { var pane: HTMLElement = <any>atom.views.getView(atom.workspace.getActivePane()); if (pane) { var title = pane.querySelector('.title.temp'); if (title) { title.classList.remove('temp'); } var tab = pane.querySelector('.preview-tab.active'); if (tab) { tab.classList.remove('preview-tab'); (<any>tab).isPreviewTab = false; } } } export function applyAllChanges(changes: OmniSharp.Models.ModifiedFileResponse[]) { resetPreviewTab(); return Observable.from(changes || []) .concatMap(change => atom.workspace.open(change.FileName, undefined) .then(editor => { resetPreviewTab(); applyChanges(editor, change); })) .subscribe(); }
Fix apply changes to work when response is null
Fix apply changes to work when response is null
TypeScript
mit
OmniSharp/omnisharp-atom,OmniSharp/omnisharp-atom,OmniSharp/omnisharp-atom
--- +++ @@ -0,0 +1,51 @@ +var Range = require('atom').Range; +import {Observable} from "rx"; + + +export function applyChanges(editor: Atom.TextEditor, response: { Changes: OmniSharp.Models.LinePositionSpanTextChange[]; }); +export function applyChanges(editor: Atom.TextEditor, response: { Buffer: string }); +export function applyChanges(editor: Atom.TextEditor, response: any) { + if (response && response.Changes) { + var buffer = editor.getBuffer(); + var checkpoint = buffer.createCheckpoint(); + + response.Changes.forEach((change) => { + var range = new Range([change.StartLine, change.StartColumn], [change.EndLine, change.EndColumn]); + buffer.setTextInRange(range, change.NewText); + }); + + buffer.groupChangesSinceCheckpoint(checkpoint); + } else if (response && response.Buffer) { + editor.setText(response.Buffer) + } +} + +// If you have preview tabs enabled, +// they will actually try to close +// with changes still. +function resetPreviewTab() { + var pane: HTMLElement = <any>atom.views.getView(atom.workspace.getActivePane()); + if (pane) { + var title = pane.querySelector('.title.temp'); + if (title) { + title.classList.remove('temp'); + } + + var tab = pane.querySelector('.preview-tab.active'); + if (tab) { + tab.classList.remove('preview-tab'); + (<any>tab).isPreviewTab = false; + } + } +} + +export function applyAllChanges(changes: OmniSharp.Models.ModifiedFileResponse[]) { + resetPreviewTab(); + return Observable.from(changes || []) + .concatMap(change => atom.workspace.open(change.FileName, undefined) + .then(editor => { + resetPreviewTab(); + applyChanges(editor, change); + })) + .subscribe(); +}
fc192d4c0baa70da3e523f069d2332ee3a3278b5
lib/asyncutil_test.ts
lib/asyncutil_test.ts
import Q = require('q'); import testLib = require('./test'); import asyncutil = require('./asyncutil'); testLib.addAsyncTest('test run sequence', (assert) => { var values = [1, 1, 2, 3, 5, 8, 13]; var runOrder : number[] = []; var funcs : Array<() => Q.Promise<number>> = []; values.forEach((value, index) => { funcs.push(() => { runOrder.push(index+1); return Q.resolve(value); }); }); asyncutil.runSequence(funcs).then((result) => { testLib.assertEqual(assert, result, values); testLib.assertEqual(assert, runOrder, [1, 2, 3, 4, 5, 6, 7]); testLib.continueTests(); }); }); testLib.runTests();
Add a missing unit test suite file to Git
Add a missing unit test suite file to Git
TypeScript
bsd-3-clause
robertknight/passcards,robertknight/passcards,robertknight/passcards,robertknight/passcards
--- +++ @@ -0,0 +1,26 @@ +import Q = require('q'); + +import testLib = require('./test'); +import asyncutil = require('./asyncutil'); + +testLib.addAsyncTest('test run sequence', (assert) => { + var values = [1, 1, 2, 3, 5, 8, 13]; + var runOrder : number[] = []; + + var funcs : Array<() => Q.Promise<number>> = []; + values.forEach((value, index) => { + funcs.push(() => { + runOrder.push(index+1); + return Q.resolve(value); + }); + }); + + asyncutil.runSequence(funcs).then((result) => { + testLib.assertEqual(assert, result, values); + testLib.assertEqual(assert, runOrder, [1, 2, 3, 4, 5, 6, 7]); + testLib.continueTests(); + }); +}); + +testLib.runTests(); +
a500f5ce64c3994f25721970c00e1c84eee15148
server/src/util/util.ts
server/src/util/util.ts
export function asPromise<T>(thenable: { then(fnOnFulfil: (value: T) => T | Promise<T> | void, fnOnReject?: (reason?: any) => any): any }) { return new Promise<T>((resolve, reject) => { thenable.then(resolve, reject); }); }
Convert Rx.Promise to ES2015 Promise
Convert Rx.Promise to ES2015 Promise
TypeScript
mit
Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker
--- +++ @@ -0,0 +1,6 @@ + +export function asPromise<T>(thenable: { then(fnOnFulfil: (value: T) => T | Promise<T> | void, fnOnReject?: (reason?: any) => any): any }) { + return new Promise<T>((resolve, reject) => { + thenable.then(resolve, reject); + }); +}
6869a05090fae498c711f1bbfa691f2cec59b3f1
lib/query/context.ts
lib/query/context.ts
/** * Copyright 2018 The Lovefield Project Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {assert} from '../base/assert'; import {Predicate} from '../base/predicate'; import {PredicateNode} from '../pred/predicate_node'; import {ValuePredicate} from '../pred/value_predicate'; import {Database} from '../schema/database'; import {Table} from '../schema/table'; // Base context for all query types. export abstract class Context { // Creates predicateMap such that predicates can be located by ID. private static buildPredicateMap(rootPredicate: PredicateNode): Map<number, Predicate> { const predicateMap = new Map<number, Predicate>(); rootPredicate.traverse((n) => { const node = n as PredicateNode as Predicate; predicateMap.set(node.getId(), node); return true; }); return predicateMap; } public schema: Database; public where: Predicate|null; public clonedFrom: Context|null; // A map used for locating predicates by ID. Instantiated lazily. private predicateMap: Map<number, Predicate>; constructor(schema: Database) { this.schema = schema; this.clonedFrom = null; this.where = null; this.predicateMap = null as any as Map<number, Predicate>; } public getPredicate(id: number): Predicate { if (this.predicateMap === null && this.where !== null) { this.predicateMap = Context.buildPredicateMap(this.where as PredicateNode); } const predicate: Predicate = this.predicateMap.get(id) as Predicate; assert(predicate !== undefined); return predicate; } public bind(values: any[]): Context { assert(this.clonedFrom === null); return this; } public bindValuesInSearchCondition(values: any[]): void { const searchCondition: PredicateNode = this.where as PredicateNode; if (searchCondition !== null) { searchCondition.traverse((node) => { if (node instanceof ValuePredicate) { node.bind(values); } return true; }); } } public abstract getScope(): Set<Table>; public abstract clone(): Context; protected cloneBase(context: Context): void { if (context.where) { this.where = context.where.copy(); } this.clonedFrom = context; } }
Add Context to setup query/ dir
Add Context to setup query/ dir
TypeScript
apache-2.0
arthurhsu/lovefield-ts,arthurhsu/lovefield-ts
--- +++ @@ -0,0 +1,88 @@ +/** + * Copyright 2018 The Lovefield Project Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {assert} from '../base/assert'; +import {Predicate} from '../base/predicate'; +import {PredicateNode} from '../pred/predicate_node'; +import {ValuePredicate} from '../pred/value_predicate'; +import {Database} from '../schema/database'; +import {Table} from '../schema/table'; + +// Base context for all query types. +export abstract class Context { + // Creates predicateMap such that predicates can be located by ID. + private static buildPredicateMap(rootPredicate: PredicateNode): + Map<number, Predicate> { + const predicateMap = new Map<number, Predicate>(); + rootPredicate.traverse((n) => { + const node = n as PredicateNode as Predicate; + predicateMap.set(node.getId(), node); + return true; + }); + return predicateMap; + } + + public schema: Database; + public where: Predicate|null; + public clonedFrom: Context|null; + + // A map used for locating predicates by ID. Instantiated lazily. + private predicateMap: Map<number, Predicate>; + + constructor(schema: Database) { + this.schema = schema; + this.clonedFrom = null; + this.where = null; + this.predicateMap = null as any as Map<number, Predicate>; + } + + public getPredicate(id: number): Predicate { + if (this.predicateMap === null && this.where !== null) { + this.predicateMap = + Context.buildPredicateMap(this.where as PredicateNode); + } + const predicate: Predicate = this.predicateMap.get(id) as Predicate; + assert(predicate !== undefined); + return predicate; + } + + public bind(values: any[]): Context { + assert(this.clonedFrom === null); + return this; + } + + public bindValuesInSearchCondition(values: any[]): void { + const searchCondition: PredicateNode = this.where as PredicateNode; + if (searchCondition !== null) { + searchCondition.traverse((node) => { + if (node instanceof ValuePredicate) { + node.bind(values); + } + return true; + }); + } + } + + public abstract getScope(): Set<Table>; + public abstract clone(): Context; + + protected cloneBase(context: Context): void { + if (context.where) { + this.where = context.where.copy(); + } + this.clonedFrom = context; + } +}
2c073ed4302f88ed088d24c18389d1ae0cef408f
test/server/requests.ts
test/server/requests.ts
// NOTE Running these tests requires the crossroads-education/eta-web-test module to be installed. process.env.ETA_TESTING = "true"; process.env.ETA_AUTH_PROVIDER = "cre-web-test"; import tests from "../../server/api/tests"; before(function(done) { this.timeout(20000); // plenty of time to initialize the server tests.init().then(() => { done(); }).catch(err => console.error(err)); }); describe("Requests", () => { it("should handle a 404 request properly", done => { tests.request() .get("/test/foobar") .expect(404, done); }); it("should handle a 500 request properly", done => { tests.request() .get("/test/error") .expect(500, done); }); });
Implement basic initial integration tests for 404 and 500
Implement basic initial integration tests for 404 and 500
TypeScript
mit
crossroads-education/eta,crossroads-education/eta
--- +++ @@ -0,0 +1,26 @@ +// NOTE Running these tests requires the crossroads-education/eta-web-test module to be installed. + +process.env.ETA_TESTING = "true"; +process.env.ETA_AUTH_PROVIDER = "cre-web-test"; + +import tests from "../../server/api/tests"; + +before(function(done) { + this.timeout(20000); // plenty of time to initialize the server + tests.init().then(() => { + done(); + }).catch(err => console.error(err)); +}); + +describe("Requests", () => { + it("should handle a 404 request properly", done => { + tests.request() + .get("/test/foobar") + .expect(404, done); + }); + it("should handle a 500 request properly", done => { + tests.request() + .get("/test/error") + .expect(500, done); + }); +});
84ec5813b66df26a172c3166aaedc21ddf327536
desktop/app/src/sandy-chrome/appinspect/troubleshooting/GuideEndScreen.tsx
desktop/app/src/sandy-chrome/appinspect/troubleshooting/GuideEndScreen.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import {Button, Modal} from 'antd'; import {Layout} from 'flipper-plugin'; import {getInstance as getFormInstance} from '../../../fb-stubs/Logger'; import {useDispatch} from '../../../utils/useStore'; import {setStaticView} from '../../../reducers/connections'; import SupportRequestFormV2 from '../../../fb-stubs/SupportRequestFormV2'; export function GuideEndScreen(props: { showModal: boolean; toggleModal: (arg0: boolean) => void; }) { const dispatch = useDispatch(); const problemSolved = () => { props.toggleModal(false); }; const loadForm = () => { getFormInstance().track('usage', 'support-form-source', { source: 'sidebar', group: undefined, }); dispatch(setStaticView(SupportRequestFormV2)); problemSolved(); }; return ( <Modal title="Has your problem been solved OR do you want to file a support request?" visible={props.showModal} width={650} footer={null} onCancel={() => props.toggleModal(false)} bodyStyle={{maxHeight: 800, overflow: 'auto'}}> <Layout.Horizontal gap="huge"> <Button type="primary" style={{flex: 1, marginBottom: 18}} onClick={problemSolved}> Problem Solved </Button> </Layout.Horizontal> <Layout.Horizontal gap="huge"> <Button type="primary" style={{flex: 1}} onClick={loadForm}> File Support Request </Button> </Layout.Horizontal> </Modal> ); }
Add modal dialogue for the end screen
Add modal dialogue for the end screen Summary: - Added a dialogue with 2 possible end state buttons - Problem Solved - File Support Request - This diff is the start of the implementation of the troubleshooting wizard. - The previously implemented troubleshooting button (D29993355 (https://github.com/facebook/flipper/commit/921a65bc17ce4a9fb9d65689fe8e8d27ebc843fc)) now links to a modal dialogue box. - This is essentially the last screen of the troubleshooting guide to be implemented. - We have options for a user to either select file a support request if the issue persists after navigating the guide or click on problem solved if the guide helped them solve it. - Selecting option 2 (file support request) links to the pre-existing form The modal has been implemented as an independent reusable component and can be easily extended. Reviewed By: passy Differential Revision: D30069270 fbshipit-source-id: f61bf8c03de786e11b7f06194328dbee703abf8b
TypeScript
mit
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
--- +++ @@ -0,0 +1,58 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import React from 'react'; +import {Button, Modal} from 'antd'; +import {Layout} from 'flipper-plugin'; +import {getInstance as getFormInstance} from '../../../fb-stubs/Logger'; +import {useDispatch} from '../../../utils/useStore'; +import {setStaticView} from '../../../reducers/connections'; +import SupportRequestFormV2 from '../../../fb-stubs/SupportRequestFormV2'; + +export function GuideEndScreen(props: { + showModal: boolean; + toggleModal: (arg0: boolean) => void; +}) { + const dispatch = useDispatch(); + const problemSolved = () => { + props.toggleModal(false); + }; + const loadForm = () => { + getFormInstance().track('usage', 'support-form-source', { + source: 'sidebar', + group: undefined, + }); + dispatch(setStaticView(SupportRequestFormV2)); + problemSolved(); + }; + + return ( + <Modal + title="Has your problem been solved OR do you want to file a support request?" + visible={props.showModal} + width={650} + footer={null} + onCancel={() => props.toggleModal(false)} + bodyStyle={{maxHeight: 800, overflow: 'auto'}}> + <Layout.Horizontal gap="huge"> + <Button + type="primary" + style={{flex: 1, marginBottom: 18}} + onClick={problemSolved}> + Problem Solved + </Button> + </Layout.Horizontal> + <Layout.Horizontal gap="huge"> + <Button type="primary" style={{flex: 1}} onClick={loadForm}> + File Support Request + </Button> + </Layout.Horizontal> + </Modal> + ); +}
e437bae6e3d475d52c261eee51bf430df156ab59
test/property-decorators/to-lowercase.spec.ts
test/property-decorators/to-lowercase.spec.ts
import { ToLowercase } from './../../src/'; describe('ToLowercase decorator', () => { it('should throw an error when is applied over non string property', () => { class TestClassToLowercaseProperty { @ToLowercase() myProp: number; } let testClass = new TestClassToLowercaseProperty(); expect(() => testClass.myProp = 7).toThrowError('The ToLowercase decorator has to be used over string object'); }); it('should apply default behavior', () => { class TestClassToLowercaseProperty { @ToLowercase() myProp: string; } let testClass = new TestClassToLowercaseProperty(); let stringToAssign = 'A long String to Be tested'; testClass.myProp = stringToAssign; expect(testClass.myProp).toEqual(stringToAssign.toLowerCase()); }); it('should use locale', () => { class TestClassToLowercaseProperty { @ToLowercase({ useLocale: true }) myProp: string; } let testClass = new TestClassToLowercaseProperty(); let stringToAssign = 'A long String to Be tested'; testClass.myProp = stringToAssign; expect(testClass.myProp).toEqual(stringToAssign.toLocaleLowerCase()); }); });
Add unit test cases for toLowercase decorator
Add unit test cases for toLowercase decorator
TypeScript
mit
semagarcia/typescript-decorators,semagarcia/typescript-decorators
--- +++ @@ -0,0 +1,35 @@ +import { ToLowercase } from './../../src/'; + +describe('ToLowercase decorator', () => { + + it('should throw an error when is applied over non string property', () => { + class TestClassToLowercaseProperty { + @ToLowercase() myProp: number; + } + let testClass = new TestClassToLowercaseProperty(); + expect(() => testClass.myProp = 7).toThrowError('The ToLowercase decorator has to be used over string object'); + }); + + it('should apply default behavior', () => { + class TestClassToLowercaseProperty { + @ToLowercase() myProp: string; + } + + let testClass = new TestClassToLowercaseProperty(); + let stringToAssign = 'A long String to Be tested'; + testClass.myProp = stringToAssign; + expect(testClass.myProp).toEqual(stringToAssign.toLowerCase()); + }); + + it('should use locale', () => { + class TestClassToLowercaseProperty { + @ToLowercase({ useLocale: true }) myProp: string; + } + + let testClass = new TestClassToLowercaseProperty(); + let stringToAssign = 'A long String to Be tested'; + testClass.myProp = stringToAssign; + expect(testClass.myProp).toEqual(stringToAssign.toLocaleLowerCase()); + }); + +});
29c4fef65a897b146d780319037ad547a6061541
src/components/Watchers/EmptyWatchers.tsx
src/components/Watchers/EmptyWatchers.tsx
import * as React from 'react'; import { NonIdealState } from '@blueprintjs/core'; export interface Props {} class EmptyWatchers extends React.PureComponent<Props, never> { public render() { return ( <NonIdealState title="You have no watchers." description="Watchers periodically will accept a HIT. They're useful for hoarding lots of HITs or snagging rare ones." visual="menu-closed" /> ); } } export default EmptyWatchers;
Add empty state for watchers.
Add empty state for watchers.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -0,0 +1,18 @@ +import * as React from 'react'; +import { NonIdealState } from '@blueprintjs/core'; + +export interface Props {} + +class EmptyWatchers extends React.PureComponent<Props, never> { + public render() { + return ( + <NonIdealState + title="You have no watchers." + description="Watchers periodically will accept a HIT. They're useful for hoarding lots of HITs or snagging rare ones." + visual="menu-closed" + /> + ); + } +} + +export default EmptyWatchers;
0764c64dde659ca9d06c7cb3124677c4efd2785a
db/migration/1559633072583-AddForeignKeyConstraints.ts
db/migration/1559633072583-AddForeignKeyConstraints.ts
import {MigrationInterface, QueryRunner} from "typeorm"; export class AddForeignKeyConstraints1559633072583 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { // Remove all chart_slug_redirects that have had their chart deleted await queryRunner.query(` DELETE t FROM chart_slug_redirects AS t LEFT JOIN charts ON charts.id = t.chart_id WHERE charts.id IS NULL `) await queryRunner.query("ALTER TABLE `chart_slug_redirects` ADD CONSTRAINT `chart_slug_redirects_chart_id` FOREIGN KEY (`chart_id`) REFERENCES `charts`(`id`)") await queryRunner.query("ALTER TABLE `chart_revisions` ADD CONSTRAINT `chart_revisions_userId` FOREIGN KEY (`userId`) REFERENCES `users`(`id`)") } public async down(queryRunner: QueryRunner): Promise<any> { await queryRunner.query("ALTER TABLE `chart_slug_redirects` DROP FOREIGN KEY `chart_slug_redirects_chart_id`") await queryRunner.query("ALTER TABLE `chart_revisions` DROP FOREIGN KEY `chart_revisions_userId`") } }
Add foreign keys for chart_revisions & chart_slug_redirects
Add foreign keys for chart_revisions & chart_slug_redirects Ideally, chart_revisions should also have a chartId foreign key, but then charts that get deleted must have all revisions deleted. It's better to not enforce this constraint. In the future, we should really just *mark* charts as deleted, not delete the chart rows. Same applies for the other tables.
TypeScript
mit
owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher
--- +++ @@ -0,0 +1,21 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +export class AddForeignKeyConstraints1559633072583 implements MigrationInterface { + + public async up(queryRunner: QueryRunner): Promise<any> { + // Remove all chart_slug_redirects that have had their chart deleted + await queryRunner.query(` + DELETE t FROM chart_slug_redirects AS t + LEFT JOIN charts ON charts.id = t.chart_id + WHERE charts.id IS NULL + `) + await queryRunner.query("ALTER TABLE `chart_slug_redirects` ADD CONSTRAINT `chart_slug_redirects_chart_id` FOREIGN KEY (`chart_id`) REFERENCES `charts`(`id`)") + await queryRunner.query("ALTER TABLE `chart_revisions` ADD CONSTRAINT `chart_revisions_userId` FOREIGN KEY (`userId`) REFERENCES `users`(`id`)") + } + + public async down(queryRunner: QueryRunner): Promise<any> { + await queryRunner.query("ALTER TABLE `chart_slug_redirects` DROP FOREIGN KEY `chart_slug_redirects_chart_id`") + await queryRunner.query("ALTER TABLE `chart_revisions` DROP FOREIGN KEY `chart_revisions_userId`") + } + +}
d90b63ede980d5b3dd5962f6881b8b1a0b8286d9
connect/connect-tests.ts
connect/connect-tests.ts
/// <reference path="./connect.d.ts" /> import * as http from "http"; import * as connect from "connect"; const app = connect(); // log all requests app.use((req, res, next) => { console.log(req, res); next(); }); // Stop on errors app.use((err, req, res, next) => { if (err) { return res.end(`Error: ${err}`); } next(); }); // respond to all requests app.use((req, res) => { res.end("Hello from Connect!\n"); }); //create node.js http server and listen on port http.createServer(app).listen(3000); //create node.js http server and listen on port using connect shortcut app.listen(3000);
Add tests for connect typings
Add tests for connect typings
TypeScript
mit
teves-castro/DefinitelyTyped,arusakov/DefinitelyTyped,stacktracejs/DefinitelyTyped,donnut/DefinitelyTyped,mattanja/DefinitelyTyped,pwelter34/DefinitelyTyped,xStrom/DefinitelyTyped,borisyankov/DefinitelyTyped,behzad888/DefinitelyTyped,abbasmhd/DefinitelyTyped,schmuli/DefinitelyTyped,glenndierckx/DefinitelyTyped,greglo/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,nmalaguti/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,rolandzwaga/DefinitelyTyped,mshmelev/DefinitelyTyped,esperco/DefinitelyTyped,UzEE/DefinitelyTyped,herrmanno/DefinitelyTyped,bdoss/DefinitelyTyped,takenet/DefinitelyTyped,nakakura/DefinitelyTyped,AgentME/DefinitelyTyped,sixinli/DefinitelyTyped,use-strict/DefinitelyTyped,syuilo/DefinitelyTyped,zuzusik/DefinitelyTyped,wilfrem/DefinitelyTyped,gandjustas/DefinitelyTyped,onecentlin/DefinitelyTyped,pocesar/DefinitelyTyped,progre/DefinitelyTyped,arusakov/DefinitelyTyped,ashwinr/DefinitelyTyped,davidpricedev/DefinitelyTyped,UzEE/DefinitelyTyped,sandersky/DefinitelyTyped,smrq/DefinitelyTyped,teves-castro/DefinitelyTyped,flyfishMT/DefinitelyTyped,aciccarello/DefinitelyTyped,drinchev/DefinitelyTyped,aciccarello/DefinitelyTyped,HPFOD/DefinitelyTyped,subjectix/DefinitelyTyped,ajtowf/DefinitelyTyped,stacktracejs/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,danfma/DefinitelyTyped,abbasmhd/DefinitelyTyped,Penryn/DefinitelyTyped,Zzzen/DefinitelyTyped,ashwinr/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,elisee/DefinitelyTyped,alexdresko/DefinitelyTyped,hellopao/DefinitelyTyped,jraymakers/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,greglo/DefinitelyTyped,frogcjn/DefinitelyTyped,nakakura/DefinitelyTyped,jimthedev/DefinitelyTyped,reppners/DefinitelyTyped,sledorze/DefinitelyTyped,onecentlin/DefinitelyTyped,schmuli/DefinitelyTyped,martinduparc/DefinitelyTyped,emanuelhp/DefinitelyTyped,Dashlane/DefinitelyTyped,Pro/DefinitelyTyped,HPFOD/DefinitelyTyped,paulmorphy/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,abner/DefinitelyTyped,mareek/DefinitelyTyped,evandrewry/DefinitelyTyped,zuzusik/DefinitelyTyped,alvarorahul/DefinitelyTyped,fredgalvao/DefinitelyTyped,alvarorahul/DefinitelyTyped,chrootsu/DefinitelyTyped,dflor003/DefinitelyTyped,magny/DefinitelyTyped,fredgalvao/DefinitelyTyped,chrismbarr/DefinitelyTyped,benishouga/DefinitelyTyped,AgentME/DefinitelyTyped,arma-gast/DefinitelyTyped,Zorgatone/DefinitelyTyped,donnut/DefinitelyTyped,musicist288/DefinitelyTyped,pocesar/DefinitelyTyped,arcticwaters/DefinitelyTyped,RX14/DefinitelyTyped,martinduparc/DefinitelyTyped,nitintutlani/DefinitelyTyped,Zzzen/DefinitelyTyped,dmoonfire/DefinitelyTyped,chrismbarr/DefinitelyTyped,paulmorphy/DefinitelyTyped,alainsahli/DefinitelyTyped,reppners/DefinitelyTyped,whoeverest/DefinitelyTyped,damianog/DefinitelyTyped,QuatroCode/DefinitelyTyped,esperco/DefinitelyTyped,rschmukler/DefinitelyTyped,gyohk/DefinitelyTyped,egeland/DefinitelyTyped,hellopao/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,olemp/DefinitelyTyped,philippstucki/DefinitelyTyped,gandjustas/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,zuzusik/DefinitelyTyped,raijinsetsu/DefinitelyTyped,jraymakers/DefinitelyTyped,daptiv/DefinitelyTyped,Karabur/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,vagarenko/DefinitelyTyped,ryan10132/DefinitelyTyped,axelcostaspena/DefinitelyTyped,georgemarshall/DefinitelyTyped,aindlq/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,mattblang/DefinitelyTyped,dmoonfire/DefinitelyTyped,benliddicott/DefinitelyTyped,YousefED/DefinitelyTyped,raijinsetsu/DefinitelyTyped,subash-a/DefinitelyTyped,shlomiassaf/DefinitelyTyped,PopSugar/DefinitelyTyped,nobuoka/DefinitelyTyped,rschmukler/DefinitelyTyped,newclear/DefinitelyTyped,olemp/DefinitelyTyped,chrootsu/DefinitelyTyped,optical/DefinitelyTyped,erosb/DefinitelyTyped,shlomiassaf/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,arcticwaters/DefinitelyTyped,micurs/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,Dominator008/DefinitelyTyped,Litee/DefinitelyTyped,georgemarshall/DefinitelyTyped,jimthedev/DefinitelyTyped,richardTowers/DefinitelyTyped,markogresak/DefinitelyTyped,martinduparc/DefinitelyTyped,bennett000/DefinitelyTyped,borisyankov/DefinitelyTyped,abner/DefinitelyTyped,takenet/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,tan9/DefinitelyTyped,chbrown/DefinitelyTyped,mcliment/DefinitelyTyped,yuit/DefinitelyTyped,davidpricedev/DefinitelyTyped,applesaucers/lodash-invokeMap,scriby/DefinitelyTyped,alextkachman/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,jsaelhof/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,isman-usoh/DefinitelyTyped,syuilo/DefinitelyTyped,nitintutlani/DefinitelyTyped,yuit/DefinitelyTyped,omidkrad/DefinitelyTyped,emanuelhp/DefinitelyTyped,hatz48/DefinitelyTyped,jsaelhof/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,alextkachman/DefinitelyTyped,dydek/DefinitelyTyped,stephenjelfs/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,vagarenko/DefinitelyTyped,rcchen/DefinitelyTyped,OpenMaths/DefinitelyTyped,AgentME/DefinitelyTyped,minodisk/DefinitelyTyped,Karabur/DefinitelyTyped,one-pieces/DefinitelyTyped,nainslie/DefinitelyTyped,RX14/DefinitelyTyped,hellopao/DefinitelyTyped,flyfishMT/DefinitelyTyped,gcastre/DefinitelyTyped,mshmelev/DefinitelyTyped,jasonswearingen/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,Ptival/DefinitelyTyped,newclear/DefinitelyTyped,benishouga/DefinitelyTyped,wilfrem/DefinitelyTyped,mattanja/DefinitelyTyped,danfma/DefinitelyTyped,sledorze/DefinitelyTyped,eugenpodaru/DefinitelyTyped,johan-gorter/DefinitelyTyped,bennett000/DefinitelyTyped,egeland/DefinitelyTyped,MugeSo/DefinitelyTyped,bilou84/DefinitelyTyped,behzad888/DefinitelyTyped,xStrom/DefinitelyTyped,frogcjn/DefinitelyTyped,mhegazy/DefinitelyTyped,amanmahajan7/DefinitelyTyped,pwelter34/DefinitelyTyped,QuatroCode/DefinitelyTyped,philippstucki/DefinitelyTyped,nainslie/DefinitelyTyped,sclausen/DefinitelyTyped,Litee/DefinitelyTyped,Zorgatone/DefinitelyTyped,trystanclarke/DefinitelyTyped,applesaucers/lodash-invokeMap,arma-gast/DefinitelyTyped,MugeSo/DefinitelyTyped,gyohk/DefinitelyTyped,optical/DefinitelyTyped,georgemarshall/DefinitelyTyped,damianog/DefinitelyTyped,AgentME/DefinitelyTyped,minodisk/DefinitelyTyped,johan-gorter/DefinitelyTyped,alexdresko/DefinitelyTyped,OpenMaths/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,progre/DefinitelyTyped,psnider/DefinitelyTyped,psnider/DefinitelyTyped,subash-a/DefinitelyTyped,dydek/DefinitelyTyped,nycdotnet/DefinitelyTyped,stephenjelfs/DefinitelyTyped,bdoss/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,mjjames/DefinitelyTyped,nobuoka/DefinitelyTyped,tan9/DefinitelyTyped,timjk/DefinitelyTyped,nycdotnet/DefinitelyTyped,mhegazy/DefinitelyTyped,YousefED/DefinitelyTyped,lseguin42/DefinitelyTyped,Syati/DefinitelyTyped,drinchev/DefinitelyTyped,ajtowf/DefinitelyTyped,smrq/DefinitelyTyped,nmalaguti/DefinitelyTyped,elisee/DefinitelyTyped,jasonswearingen/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,EnableSoftware/DefinitelyTyped,Syati/DefinitelyTyped,mcrawshaw/DefinitelyTyped,magny/DefinitelyTyped,florentpoujol/DefinitelyTyped,rcchen/DefinitelyTyped,mattblang/DefinitelyTyped,arusakov/DefinitelyTyped,Penryn/DefinitelyTyped,Dashlane/DefinitelyTyped,schmuli/DefinitelyTyped,mjjames/DefinitelyTyped,dsebastien/DefinitelyTyped,psnider/DefinitelyTyped,Pro/DefinitelyTyped,trystanclarke/DefinitelyTyped,Dominator008/DefinitelyTyped,jbrantly/DefinitelyTyped,georgemarshall/DefinitelyTyped,vasek17/DefinitelyTyped,florentpoujol/DefinitelyTyped,rolandzwaga/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,gcastre/DefinitelyTyped,use-strict/DefinitelyTyped,amir-arad/DefinitelyTyped,aciccarello/DefinitelyTyped,mareek/DefinitelyTyped,hatz48/DefinitelyTyped,EnableSoftware/DefinitelyTyped,benishouga/DefinitelyTyped,dsebastien/DefinitelyTyped,nfriend/DefinitelyTyped,mcrawshaw/DefinitelyTyped,jimthedev/DefinitelyTyped,sclausen/DefinitelyTyped,Ptival/DefinitelyTyped,adamcarr/DefinitelyTyped,amanmahajan7/DefinitelyTyped,pocesar/DefinitelyTyped,isman-usoh/DefinitelyTyped,glenndierckx/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,scriby/DefinitelyTyped,AbraaoAlves/DefinitelyTyped
--- +++ @@ -0,0 +1,32 @@ +/// <reference path="./connect.d.ts" /> + +import * as http from "http"; +import * as connect from "connect"; + +const app = connect(); + +// log all requests +app.use((req, res, next) => { + console.log(req, res); + next(); +}); + +// Stop on errors +app.use((err, req, res, next) => { + if (err) { + return res.end(`Error: ${err}`); + } + + next(); +}); + +// respond to all requests +app.use((req, res) => { + res.end("Hello from Connect!\n"); +}); + +//create node.js http server and listen on port +http.createServer(app).listen(3000); + +//create node.js http server and listen on port using connect shortcut +app.listen(3000);
5d79995db954c8ec568cc64fab27c9c4d21ffad6
src/components/Watchers/AddWatcherToast.tsx
src/components/Watchers/AddWatcherToast.tsx
import { connect, Dispatch } from 'react-redux'; import { TextContainer } from '@shopify/polaris'; import { AddWatcher, addWatcher } from '../../actions/watcher'; import * as React from 'react'; import { Watcher, SearchResult } from '../../types'; export interface OwnProps { readonly hit: SearchResult; } export interface Handlers { readonly onAddWatcher: (watcher: Watcher) => void; } class AddWatcherToast extends React.Component<OwnProps & Handlers, never> { public render() { return <TextContainer>Sample Text</TextContainer>; } } const mapDispatch = (dispatch: Dispatch<AddWatcher>): Handlers => ({ onAddWatcher: (watcher: Watcher) => dispatch(addWatcher(watcher)) }); export default connect(null, mapDispatch)(AddWatcherToast);
Add a connected component to add watchers from a toast.
Add a connected component to add watchers from a toast.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -0,0 +1,25 @@ +import { connect, Dispatch } from 'react-redux'; +import { TextContainer } from '@shopify/polaris'; +import { AddWatcher, addWatcher } from '../../actions/watcher'; +import * as React from 'react'; +import { Watcher, SearchResult } from '../../types'; + +export interface OwnProps { + readonly hit: SearchResult; +} + +export interface Handlers { + readonly onAddWatcher: (watcher: Watcher) => void; +} + +class AddWatcherToast extends React.Component<OwnProps & Handlers, never> { + public render() { + return <TextContainer>Sample Text</TextContainer>; + } +} + +const mapDispatch = (dispatch: Dispatch<AddWatcher>): Handlers => ({ + onAddWatcher: (watcher: Watcher) => dispatch(addWatcher(watcher)) +}); + +export default connect(null, mapDispatch)(AddWatcherToast);
16a87c59ee14e75fc2e55d4d129f62bd2dde90e2
src/modal/modal-options.ts
src/modal/modal-options.ts
/** * Created by William on 10/07/2017. */ export interface ModalOptions { icon: string; title: string; color?: string; height?: number; width?: number; draggable?: boolean; maximizable?: boolean; minimizable?: boolean; }
Create interface for modal options.
feat(modal): Create interface for modal options.
TypeScript
mit
TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui
--- +++ @@ -0,0 +1,13 @@ +/** + * Created by William on 10/07/2017. + */ +export interface ModalOptions { + icon: string; + title: string; + color?: string; + height?: number; + width?: number; + draggable?: boolean; + maximizable?: boolean; + minimizable?: boolean; +}
1e123fc91a0d23f65c4b42b063b9422c62314823
app/src/ui/lib/tooltipped-content.tsx
app/src/ui/lib/tooltipped-content.tsx
import * as React from 'react' import { ITooltipProps, Tooltip } from './tooltip' import { createObservableRef } from './observable-ref' interface ITooltippedContentProps extends Omit<ITooltipProps<HTMLElement>, 'target'> { readonly tooltip: JSX.Element | string readonly wrapperElement?: 'span' | 'div' } /** A button component that can be unchecked or checked by the user. */ export class TooltippedContent extends React.Component< ITooltippedContentProps > { private wrapperRef = createObservableRef<HTMLElement>() public render() { const { tooltip, wrapperElement, children, ...rest } = this.props return React.createElement(wrapperElement ?? 'span', { ref: this.wrapperRef, children: ( <> <Tooltip target={this.wrapperRef} {...rest}> {tooltip} </Tooltip> {children} </> ), }) } }
Add a simpler tooltip component
Add a simpler tooltip component
TypeScript
mit
shiftkey/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,say25/desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,desktop/desktop,artivilla/desktop
--- +++ @@ -0,0 +1,32 @@ +import * as React from 'react' +import { ITooltipProps, Tooltip } from './tooltip' +import { createObservableRef } from './observable-ref' + +interface ITooltippedContentProps + extends Omit<ITooltipProps<HTMLElement>, 'target'> { + readonly tooltip: JSX.Element | string + readonly wrapperElement?: 'span' | 'div' +} + +/** A button component that can be unchecked or checked by the user. */ +export class TooltippedContent extends React.Component< + ITooltippedContentProps +> { + private wrapperRef = createObservableRef<HTMLElement>() + + public render() { + const { tooltip, wrapperElement, children, ...rest } = this.props + + return React.createElement(wrapperElement ?? 'span', { + ref: this.wrapperRef, + children: ( + <> + <Tooltip target={this.wrapperRef} {...rest}> + {tooltip} + </Tooltip> + {children} + </> + ), + }) + } +}
8c4257bd4d441b017df4c75a0ac133462227a22a
src/components/AccordionItemHeading.spec.tsx
src/components/AccordionItemHeading.spec.tsx
import * as React from 'react'; import { cleanup, render } from 'react-testing-library'; import Accordion from './Accordion'; import AccordionItem from './AccordionItem'; import AccordionItemHeading from './AccordionItemHeading'; enum UUIDS { FOO = 'FOO', BAR = 'Bar', } describe('AccordionItem', () => { afterEach(() => { cleanup(); }); it('renders without erroring', () => { expect(() => { render(<Accordion />); }).not.toThrow(); }); describe('className + expandedClassName', () => { it('are “BEM” by default', () => { const { getByTestId } = render( <Accordion preExpanded={[UUIDS.FOO]}> <AccordionItem uuid={UUIDS.FOO}> <AccordionItemHeading data-testid={UUIDS.FOO} /> </AccordionItem> <AccordionItem uuid={UUIDS.BAR}> <AccordionItemHeading data-testid={UUIDS.BAR} /> </AccordionItem> </Accordion>, ); expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ 'accordion__heading', 'accordion__heading--expanded', ]); expect(Array.from(getByTestId(UUIDS.BAR).classList)).toEqual([ 'accordion__heading', ]); }); it('can be overridden', () => { const { getByTestId } = render( <Accordion preExpanded={[UUIDS.FOO]}> <AccordionItem uuid={UUIDS.FOO}> <AccordionItemHeading data-testid={UUIDS.FOO} className="foo" expandedClassName="foo--expanded" /> </AccordionItem> <AccordionItem uuid={UUIDS.BAR}> <AccordionItemHeading data-testid={UUIDS.BAR} className="foo" expandedClassName="foo--expanded" /> </AccordionItem> </Accordion>, ); expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ 'foo', 'foo--expanded', ]); expect(Array.from(getByTestId(UUIDS.BAR).classList)).toEqual([ 'foo', ]); }); }); });
Add unit tests for classnames in AccordionItemHeading
Add unit tests for classnames in AccordionItemHeading
TypeScript
mit
springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion
--- +++ @@ -0,0 +1,74 @@ +import * as React from 'react'; +import { cleanup, render } from 'react-testing-library'; +import Accordion from './Accordion'; +import AccordionItem from './AccordionItem'; +import AccordionItemHeading from './AccordionItemHeading'; + +enum UUIDS { + FOO = 'FOO', + BAR = 'Bar', +} + +describe('AccordionItem', () => { + afterEach(() => { + cleanup(); + }); + + it('renders without erroring', () => { + expect(() => { + render(<Accordion />); + }).not.toThrow(); + }); + + describe('className + expandedClassName', () => { + it('are “BEM” by default', () => { + const { getByTestId } = render( + <Accordion preExpanded={[UUIDS.FOO]}> + <AccordionItem uuid={UUIDS.FOO}> + <AccordionItemHeading data-testid={UUIDS.FOO} /> + </AccordionItem> + <AccordionItem uuid={UUIDS.BAR}> + <AccordionItemHeading data-testid={UUIDS.BAR} /> + </AccordionItem> + </Accordion>, + ); + + expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ + 'accordion__heading', + 'accordion__heading--expanded', + ]); + expect(Array.from(getByTestId(UUIDS.BAR).classList)).toEqual([ + 'accordion__heading', + ]); + }); + + it('can be overridden', () => { + const { getByTestId } = render( + <Accordion preExpanded={[UUIDS.FOO]}> + <AccordionItem uuid={UUIDS.FOO}> + <AccordionItemHeading + data-testid={UUIDS.FOO} + className="foo" + expandedClassName="foo--expanded" + /> + </AccordionItem> + <AccordionItem uuid={UUIDS.BAR}> + <AccordionItemHeading + data-testid={UUIDS.BAR} + className="foo" + expandedClassName="foo--expanded" + /> + </AccordionItem> + </Accordion>, + ); + + expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ + 'foo', + 'foo--expanded', + ]); + expect(Array.from(getByTestId(UUIDS.BAR).classList)).toEqual([ + 'foo', + ]); + }); + }); +});
4859ec67e7dccfadf4602fd53af97c9dda836101
src/parser/shared/modules/helpers/Stacks.tsx
src/parser/shared/modules/helpers/Stacks.tsx
import { EventType } from 'parser/core/Events'; /** * Returns the current stacks on a given event * @param event */ export function currentStacks(event: any) { switch (event.type) { case EventType.RemoveBuff || EventType.RemoveDebuff: return 0; case EventType.ApplyBuff || EventType.ApplyDebuff: return 1; case EventType.ApplyBuffStack || EventType.RemoveBuffStack || EventType.ApplyDebuffStack || EventType.RemoveDebuffStack: return event.stack; default: return null; } }
Add a shared stacks helper
Add a shared stacks helper
TypeScript
agpl-3.0
anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,yajinni/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer
--- +++ @@ -0,0 +1,18 @@ +import { EventType } from 'parser/core/Events'; + +/** + * Returns the current stacks on a given event + * @param event + */ +export function currentStacks(event: any) { + switch (event.type) { + case EventType.RemoveBuff || EventType.RemoveDebuff: + return 0; + case EventType.ApplyBuff || EventType.ApplyDebuff: + return 1; + case EventType.ApplyBuffStack || EventType.RemoveBuffStack || EventType.ApplyDebuffStack || EventType.RemoveDebuffStack: + return event.stack; + default: + return null; + } +}
a7d85383fcabf87f49d347a9e9e2263067d0a149
src/utils/parseStatus.ts
src/utils/parseStatus.ts
import { statusDate } from '../constants/querySelectors'; import { List } from 'immutable'; /** * Returns a list of Mturk's URL encoded date strings for each day that has * HIT data. * @param html */ export const parseStatusPage = (html: Document): List<string> => { const dateCells = html.querySelectorAll(statusDate); if (dateCells) { const unfilteredDates = Array.from(dateCells).reduce( (listOfDates: List<string>, date: HTMLTableDataCellElement) => listOfDates.push(parseEncodedDateString(date)), List() ); return unfilteredDates.filter((el: string) => el !== '') as List<string>; } else { return List(); } }; const parseEncodedDateString = (input: HTMLTableDataCellElement): string => { const anchorElem = input.querySelector('a'); if (anchorElem && anchorElem.getAttribute('href')) { return (anchorElem.getAttribute('href') as string).split('encodedDate=')[1]; } else { return ''; } };
Add parsing functions for status summary page.
Add parsing functions for status summary page.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -0,0 +1,31 @@ +import { statusDate } from '../constants/querySelectors'; +import { List } from 'immutable'; + +/** + * Returns a list of Mturk's URL encoded date strings for each day that has + * HIT data. + * @param html + */ +export const parseStatusPage = (html: Document): List<string> => { + const dateCells = html.querySelectorAll(statusDate); + if (dateCells) { + const unfilteredDates = Array.from(dateCells).reduce( + (listOfDates: List<string>, date: HTMLTableDataCellElement) => + listOfDates.push(parseEncodedDateString(date)), + List() + ); + + return unfilteredDates.filter((el: string) => el !== '') as List<string>; + } else { + return List(); + } +}; + +const parseEncodedDateString = (input: HTMLTableDataCellElement): string => { + const anchorElem = input.querySelector('a'); + if (anchorElem && anchorElem.getAttribute('href')) { + return (anchorElem.getAttribute('href') as string).split('encodedDate=')[1]; + } else { + return ''; + } +};
c77b2cdeda8ba93982b01a43c1f6988de73eaef7
tests/cypress/tests/unit/loadingState.ts
tests/cypress/tests/unit/loadingState.ts
import dataLoading from 'dash-table/derived/table/data_loading'; describe('loading state uneditable', () => { it('returns true when data are loading', () => { const loading = dataLoading({ is_loading: true, prop_name: 'data', component_name: '' }); expect(loading).to.equal(true); }); it('returns false when a non-data prop is loading', () => { const loading = dataLoading({ is_loading: true, prop_name: 'style_cell_conditional', component_name: '' }); expect(loading).to.equal(false); }); it('returns false when table is not loading', () => { const loading = dataLoading({ is_loading: false, prop_name: 'data', component_name: '' }); expect(loading).to.equal(false); }); });
Add unit test for data_loading.
Add unit test for data_loading.
TypeScript
mit
plotly/dash-table,plotly/dash-table,plotly/dash-table
--- +++ @@ -0,0 +1,35 @@ +import dataLoading from 'dash-table/derived/table/data_loading'; + +describe('loading state uneditable', () => { + + it('returns true when data are loading', () => { + const loading = dataLoading({ + is_loading: true, + prop_name: 'data', + component_name: '' + }); + + expect(loading).to.equal(true); + }); + + it('returns false when a non-data prop is loading', () => { + const loading = dataLoading({ + is_loading: true, + prop_name: 'style_cell_conditional', + component_name: '' + }); + + expect(loading).to.equal(false); + }); + + it('returns false when table is not loading', () => { + const loading = dataLoading({ + is_loading: false, + prop_name: 'data', + component_name: '' + }); + + expect(loading).to.equal(false); + }); + +});
62e6b1ffe5ed78f23ebd249ac1c7ea14dc115259
platforms/platform-alexa/src/AlexaHandles.ts
platforms/platform-alexa/src/AlexaHandles.ts
import { PermissionStatus } from './interfaces'; import { HandleOptions, Jovo } from '@jovotech/framework'; import { AlexaRequest } from './AlexaRequest'; export type PermissionType = 'timers' | 'reminders'; export class AlexaHandles { static onPermission(status: PermissionStatus, type?: PermissionType): HandleOptions { return { types: ['Connections.Response'], platforms: ['alexa'], if: (jovo: Jovo) => (jovo.$request as AlexaRequest).request?.name === 'AskFor' && (jovo.$request as AlexaRequest).request?.payload?.status === status && (type ? (jovo.$request as AlexaRequest).request?.payload?.permissionScope === `alexa::alerts:${type}:skill:readwrite` : true), }; } static onPermissionAccepted(type?: PermissionType): HandleOptions { return AlexaHandles.onPermission('ACCEPTED', type); } static onPermissionDenied(type?: PermissionType): HandleOptions { return AlexaHandles.onPermission('DENIED', type); } }
Add initial handle helpers for Alexa
:sparkles: Add initial handle helpers for Alexa
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -0,0 +1,29 @@ +import { PermissionStatus } from './interfaces'; +import { HandleOptions, Jovo } from '@jovotech/framework'; +import { AlexaRequest } from './AlexaRequest'; + +export type PermissionType = 'timers' | 'reminders'; + +export class AlexaHandles { + static onPermission(status: PermissionStatus, type?: PermissionType): HandleOptions { + return { + types: ['Connections.Response'], + platforms: ['alexa'], + if: (jovo: Jovo) => + (jovo.$request as AlexaRequest).request?.name === 'AskFor' && + (jovo.$request as AlexaRequest).request?.payload?.status === status && + (type + ? (jovo.$request as AlexaRequest).request?.payload?.permissionScope === + `alexa::alerts:${type}:skill:readwrite` + : true), + }; + } + + static onPermissionAccepted(type?: PermissionType): HandleOptions { + return AlexaHandles.onPermission('ACCEPTED', type); + } + + static onPermissionDenied(type?: PermissionType): HandleOptions { + return AlexaHandles.onPermission('DENIED', type); + } +}
d784f019c33d1e85969f6c0a97689273d3efd8c7
src/Test/Ast/Config/Nsfw.ts
src/Test/Ast/Config/Nsfw.ts
import { expect } from 'chai' import Up from '../../../index' import { insideDocumentAndParagraph } from '../Helpers' import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode' import { NotSafeForWorkNode } from '../../../SyntaxNodes/NotSafeForWorkNode' describe('The term that represents NSFW conventions', () => { const up = new Up({ i18n: { terms: { nsfw: 'explicit' } } }) it('comes from the "nsfw" config term ', () => { expect(up.toAst('[explicit: Ash fights naked Gary]')).to.be.eql( insideDocumentAndParagraph([ new NotSafeForWorkNode([ new PlainTextNode('Ash fights naked Gary') ]) ])) }) it('is case-insensitive even when custom', () => { const uppercase = '[EXPLICIT: Ash fights naked Gary]' const mixedCase = '[eXplIciT: Ash fights naked Gary]' expect(up.toAst(uppercase)).to.be.eql(up.toAst(mixedCase)) }) })
Add 2 failing nsfw tests
Add 2 failing nsfw tests
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,30 @@ +import { expect } from 'chai' +import Up from '../../../index' +import { insideDocumentAndParagraph } from '../Helpers' +import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode' +import { NotSafeForWorkNode } from '../../../SyntaxNodes/NotSafeForWorkNode' + + +describe('The term that represents NSFW conventions', () => { + const up = new Up({ + i18n: { + terms: { nsfw: 'explicit' } + } + }) + + it('comes from the "nsfw" config term ', () => { + expect(up.toAst('[explicit: Ash fights naked Gary]')).to.be.eql( + insideDocumentAndParagraph([ + new NotSafeForWorkNode([ + new PlainTextNode('Ash fights naked Gary') + ]) + ])) + }) + + it('is case-insensitive even when custom', () => { + const uppercase = '[EXPLICIT: Ash fights naked Gary]' + const mixedCase = '[eXplIciT: Ash fights naked Gary]' + + expect(up.toAst(uppercase)).to.be.eql(up.toAst(mixedCase)) + }) +})
2cdbc68f690138410785db1cb4fcbd64e36e4203
node-progress/node-progress-test.ts
node-progress/node-progress-test.ts
/// <reference path="node-progress.d.ts"/> var ProgressBar = require('progress'); /** * Usage example from https://github.com/tj/node-progress */ var bar = new ProgressBar(':bar', { total: 10 }); var timer = setInterval(function () { bar.tick(); if (bar.complete) { console.log('\ncomplete\n'); clearInterval(timer); } }, 100); /** * Custom token example from https://github.com/tj/node-progress */ var bar = new ProgressBar(':current: :token1 :token2', { total: 3 }); bar.tick({ 'token1': "Hello", 'token2': "World!\n" }); bar.tick(2, { 'token1': "Goodbye", 'token2': "World!" });
Add test case for node-progress
Add test case for node-progress
TypeScript
mit
stephenjelfs/DefinitelyTyped,isman-usoh/DefinitelyTyped,applesaucers/lodash-invokeMap,use-strict/DefinitelyTyped,wkrueger/DefinitelyTyped,OfficeDev/DefinitelyTyped,aldo-roman/DefinitelyTyped,Dominator008/DefinitelyTyped,chrootsu/DefinitelyTyped,lbesson/DefinitelyTyped,sandersky/DefinitelyTyped,chrismbarr/DefinitelyTyped,hellopao/DefinitelyTyped,bilou84/DefinitelyTyped,RX14/DefinitelyTyped,zuzusik/DefinitelyTyped,frogcjn/DefinitelyTyped,AgentME/DefinitelyTyped,sixinli/DefinitelyTyped,gcastre/DefinitelyTyped,ajtowf/DefinitelyTyped,pocesar/DefinitelyTyped,Zorgatone/DefinitelyTyped,igorsechyn/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,aciccarello/DefinitelyTyped,evandrewry/DefinitelyTyped,ryan10132/DefinitelyTyped,RX14/DefinitelyTyped,Penryn/DefinitelyTyped,elisee/DefinitelyTyped,UzEE/DefinitelyTyped,johan-gorter/DefinitelyTyped,donnut/DefinitelyTyped,HPFOD/DefinitelyTyped,nycdotnet/DefinitelyTyped,jimthedev/DefinitelyTyped,jsaelhof/DefinitelyTyped,emanuelhp/DefinitelyTyped,greglo/DefinitelyTyped,pwelter34/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,amir-arad/DefinitelyTyped,alextkachman/DefinitelyTyped,behzad888/DefinitelyTyped,sledorze/DefinitelyTyped,arusakov/DefinitelyTyped,YousefED/DefinitelyTyped,drinchev/DefinitelyTyped,esperco/DefinitelyTyped,onecentlin/DefinitelyTyped,syntax42/DefinitelyTyped,martinduparc/DefinitelyTyped,igorraush/DefinitelyTyped,vasek17/DefinitelyTyped,Bobjoy/DefinitelyTyped,johan-gorter/DefinitelyTyped,aindlq/DefinitelyTyped,emanuelhp/DefinitelyTyped,hafenr/DefinitelyTyped,yuit/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,Chris380/DefinitelyTyped,frogcjn/DefinitelyTyped,MugeSo/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,alvarorahul/DefinitelyTyped,hatz48/DefinitelyTyped,UzEE/DefinitelyTyped,Syati/DefinitelyTyped,arcticwaters/DefinitelyTyped,stacktracejs/DefinitelyTyped,arma-gast/DefinitelyTyped,musicist288/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,bennett000/DefinitelyTyped,drillbits/DefinitelyTyped,vagarenko/DefinitelyTyped,stanislavHamara/DefinitelyTyped,markogresak/DefinitelyTyped,philippstucki/DefinitelyTyped,smrq/DefinitelyTyped,adamcarr/DefinitelyTyped,robert-voica/DefinitelyTyped,egeland/DefinitelyTyped,Litee/DefinitelyTyped,innerverse/DefinitelyTyped,mcrawshaw/DefinitelyTyped,whoeverest/DefinitelyTyped,donnut/DefinitelyTyped,nycdotnet/DefinitelyTyped,benishouga/DefinitelyTyped,ciriarte/DefinitelyTyped,danfma/DefinitelyTyped,aciccarello/DefinitelyTyped,greglo/DefinitelyTyped,schmuli/DefinitelyTyped,shahata/DefinitelyTyped,rcchen/DefinitelyTyped,arusakov/DefinitelyTyped,tan9/DefinitelyTyped,fnipo/DefinitelyTyped,psnider/DefinitelyTyped,Ptival/DefinitelyTyped,mvarblow/DefinitelyTyped,applesaucers/lodash-invokeMap,flyfishMT/DefinitelyTyped,onecentlin/DefinitelyTyped,alexdresko/DefinitelyTyped,mareek/DefinitelyTyped,rushi216/DefinitelyTyped,herrmanno/DefinitelyTyped,arusakov/DefinitelyTyped,zalamtech/DefinitelyTyped,elisee/DefinitelyTyped,nobuoka/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,trystanclarke/DefinitelyTyped,wcomartin/DefinitelyTyped,NelsonLamprecht/DefinitelyTyped,algorithme/DefinitelyTyped,alvarorahul/DefinitelyTyped,philippstucki/DefinitelyTyped,forumone/DefinitelyTyped,Dominator008/DefinitelyTyped,fredgalvao/DefinitelyTyped,vincentw56/DefinitelyTyped,RedSeal-co/DefinitelyTyped,abbasmhd/DefinitelyTyped,Mek7/DefinitelyTyped,abner/DefinitelyTyped,trystanclarke/DefinitelyTyped,xStrom/DefinitelyTyped,giggio/DefinitelyTyped,gyohk/DefinitelyTyped,nakakura/DefinitelyTyped,raijinsetsu/DefinitelyTyped,florentpoujol/DefinitelyTyped,zuzusik/DefinitelyTyped,erosb/DefinitelyTyped,subjectix/DefinitelyTyped,dydek/DefinitelyTyped,borisyankov/DefinitelyTyped,nainslie/DefinitelyTyped,hiraash/DefinitelyTyped,ashwinr/DefinitelyTyped,chbrown/DefinitelyTyped,Litee/DefinitelyTyped,mcliment/DefinitelyTyped,nitintutlani/DefinitelyTyped,behzad888/DefinitelyTyped,nobuoka/DefinitelyTyped,reppners/DefinitelyTyped,dsebastien/DefinitelyTyped,wilfrem/DefinitelyTyped,gcastre/DefinitelyTyped,Gmulti/DefinitelyTyped,EnableSoftware/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,sclausen/DefinitelyTyped,AgentME/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,mweststrate/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,magny/DefinitelyTyped,abbasmhd/DefinitelyTyped,benishouga/DefinitelyTyped,glenndierckx/DefinitelyTyped,Zzzen/DefinitelyTyped,ErykB2000/DefinitelyTyped,progre/DefinitelyTyped,damianog/DefinitelyTyped,mattanja/DefinitelyTyped,mszczepaniak/DefinitelyTyped,Ridermansb/DefinitelyTyped,georgemarshall/DefinitelyTyped,dflor003/DefinitelyTyped,paulmorphy/DefinitelyTyped,mcrawshaw/DefinitelyTyped,bennett000/DefinitelyTyped,olemp/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,esperco/DefinitelyTyped,aroder/DefinitelyTyped,mattblang/DefinitelyTyped,minodisk/DefinitelyTyped,nabeix/DefinitelyTyped,gandjustas/DefinitelyTyped,yuit/DefinitelyTyped,munxar/DefinitelyTyped,Lorisu/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,Dashlane/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,mjjames/DefinitelyTyped,mjjames/DefinitelyTyped,Saneyan/DefinitelyTyped,micurs/DefinitelyTyped,TheBay0r/DefinitelyTyped,schmuli/DefinitelyTyped,shlomiassaf/DefinitelyTyped,omidkrad/DefinitelyTyped,isman-usoh/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,Pro/DefinitelyTyped,QuatroCode/DefinitelyTyped,stacktracejs/DefinitelyTyped,deeleman/DefinitelyTyped,shlomiassaf/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,daptiv/DefinitelyTyped,nitintutlani/DefinitelyTyped,davidpricedev/DefinitelyTyped,zuzusik/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,arma-gast/DefinitelyTyped,Ptival/DefinitelyTyped,mattblang/DefinitelyTyped,nainslie/DefinitelyTyped,jsaelhof/DefinitelyTyped,subash-a/DefinitelyTyped,EnableSoftware/DefinitelyTyped,egeland/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,pwelter34/DefinitelyTyped,jasonswearingen/DefinitelyTyped,ashwinr/DefinitelyTyped,xStrom/DefinitelyTyped,KonaTeam/DefinitelyTyped,magny/DefinitelyTyped,HPFOD/DefinitelyTyped,sledorze/DefinitelyTyped,chrismbarr/DefinitelyTyped,drinchev/DefinitelyTyped,georgemarshall/DefinitelyTyped,brainded/DefinitelyTyped,wilfrem/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,mwain/DefinitelyTyped,dsebastien/DefinitelyTyped,benliddicott/DefinitelyTyped,acepoblete/DefinitelyTyped,Dashlane/DefinitelyTyped,mhegazy/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,Zzzen/DefinitelyTyped,newclear/DefinitelyTyped,mattanja/DefinitelyTyped,minodisk/DefinitelyTyped,OpenMaths/DefinitelyTyped,benishouga/DefinitelyTyped,timramone/DefinitelyTyped,ajtowf/DefinitelyTyped,Karabur/DefinitelyTyped,nmalaguti/DefinitelyTyped,dydek/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,eugenpodaru/DefinitelyTyped,jbrantly/DefinitelyTyped,dmoonfire/DefinitelyTyped,laco0416/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,sclausen/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,pocesar/DefinitelyTyped,martinduparc/DefinitelyTyped,schmuli/DefinitelyTyped,hatz48/DefinitelyTyped,syuilo/DefinitelyTyped,stephenjelfs/DefinitelyTyped,axelcostaspena/DefinitelyTyped,optical/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,glenndierckx/DefinitelyTyped,dragouf/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,rschmukler/DefinitelyTyped,rolandzwaga/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,tan9/DefinitelyTyped,nmalaguti/DefinitelyTyped,richardTowers/DefinitelyTyped,use-strict/DefinitelyTyped,alexdresko/DefinitelyTyped,abner/DefinitelyTyped,florentpoujol/DefinitelyTyped,gyohk/DefinitelyTyped,rschmukler/DefinitelyTyped,takenet/DefinitelyTyped,dmoonfire/DefinitelyTyped,teves-castro/DefinitelyTyped,syuilo/DefinitelyTyped,Syati/DefinitelyTyped,paulmorphy/DefinitelyTyped,psnider/DefinitelyTyped,kuon/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,jraymakers/DefinitelyTyped,amanmahajan7/DefinitelyTyped,iCoreSolutions/DefinitelyTyped,optical/DefinitelyTyped,amanmahajan7/DefinitelyTyped,YousefED/DefinitelyTyped,dumbmatter/DefinitelyTyped,rolandzwaga/DefinitelyTyped,Pro/DefinitelyTyped,takenet/DefinitelyTyped,mshmelev/DefinitelyTyped,flyfishMT/DefinitelyTyped,opichals/DefinitelyTyped,nelsonmorais/DefinitelyTyped,subash-a/DefinitelyTyped,chrootsu/DefinitelyTyped,gandjustas/DefinitelyTyped,mareek/DefinitelyTyped,borisyankov/DefinitelyTyped,chadoliver/DefinitelyTyped,AgentME/DefinitelyTyped,jasonswearingen/DefinitelyTyped,one-pieces/DefinitelyTyped,hellopao/DefinitelyTyped,OpenMaths/DefinitelyTyped,fishgoh0nk/DefinitelyTyped,QuatroCode/DefinitelyTyped,rcchen/DefinitelyTyped,MugeSo/DefinitelyTyped,maxlang/DefinitelyTyped,nakakura/DefinitelyTyped,raijinsetsu/DefinitelyTyped,psnider/DefinitelyTyped,pocesar/DefinitelyTyped,alainsahli/DefinitelyTyped,DeluxZ/DefinitelyTyped,jraymakers/DefinitelyTyped,smrq/DefinitelyTyped,jimthedev/DefinitelyTyped,alextkachman/DefinitelyTyped,martinduparc/DefinitelyTyped,vagarenko/DefinitelyTyped,mshmelev/DefinitelyTyped,reppners/DefinitelyTyped,aciccarello/DefinitelyTyped,mendix/DefinitelyTyped,timjk/DefinitelyTyped,fredgalvao/DefinitelyTyped,arcticwaters/DefinitelyTyped,Penryn/DefinitelyTyped,olemp/DefinitelyTyped,AgentME/DefinitelyTyped,bluong/DefinitelyTyped,danfma/DefinitelyTyped,jimthedev/DefinitelyTyped,scriby/DefinitelyTyped,newclear/DefinitelyTyped,zhiyiting/DefinitelyTyped,jccarvalhosa/DefinitelyTyped,ayanoin/DefinitelyTyped,NCARalph/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,moonpyk/DefinitelyTyped,georgemarshall/DefinitelyTyped,lseguin42/DefinitelyTyped,Zorgatone/DefinitelyTyped,teves-castro/DefinitelyTyped,hellopao/DefinitelyTyped,mhegazy/DefinitelyTyped,bdoss/DefinitelyTyped,nfriend/DefinitelyTyped,georgemarshall/DefinitelyTyped,damianog/DefinitelyTyped,Karabur/DefinitelyTyped,olivierlemasle/DefinitelyTyped,progre/DefinitelyTyped,bdoss/DefinitelyTyped,davidpricedev/DefinitelyTyped,PopSugar/DefinitelyTyped,scriby/DefinitelyTyped
--- +++ @@ -0,0 +1,32 @@ +/// <reference path="node-progress.d.ts"/> + +var ProgressBar = require('progress'); + + +/** + * Usage example from https://github.com/tj/node-progress + */ +var bar = new ProgressBar(':bar', { total: 10 }); +var timer = setInterval(function () { + bar.tick(); + if (bar.complete) { + console.log('\ncomplete\n'); + clearInterval(timer); + } +}, 100); + + +/** + * Custom token example from https://github.com/tj/node-progress + */ +var bar = new ProgressBar(':current: :token1 :token2', { total: 3 }); + +bar.tick({ + 'token1': "Hello", + 'token2': "World!\n" +}); + +bar.tick(2, { + 'token1': "Goodbye", + 'token2': "World!" +});
0f91dec2bf5daecce65cb16ba95189061ef4ce31
packages/ivi/__tests__/element_factory.spec.ts
packages/ivi/__tests__/element_factory.spec.ts
import { VNodeFlags } from "../src/vdom/flags"; import { elementFactory } from "../src/vdom/element"; import * as h from "./utils/html"; const div = h.div(); const input = h.input(); const divFactory = elementFactory(div); const inputFactory = elementFactory(input); test(`div flags`, () => { expect(divFactory()._flags & ~VNodeFlags.ElementFactory).toBe(h.div()._flags); }); test(`input flags`, () => { expect(inputFactory()._flags & ~VNodeFlags.ElementFactory).toBe(h.input()._flags); }); test(`div factory`, () => { expect(divFactory()._tag).toBe(div); }); test(`input factory`, () => { expect(inputFactory()._tag).toBe(input); }); test(`default className = undefined`, () => { expect(divFactory()._className).toBeUndefined(); }); test(`className = undefined`, () => { expect(divFactory(undefined)._className).toBeUndefined(); }); test(`className = "a"`, () => { expect(divFactory("a")._className).toBe("a"); });
Add more element factory tests
Add more element factory tests
TypeScript
mit
ivijs/ivi,ivijs/ivi
--- +++ @@ -0,0 +1,36 @@ +import { VNodeFlags } from "../src/vdom/flags"; +import { elementFactory } from "../src/vdom/element"; +import * as h from "./utils/html"; + +const div = h.div(); +const input = h.input(); +const divFactory = elementFactory(div); +const inputFactory = elementFactory(input); + +test(`div flags`, () => { + expect(divFactory()._flags & ~VNodeFlags.ElementFactory).toBe(h.div()._flags); +}); + +test(`input flags`, () => { + expect(inputFactory()._flags & ~VNodeFlags.ElementFactory).toBe(h.input()._flags); +}); + +test(`div factory`, () => { + expect(divFactory()._tag).toBe(div); +}); + +test(`input factory`, () => { + expect(inputFactory()._tag).toBe(input); +}); + +test(`default className = undefined`, () => { + expect(divFactory()._className).toBeUndefined(); +}); + +test(`className = undefined`, () => { + expect(divFactory(undefined)._className).toBeUndefined(); +}); + +test(`className = "a"`, () => { + expect(divFactory("a")._className).toBe("a"); +});
fb042657ab2579469a8f3d73b306516d15da3a0d
saleor/static/dashboard-next/home/queries.ts
saleor/static/dashboard-next/home/queries.ts
import gql from "graphql-tag"; import { TypedQuery } from "../queries"; import { Home } from "./types/Home"; const home = gql` query Home { salesToday: ordersTotal(period: TODAY) { gross { amount currency } } ordersToday: orders(created: TODAY) { totalCount } ordersToFulfill: orders(status: READY_TO_FULFILL, created: TODAY) { totalCount } ordersToCapture: orders(status: READY_TO_CAPTURE, created: TODAY) { totalCount } productsOutOfStock: products(stockAvailability: OUT_OF_STOCK) { totalCount } productTopToday: reportProductSales(period: TODAY, first: 5) { edges { node { id revenue(period: TODAY) { gross { amount currency } } attributes { value { id name sortOrder } } product { id name thumbnailUrl } quantityOrdered } } } activities: homepageEvents(last: 10) { edges { node { amount composedId date email emailType id message orderNumber oversoldItems quantity type user { id email } } } } } `; export const HomePageQuery = TypedQuery<Home, {}>(home);
import gql from "graphql-tag"; import { TypedQuery } from "../queries"; import { Home } from "./types/Home"; const home = gql` query Home { salesToday: ordersTotal(period: TODAY) { gross { amount currency } } ordersToday: orders(created: TODAY) { totalCount } ordersToFulfill: orders(status: READY_TO_FULFILL) { totalCount } ordersToCapture: orders(status: READY_TO_CAPTURE) { totalCount } productsOutOfStock: products(stockAvailability: OUT_OF_STOCK) { totalCount } productTopToday: reportProductSales(period: TODAY, first: 5) { edges { node { id revenue(period: TODAY) { gross { amount currency } } attributes { value { id name sortOrder } } product { id name thumbnailUrl } quantityOrdered } } } activities: homepageEvents(last: 10) { edges { node { amount composedId date email emailType id message orderNumber oversoldItems quantity type user { id email } } } } } `; export const HomePageQuery = TypedQuery<Home, {}>(home);
Use all-time values to order stats
Use all-time values to order stats
TypeScript
bsd-3-clause
UITools/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor
--- +++ @@ -14,10 +14,10 @@ ordersToday: orders(created: TODAY) { totalCount } - ordersToFulfill: orders(status: READY_TO_FULFILL, created: TODAY) { + ordersToFulfill: orders(status: READY_TO_FULFILL) { totalCount } - ordersToCapture: orders(status: READY_TO_CAPTURE, created: TODAY) { + ordersToCapture: orders(status: READY_TO_CAPTURE) { totalCount } productsOutOfStock: products(stockAvailability: OUT_OF_STOCK) {
0b3e6e213573706155aa46f92da8c645ace66688
app/src/main-process/authenticated-avatar-filter.ts
app/src/main-process/authenticated-avatar-filter.ts
import { EndpointToken } from '../lib/endpoint-token' import { OrderedWebRequest } from './ordered-webrequest' export function installAuthenticatedAvatarFilter( orderedWebRequest: OrderedWebRequest ) { let originTokens = new Map<string, string>() orderedWebRequest.onBeforeSendHeaders.addEventListener(async details => { const { origin, pathname } = new URL(details.url) const token = originTokens.get(origin) if (token && pathname.startsWith('/api/v3/enterprise/avatars/')) { return { requestHeaders: { ...details.requestHeaders, Authorization: `token ${token}`, }, } } return {} }) return (accounts: ReadonlyArray<EndpointToken>) => { originTokens = new Map( accounts.map(({ endpoint, token }) => [new URL(endpoint).origin, token]) ) } }
Add a filter which populates the auth header for avatar requests
Add a filter which populates the auth header for avatar requests
TypeScript
mit
j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,j-f1/forked-desktop,desktop/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop
--- +++ @@ -0,0 +1,30 @@ +import { EndpointToken } from '../lib/endpoint-token' +import { OrderedWebRequest } from './ordered-webrequest' + +export function installAuthenticatedAvatarFilter( + orderedWebRequest: OrderedWebRequest +) { + let originTokens = new Map<string, string>() + + orderedWebRequest.onBeforeSendHeaders.addEventListener(async details => { + const { origin, pathname } = new URL(details.url) + const token = originTokens.get(origin) + + if (token && pathname.startsWith('/api/v3/enterprise/avatars/')) { + return { + requestHeaders: { + ...details.requestHeaders, + Authorization: `token ${token}`, + }, + } + } + + return {} + }) + + return (accounts: ReadonlyArray<EndpointToken>) => { + originTokens = new Map( + accounts.map(({ endpoint, token }) => [new URL(endpoint).origin, token]) + ) + } +}
862c769f8dc224adfb362e9d22a2a9693e5c9292
ui/test/statusbar.spec.ts
ui/test/statusbar.spec.ts
"use strict"; import {Statusbar} from "../src/app/statusbar"; describe("Statusbar Test ", () => { it("should start and finish", () => { Statusbar.Start(); Statusbar.Inc(); Statusbar.Done(); }); });
Add a simple unit test for the statusbar.
Add a simple unit test for the statusbar.
TypeScript
mit
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
--- +++ @@ -0,0 +1,13 @@ +"use strict"; + +import {Statusbar} from "../src/app/statusbar"; + +describe("Statusbar Test ", () => { + + it("should start and finish", () => { + Statusbar.Start(); + Statusbar.Inc(); + Statusbar.Done(); + }); + +});
ddda6853a2ddc38cf09e0b2d12dd7c45d90ba713
test/reducers/slides/actions/addPluginToCurrentSlide-spec.ts
test/reducers/slides/actions/addPluginToCurrentSlide-spec.ts
import { expect } from 'chai'; import { ADD_PLUGIN_TO_CURRENT_SLIDE } from '../../../../app/constants/slides.constants'; export default function(initialState: any, reducer: any, slide: any) { const plugin1 = 'plugin1'; describe('ADD_PLUGIN_TO_CURRENT_SLIDE', () => { it('should add a new plugin to selected slide', () => { expect( reducer(initialState, { type: ADD_PLUGIN_TO_CURRENT_SLIDE, plugin: plugin1, slideNumber: 0 }) ).to.deep.equal([{ plugins: ['plugin1'], state: { backgroundColor: { r: 255, g: 255, b: 255, a: 100 }, transition: { right: 'rotate-push-left-move-from-right', left: 'rotate-push-right-move-from-left', } } }]); }); it('should add new plugins to the end of the plugin list', () => { const _initialState = [{ plugins: ['plugin5', 'plugin4'], state: { backgroundColor: { r: 255, g: 255, b: 255, a: 100 }, transition: { right: 'rotate-push-left-move-from-right', left: 'rotate-push-right-move-from-left', } } }]; expect(reducer(_initialState, { type: ADD_PLUGIN_TO_CURRENT_SLIDE, plugin: plugin1, slideNumber: 0 })).to.deep.equal([{ plugins: ['plugin5', 'plugin4', plugin1], state: { backgroundColor: { r: 255, g: 255, b: 255, a: 100 }, transition: { right: 'rotate-push-left-move-from-right', left: 'rotate-push-right-move-from-left', } } }]); }); }); }
Add ADD_PLUGIN_TO_CURRENT_SLIDE spec for slides reducer
test: Add ADD_PLUGIN_TO_CURRENT_SLIDE spec for slides reducer
TypeScript
mit
DevDecks/devdecks,chengsieuly/devdecks,chengsieuly/devdecks,Team-CHAD/DevDecks,DevDecks/devdecks,Team-CHAD/DevDecks,DevDecks/devdecks,Team-CHAD/DevDecks,chengsieuly/devdecks
--- +++ @@ -0,0 +1,55 @@ +import { expect } from 'chai'; +import { ADD_PLUGIN_TO_CURRENT_SLIDE } from '../../../../app/constants/slides.constants'; + +export default function(initialState: any, reducer: any, slide: any) { + const plugin1 = 'plugin1'; + + describe('ADD_PLUGIN_TO_CURRENT_SLIDE', () => { + it('should add a new plugin to selected slide', () => { + expect( + reducer(initialState, { + type: ADD_PLUGIN_TO_CURRENT_SLIDE, + plugin: plugin1, + slideNumber: 0 + }) + ).to.deep.equal([{ + plugins: ['plugin1'], + state: { + backgroundColor: { r: 255, g: 255, b: 255, a: 100 }, + transition: { + right: 'rotate-push-left-move-from-right', + left: 'rotate-push-right-move-from-left', + } + } + }]); + }); + + it('should add new plugins to the end of the plugin list', () => { + const _initialState = [{ + plugins: ['plugin5', 'plugin4'], + state: { + backgroundColor: { r: 255, g: 255, b: 255, a: 100 }, + transition: { + right: 'rotate-push-left-move-from-right', + left: 'rotate-push-right-move-from-left', + } + } + }]; + + expect(reducer(_initialState, { + type: ADD_PLUGIN_TO_CURRENT_SLIDE, + plugin: plugin1, + slideNumber: 0 + })).to.deep.equal([{ + plugins: ['plugin5', 'plugin4', plugin1], + state: { + backgroundColor: { r: 255, g: 255, b: 255, a: 100 }, + transition: { + right: 'rotate-push-left-move-from-right', + left: 'rotate-push-right-move-from-left', + } + } + }]); + }); + }); +}
5a9471e2204a1aca3ddecce67bf26995b97b2596
src/angular-app/bellows/apps/changepassword/change-password-app.component.ts
src/angular-app/bellows/apps/changepassword/change-password-app.component.ts
import * as angular from 'angular'; import { UserService } from '../../core/api/user.service'; import { NoticeService } from '../../core/notice/notice.service'; import { SessionService } from '../../core/session.service'; export class ChangePasswordAppController implements angular.IController { old_password: string; password: string; confirm_password: string; static $inject = ['userService', 'sessionService', 'silNoticeService']; constructor(private userService: UserService, private sessionService: SessionService, private notice: NoticeService) {} updatePassword() { if (this.password === this.confirm_password) { this.sessionService.getSession().then((session) => { const user = session.userId(); const password = this.password; this.userService.changePassword(user, password).then(() => { this.notice.push(this.notice.SUCCESS, 'Password updated successfully'); this.password = this.confirm_password = ''; }); }); } }; } export const ChangePasswordAppComponent: angular.IComponentOptions = { controller: ChangePasswordAppController, templateUrl: '/angular-app/bellows/apps/changepassword/change-password-app.component.html' };
import * as angular from 'angular'; import { UserService } from '../../core/api/user.service'; import { NoticeService } from '../../core/notice/notice.service'; import { SessionService } from '../../core/session.service'; export class ChangePasswordAppController implements angular.IController { password: string; confirm_password: string; static $inject = ['userService', 'sessionService', 'silNoticeService']; constructor(private userService: UserService, private sessionService: SessionService, private notice: NoticeService) {} updatePassword() { if (this.password === this.confirm_password) { this.sessionService.getSession().then((session) => { const user = session.userId(); const password = this.password; this.userService.changePassword(user, password).then(() => { this.notice.push(this.notice.SUCCESS, 'Password updated successfully'); this.password = this.confirm_password = ''; }); }); } }; } export const ChangePasswordAppComponent: angular.IComponentOptions = { controller: ChangePasswordAppController, templateUrl: '/angular-app/bellows/apps/changepassword/change-password-app.component.html' };
Revert "Added new field to password change"
Revert "Added new field to password change" This reverts commit 3664fab3e0f5155dc2c824894b715f98ede4159e.
TypeScript
mit
sillsdev/web-scriptureforge,ermshiperete/web-languageforge,ermshiperete/web-languageforge,ermshiperete/web-languageforge,sillsdev/web-scriptureforge,sillsdev/web-scriptureforge,sillsdev/web-scriptureforge,ermshiperete/web-languageforge,ermshiperete/web-languageforge,ermshiperete/web-languageforge,sillsdev/web-scriptureforge,sillsdev/web-scriptureforge,sillsdev/web-scriptureforge,ermshiperete/web-languageforge,sillsdev/web-scriptureforge,ermshiperete/web-languageforge
--- +++ @@ -5,7 +5,6 @@ import { SessionService } from '../../core/session.service'; export class ChangePasswordAppController implements angular.IController { - old_password: string; password: string; confirm_password: string;
773edddcf2a4060fe7b368ab0313ddbcea6f4305
src/tsa.ts
src/tsa.ts
/// <reference path="../typings/main.d.ts" /> /// <reference path="../node_modules/typescript/lib/typescript.d.ts" /> var vorpal = require('vorpal')(); vorpal .command('foo', 'Outputs "bar".') .action(function(args, callback) { this.log('bar'); callback(); }); vorpal .show() .parse(process.argv);
Use parse instead of just show
Use parse instead of just show
TypeScript
mit
sandermvanvliet/tsa,sandermvanvliet/tsa
--- +++ @@ -0,0 +1,15 @@ +/// <reference path="../typings/main.d.ts" /> +/// <reference path="../node_modules/typescript/lib/typescript.d.ts" /> + +var vorpal = require('vorpal')(); + +vorpal + .command('foo', 'Outputs "bar".') + .action(function(args, callback) { + this.log('bar'); + callback(); + }); + +vorpal + .show() + .parse(process.argv);
6756d3e3e21e5663a81e63ecb2b8f058ea1ae3ad
src/lib/ogs-rr6-shims.tsx
src/lib/ogs-rr6-shims.tsx
/* * Copyright 2012-2022 Online-Go.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* This file contains shims to make it so we can use our pre-existing class * React components with React Router 6. We should strive to elimiate this the * need for this in time. */ import React from "react"; import { useLocation, useParams } from "react-router-dom"; // Types derived heavily from @types/react-router-dom, with some fields we don't use eliminated export interface StaticContext { statusCode?: number | undefined; } export interface match<Params extends { [K in keyof Params]?: string } = {}> { params: Params; path: string; url: string; } export interface RouteComponentProps<Params extends Partial<Record<keyof Params, string>> = {}> { location: Location; match: match<Params>; } export function rr6ClassShim(Class: React.ComponentType<any>): (props: any) => JSX.Element { return (props) => { const location = useLocation(); const params = useParams(); const { pathname = "/", search = "", hash = "" } = location; const path = pathname + search + hash; const match = { url: globalThis.location.origin + path, path, params, }; return <Class {...{ location, match }} {...props} />; }; }
Add missing ogs rr6 shims
Add missing ogs rr6 shims
TypeScript
agpl-3.0
online-go/online-go.com,online-go/online-go.com,online-go/online-go.com,online-go/online-go.com,online-go/online-go.com
--- +++ @@ -0,0 +1,58 @@ +/* + * Copyright 2012-2022 Online-Go.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* This file contains shims to make it so we can use our pre-existing class + * React components with React Router 6. We should strive to elimiate this the + * need for this in time. */ + +import React from "react"; +import { useLocation, useParams } from "react-router-dom"; + +// Types derived heavily from @types/react-router-dom, with some fields we don't use eliminated + +export interface StaticContext { + statusCode?: number | undefined; +} + +export interface match<Params extends { [K in keyof Params]?: string } = {}> { + params: Params; + path: string; + url: string; +} + +export interface RouteComponentProps<Params extends Partial<Record<keyof Params, string>> = {}> { + location: Location; + match: match<Params>; +} + +export function rr6ClassShim(Class: React.ComponentType<any>): (props: any) => JSX.Element { + return (props) => { + const location = useLocation(); + const params = useParams(); + + const { pathname = "/", search = "", hash = "" } = location; + + const path = pathname + search + hash; + + const match = { + url: globalThis.location.origin + path, + path, + params, + }; + + return <Class {...{ location, match }} {...props} />; + }; +}
f5f183801b55d65fa20661f2c77b71d144083bbe
src/browser/vcs/dummies.ts
src/browser/vcs/dummies.ts
import * as path from 'path'; import { Dummy, TextDummy, TypesDummy } from '../../../test/helpers'; import { VcsFileChange, VcsFileChangeStatusTypes } from '../../core/vcs'; export class VcsFileChangeDummy implements Dummy<VcsFileChange> { private filePath = new TextDummy('file'); private status = new TypesDummy<VcsFileChangeStatusTypes>([ VcsFileChangeStatusTypes.REMOVED, VcsFileChangeStatusTypes.MODIFIED, VcsFileChangeStatusTypes.RENAMED, VcsFileChangeStatusTypes.NEW, ]); constructor(public readonly workspaceDir: string = '/test/workspace') { } create(status = this.status.create()): VcsFileChange { const filePath = this.filePath.create(); let fileChange = { filePath, workingDirectoryPath: this.workspaceDir, absoluteFilePath: path.resolve(this.workspaceDir, filePath), status, } as VcsFileChange; if (status === VcsFileChangeStatusTypes.RENAMED) { fileChange = { ...fileChange, headToIndexDiff: { oldFilePath: 'old-file', newFilePath: filePath, }, }; } return fileChange; } }
Add vcs file change dummy
Add vcs file change dummy
TypeScript
mit
seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary
--- +++ @@ -0,0 +1,39 @@ +import * as path from 'path'; +import { Dummy, TextDummy, TypesDummy } from '../../../test/helpers'; +import { VcsFileChange, VcsFileChangeStatusTypes } from '../../core/vcs'; + + +export class VcsFileChangeDummy implements Dummy<VcsFileChange> { + private filePath = new TextDummy('file'); + private status = new TypesDummy<VcsFileChangeStatusTypes>([ + VcsFileChangeStatusTypes.REMOVED, + VcsFileChangeStatusTypes.MODIFIED, + VcsFileChangeStatusTypes.RENAMED, + VcsFileChangeStatusTypes.NEW, + ]); + + constructor(public readonly workspaceDir: string = '/test/workspace') { + } + + create(status = this.status.create()): VcsFileChange { + const filePath = this.filePath.create(); + let fileChange = { + filePath, + workingDirectoryPath: this.workspaceDir, + absoluteFilePath: path.resolve(this.workspaceDir, filePath), + status, + } as VcsFileChange; + + if (status === VcsFileChangeStatusTypes.RENAMED) { + fileChange = { + ...fileChange, + headToIndexDiff: { + oldFilePath: 'old-file', + newFilePath: filePath, + }, + }; + } + + return fileChange; + } +}
f04db92629c50c8a88768591f46bbd5f23989448
db/migration/1551319875625-DataValuesYearIndex.ts
db/migration/1551319875625-DataValuesYearIndex.ts
import {MigrationInterface, QueryRunner} from "typeorm"; export class DataValuesYearIndex1551319875625 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { await queryRunner.query("CREATE INDEX data_values_year ON data_values (year);") } public async down(queryRunner: QueryRunner): Promise<any> { } }
Add index on year data_values
Add index on year data_values
TypeScript
mit
owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher
--- +++ @@ -0,0 +1,12 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +export class DataValuesYearIndex1551319875625 implements MigrationInterface { + + public async up(queryRunner: QueryRunner): Promise<any> { + await queryRunner.query("CREATE INDEX data_values_year ON data_values (year);") + } + + public async down(queryRunner: QueryRunner): Promise<any> { + } + +}
563b8d29f43b406b8ab126d5ba16bf30df377eea
scripts/android/postlink.ts
scripts/android/postlink.ts
import { modifyManifest } from './modifyManifest'; export function postlinkAndroid() { try { modifyManifest(); } catch (e) { console.warn('Failed to automatically update android manifest. Please continue manually'); } }
Refactor - split script into small modules
Refactor - split script into small modules
TypeScript
mit
doomsower/react-native-vkontakte-login,doomsower/react-native-vkontakte-login,doomsower/react-native-vkontakte-login,doomsower/react-native-vkontakte-login
--- +++ @@ -0,0 +1,9 @@ +import { modifyManifest } from './modifyManifest'; + +export function postlinkAndroid() { + try { + modifyManifest(); + } catch (e) { + console.warn('Failed to automatically update android manifest. Please continue manually'); + } +}
52d360a3f24387114b7e4be637aeabb10f0a9c72
webpack/refresh_token.ts
webpack/refresh_token.ts
import axios from "axios"; import { API } from "./api/index"; import { AuthState } from "./auth/interfaces"; import { HttpData } from "./util"; import { setToken } from "./auth/actions"; /** Grab a new token from the API (won't extend token's exp. date). * Redirect to home page on failure. */ export let maybeRefreshToken = (old: AuthState): Promise<AuthState> => { API.setBaseUrl(old.token.unencoded.iss); setToken(old); // The Axios interceptors might not be set yet. type Resp = HttpData<AuthState>; return axios.get(API.current.tokensPath).then((x: Resp) => { setToken(old); return x.data; }, (x) => { return Promise.reject("X"); }); };
import axios from "axios"; import { API } from "./api/index"; import { AuthState } from "./auth/interfaces"; import { HttpData, goHome } from "./util"; import { setToken } from "./auth/actions"; type Resp = HttpData<AuthState>; /** What to do when the Token refresh request completes. */ const ok = (x: Resp) => { setToken(x.data); // Start using new token in HTTP requests. return x.data; }; /** Grab a new token from the API (won't extend token's exp. date). * Redirect to home page on failure. */ export let maybeRefreshToken = (old: AuthState): Promise<AuthState> => { API.setBaseUrl(old.token.unencoded.iss); setToken(old); // Precaution: The Axios interceptors might not be set yet. return axios.get(API.current.tokensPath).then(ok, goHome); };
Reduce block nesting level. NEXT: Tests
Reduce block nesting level. NEXT: Tests
TypeScript
mit
RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API
--- +++ @@ -1,20 +1,21 @@ import axios from "axios"; import { API } from "./api/index"; import { AuthState } from "./auth/interfaces"; -import { HttpData } from "./util"; +import { HttpData, goHome } from "./util"; import { setToken } from "./auth/actions"; + +type Resp = HttpData<AuthState>; + +/** What to do when the Token refresh request completes. */ +const ok = (x: Resp) => { + setToken(x.data); // Start using new token in HTTP requests. + return x.data; +}; /** Grab a new token from the API (won't extend token's exp. date). * Redirect to home page on failure. */ export let maybeRefreshToken = (old: AuthState): Promise<AuthState> => { API.setBaseUrl(old.token.unencoded.iss); - setToken(old); // The Axios interceptors might not be set yet. - type Resp = HttpData<AuthState>; - - return axios.get(API.current.tokensPath).then((x: Resp) => { - setToken(old); - return x.data; - }, (x) => { - return Promise.reject("X"); - }); + setToken(old); // Precaution: The Axios interceptors might not be set yet. + return axios.get(API.current.tokensPath).then(ok, goHome); };
2c771d515d2936909ac559f254234acd1cb35414
ui/src/timeMachine/constants/queryBuilder.ts
ui/src/timeMachine/constants/queryBuilder.ts
import {WINDOW_PERIOD} from 'src/variables/constants' export interface QueryFn { name: string flux: string aggregate: boolean } export const FUNCTIONS: QueryFn[] = [ {name: 'mean', flux: `|> mean()`, aggregate: true}, {name: 'median', flux: '|> toFloat()\n |> median()', aggregate: true}, {name: 'max', flux: '|> max()', aggregate: true}, {name: 'min', flux: '|> min()', aggregate: true}, {name: 'sum', flux: '|> sum()', aggregate: true}, { name: 'derivative', flux: `|> derivative(unit: ${WINDOW_PERIOD}, nonNegative: false)`, aggregate: false, }, {name: 'distinct', flux: '|> distinct()', aggregate: false}, {name: 'count', flux: '|> count()', aggregate: false}, {name: 'increase', flux: '|> increase()', aggregate: false}, {name: 'skew', flux: '|> skew()', aggregate: false}, {name: 'spread', flux: '|> spread()', aggregate: false}, {name: 'stddev', flux: '|> stddev()', aggregate: true}, {name: 'first', flux: '|> first()', aggregate: true}, {name: 'last', flux: '|> last()', aggregate: true}, {name: 'unique', flux: '|> unique()', aggregate: false}, {name: 'sort', flux: '|> sort()', aggregate: false}, ]
import {WINDOW_PERIOD, OPTION_NAME} from 'src/variables/constants' export interface QueryFn { name: string flux: string aggregate: boolean } export const FUNCTIONS: QueryFn[] = [ {name: 'mean', flux: `|> mean()`, aggregate: true}, {name: 'median', flux: '|> toFloat()\n |> median()', aggregate: true}, {name: 'max', flux: '|> max()', aggregate: true}, {name: 'min', flux: '|> min()', aggregate: true}, {name: 'sum', flux: '|> sum()', aggregate: true}, { name: 'derivative', flux: `|> derivative(unit: ${OPTION_NAME}.${WINDOW_PERIOD}, nonNegative: false)`, aggregate: false, }, {name: 'distinct', flux: '|> distinct()', aggregate: false}, {name: 'count', flux: '|> count()', aggregate: false}, {name: 'increase', flux: '|> increase()', aggregate: false}, {name: 'skew', flux: '|> skew()', aggregate: false}, {name: 'spread', flux: '|> spread()', aggregate: false}, {name: 'stddev', flux: '|> stddev()', aggregate: true}, {name: 'first', flux: '|> first()', aggregate: true}, {name: 'last', flux: '|> last()', aggregate: true}, {name: 'unique', flux: '|> unique()', aggregate: false}, {name: 'sort', flux: '|> sort()', aggregate: false}, ]
Fix building queries with derivatives
Fix building queries with derivatives
TypeScript
mit
mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,li-ang/influxdb,nooproblem/influxdb,li-ang/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb
--- +++ @@ -1,4 +1,4 @@ -import {WINDOW_PERIOD} from 'src/variables/constants' +import {WINDOW_PERIOD, OPTION_NAME} from 'src/variables/constants' export interface QueryFn { name: string @@ -14,7 +14,7 @@ {name: 'sum', flux: '|> sum()', aggregate: true}, { name: 'derivative', - flux: `|> derivative(unit: ${WINDOW_PERIOD}, nonNegative: false)`, + flux: `|> derivative(unit: ${OPTION_NAME}.${WINDOW_PERIOD}, nonNegative: false)`, aggregate: false, }, {name: 'distinct', flux: '|> distinct()', aggregate: false},
9c27c88bdc91a95c21d18dea899b968d888adddd
CeraonUI/src/Store/CeraonDispatcher.ts
CeraonUI/src/Store/CeraonDispatcher.ts
import CeraonStore from './CeraonStore'; import CeraonAction from '../Actions/CeraonAction'; // Separate dispatch file to hide the rest of the actions that can be taken on CeraonStore export default function dispatch(action: CeraonAction) { CeraonStore.dispatch(action); }
Add dispatcher to hide getState functions from consumers that only need to dispatch
Add dispatcher to hide getState functions from consumers that only need to dispatch
TypeScript
bsd-3-clause
Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound
--- +++ @@ -0,0 +1,7 @@ +import CeraonStore from './CeraonStore'; +import CeraonAction from '../Actions/CeraonAction'; + +// Separate dispatch file to hide the rest of the actions that can be taken on CeraonStore +export default function dispatch(action: CeraonAction) { + CeraonStore.dispatch(action); +}
ba7340ddbc8af893a3498271b0853bd7f7876305
test/property-decorators/range.spec.ts
test/property-decorators/range.spec.ts
import { Range } from './../../src/'; describe('Range decorator', () => { it('should throw an error when no annotations are provided', () => { expect(() => { class TestClassRangeValue { @Range() // This will throw a TypeScript error (obviously) myNumber: number; } }).toThrowError('No range options provided'); }); it('should throw an error when the min and ax range values are invalid', () => { expect(() => { class TestClassRangeValue { @Range({ max: 0, min: 10 }) myNumber: number; } }).toThrowError('The min range value has to be less than max value'); }); it('should throw an error when the min value are invalid (not a number)', () => { expect(() => { class TestClassRangeValue { @Range({ max: 10, min: +'A' }) myNumber: number; } }).toThrowError('The min range value is mandatory'); }); it('should throw an error when the max value are invalid (not a number)', () => { expect(() => { class TestClassRangeValue { @Range({ min: 0, max: +'A' }) myNumber: number; } }).toThrowError('The max range value is mandatory'); }); it('should assign a valid value (inside the range)', () => { class TestClassRangeValue { @Range({ min: 0, max: 10 }) myNumber: number; } let testClass = new TestClassRangeValue(); let valueToAssign = 5; testClass.myNumber = valueToAssign; expect(testClass.myNumber).toEqual(valueToAssign); }); it('should protect the value when invalid value is assigned', () => { class TestClassRangeValue { @Range({ min: 0, max: 10, protect: true }) myNumber: number; } let testClass = new TestClassRangeValue(); let valueToAssign = 5; testClass.myNumber = valueToAssign; testClass.myNumber = 15; expect(testClass.myNumber).toEqual(valueToAssign); }); it('should throw an error when invalid value is assigned', () => { class TestClassRangeValue { @Range({ min: 0, max: 10, protect: false, throwOutOfRange: true }) myNumber: number; } let testClass = new TestClassRangeValue(); let valueToAssign = 5; testClass.myNumber = valueToAssign; expect(() => testClass.myNumber = 15).toThrowError('Value out of range!'); }); });
Add unit tests for range decorator
Add unit tests for range decorator
TypeScript
mit
semagarcia/typescript-decorators,semagarcia/typescript-decorators
--- +++ @@ -0,0 +1,78 @@ +import { Range } from './../../src/'; + +describe('Range decorator', () => { + + it('should throw an error when no annotations are provided', () => { + expect(() => { + class TestClassRangeValue { + @Range() // This will throw a TypeScript error (obviously) + myNumber: number; + } + }).toThrowError('No range options provided'); + }); + + it('should throw an error when the min and ax range values are invalid', () => { + expect(() => { + class TestClassRangeValue { + @Range({ max: 0, min: 10 }) + myNumber: number; + } + }).toThrowError('The min range value has to be less than max value'); + }); + + it('should throw an error when the min value are invalid (not a number)', () => { + expect(() => { + class TestClassRangeValue { + @Range({ max: 10, min: +'A' }) + myNumber: number; + } + }).toThrowError('The min range value is mandatory'); + }); + + it('should throw an error when the max value are invalid (not a number)', () => { + expect(() => { + class TestClassRangeValue { + @Range({ min: 0, max: +'A' }) + myNumber: number; + } + }).toThrowError('The max range value is mandatory'); + }); + + it('should assign a valid value (inside the range)', () => { + class TestClassRangeValue { + @Range({ min: 0, max: 10 }) + myNumber: number; + } + + let testClass = new TestClassRangeValue(); + let valueToAssign = 5; + testClass.myNumber = valueToAssign; + expect(testClass.myNumber).toEqual(valueToAssign); + }); + + it('should protect the value when invalid value is assigned', () => { + class TestClassRangeValue { + @Range({ min: 0, max: 10, protect: true }) + myNumber: number; + } + + let testClass = new TestClassRangeValue(); + let valueToAssign = 5; + testClass.myNumber = valueToAssign; + testClass.myNumber = 15; + expect(testClass.myNumber).toEqual(valueToAssign); + }); + + it('should throw an error when invalid value is assigned', () => { + class TestClassRangeValue { + @Range({ min: 0, max: 10, protect: false, throwOutOfRange: true }) + myNumber: number; + } + + let testClass = new TestClassRangeValue(); + let valueToAssign = 5; + testClass.myNumber = valueToAssign; + expect(() => testClass.myNumber = 15).toThrowError('Value out of range!'); + }); + +});
6daee807ab903c6730dce84e172b934f3a48e4ca
types/emoji-mart/index.d.ts
types/emoji-mart/index.d.ts
// Type definitions for emoji-mart 2.8 // Project: https://github.com/missive/emoji-mart // Definitions by: Diogo Franco <https://github.com/Kovensky> // Nick Winans <https://github.com/Nicell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 export * from './dist-es';
// Type definitions for emoji-mart 2.8 // Project: https://github.com/missive/emoji-mart // Definitions by: Diogo Franco <https://github.com/Kovensky> // Nick Winans <https://github.com/Nicell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 export * from './dist-es';
Set TypeScript version back to 2.8
Set TypeScript version back to 2.8
TypeScript
mit
dsebastien/DefinitelyTyped,magny/DefinitelyTyped,mcliment/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped
--- +++ @@ -3,6 +3,6 @@ // Definitions by: Diogo Franco <https://github.com/Kovensky> // Nick Winans <https://github.com/Nicell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.9 +// TypeScript Version: 2.8 export * from './dist-es';
9e7c61b5779ed9985955d62a838af34a17b08487
server/src/SettingsCache.ts
server/src/SettingsCache.ts
import { TextDocument, WorkspaceFolder } from 'vscode-languageserver'; export type RubyEnvironment = { PATH: string; RUBY_VERSION: string; RUBY_ROOT: string; GEM_HOME: string; GEM_PATH: string; GEM_ROOT: string; }; export interface RubyConfiguration {} class SettingsCache<P extends WorkspaceFolder | TextDocument, T> { private cache: Map<string, T>; public fetcher: (target: string[]) => Promise<T[]>; constructor() { this.cache = new Map(); } public set(target: P | string, env: T): void { const key = typeof target === 'string' ? target : target.uri; this.cache.set(key, env); } public setAll(targets: { [key: string]: T }): void { for (const target of Object.keys(targets)) { this.set(target, targets[target]); } } public delete(target: P): boolean { return this.cache.delete(target.uri); } public deleteAll(targets: P[]): void { for (const target of targets) { this.delete(target); } } public async get(target: P | string): Promise<T | undefined> { const key = typeof target === 'string' ? target : target.uri; let settings: T = this.cache.get(key); if (!settings) { const result = await this.fetcher([key]); settings = result.length > 0 ? result[0] : undefined; if (settings) { this.set(key, settings); } } return settings; } public async getAll(targets: P[]): Promise<{ [key: string]: T }> { const settings: { [key: string]: T } = {}; for (const target of targets) { settings[target.uri] = await this.get(target); } return settings; } public flush(): void { this.cache.clear(); } public toString(): string { return this.cache.toString(); } } export const documentConfigurationCache = new SettingsCache<TextDocument, RubyConfiguration>(); export const workspaceRubyEnvironmentCache = new SettingsCache<WorkspaceFolder, RubyEnvironment>();
Add generic SettingCache for caching configuration and environments
Add generic SettingCache for caching configuration and environments
TypeScript
mit
rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby
--- +++ @@ -0,0 +1,78 @@ +import { TextDocument, WorkspaceFolder } from 'vscode-languageserver'; + +export type RubyEnvironment = { + PATH: string; + RUBY_VERSION: string; + RUBY_ROOT: string; + GEM_HOME: string; + GEM_PATH: string; + GEM_ROOT: string; +}; + +export interface RubyConfiguration {} + +class SettingsCache<P extends WorkspaceFolder | TextDocument, T> { + private cache: Map<string, T>; + public fetcher: (target: string[]) => Promise<T[]>; + + constructor() { + this.cache = new Map(); + } + + public set(target: P | string, env: T): void { + const key = typeof target === 'string' ? target : target.uri; + this.cache.set(key, env); + } + + public setAll(targets: { [key: string]: T }): void { + for (const target of Object.keys(targets)) { + this.set(target, targets[target]); + } + } + + public delete(target: P): boolean { + return this.cache.delete(target.uri); + } + + public deleteAll(targets: P[]): void { + for (const target of targets) { + this.delete(target); + } + } + + public async get(target: P | string): Promise<T | undefined> { + const key = typeof target === 'string' ? target : target.uri; + let settings: T = this.cache.get(key); + if (!settings) { + const result = await this.fetcher([key]); + settings = result.length > 0 ? result[0] : undefined; + + if (settings) { + this.set(key, settings); + } + } + + return settings; + } + + public async getAll(targets: P[]): Promise<{ [key: string]: T }> { + const settings: { [key: string]: T } = {}; + + for (const target of targets) { + settings[target.uri] = await this.get(target); + } + + return settings; + } + + public flush(): void { + this.cache.clear(); + } + + public toString(): string { + return this.cache.toString(); + } +} + +export const documentConfigurationCache = new SettingsCache<TextDocument, RubyConfiguration>(); +export const workspaceRubyEnvironmentCache = new SettingsCache<WorkspaceFolder, RubyEnvironment>();
95e97642971ee4b6c5189c41958599f23dcfc175
javascript/signature/subtle/index.ts
javascript/signature/subtle/index.ts
export {default as EcdsaSign} from 'goog:tink.subtle.EcdsaSign'; // from //third_party/tink/javascript/subtle:signature export {EcdsaSignatureEncodingType, exportCryptoKey, generateKeyPair, importPrivateKey, importPublicKey} from 'goog:tink.subtle.EllipticCurves'; // from //third_party/tink/javascript/subtle
Create new TypeScript import paths for signature/subtle
Create new TypeScript import paths for signature/subtle This is part of the ongoing TypeScript migration efforts. It was omitted from the first round due to open questions about how to handle it. This change just addresses the import paths; there may be more changes later. PiperOrigin-RevId: 303225203
TypeScript
apache-2.0
google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink
--- +++ @@ -0,0 +1,2 @@ +export {default as EcdsaSign} from 'goog:tink.subtle.EcdsaSign'; // from //third_party/tink/javascript/subtle:signature +export {EcdsaSignatureEncodingType, exportCryptoKey, generateKeyPair, importPrivateKey, importPublicKey} from 'goog:tink.subtle.EllipticCurves'; // from //third_party/tink/javascript/subtle
e9b2da97d237776e2879c33038cd16849a7727d5
src/constants/google-play.ts
src/constants/google-play.ts
export const GooglePlayConstants = { PLAY_STORE_ROOT_WEB: `https://play.google.com/store/apps/details?hl=en&id=`, PLAY_STORE_PACKAGE_NOT_PUBLISHED_IDENTIFIER: ` We're sorry, the requested URL was not found on this server. `, VERSION_REGEX: /itemprop="softwareVersion">\s*([0-9.]*)\s*<\/div>\s*<\/div>/gm, DATE_REGEX: /itemprop="datePublished">\s*([\w\s,]*)\s*<\/div>\s*<\/div>/gm, }
Create google play related constants
Create google play related constants
TypeScript
apache-2.0
chronogolf/nativescript-store-update,chronogolf/nativescript-store-update,chronogolf/nativescript-store-update,chronogolf/nativescript-store-update
--- +++ @@ -0,0 +1,8 @@ +export const GooglePlayConstants = { + PLAY_STORE_ROOT_WEB: `https://play.google.com/store/apps/details?hl=en&id=`, + PLAY_STORE_PACKAGE_NOT_PUBLISHED_IDENTIFIER: ` + We're sorry, the requested URL was not found on this server. + `, + VERSION_REGEX: /itemprop="softwareVersion">\s*([0-9.]*)\s*<\/div>\s*<\/div>/gm, + DATE_REGEX: /itemprop="datePublished">\s*([\w\s,]*)\s*<\/div>\s*<\/div>/gm, +}
1a84384b3a464e162783745a7c9e0d7350a67ae0
tests/test_basic_classes.ts
tests/test_basic_classes.ts
import eventtypes = require('../lib/epcisevents'); var assert = require('assert'); describe('Basic class functionality', () => { it('check the epcClass parser in the Quantity class', (done) => { var quantity = new eventtypes.EPCIS.Quantity(); quantity.setEpcClass('urn:epc:idpat:sgtin:myidentifier'); assert.equal(quantity.type, 'urn:epc:idpat:sgtin'); assert.equal(quantity.identifier, 'myidentifier'); assert.equal(quantity.epcClass(), 'urn:epc:idpat:sgtin:myidentifier'); done(); }); });
Add test for Quantity class
Add test for Quantity class
TypeScript
mit
matgnt/epcis-js,matgnt/epcis-js
--- +++ @@ -0,0 +1,20 @@ +import eventtypes = require('../lib/epcisevents'); +var assert = require('assert'); + +describe('Basic class functionality', () => { + + it('check the epcClass parser in the Quantity class', (done) => { + var quantity = new eventtypes.EPCIS.Quantity(); + + quantity.setEpcClass('urn:epc:idpat:sgtin:myidentifier'); + + assert.equal(quantity.type, 'urn:epc:idpat:sgtin'); + assert.equal(quantity.identifier, 'myidentifier'); + + assert.equal(quantity.epcClass(), 'urn:epc:idpat:sgtin:myidentifier'); + + done(); + }); + + +});
28ef2fe2da17c644ee8991fba5b917a7418f7c5f
app/test/unit/enum-test.ts
app/test/unit/enum-test.ts
import { parseEnumValue } from '../../src/lib/enum' enum TestEnum { Foo = 'foo', Bar = 'bar is the thing', } describe('parseEnumValue', () => { it('parses an enum type from a string', () => { expect(parseEnumValue(TestEnum, 'foo')).toBe(TestEnum.Foo) expect(parseEnumValue(TestEnum, TestEnum.Foo)).toBe(TestEnum.Foo) expect(parseEnumValue(TestEnum, 'bar is the thing')).toBe(TestEnum.Bar) expect(parseEnumValue(TestEnum, TestEnum.Bar)).toBe(TestEnum.Bar) }) it("returns undefined when enum value doesn't exist", () => { expect(parseEnumValue(TestEnum, 'baz')).toBe(undefined) }) it('ignores inherited values', () => { // Note: The only way I can think of that this would happen is if someone // monkey-patches Object but we're not going to taint the test suite for // that so we'll create a fake enum const parent = Object.create(null) parent.foo = 'bar' const child = Object.create(parent) expect('foo' in child).toBeTrue() expect(child.foo).toBe('bar') expect(parseEnumValue(child, 'bar')).toBe(undefined) }) })
Add some tests forr good measure
Add some tests forr good measure
TypeScript
mit
shiftkey/desktop,desktop/desktop,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,desktop/desktop,say25/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,say25/desktop,say25/desktop,artivilla/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop
--- +++ @@ -0,0 +1,33 @@ +import { parseEnumValue } from '../../src/lib/enum' + +enum TestEnum { + Foo = 'foo', + Bar = 'bar is the thing', +} + +describe('parseEnumValue', () => { + it('parses an enum type from a string', () => { + expect(parseEnumValue(TestEnum, 'foo')).toBe(TestEnum.Foo) + expect(parseEnumValue(TestEnum, TestEnum.Foo)).toBe(TestEnum.Foo) + expect(parseEnumValue(TestEnum, 'bar is the thing')).toBe(TestEnum.Bar) + expect(parseEnumValue(TestEnum, TestEnum.Bar)).toBe(TestEnum.Bar) + }) + + it("returns undefined when enum value doesn't exist", () => { + expect(parseEnumValue(TestEnum, 'baz')).toBe(undefined) + }) + + it('ignores inherited values', () => { + // Note: The only way I can think of that this would happen is if someone + // monkey-patches Object but we're not going to taint the test suite for + // that so we'll create a fake enum + const parent = Object.create(null) + parent.foo = 'bar' + + const child = Object.create(parent) + + expect('foo' in child).toBeTrue() + expect(child.foo).toBe('bar') + expect(parseEnumValue(child, 'bar')).toBe(undefined) + }) +})
a4be682d87b359713fe7f4f9fadeece6ed132ee0
src/Test/Ast/Config/Table.ts
src/Test/Ast/Config/Table.ts
import { expect } from 'chai' import Up from '../../../index' import { DocumentNode } from '../../../SyntaxNodes/DocumentNode' import { TableNode } from '../../../SyntaxNodes/TableNode' import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode' describe('The term that represents table conventions', () => { const up = new Up({ i18n: { terms: { table: 'data' } } }) it('comes from the "table" config term', () => { const text = ` Data: Game; Release Date Chrono Trigger; 1995 Chrono Cross; 1999` expect(up.toAst(text)).to.be.eql( new DocumentNode([ new TableNode( new TableNode.Header([ new TableNode.Header.Cell([new PlainTextNode('Game')]), new TableNode.Header.Cell([new PlainTextNode('Release Date')]) ]), [ new TableNode.Row([ new TableNode.Row.Cell([new PlainTextNode('Chrono Trigger')]), new TableNode.Row.Cell([new PlainTextNode('1995')]) ]), new TableNode.Row([ new TableNode.Row.Cell([new PlainTextNode('Chrono Cross')]), new TableNode.Row.Cell([new PlainTextNode('1999')]) ]) ]) ])) }) it('is case-insensitive even when custom', () => { const uppercase = ` Data: Game; Release Date Chrono Trigger; 1995 Chrono Cross; 1999` const mixedCase = ` dAtA: Game; Release Date Chrono Trigger; 1995 Chrono Cross; 1999` expect(up.toAst(uppercase)).to.be.eql(up.toAst(mixedCase)) }) })
Add 2 passing table config tests
Add 2 passing table config tests
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,59 @@ +import { expect } from 'chai' +import Up from '../../../index' +import { DocumentNode } from '../../../SyntaxNodes/DocumentNode' +import { TableNode } from '../../../SyntaxNodes/TableNode' +import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode' + + +describe('The term that represents table conventions', () => { + const up = new Up({ + i18n: { + terms: { table: 'data' } + } + }) + + it('comes from the "table" config term', () => { + const text = ` +Data: + +Game; Release Date +Chrono Trigger; 1995 +Chrono Cross; 1999` + + expect(up.toAst(text)).to.be.eql( + new DocumentNode([ + new TableNode( + new TableNode.Header([ + new TableNode.Header.Cell([new PlainTextNode('Game')]), + new TableNode.Header.Cell([new PlainTextNode('Release Date')]) + ]), [ + new TableNode.Row([ + new TableNode.Row.Cell([new PlainTextNode('Chrono Trigger')]), + new TableNode.Row.Cell([new PlainTextNode('1995')]) + ]), + new TableNode.Row([ + new TableNode.Row.Cell([new PlainTextNode('Chrono Cross')]), + new TableNode.Row.Cell([new PlainTextNode('1999')]) + ]) + ]) + ])) + }) + + it('is case-insensitive even when custom', () => { + const uppercase = ` +Data: + +Game; Release Date +Chrono Trigger; 1995 +Chrono Cross; 1999` + + const mixedCase = ` +dAtA: + +Game; Release Date +Chrono Trigger; 1995 +Chrono Cross; 1999` + + expect(up.toAst(uppercase)).to.be.eql(up.toAst(mixedCase)) + }) +})
b6aff98fd7fbb78532de718ff561f26fb7c43c61
tests/cases/compiler/contravariantInferenceAndTypeGuard.ts
tests/cases/compiler/contravariantInferenceAndTypeGuard.ts
// @strict: true interface ListItem<TData> { prev: ListItem<TData> | null; next: ListItem<TData> | null; data: TData; } type IteratorFn<TData, TResult, TContext = List<TData>> = (this: TContext, item: TData, node: ListItem<TData>, list: List<TData>) => TResult; type FilterFn<TData, TResult extends TData, TContext = List<TData>> = (this: TContext, item: TData, node: ListItem<TData>, list: List<TData>) => item is TResult; declare class List<TData> { filter<TContext, TResult extends TData>(fn: FilterFn<TData, TResult, TContext>, context: TContext): List<TResult>; filter<TResult extends TData>(fn: FilterFn<TData, TResult>): List<TResult>; filter<TContext>(fn: IteratorFn<TData, boolean, TContext>, context: TContext): List<TData>; filter(fn: IteratorFn<TData, boolean>): List<TData>; } interface Test { a: string; } const list2 = new List<Test | null>(); const filter1 = list2.filter(function(item, node, list): item is Test { this.b; // $ExpectType string item; // $ExpectType Test | null node; // $ExpectType ListItem<Test | null> list; // $ExpectType List<Test | null> return !!item; }, {b: 'c'}); const x: List<Test> = filter1; // $ExpectType List<Test>
Add test relating type predicates with and without this parameters
Add test relating type predicates with and without this parameters
TypeScript
apache-2.0
kpreisser/TypeScript,weswigham/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,nojvek/TypeScript,minestarks/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,weswigham/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,alexeagle/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,RyanCavanaugh/TypeScript,Microsoft/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,Microsoft/TypeScript,kitsonk/TypeScript,kpreisser/TypeScript,minestarks/TypeScript,microsoft/TypeScript,kitsonk/TypeScript,RyanCavanaugh/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,Microsoft/TypeScript,alexeagle/TypeScript
--- +++ @@ -0,0 +1,27 @@ +// @strict: true +interface ListItem<TData> { + prev: ListItem<TData> | null; + next: ListItem<TData> | null; + data: TData; +} +type IteratorFn<TData, TResult, TContext = List<TData>> = (this: TContext, item: TData, node: ListItem<TData>, list: List<TData>) => TResult; +type FilterFn<TData, TResult extends TData, TContext = List<TData>> = (this: TContext, item: TData, node: ListItem<TData>, list: List<TData>) => item is TResult; + +declare class List<TData> { + filter<TContext, TResult extends TData>(fn: FilterFn<TData, TResult, TContext>, context: TContext): List<TResult>; + filter<TResult extends TData>(fn: FilterFn<TData, TResult>): List<TResult>; + filter<TContext>(fn: IteratorFn<TData, boolean, TContext>, context: TContext): List<TData>; + filter(fn: IteratorFn<TData, boolean>): List<TData>; +} +interface Test { + a: string; +} +const list2 = new List<Test | null>(); +const filter1 = list2.filter(function(item, node, list): item is Test { + this.b; // $ExpectType string + item; // $ExpectType Test | null + node; // $ExpectType ListItem<Test | null> + list; // $ExpectType List<Test | null> + return !!item; +}, {b: 'c'}); +const x: List<Test> = filter1; // $ExpectType List<Test>
481a101e6a230f5cb91c3a1b74d24661597d9a6f
src/lib/batcher.ts
src/lib/batcher.ts
/* * Copyright (C) 2012-2017 Online-Go.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // There are some cases where it is more efficient to perform a series of // operations together asynchronously than it is to perform them one at a // time when the need arises. The classic example of this is requests to // the back end. export class Batcher<T> { private action: (values: Array<T>) => void; private values: Array<T>; constructor(action: (values: Array<T>) => void) { this.action = action; this.values = []; } // Perform the action on the given value soon. It is OK to call // this method from within the action function, but the action will // not be executed on the new values immediately. soon(value: T): void { if (this.values.length === 0) { setTimeout(this.perform, 0); } this.values.push(value); } private perform = () => { let values = this.values; this.values = []; this.action(values); } }
Introduce a new Batcher class for batching up multiple operations.
Introduce a new Batcher class for batching up multiple operations.
TypeScript
agpl-3.0
lemurek/online-go.com,BarneyStratford/online-go.com,lemurek/online-go.com,online-go/online-go.com,online-go/online-go.com,lemurek/online-go.com,online-go/online-go.com,BarneyStratford/online-go.com,online-go/online-go.com,online-go/online-go.com,BarneyStratford/online-go.com,lemurek/online-go.com,BarneyStratford/online-go.com
--- +++ @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2012-2017 Online-Go.com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// There are some cases where it is more efficient to perform a series of +// operations together asynchronously than it is to perform them one at a +// time when the need arises. The classic example of this is requests to +// the back end. +export class Batcher<T> { + private action: (values: Array<T>) => void; + private values: Array<T>; + + constructor(action: (values: Array<T>) => void) { + this.action = action; + this.values = []; + } + + // Perform the action on the given value soon. It is OK to call + // this method from within the action function, but the action will + // not be executed on the new values immediately. + soon(value: T): void { + if (this.values.length === 0) { + setTimeout(this.perform, 0); + } + this.values.push(value); + } + + private perform = () => { + let values = this.values; + this.values = []; + this.action(values); + } +}