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
|
---|---|---|---|---|---|---|---|---|---|---|
73415cd4b02160eb30e393baf8beca9a00c8d550 | build/server/server.env=node.ts | build/server/server.env=node.ts | class $mol_build_server extends $mol_server {
expressGenerator() {
return ( req : any , res : any , next : () => void )=> {
try {
return this.generator( req.url ) || next()
} catch( error ) {
$mol_atom_restore( error )
if( req.url.match( /\.js$/ ) ) {
console.error( error )
res.send( `console.error( ${ JSON.stringify( error.message ) } )` ).end()
} else {
throw error
}
}
}
}
build() : $mol_build {
return null
}
@ $mol_prop()
generator( path : string ) {
var matched = path.match( /^((?:\/\w+)+)\/-\/(\w+(?:.\w+)+)$/ )
if( !matched ) return null
var build = this.build()
var [ path , path , bundle ] = matched
path = build.root().resolve( path ).path()
build.bundle({ path , bundle })
return <void> null
}
port() {
return 80
}
}
| class $mol_build_server extends $mol_server {
expressGenerator() {
return ( req : any , res : any , next : () => void )=> {
try {
return this.generator( req.url ) || next()
} catch( error ) {
$mol_atom_restore( error )
if( req.url.match( /\.js$/ ) ) {
console.error( error )
res.send( `console.error( ${ JSON.stringify( error.message ) } )` ).end()
} else {
throw error
}
}
}
}
build() : $mol_build {
return null
}
@ $mol_prop()
generator( path : string ) {
var matched = path.match( /^((?:\/\w+)+)\/-\/(\w+(?:.\w+)+)$/ )
if( !matched ) return null
var build = this.build()
var [ path , path , bundle ] = matched
path = build.root().resolve( path ).path()
build.bundle({ path , bundle })
return <void> null
}
port() {
return 8080
}
}
| Use 8080 port instead of 80 by default to reduce errors on some systems. | Use 8080 port instead of 80 by default to reduce errors on some systems.
| TypeScript | mit | eigenmethod/mol,nin-jin/mol,nin-jin/mol,eigenmethod/mol,nin-jin/mol,eigenmethod/mol | ---
+++
@@ -36,7 +36,7 @@
}
port() {
- return 80
+ return 8080
}
} |
e9330d49949e64a103cb9f7eb303c4b2cb300b90 | tests/cases/fourslash/codeFixReplaceQualifiedNameWithIndexedAccessType01.ts | tests/cases/fourslash/codeFixReplaceQualifiedNameWithIndexedAccessType01.ts | /// <reference path='fourslash.ts' />
//// export interface Foo {
//// bar: string;
//// }
//// const x: [|Foo.bar|] = ""
verify.rangeAfterCodeFix(`Foo["bar"]`);
| Add test case for code fixes on qualified names used instead of indexed access types. | Add test case for code fixes on qualified names used instead of indexed access types.
| TypeScript | apache-2.0 | kitsonk/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,SaschaNaz/TypeScript,kitsonk/TypeScript,synaptek/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,kpreisser/TypeScript,RyanCavanaugh/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,synaptek/TypeScript,minestarks/TypeScript,TukekeSoft/TypeScript,basarat/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,synaptek/TypeScript,microsoft/TypeScript,nojvek/TypeScript,Eyas/TypeScript,minestarks/TypeScript,basarat/TypeScript,microsoft/TypeScript,weswigham/TypeScript,basarat/TypeScript,Eyas/TypeScript,synaptek/TypeScript,microsoft/TypeScript,kpreisser/TypeScript,Microsoft/TypeScript,RyanCavanaugh/TypeScript,TukekeSoft/TypeScript,Microsoft/TypeScript,Eyas/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript,Microsoft/TypeScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,nojvek/TypeScript,Eyas/TypeScript | ---
+++
@@ -0,0 +1,8 @@
+/// <reference path='fourslash.ts' />
+
+//// export interface Foo {
+//// bar: string;
+//// }
+//// const x: [|Foo.bar|] = ""
+
+verify.rangeAfterCodeFix(`Foo["bar"]`); |
|
d25ff39991efef7d7d7651f1517061defc26f55d | ui/src/shared/components/overlay/OverlayHeading.tsx | ui/src/shared/components/overlay/OverlayHeading.tsx | import React, {PureComponent, ReactChildren} from 'react'
interface Props {
children?: ReactChildren
title: string
onDismiss?: () => void
}
class OverlayHeading extends PureComponent<Props> {
constructor(props: Props) {
super(props)
}
public render() {
const {title, onDismiss, children} = this.props
return (
<div className="overlay--heading">
<div className="overlay--title">{title}</div>
{onDismiss && (
<button className="overlay--dismiss" onClick={onDismiss} />
)}
{children && children}
</div>
)
}
}
export default OverlayHeading
| import React, {PureComponent, ReactChildren} from 'react'
interface Props {
children?: ReactChildren | JSX.Element
title: string
onDismiss?: () => void
}
class OverlayHeading extends PureComponent<Props> {
constructor(props: Props) {
super(props)
}
public render() {
const {title, onDismiss, children} = this.props
return (
<div className="overlay--heading">
<div className="overlay--title">{title}</div>
{onDismiss && (
<button className="overlay--dismiss" onClick={onDismiss} />
)}
{children && children}
</div>
)
}
}
export default OverlayHeading
| Allow plain HTML elements as children | Allow plain HTML elements as children
| TypeScript | mit | nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb | ---
+++
@@ -1,7 +1,7 @@
import React, {PureComponent, ReactChildren} from 'react'
interface Props {
- children?: ReactChildren
+ children?: ReactChildren | JSX.Element
title: string
onDismiss?: () => void
} |
d02e7c30fe3d1be406043bb02713db32718597e8 | src/lib/common/event-registry.ts | src/lib/common/event-registry.ts | import {
ElementRef,
Injectable,
Renderer2
} from '@angular/core';
type UnlistenerMap = WeakMap<EventListener, Function>;
@Injectable()
export class EventRegistry {
private unlisteners: Map<string, UnlistenerMap> = new Map<string, UnlistenerMap>();
constructor() { }
listen_(renderer: Renderer2, type: string, listener: EventListener, ref: ElementRef) {
if (!this.unlisteners.has(type)) {
this.unlisteners.set(type, new WeakMap<EventListener, Function>());
}
const unlistener = renderer.listen(ref.nativeElement, type, listener);
this.unlisteners.get(type).set(listener, unlistener);
}
unlisten_(type: string, listener: EventListener) {
if (!this.unlisteners.has(type)) {
return;
}
const unlisteners = this.unlisteners.get(type);
if (!unlisteners.has(listener)) {
return;
}
unlisteners.get(listener)();
unlisteners.delete(listener);
}
}
| Add EventRegistry for Listen/Unlisten management | feat(infrastructure): Add EventRegistry for Listen/Unlisten management
| TypeScript | mit | trimox/angular-mdc-web,trimox/angular-mdc-web | ---
+++
@@ -0,0 +1,34 @@
+import {
+ ElementRef,
+ Injectable,
+ Renderer2
+} from '@angular/core';
+
+type UnlistenerMap = WeakMap<EventListener, Function>;
+
+@Injectable()
+export class EventRegistry {
+ private unlisteners: Map<string, UnlistenerMap> = new Map<string, UnlistenerMap>();
+
+ constructor() { }
+
+ listen_(renderer: Renderer2, type: string, listener: EventListener, ref: ElementRef) {
+ if (!this.unlisteners.has(type)) {
+ this.unlisteners.set(type, new WeakMap<EventListener, Function>());
+ }
+ const unlistener = renderer.listen(ref.nativeElement, type, listener);
+ this.unlisteners.get(type).set(listener, unlistener);
+ }
+
+ unlisten_(type: string, listener: EventListener) {
+ if (!this.unlisteners.has(type)) {
+ return;
+ }
+ const unlisteners = this.unlisteners.get(type);
+ if (!unlisteners.has(listener)) {
+ return;
+ }
+ unlisteners.get(listener)();
+ unlisteners.delete(listener);
+ }
+} |
|
a6448afdf3e0e490889caf6e397f210db90d4d2f | test/method-decorators/deprecated.spec.ts | test/method-decorators/deprecated.spec.ts | import { DeprecatedMethod } from './../../src/';
describe('DeprecatedMethod decorator', () => {
it('should throw an exception', () => {
class TestDeprecatedMethodDecorator {
@DeprecatedMethod()
method() {
console.log('I am a deprecated method');
}
}
let testClass = new TestDeprecatedMethodDecorator();
expect(() => testClass.method()).toThrowError('This method has been deprecated!');
});
it('should throw an exception', () => {
class TestDeprecatedMethodDecorator {
@DeprecatedMethod('Deprecated method!!')
method() {
console.log('I am a deprecated method');
}
}
let testClass = new TestDeprecatedMethodDecorator();
expect(() => testClass.method()).toThrowError('Deprecated method!!');
});
}); | Add test for deprecated method decorator | Add test for deprecated method decorator
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -0,0 +1,29 @@
+import { DeprecatedMethod } from './../../src/';
+
+describe('DeprecatedMethod decorator', () => {
+
+ it('should throw an exception', () => {
+ class TestDeprecatedMethodDecorator {
+ @DeprecatedMethod()
+ method() {
+ console.log('I am a deprecated method');
+ }
+ }
+
+ let testClass = new TestDeprecatedMethodDecorator();
+ expect(() => testClass.method()).toThrowError('This method has been deprecated!');
+ });
+
+ it('should throw an exception', () => {
+ class TestDeprecatedMethodDecorator {
+ @DeprecatedMethod('Deprecated method!!')
+ method() {
+ console.log('I am a deprecated method');
+ }
+ }
+
+ let testClass = new TestDeprecatedMethodDecorator();
+ expect(() => testClass.method()).toThrowError('Deprecated method!!');
+ });
+
+}); |
|
8c5130a3d8981fea9cb2caeaf5491c1ea7788087 | test/reducers/slides/actions/openNewDeck-spec.ts | test/reducers/slides/actions/openNewDeck-spec.ts | import { expect } from 'chai';
import { OPEN_NEW_DECK } from '../../../../app/constants/slides.constants';
export default function(initialState: any, reducer: any, slide: any) {
const dummySlide1 = {
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',
}
}
};
describe('OPEN_NEW_DECK', () => {
const _initialState = [slide, dummySlide1];
it('should reset slides state to a single slide with no plugins', () => {
expect(reducer(_initialState, { type: OPEN_NEW_DECK })).to.deep.equal(initialState);
});
});
}
| Add test for OPEN_NEW_DECK for slides reducer | test: Add test for OPEN_NEW_DECK for slides reducer
| TypeScript | mit | chengsieuly/devdecks,Team-CHAD/DevDecks,Team-CHAD/DevDecks,Team-CHAD/DevDecks,chengsieuly/devdecks,DevDecks/devdecks,DevDecks/devdecks,chengsieuly/devdecks,DevDecks/devdecks | ---
+++
@@ -0,0 +1,22 @@
+import { expect } from 'chai';
+import { OPEN_NEW_DECK } from '../../../../app/constants/slides.constants';
+
+export default function(initialState: any, reducer: any, slide: any) {
+ const dummySlide1 = {
+ 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',
+ }
+ }
+ };
+
+ describe('OPEN_NEW_DECK', () => {
+ const _initialState = [slide, dummySlide1];
+ it('should reset slides state to a single slide with no plugins', () => {
+ expect(reducer(_initialState, { type: OPEN_NEW_DECK })).to.deep.equal(initialState);
+ });
+ });
+} |
|
831ccc6644fe8677c816c4fc8ead386a59861fb1 | src/parser/hunter/shared/modules/talents/ChimaeraShot.tsx | src/parser/hunter/shared/modules/talents/ChimaeraShot.tsx | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS/index';
import ItemDamageDone from 'interface/ItemDamageDone';
import AverageTargetsHit from 'interface/others/AverageTargetsHit';
import Statistic from 'interface/statistics/Statistic';
import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText/index';
import Events, { DamageEvent } from 'parser/core/Events';
/**
* A two-headed shot that hits your primary target and another nearby target, dealing 720% Nature damage to one and 720% Frost damage to the other.
*
* Example log:
* https://www.warcraftlogs.com/reports/3hpLckCDdjWXqFyT#fight=5&type=damage-done&source=2&ability=-53209
*/
class ChimaeraShot extends Analyzer {
damage = 0;
casts = 0;
hits = 0;
constructor(options: any) {
super(options);
this.active = this.selectedCombatant.hasTalent(SPELLS.CHIMAERA_SHOT_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.CHIMAERA_SHOT_TALENT), () => { this.casts += 1; });
this.addEventListener(Events.damage.by(SELECTED_PLAYER)
.spell([SPELLS.CHIMAERA_SHOT_FROST_DAMAGE, SPELLS.CHIMAERA_SHOT_NATURE_DAMAGE]), this.onChimaeraDamage);
}
onChimaeraDamage(event: DamageEvent) {
this.hits += 1;
this.damage += event.amount + (event.absorbed || 0);
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.OPTIONAL(13)}
size="flexible"
category={STATISTIC_CATEGORY.TALENTS}
>
<BoringSpellValueText spell={SPELLS.CHIMAERA_SHOT_TALENT}>
<>
<ItemDamageDone amount={this.damage} /> <br />
<AverageTargetsHit casts={this.casts} hits={this.hits} />
</>
</BoringSpellValueText>
</Statistic>
);
}
}
export default ChimaeraShot;
| Update Chimaera Shot to also exist for Marksmanship | [Hunter] Update Chimaera Shot to also exist for Marksmanship
| TypeScript | agpl-3.0 | yajinni/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,Juko8/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,anom0ly/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,Juko8/WoWAnalyzer,yajinni/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer | ---
+++
@@ -0,0 +1,55 @@
+import React from 'react';
+import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
+import SPELLS from 'common/SPELLS/index';
+import ItemDamageDone from 'interface/ItemDamageDone';
+import AverageTargetsHit from 'interface/others/AverageTargetsHit';
+import Statistic from 'interface/statistics/Statistic';
+import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY';
+import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
+import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText/index';
+import Events, { DamageEvent } from 'parser/core/Events';
+
+/**
+ * A two-headed shot that hits your primary target and another nearby target, dealing 720% Nature damage to one and 720% Frost damage to the other.
+ *
+ * Example log:
+ * https://www.warcraftlogs.com/reports/3hpLckCDdjWXqFyT#fight=5&type=damage-done&source=2&ability=-53209
+ */
+class ChimaeraShot extends Analyzer {
+
+ damage = 0;
+ casts = 0;
+ hits = 0;
+
+ constructor(options: any) {
+ super(options);
+ this.active = this.selectedCombatant.hasTalent(SPELLS.CHIMAERA_SHOT_TALENT.id);
+ this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.CHIMAERA_SHOT_TALENT), () => { this.casts += 1; });
+ this.addEventListener(Events.damage.by(SELECTED_PLAYER)
+ .spell([SPELLS.CHIMAERA_SHOT_FROST_DAMAGE, SPELLS.CHIMAERA_SHOT_NATURE_DAMAGE]), this.onChimaeraDamage);
+ }
+
+ onChimaeraDamage(event: DamageEvent) {
+ this.hits += 1;
+ this.damage += event.amount + (event.absorbed || 0);
+ }
+
+ statistic() {
+ return (
+ <Statistic
+ position={STATISTIC_ORDER.OPTIONAL(13)}
+ size="flexible"
+ category={STATISTIC_CATEGORY.TALENTS}
+ >
+ <BoringSpellValueText spell={SPELLS.CHIMAERA_SHOT_TALENT}>
+ <>
+ <ItemDamageDone amount={this.damage} /> <br />
+ <AverageTargetsHit casts={this.casts} hits={this.hits} />
+ </>
+ </BoringSpellValueText>
+ </Statistic>
+ );
+ }
+}
+
+export default ChimaeraShot; |
|
b0118425f0eb0ae28115c8bfba931797a7dd86f8 | test/views/components/note_list_test.ts | test/views/components/note_list_test.ts | import * as helper from '../../test_helper';
var remoteConsole = require('remote').require('console')
describe('note-list', () => {
var noteList = null;
helper.useComponent(
'../../build/views/components/note-list/note-list.html',
(_) => { noteList = _ },
'ul', 'adv-note-list');
describe('#addItem', () => {
beforeEach(() => {
noteList.addItem('my_note.md', 'my_title', 'my_content');
});
it('adds an note with title and content', () => {
var innterHTML = noteList.innerHTML;
assert.include(innterHTML, 'my_title');
assert.include(innterHTML, 'my_content');
});
});
describe('#clearItems', () => {
beforeEach(() => {
noteList.addItem('my_note.md', 'my_title', 'my_content');
noteList.clearItems();
});
it('remote items from list', () => {
var innterHTML = noteList.innerHTML;
assert.notInclude(innterHTML, 'my_title');
assert.notInclude(innterHTML, 'my_content');
});
});
describe('events', () => {
beforeEach(() => {
noteList.addItem('my_note.md', 'my_title', 'my_content');
});
it('emits item_click event', (done) => {
noteList.addEventListener('item_click', (e) => {
assert.equal(e.detail.filename, 'my_note.md');
done();
});
noteList.querySelector('li').click();
});
});
});
| Add tests for note-list components | Add tests for note-list components
| TypeScript | mit | ueokande/adversaria,ueokande/adversaria,ueokande/adversaria | ---
+++
@@ -0,0 +1,46 @@
+import * as helper from '../../test_helper';
+var remoteConsole = require('remote').require('console')
+
+describe('note-list', () => {
+ var noteList = null;
+ helper.useComponent(
+ '../../build/views/components/note-list/note-list.html',
+ (_) => { noteList = _ },
+ 'ul', 'adv-note-list');
+
+ describe('#addItem', () => {
+ beforeEach(() => {
+ noteList.addItem('my_note.md', 'my_title', 'my_content');
+ });
+ it('adds an note with title and content', () => {
+ var innterHTML = noteList.innerHTML;
+ assert.include(innterHTML, 'my_title');
+ assert.include(innterHTML, 'my_content');
+ });
+ });
+
+ describe('#clearItems', () => {
+ beforeEach(() => {
+ noteList.addItem('my_note.md', 'my_title', 'my_content');
+ noteList.clearItems();
+ });
+ it('remote items from list', () => {
+ var innterHTML = noteList.innerHTML;
+ assert.notInclude(innterHTML, 'my_title');
+ assert.notInclude(innterHTML, 'my_content');
+ });
+ });
+
+ describe('events', () => {
+ beforeEach(() => {
+ noteList.addItem('my_note.md', 'my_title', 'my_content');
+ });
+ it('emits item_click event', (done) => {
+ noteList.addEventListener('item_click', (e) => {
+ assert.equal(e.detail.filename, 'my_note.md');
+ done();
+ });
+ noteList.querySelector('li').click();
+ });
+ });
+}); |
|
ca2219af4958d19fc202c670e1f583135457b49b | src/test/using_injector_test.ts | src/test/using_injector_test.ts | import {
it,
describe,
expect,
inject
} from 'angular2/testing';
import {
APP_ID
} from 'angular2/angular2';
describe('default test injector', () => {
it('should provide default pipes', inject([APP_ID], (id) => {
expect(id).toBe('a');
}));
});
| Add tests using the injector | Add tests using the injector
| TypeScript | apache-2.0 | katonap/ng2-test-seed,katonap/ng2-test-seed,katonap/ng2-test-seed | ---
+++
@@ -0,0 +1,16 @@
+import {
+ it,
+ describe,
+ expect,
+ inject
+} from 'angular2/testing';
+import {
+ APP_ID
+} from 'angular2/angular2';
+
+
+describe('default test injector', () => {
+ it('should provide default pipes', inject([APP_ID], (id) => {
+ expect(id).toBe('a');
+ }));
+}); |
|
1c25fc418e948df22364b33338b81f9d7e1d95ff | bids-validator/src/types/issues.ts | bids-validator/src/types/issues.ts | const warning = Symbol('warning')
const error = Symbol('error')
const ignore = Symbol('ignore')
type Severity = typeof warning | typeof error | typeof ignore
export interface IssueFileDetail {
name: string
path: string
relativePath: string
}
export interface IssueFile {
key: string
code: number
file: IssueFileDetail
evidence: String
line: number
character: number
severity: Severity
reason: string
helpUrl: string
}
/**
* Dataset issue, derived from OpenNeuro schema and existing validator implementation
*/
export interface Issue {
severity: Severity
key: string
code: number
reason: string
files: [IssueFile?]
additionalFileCount: number
helpUrl: string
}
| Add issue types from OpenNeuro | Add issue types from OpenNeuro
| TypeScript | mit | nellh/bids-validator,nellh/bids-validator,nellh/bids-validator | ---
+++
@@ -0,0 +1,35 @@
+const warning = Symbol('warning')
+const error = Symbol('error')
+const ignore = Symbol('ignore')
+type Severity = typeof warning | typeof error | typeof ignore
+
+export interface IssueFileDetail {
+ name: string
+ path: string
+ relativePath: string
+}
+
+export interface IssueFile {
+ key: string
+ code: number
+ file: IssueFileDetail
+ evidence: String
+ line: number
+ character: number
+ severity: Severity
+ reason: string
+ helpUrl: string
+}
+
+/**
+ * Dataset issue, derived from OpenNeuro schema and existing validator implementation
+ */
+export interface Issue {
+ severity: Severity
+ key: string
+ code: number
+ reason: string
+ files: [IssueFile?]
+ additionalFileCount: number
+ helpUrl: string
+} |
|
ab6479243b7da21316cf872490bd9b3db45df645 | functions/src/patch/firestore-api.ts | functions/src/patch/firestore-api.ts | export interface FirestoreApiBody {
fields: MapValue
}
type FieldValue =
StringValue |
BooleanValue |
ArrayValue |
IntegerValue |
DoubleValue |
MapValue |
NullValue |
ReferenceValue |
TimestampValue
interface StringValue {
'stringValue': string
}
interface BooleanValue {
'booleanValue': string
}
interface ArrayValue {
values: FieldValue[]
}
interface IntegerValue {
'integerValue': number
}
interface DoubleValue {
'doubleValue': number
}
interface MapValue {
fields: {
[fieldName: string]: FieldValue
}
}
interface NullValue {
'nullValue': null
}
interface ReferenceValue {
'referenceValue': string
}
interface TimestampValue {
'timestampValue': number
}
| Add firestore api body types | Add firestore api body types
| TypeScript | apache-2.0 | squanchy-dev/squanchy-firebase,squanchy-dev/squanchy-firebase | ---
+++
@@ -0,0 +1,52 @@
+export interface FirestoreApiBody {
+ fields: MapValue
+}
+
+type FieldValue =
+ StringValue |
+ BooleanValue |
+ ArrayValue |
+ IntegerValue |
+ DoubleValue |
+ MapValue |
+ NullValue |
+ ReferenceValue |
+ TimestampValue
+
+interface StringValue {
+ 'stringValue': string
+}
+
+interface BooleanValue {
+ 'booleanValue': string
+}
+
+interface ArrayValue {
+ values: FieldValue[]
+}
+
+interface IntegerValue {
+ 'integerValue': number
+}
+
+interface DoubleValue {
+ 'doubleValue': number
+}
+
+interface MapValue {
+ fields: {
+ [fieldName: string]: FieldValue
+ }
+}
+
+interface NullValue {
+ 'nullValue': null
+}
+
+interface ReferenceValue {
+ 'referenceValue': string
+}
+
+interface TimestampValue {
+ 'timestampValue': number
+} |
|
737d1170242ebb6ea0478dd0459d2d6d31d5385b | pages/open-source.tsx | pages/open-source.tsx | import { NextPage } from "next"
import Head from "next/head"
import Page from "../layouts/main"
const OpenSourcePage: NextPage = () => {
return (
<Page>
<Head>
<title>Open Source :: Joseph Duffy, iOS Developer</title>
<meta name="description" content="Open source projects created or contributed to by Joseph Duffy" />
</Head>
<h1>Open Source</h1>
<p>
I am a big believer in open source software, which I contribute to through GitHub. Below are a few of the projects I have created or heavily contributed to. To view all of my contributions to open source projects view entries under the <a href="/tags/open-source" rel="tag">open-source tag</a>.
</p>
</Page>
)
}
export default OpenSourcePage
| Add start of Open Source page | Add start of Open Source page
| TypeScript | mit | JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk | ---
+++
@@ -0,0 +1,20 @@
+import { NextPage } from "next"
+import Head from "next/head"
+import Page from "../layouts/main"
+
+const OpenSourcePage: NextPage = () => {
+ return (
+ <Page>
+ <Head>
+ <title>Open Source :: Joseph Duffy, iOS Developer</title>
+ <meta name="description" content="Open source projects created or contributed to by Joseph Duffy" />
+ </Head>
+ <h1>Open Source</h1>
+ <p>
+ I am a big believer in open source software, which I contribute to through GitHub. Below are a few of the projects I have created or heavily contributed to. To view all of my contributions to open source projects view entries under the <a href="/tags/open-source" rel="tag">open-source tag</a>.
+ </p>
+ </Page>
+ )
+}
+
+export default OpenSourcePage |
|
47d86ae32c670c29635f164ac47d0ee1122e8535 | tests/unit/adapters/active-model-adapter-errors-test.ts | tests/unit/adapters/active-model-adapter-errors-test.ts | import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import Pretender from 'pretender';
import { TestContext } from 'ember-test-helpers';
let pretender: Pretender;
import DS from 'ember-data';
import attr from 'ember-data/attr';
import ActiveModelAdapter from 'active-model-adapter';
class Book extends DS.Model {
@attr('string') name!: string;
@attr('string') genre!: string;
}
class ApplicationAdapter extends ActiveModelAdapter {}
module('Unit | Adapter | active model adapter errors test', function(hooks) {
setupTest(hooks);
hooks.beforeEach(function(this: TestContext) {
pretender = new Pretender(function() {});
this.owner.register('adapter:application', ApplicationAdapter);
this.owner.register('model:book', Book);
});
hooks.afterEach(function() {
pretender.shutdown();
})
test('errors can be iterated once intercepted by the adapter', async function(this: TestContext, assert) {
assert.expect(2);
const store = this.owner.lookup('service:store');
store.push({
data: {
type: 'book',
id: '1',
name: 'Bossypants',
genre: 'Memoir'
}
});
const post = store.peekRecord('book', 1);
pretender.put('/books/1', function(_req) {
const headers = {};
const httpStatus = 422;
const payload = {
errors: {
name: ['rejected'],
genre: ['rejected']
}
};
return [httpStatus, headers, JSON.stringify(payload)];
});
post.setProperties({
name: 'Yes, Please',
memoir: 'Comedy'
});
try {
await post.save();
} catch (e) {
assert.equal(
post.get('errors.name')[0].message,
'rejected',
'model.errors.attribute_name works'
);
assert.deepEqual(
post.get('errors.messages'),
['rejected', 'rejected'],
'errors.messages works'
);
}
});
});
| Add test for adapter errors | Add test for adapter errors
| TypeScript | mit | ember-data/active-model-adapter,ember-data/active-model-adapter,ember-data/active-model-adapter | ---
+++
@@ -0,0 +1,80 @@
+import { module, test } from 'qunit';
+import { setupTest } from 'ember-qunit';
+import Pretender from 'pretender';
+import { TestContext } from 'ember-test-helpers';
+
+let pretender: Pretender;
+
+import DS from 'ember-data';
+import attr from 'ember-data/attr';
+import ActiveModelAdapter from 'active-model-adapter';
+
+class Book extends DS.Model {
+ @attr('string') name!: string;
+ @attr('string') genre!: string;
+}
+
+class ApplicationAdapter extends ActiveModelAdapter {}
+
+module('Unit | Adapter | active model adapter errors test', function(hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function(this: TestContext) {
+ pretender = new Pretender(function() {});
+ this.owner.register('adapter:application', ApplicationAdapter);
+ this.owner.register('model:book', Book);
+ });
+
+ hooks.afterEach(function() {
+ pretender.shutdown();
+ })
+
+ test('errors can be iterated once intercepted by the adapter', async function(this: TestContext, assert) {
+ assert.expect(2);
+
+ const store = this.owner.lookup('service:store');
+
+ store.push({
+ data: {
+ type: 'book',
+ id: '1',
+ name: 'Bossypants',
+ genre: 'Memoir'
+ }
+ });
+
+ const post = store.peekRecord('book', 1);
+
+ pretender.put('/books/1', function(_req) {
+ const headers = {};
+ const httpStatus = 422;
+ const payload = {
+ errors: {
+ name: ['rejected'],
+ genre: ['rejected']
+ }
+ };
+ return [httpStatus, headers, JSON.stringify(payload)];
+ });
+
+ post.setProperties({
+ name: 'Yes, Please',
+ memoir: 'Comedy'
+ });
+
+ try {
+ await post.save();
+ } catch (e) {
+ assert.equal(
+ post.get('errors.name')[0].message,
+ 'rejected',
+ 'model.errors.attribute_name works'
+ );
+ assert.deepEqual(
+ post.get('errors.messages'),
+ ['rejected', 'rejected'],
+ 'errors.messages works'
+ );
+ }
+ });
+}); |
|
1fae391e07620a33381f14c61ebc4357deecf150 | src/core/dummies.ts | src/core/dummies.ts | import { Dummy, TextDummy, TypesDummy } from '../../test/helpers';
import { VcsAuthenticationInfo, VcsAuthenticationTypes } from './vcs';
export class VcsAuthenticationInfoDummy extends Dummy<VcsAuthenticationInfo> {
private type = new TypesDummy<VcsAuthenticationTypes>([
VcsAuthenticationTypes.BASIC,
VcsAuthenticationTypes.OAUTH2_TOKEN,
]);
private authorizationHeader = new TextDummy('AuthorizationHeader');
private providerName = new TextDummy('provider');
private userName = new TextDummy('username');
private password = new TextDummy('password');
private token = new TextDummy('token');
create(type?: VcsAuthenticationTypes): VcsAuthenticationInfo {
return {
type: type ? type : this.type.create(),
authorizationHeader: this.authorizationHeader.create(),
providerName: this.providerName.create(),
username: this.userName.create(),
password: this.password.create(),
token: this.token.create(),
};
}
}
| Add vcs authentication info dummy | Add vcs authentication info dummy
| TypeScript | mit | seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary | ---
+++
@@ -0,0 +1,26 @@
+import { Dummy, TextDummy, TypesDummy } from '../../test/helpers';
+import { VcsAuthenticationInfo, VcsAuthenticationTypes } from './vcs';
+
+
+export class VcsAuthenticationInfoDummy extends Dummy<VcsAuthenticationInfo> {
+ private type = new TypesDummy<VcsAuthenticationTypes>([
+ VcsAuthenticationTypes.BASIC,
+ VcsAuthenticationTypes.OAUTH2_TOKEN,
+ ]);
+ private authorizationHeader = new TextDummy('AuthorizationHeader');
+ private providerName = new TextDummy('provider');
+ private userName = new TextDummy('username');
+ private password = new TextDummy('password');
+ private token = new TextDummy('token');
+
+ create(type?: VcsAuthenticationTypes): VcsAuthenticationInfo {
+ return {
+ type: type ? type : this.type.create(),
+ authorizationHeader: this.authorizationHeader.create(),
+ providerName: this.providerName.create(),
+ username: this.userName.create(),
+ password: this.password.create(),
+ token: this.token.create(),
+ };
+ }
+} |
|
074e6763fa334c50a5d3064fc26c954700748381 | src/__tests__/github_issues/271-test.ts | src/__tests__/github_issues/271-test.ts | import { SchemaComposer, graphql } from 'graphql-compose';
import { composeMongoose } from '../../index';
import { mongoose } from '../../__mocks__/mongooseCommon';
import { Document } from 'mongoose';
import { convertSchemaToGraphQL } from '../../../src/fieldsConverter';
const schemaComposer = new SchemaComposer<{ req: any }>();
const AuthorSchema = new mongoose.Schema(
{
name: { type: String },
age: { type: Number },
isAlive: { type: Boolean },
},
{ _id: false }
);
const BookSchema = new mongoose.Schema({
_id: { type: Number },
title: { type: String, required: true },
pageCount: { type: Number },
author: { type: AuthorSchema },
});
interface IAuthor {
name: string;
age: number;
isAlive: boolean;
}
interface IBook extends Document {
_id: number;
title: string;
author: IAuthor;
pageCount?: number;
}
const BookModel = mongoose.model<IBook>('Book', BookSchema);
convertSchemaToGraphQL(AuthorSchema, 'Author', schemaComposer);
const BookTC = composeMongoose(BookModel, { schemaComposer });
schemaComposer.Query.addFields({
bookById: BookTC.mongooseResolvers.findById(),
bookFindOne: BookTC.mongooseResolvers.findOne(),
booksMany: BookTC.mongooseResolvers.findMany(),
});
const schema = schemaComposer.buildSchema();
beforeAll(async () => {
mongoose.set('debug', true);
await BookModel.base.createConnection();
await BookModel.create({
_id: 1,
title: 'Atlas Shrugged',
author: { age: new Date().getFullYear() - 1905, isAlive: false, name: 'Ayn Rand' },
pageCount: 1168,
});
});
afterAll(() => {
mongoose.set('debug', false);
BookModel.base.disconnect();
});
describe('nested projection - issue #271', () => {
it('Happy Path', async () => {
const result = await graphql.graphql({
schema,
source: `query {
booksMany {
title
pageCount
author { name }
}
}`,
contextValue: {},
});
console.log(JSON.stringify(result));
// expect(BookModel.find).toHaveBeenCalledTimes(1);
// expect(BookModel.find).toHaveBeenCalledWith(
// {},
// { limit: 1000, projection: { title: true, pageCount: true, 'author.name': true } }
// );
});
});
| Add test for nested projection | Add test for nested projection
Not uet failing but I have set mongoose debug to true which will show the find query being run during the test.
This shows that the entire Author subdocument is being fetching.
| TypeScript | mit | nodkz/graphql-compose-mongoose | ---
+++
@@ -0,0 +1,86 @@
+import { SchemaComposer, graphql } from 'graphql-compose';
+import { composeMongoose } from '../../index';
+import { mongoose } from '../../__mocks__/mongooseCommon';
+import { Document } from 'mongoose';
+import { convertSchemaToGraphQL } from '../../../src/fieldsConverter';
+const schemaComposer = new SchemaComposer<{ req: any }>();
+
+const AuthorSchema = new mongoose.Schema(
+ {
+ name: { type: String },
+ age: { type: Number },
+ isAlive: { type: Boolean },
+ },
+ { _id: false }
+);
+
+const BookSchema = new mongoose.Schema({
+ _id: { type: Number },
+ title: { type: String, required: true },
+ pageCount: { type: Number },
+ author: { type: AuthorSchema },
+});
+
+interface IAuthor {
+ name: string;
+ age: number;
+ isAlive: boolean;
+}
+
+interface IBook extends Document {
+ _id: number;
+ title: string;
+ author: IAuthor;
+ pageCount?: number;
+}
+
+const BookModel = mongoose.model<IBook>('Book', BookSchema);
+
+convertSchemaToGraphQL(AuthorSchema, 'Author', schemaComposer);
+
+const BookTC = composeMongoose(BookModel, { schemaComposer });
+
+schemaComposer.Query.addFields({
+ bookById: BookTC.mongooseResolvers.findById(),
+ bookFindOne: BookTC.mongooseResolvers.findOne(),
+ booksMany: BookTC.mongooseResolvers.findMany(),
+});
+
+const schema = schemaComposer.buildSchema();
+
+beforeAll(async () => {
+ mongoose.set('debug', true);
+ await BookModel.base.createConnection();
+ await BookModel.create({
+ _id: 1,
+ title: 'Atlas Shrugged',
+ author: { age: new Date().getFullYear() - 1905, isAlive: false, name: 'Ayn Rand' },
+ pageCount: 1168,
+ });
+});
+afterAll(() => {
+ mongoose.set('debug', false);
+ BookModel.base.disconnect();
+});
+
+describe('nested projection - issue #271', () => {
+ it('Happy Path', async () => {
+ const result = await graphql.graphql({
+ schema,
+ source: `query {
+ booksMany {
+ title
+ pageCount
+ author { name }
+ }
+ }`,
+ contextValue: {},
+ });
+ console.log(JSON.stringify(result));
+ // expect(BookModel.find).toHaveBeenCalledTimes(1);
+ // expect(BookModel.find).toHaveBeenCalledWith(
+ // {},
+ // { limit: 1000, projection: { title: true, pageCount: true, 'author.name': true } }
+ // );
+ });
+}); |
|
e6f786759ad8b51e2f574437e17aede6989876ab | src/tests/integration/HttpTests.ts | src/tests/integration/HttpTests.ts | /*
Copyright 2019 The Matrix.org Foundation C.I.C.
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 { SlackHookHandler } from "../../SlackHookHandler";
import { FakeMain } from "../utils/fakeMain";
import { Main } from "../../Main";
import { expect } from "chai";
import * as request from "request-promise-native";
import { Response } from "request";
// tslint:disable: no-unused-expression no-any
function constructHarness() {
const main = new FakeMain();
const hooks = new SlackHookHandler(main as unknown as Main);
return { hooks, main };
}
let harness: { hooks: SlackHookHandler, main: FakeMain };
describe("HttpTests", () => {
beforeEach(() => {
harness = constructHarness();
});
it("will respond 201 to a health check", async () => {
await harness.hooks.startAndListen(57000);
const res = await request.get("http://localhost:57000/health", {
resolveWithFullResponse: true,
}) as Response;
expect(res.statusCode).to.equal(201);
expect(res.body).to.be.empty;
});
afterEach(async () => {
await harness.hooks.close();
});
});
| Add tests to check health check endpoint | Add tests to check health check endpoint
| TypeScript | apache-2.0 | matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack | ---
+++
@@ -0,0 +1,51 @@
+/*
+Copyright 2019 The Matrix.org Foundation C.I.C.
+
+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 { SlackHookHandler } from "../../SlackHookHandler";
+import { FakeMain } from "../utils/fakeMain";
+import { Main } from "../../Main";
+import { expect } from "chai";
+import * as request from "request-promise-native";
+import { Response } from "request";
+
+// tslint:disable: no-unused-expression no-any
+
+function constructHarness() {
+ const main = new FakeMain();
+ const hooks = new SlackHookHandler(main as unknown as Main);
+ return { hooks, main };
+}
+
+let harness: { hooks: SlackHookHandler, main: FakeMain };
+
+describe("HttpTests", () => {
+
+ beforeEach(() => {
+ harness = constructHarness();
+ });
+
+ it("will respond 201 to a health check", async () => {
+ await harness.hooks.startAndListen(57000);
+ const res = await request.get("http://localhost:57000/health", {
+ resolveWithFullResponse: true,
+ }) as Response;
+ expect(res.statusCode).to.equal(201);
+ expect(res.body).to.be.empty;
+ });
+
+ afterEach(async () => {
+ await harness.hooks.close();
+ });
+}); |
|
d0d1ee918ff4e5ba72c6b350741f57fa723fdbea | tests/cases/fourslash/completionListForUnicodeEscapeName.ts | tests/cases/fourslash/completionListForUnicodeEscapeName.ts | /// <reference path='fourslash.ts' />
////function \u0042 () { /*0*/ }
////export default function \u0043 () { /*1*/ }
////class \u0041 { /*2*/ }
/////*3*/
goTo.marker("0");
verify.not.completionListContains("B");
verify.not.completionListContains("\u0042");
goTo.marker("2");
verify.not.completionListContains("C");
verify.not.completionListContains("\u0043");
goTo.marker("2");
verify.not.completionListContains("A");
verify.not.completionListContains("\u0041");
goTo.marker("3");
verify.not.completionListContains("B");
verify.not.completionListContains("\u0042");
verify.not.completionListContains("A");
verify.not.completionListContains("\u0041");
verify.not.completionListContains("C");
verify.not.completionListContains("\u0043");
| Add test for using unicode escape as function name | Add test for using unicode escape as function name
| TypeScript | apache-2.0 | chocolatechipui/TypeScript,RReverser/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,TukekeSoft/TypeScript,shanexu/TypeScript,HereSinceres/TypeScript,jdavidberger/TypeScript,pcan/TypeScript,DLehenbauer/TypeScript,moander/TypeScript,zhengbli/TypeScript,Eyas/TypeScript,enginekit/TypeScript,nojvek/TypeScript,impinball/TypeScript,DanielRosenwasser/TypeScript,suto/TypeScript,sassson/TypeScript,kumikumi/TypeScript,fearthecowboy/TypeScript,jdavidberger/TypeScript,hitesh97/TypeScript,rodrigues-daniel/TypeScript,jwbay/TypeScript,mihailik/TypeScript,enginekit/TypeScript,Eyas/TypeScript,enginekit/TypeScript,moander/TypeScript,fabioparra/TypeScript,plantain-00/TypeScript,tempbottle/TypeScript,keir-rex/TypeScript,chuckjaz/TypeScript,billti/TypeScript,webhost/TypeScript,sassson/TypeScript,MartyIX/TypeScript,DLehenbauer/TypeScript,sassson/TypeScript,jwbay/TypeScript,rodrigues-daniel/TypeScript,zmaruo/TypeScript,moander/TypeScript,synaptek/TypeScript,erikmcc/TypeScript,yortus/TypeScript,abbasmhd/TypeScript,hoanhtien/TypeScript,kitsonk/TypeScript,evgrud/TypeScript,kingland/TypeScript,fabioparra/TypeScript,mmoskal/TypeScript,synaptek/TypeScript,suto/TypeScript,RyanCavanaugh/TypeScript,AbubakerB/TypeScript,ZLJASON/TypeScript,tempbottle/TypeScript,jeremyepling/TypeScript,gonifade/TypeScript,basarat/TypeScript,Viromo/TypeScript,jeremyepling/TypeScript,mszczepaniak/TypeScript,MartyIX/TypeScript,shiftkey/TypeScript,shovon/TypeScript,mcanthony/TypeScript,OlegDokuka/TypeScript,yortus/TypeScript,mmoskal/TypeScript,DLehenbauer/TypeScript,jteplitz602/TypeScript,fabioparra/TypeScript,MartyIX/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,jbondc/TypeScript,RReverser/TypeScript,billti/TypeScript,rgbkrk/TypeScript,RyanCavanaugh/TypeScript,yazeng/TypeScript,webhost/TypeScript,kimamula/TypeScript,jwbay/TypeScript,nycdotnet/TypeScript,ZLJASON/TypeScript,thr0w/Thr0wScript,msynk/TypeScript,kingland/TypeScript,jteplitz602/TypeScript,mihailik/TypeScript,basarat/TypeScript,fearthecowboy/TypeScript,mihailik/TypeScript,jbondc/TypeScript,DanielRosenwasser/TypeScript,samuelhorwitz/typescript,plantain-00/TypeScript,progre/TypeScript,SmallAiTT/TypeScript,kitsonk/TypeScript,pcan/TypeScript,jamesrmccallum/TypeScript,mmoskal/TypeScript,nojvek/TypeScript,synaptek/TypeScript,jbondc/TypeScript,chocolatechipui/TypeScript,nagyistoce/TypeScript,kitsonk/TypeScript,yazeng/TypeScript,plantain-00/TypeScript,DanielRosenwasser/TypeScript,rgbkrk/TypeScript,RReverser/TypeScript,mszczepaniak/TypeScript,shovon/TypeScript,jamesrmccallum/TypeScript,SimoneGianni/TypeScript,JohnZ622/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,bpowers/TypeScript,HereSinceres/TypeScript,mihailik/TypeScript,alexeagle/TypeScript,DanielRosenwasser/TypeScript,MartyIX/TypeScript,weswigham/TypeScript,progre/TypeScript,Viromo/TypeScript,matthewjh/TypeScript,basarat/TypeScript,RyanCavanaugh/TypeScript,ziacik/TypeScript,microsoft/TypeScript,shiftkey/TypeScript,samuelhorwitz/typescript,chuckjaz/TypeScript,hitesh97/TypeScript,msynk/TypeScript,ziacik/TypeScript,chuckjaz/TypeScript,plantain-00/TypeScript,mcanthony/TypeScript,Mqgh2013/TypeScript,zhengbli/TypeScript,HereSinceres/TypeScript,hoanhtien/TypeScript,SaschaNaz/TypeScript,rgbkrk/TypeScript,webhost/TypeScript,samuelhorwitz/typescript,Microsoft/TypeScript,nagyistoce/TypeScript,minestarks/TypeScript,mcanthony/TypeScript,yazeng/TypeScript,yortus/TypeScript,donaldpipowitch/TypeScript,shanexu/TypeScript,Mqgh2013/TypeScript,kimamula/TypeScript,rodrigues-daniel/TypeScript,alexeagle/TypeScript,bpowers/TypeScript,JohnZ622/TypeScript,shanexu/TypeScript,kimamula/TypeScript,keir-rex/TypeScript,TukekeSoft/TypeScript,OlegDokuka/TypeScript,SaschaNaz/TypeScript,samuelhorwitz/typescript,jdavidberger/TypeScript,Eyas/TypeScript,OlegDokuka/TypeScript,Viromo/TypeScript,matthewjh/TypeScript,gonifade/TypeScript,Viromo/TypeScript,minestarks/TypeScript,JohnZ622/TypeScript,nycdotnet/TypeScript,chuckjaz/TypeScript,minestarks/TypeScript,germ13/TypeScript,blakeembrey/TypeScript,billti/TypeScript,TukekeSoft/TypeScript,nagyistoce/TypeScript,nycdotnet/TypeScript,yortus/TypeScript,shanexu/TypeScript,jamesrmccallum/TypeScript,AbubakerB/TypeScript,vilic/TypeScript,kimamula/TypeScript,JohnZ622/TypeScript,ziacik/TypeScript,fearthecowboy/TypeScript,thr0w/Thr0wScript,ionux/TypeScript,SmallAiTT/TypeScript,AbubakerB/TypeScript,blakeembrey/TypeScript,jeremyepling/TypeScript,donaldpipowitch/TypeScript,blakeembrey/TypeScript,microsoft/TypeScript,microsoft/TypeScript,mcanthony/TypeScript,donaldpipowitch/TypeScript,Eyas/TypeScript,impinball/TypeScript,germ13/TypeScript,ionux/TypeScript,alexeagle/TypeScript,hoanhtien/TypeScript,mszczepaniak/TypeScript,thr0w/Thr0wScript,erikmcc/TypeScript,matthewjh/TypeScript,zhengbli/TypeScript,erikmcc/TypeScript,Microsoft/TypeScript,DLehenbauer/TypeScript,bpowers/TypeScript,ziacik/TypeScript,mmoskal/TypeScript,keir-rex/TypeScript,shovon/TypeScript,evgrud/TypeScript,weswigham/TypeScript,germ13/TypeScript,donaldpipowitch/TypeScript,kingland/TypeScript,fabioparra/TypeScript,zmaruo/TypeScript,ionux/TypeScript,gonifade/TypeScript,impinball/TypeScript,erikmcc/TypeScript,vilic/TypeScript,hitesh97/TypeScript,synaptek/TypeScript,progre/TypeScript,suto/TypeScript,jteplitz602/TypeScript,pcan/TypeScript,thr0w/Thr0wScript,vilic/TypeScript,shiftkey/TypeScript,SimoneGianni/TypeScript,evgrud/TypeScript,kumikumi/TypeScript,rodrigues-daniel/TypeScript,ionux/TypeScript,jwbay/TypeScript,chocolatechipui/TypeScript,moander/TypeScript,abbasmhd/TypeScript,AbubakerB/TypeScript,tempbottle/TypeScript,Mqgh2013/TypeScript,Microsoft/TypeScript,blakeembrey/TypeScript,evgrud/TypeScript,SmallAiTT/TypeScript,ZLJASON/TypeScript,msynk/TypeScript,zmaruo/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,kumikumi/TypeScript,SimoneGianni/TypeScript,abbasmhd/TypeScript,nycdotnet/TypeScript,basarat/TypeScript | ---
+++
@@ -0,0 +1,27 @@
+/// <reference path='fourslash.ts' />
+
+////function \u0042 () { /*0*/ }
+////export default function \u0043 () { /*1*/ }
+////class \u0041 { /*2*/ }
+/////*3*/
+
+goTo.marker("0");
+verify.not.completionListContains("B");
+verify.not.completionListContains("\u0042");
+
+goTo.marker("2");
+verify.not.completionListContains("C");
+verify.not.completionListContains("\u0043");
+
+goTo.marker("2");
+verify.not.completionListContains("A");
+verify.not.completionListContains("\u0041");
+
+goTo.marker("3");
+verify.not.completionListContains("B");
+verify.not.completionListContains("\u0042");
+verify.not.completionListContains("A");
+verify.not.completionListContains("\u0041");
+verify.not.completionListContains("C");
+verify.not.completionListContains("\u0043");
+ |
|
c7699bd1e179f68f0210ddbe33de295544f6126b | ee_tests/src/functional/screenshot.spec.ts | ee_tests/src/functional/screenshot.spec.ts | import { browser } from 'protractor';
import * as support from '../specs/support';
import { LandingPage } from '../specs/page_objects';
describe('Landing Page', () => {
beforeEach( async () => {
await support.desktopTestSetup();
let landingPage = new LandingPage();
await landingPage.open();
});
fit('writes the screenshot of landing page', async () => {
await expect(await browser.getTitle()).toEqual('OpenShift.io');
await support.writeScreenshot('page.png');
});
});
| Add functional test for writeScreenshot | Add functional test for writeScreenshot
| TypeScript | apache-2.0 | ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test | ---
+++
@@ -0,0 +1,19 @@
+import { browser } from 'protractor';
+import * as support from '../specs/support';
+import { LandingPage } from '../specs/page_objects';
+
+describe('Landing Page', () => {
+
+ beforeEach( async () => {
+ await support.desktopTestSetup();
+
+ let landingPage = new LandingPage();
+ await landingPage.open();
+ });
+
+ fit('writes the screenshot of landing page', async () => {
+ await expect(await browser.getTitle()).toEqual('OpenShift.io');
+ await support.writeScreenshot('page.png');
+ });
+
+}); |
|
38f78b8978d1904ef96d09621990879c0f420989 | source/push3js/pipeline.ts | source/push3js/pipeline.ts | import { EventDispatcher } from "../util/eventdispatcher";
export abstract class Pipeline extends EventDispatcher {
constructor() {
super();
}
abstract pipe(event: any): void;
destroy(): void {
this.removeAllListeners();
}
} | Define bas class of threejs pushers | Define bas class of threejs pushers
| TypeScript | apache-2.0 | Tomella/explorer-3d,Tomella/explorer-3d,Tomella/explorer-3d | ---
+++
@@ -0,0 +1,11 @@
+import { EventDispatcher } from "../util/eventdispatcher";
+
+export abstract class Pipeline extends EventDispatcher {
+ constructor() {
+ super();
+ }
+ abstract pipe(event: any): void;
+ destroy(): void {
+ this.removeAllListeners();
+ }
+} |
|
11553eba932b2718208d591b033977f0ed546d7e | app/src/redux/index.ts | app/src/redux/index.ts | import { combineReducers } from "redux";
import { all } from "redux-saga/effects";
import * as signIn from "./sign-in";
export const reducer = combineReducers({ signIn: signIn.reducer });
export function* saga() {
yield all([...signIn.sagas]);
}
| Create root saga and reducer | Create root saga and reducer
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -0,0 +1,10 @@
+import { combineReducers } from "redux";
+import { all } from "redux-saga/effects";
+
+import * as signIn from "./sign-in";
+
+export const reducer = combineReducers({ signIn: signIn.reducer });
+
+export function* saga() {
+ yield all([...signIn.sagas]);
+} |
|
2060918c050b7c5af83cac14e02c254f2cbab61a | src/Test/Ast/HeadingLevels2AndUp.ts | src/Test/Ast/HeadingLevels2AndUp.ts | /// <reference path="../../../typings/mocha/mocha.d.ts" />
/// <reference path="../../../typings/chai/chai.d.ts" />
import { expect } from 'chai'
import * as Up from '../../index'
import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
import { LinkNode } from '../../SyntaxNodes/LinkNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
import { StressNode } from '../../SyntaxNodes/StressNode'
import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode'
import { InlineAsideNode } from '../../SyntaxNodes/InlineAsideNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
describe("The first heading with an underline comprised of different characters than the top-level heading's underline", () => {
it('produces a level-2 heading node', () => {
const text =
`
Hello, world!
=============
Goodbye, world!
=-=-=-=-=-=-=-=`
expect(Up.ast(text)).to.be.eql(
new DocumentNode([
new HeadingNode([new PlainTextNode('Hello, world!')], 1),
new HeadingNode([new PlainTextNode('Goodbye, world!')], 2),
]))
})
}) | Add failing level-2 heading node test | Add failing level-2 heading node test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,39 @@
+/// <reference path="../../../typings/mocha/mocha.d.ts" />
+/// <reference path="../../../typings/chai/chai.d.ts" />
+
+import { expect } from 'chai'
+import * as Up from '../../index'
+import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
+import { LinkNode } from '../../SyntaxNodes/LinkNode'
+import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
+import { StressNode } from '../../SyntaxNodes/StressNode'
+import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
+import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
+import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
+import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode'
+import { InlineAsideNode } from '../../SyntaxNodes/InlineAsideNode'
+import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
+import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
+import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
+
+
+describe("The first heading with an underline comprised of different characters than the top-level heading's underline", () => {
+
+ it('produces a level-2 heading node', () => {
+ const text =
+ `
+Hello, world!
+=============
+
+Goodbye, world!
+=-=-=-=-=-=-=-=`
+
+ expect(Up.ast(text)).to.be.eql(
+ new DocumentNode([
+ new HeadingNode([new PlainTextNode('Hello, world!')], 1),
+ new HeadingNode([new PlainTextNode('Goodbye, world!')], 2),
+ ]))
+ })
+}) |
|
5c83025a6fbc185e4228e9a6d16b3155b7609f28 | src/modules/users/repository.ts | src/modules/users/repository.ts | import { Component } from '@nestjs/common'
import * as fs from 'fs'
import { User } from './entity'
import * as path from 'path'
@Component()
export class UsersRepository<Object extends User> {
root: string
constructor(root: string) {
this.root = root
if (!fs.existsSync(root)) fs.mkdirSync(root)
}
protected writeData(user: Object) {
fs.writeFileSync(this.getPath(user), JSON.stringify(user))
}
protected readData(name: string): Object {
return JSON.parse(fs.readFileSync(path.join(this.root, name)).toString('utf-8'))
}
getPath(user: Object): string {
return path.join(this.root, user.name)
}
create(user: Object): boolean {
if (fs.existsSync(this.getPath(user))) return false
this.writeData(user)
return true
}
delete(user: Object): void {
if (fs.existsSync(this.getPath(user))) fs.unlinkSync(this.getPath(user))
}
update(name: string, data: Partial<Object>) {
const user = <Object>{...<object>this.readData(name), ...<object>data}
this.writeData(user)
}
findOne(name: string): User {
return this.readData(name)
}
find(): User[] {
return fs.readdirSync(this.root).map(x => this.readData(x))
}
}
| Add base FS respository class | Add base FS respository class
| TypeScript | apache-2.0 | m1cr0man/m1cr0blog,m1cr0man/m1cr0blog,m1cr0man/m1cr0blog | ---
+++
@@ -0,0 +1,53 @@
+import { Component } from '@nestjs/common'
+import * as fs from 'fs'
+import { User } from './entity'
+import * as path from 'path'
+
+@Component()
+export class UsersRepository<Object extends User> {
+ root: string
+
+ constructor(root: string) {
+ this.root = root
+
+ if (!fs.existsSync(root)) fs.mkdirSync(root)
+ }
+
+ protected writeData(user: Object) {
+ fs.writeFileSync(this.getPath(user), JSON.stringify(user))
+ }
+
+ protected readData(name: string): Object {
+ return JSON.parse(fs.readFileSync(path.join(this.root, name)).toString('utf-8'))
+ }
+
+ getPath(user: Object): string {
+ return path.join(this.root, user.name)
+ }
+
+ create(user: Object): boolean {
+ if (fs.existsSync(this.getPath(user))) return false
+
+ this.writeData(user)
+
+ return true
+ }
+
+ delete(user: Object): void {
+ if (fs.existsSync(this.getPath(user))) fs.unlinkSync(this.getPath(user))
+ }
+
+ update(name: string, data: Partial<Object>) {
+ const user = <Object>{...<object>this.readData(name), ...<object>data}
+
+ this.writeData(user)
+ }
+
+ findOne(name: string): User {
+ return this.readData(name)
+ }
+
+ find(): User[] {
+ return fs.readdirSync(this.root).map(x => this.readData(x))
+ }
+} |
|
f11504922f238b9a52aff7f1a079482e7966b7c1 | types/main.d.ts | types/main.d.ts | export class TestCase {
expect(returnValue): this
describe(message: string): this
should(message: string): this
assert(message: string, assertFunction: (actualReturnValue: any) => void): this
}
export function test(testFn: Function, definerFn: Function): void
export function given(...args: any[]): TestCase
| export class TestCase {
expect(returnValue: any): this
describe(message: string): this
should(message: string): this
assert(message: string, assertFunction: (actualReturnValue: any) => void): this
}
export function test(testFn: Function, definerFn: Function): void
export function given(...args: any[]): TestCase
| Work with `noImplicitAny` ts compiler option | Work with `noImplicitAny` ts compiler option
If the TypeScript compiler is set to `strict` or has `noImplicitAny` this will cause a project not to compile | TypeScript | mit | mikec/sazerac | ---
+++
@@ -1,5 +1,5 @@
export class TestCase {
- expect(returnValue): this
+ expect(returnValue: any): this
describe(message: string): this
should(message: string): this
assert(message: string, assertFunction: (actualReturnValue: any) => void): this |
9de26873e9dc59035b3e10c1105af533573812cc | test/vuex-mockstorage-cyclic.spec.ts | test/vuex-mockstorage-cyclic.spec.ts | /**
* Created by rossng on 02/04/2018.
*/
import { Store } from 'vuex'
import Vuex = require('vuex')
import Vue = require('vue')
import VuexPersistence, { MockStorage } from '../dist'
import { assert, expect, should } from 'chai'
Vue.use(Vuex)
const mockStorage = new MockStorage()
const vuexPersist = new VuexPersistence<any, any>({
storage: mockStorage
})
const store = new Store<any>({
state: {
cyclicObject: null
},
mutations: {
storeCyclicObject(state, payload) {
state.cyclicObject = payload
}
},
plugins: [vuexPersist.plugin]
})
const getSavedStore = () => JSON.parse(mockStorage.getItem('vuex'))
describe('Storage: MockStorage, Test: cyclic object', () => {
it('should persist cyclic object', () => {
let cyclicObject: any = { foo: 10 }
cyclicObject.bar = cyclicObject
store.commit('storeCyclicObject', cyclicObject)
expect(getSavedStore().cyclicObject.foo).to.equal(10)
})
})
| Add (failing) test for cyclic object persistence | Add (failing) test for cyclic object persistence
| TypeScript | mit | championswimmer/vuex-persist,championswimmer/vuex-persist | ---
+++
@@ -0,0 +1,36 @@
+/**
+ * Created by rossng on 02/04/2018.
+ */
+import { Store } from 'vuex'
+import Vuex = require('vuex')
+import Vue = require('vue')
+import VuexPersistence, { MockStorage } from '../dist'
+import { assert, expect, should } from 'chai'
+
+Vue.use(Vuex)
+const mockStorage = new MockStorage()
+const vuexPersist = new VuexPersistence<any, any>({
+ storage: mockStorage
+})
+
+const store = new Store<any>({
+ state: {
+ cyclicObject: null
+ },
+ mutations: {
+ storeCyclicObject(state, payload) {
+ state.cyclicObject = payload
+ }
+ },
+ plugins: [vuexPersist.plugin]
+})
+const getSavedStore = () => JSON.parse(mockStorage.getItem('vuex'))
+
+describe('Storage: MockStorage, Test: cyclic object', () => {
+ it('should persist cyclic object', () => {
+ let cyclicObject: any = { foo: 10 }
+ cyclicObject.bar = cyclicObject
+ store.commit('storeCyclicObject', cyclicObject)
+ expect(getSavedStore().cyclicObject.foo).to.equal(10)
+ })
+}) |
|
211be0ae69f217db437ca13185ad76586aab5054 | tests/cases/fourslash/completionListInImportClause06.ts | tests/cases/fourslash/completionListInImportClause06.ts | /// <reference path='fourslash.ts' />
// @typeRoots: T1,T2
// @Filename: app.ts
////import * as A from "[|/*1*/|]";
// @Filename: T1/a__b/index.d.ts
////export declare let x: number;
// @Filename: T2/a__b/index.d.ts
////export declare let x: number;
// Confirm that entries are de-dup'd.
verify.completionsAt("1", [
{ name: "@a/b", replacementSpan: test.ranges()[0] },
]);
| Add regression test for de-dup'ing. | Add regression test for de-dup'ing.
| TypeScript | apache-2.0 | basarat/TypeScript,nojvek/TypeScript,basarat/TypeScript,SaschaNaz/TypeScript,Microsoft/TypeScript,alexeagle/TypeScript,alexeagle/TypeScript,RyanCavanaugh/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,microsoft/TypeScript,kpreisser/TypeScript,SaschaNaz/TypeScript,Microsoft/TypeScript,kitsonk/TypeScript,kpreisser/TypeScript,basarat/TypeScript,weswigham/TypeScript,nojvek/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,nojvek/TypeScript,weswigham/TypeScript,microsoft/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,weswigham/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,alexeagle/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,basarat/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript | ---
+++
@@ -0,0 +1,17 @@
+/// <reference path='fourslash.ts' />
+
+// @typeRoots: T1,T2
+
+// @Filename: app.ts
+////import * as A from "[|/*1*/|]";
+
+// @Filename: T1/a__b/index.d.ts
+////export declare let x: number;
+
+// @Filename: T2/a__b/index.d.ts
+////export declare let x: number;
+
+// Confirm that entries are de-dup'd.
+verify.completionsAt("1", [
+ { name: "@a/b", replacementSpan: test.ranges()[0] },
+]); |
|
3f05fcf6868a9ad08c6bf927cbf2fd5cba1dadc4 | packages/hub/db/migrations/20220301101637933_create-card-space-profiles-for-existing-merchants.ts | packages/hub/db/migrations/20220301101637933_create-card-space-profiles-for-existing-merchants.ts | import { MigrationBuilder, ColumnDefinitions } from 'node-pg-migrate';
import shortUuid from 'short-uuid';
export const shorthands: ColumnDefinitions | undefined = undefined;
export async function up(pgm: MigrationBuilder): Promise<void> {
let merchantInfoIdsWithoutCardSpaceQuery =
'SELECT merchant_infos.id FROM merchant_infos LEFT JOIN card_spaces ON merchant_infos.id = card_spaces.merchant_id WHERE card_spaces.merchant_id IS NULL';
let merchantInfoIdsWithoutCardSpace = (await pgm.db.query(merchantInfoIdsWithoutCardSpaceQuery)).rows.map(
(row: any) => row.id
);
console.log(`Inserting ${merchantInfoIdsWithoutCardSpace.length} card spaces...`);
let insertValues = merchantInfoIdsWithoutCardSpace
.map((merchantId: string) => {
return `('${shortUuid.uuid()}', '${merchantId}')`;
})
.join(', ');
if (insertValues.length === 0) {
console.log('No card spaces to insert');
return;
}
let insertQuery = `INSERT INTO card_spaces (id, merchant_id) VALUES ${insertValues} RETURNING *`;
let result = await pgm.db.query(insertQuery);
console.log(`Inserted ${result.rows.length} card spaces.`);
}
export async function down(): Promise<void> {
console.log("Cant't easily reverse this migration. Delete card spaces manually if needed.");
}
| Create card spaces for merchants | Create card spaces for merchants
| TypeScript | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack | ---
+++
@@ -0,0 +1,35 @@
+import { MigrationBuilder, ColumnDefinitions } from 'node-pg-migrate';
+import shortUuid from 'short-uuid';
+
+export const shorthands: ColumnDefinitions | undefined = undefined;
+
+export async function up(pgm: MigrationBuilder): Promise<void> {
+ let merchantInfoIdsWithoutCardSpaceQuery =
+ 'SELECT merchant_infos.id FROM merchant_infos LEFT JOIN card_spaces ON merchant_infos.id = card_spaces.merchant_id WHERE card_spaces.merchant_id IS NULL';
+
+ let merchantInfoIdsWithoutCardSpace = (await pgm.db.query(merchantInfoIdsWithoutCardSpaceQuery)).rows.map(
+ (row: any) => row.id
+ );
+
+ console.log(`Inserting ${merchantInfoIdsWithoutCardSpace.length} card spaces...`);
+
+ let insertValues = merchantInfoIdsWithoutCardSpace
+ .map((merchantId: string) => {
+ return `('${shortUuid.uuid()}', '${merchantId}')`;
+ })
+ .join(', ');
+
+ if (insertValues.length === 0) {
+ console.log('No card spaces to insert');
+ return;
+ }
+
+ let insertQuery = `INSERT INTO card_spaces (id, merchant_id) VALUES ${insertValues} RETURNING *`;
+
+ let result = await pgm.db.query(insertQuery);
+ console.log(`Inserted ${result.rows.length} card spaces.`);
+}
+
+export async function down(): Promise<void> {
+ console.log("Cant't easily reverse this migration. Delete card spaces manually if needed.");
+} |
|
ae8754822e75c07b6b51dc6024b2594045632ddb | src/index.ts | src/index.ts | import * as readline from "readline";
import {CommandParser, BattlelineEvent, Position, Card} from "./command_parser";
import {StrategyRunner} from "./strategy_runner";
import {RandomStrategy} from "./random_strategy";
// Parse all commands as the enter the system
const commandParser = new CommandParser();
// Configure the strategies
const strategy = new RandomStrategy();
const strategyRunner = new StrategyRunner(strategy);
// Connect the strategy runner to incoming commands
// All returned values are written to stdout
commandParser.on(BattlelineEvent[BattlelineEvent.NameRequest],
(position: Position) => console.log(strategyRunner.onNameRequest(position))
);
commandParser.on(BattlelineEvent[BattlelineEvent.Colors],
(colors: string[]) => strategyRunner.onColors(colors)
);
commandParser.on(BattlelineEvent[BattlelineEvent.Hand],
(cards: Card[]) => strategyRunner.onHand(cards)
);
commandParser.on(BattlelineEvent[BattlelineEvent.Claim],
(claimStatus: Position[]) => strategyRunner.onClaim(claimStatus)
);
commandParser.on(BattlelineEvent[BattlelineEvent.Flag],
(flagNum: number, position: Position, cards: Card[]) => strategyRunner.onFlag(flagNum, position, cards)
);
commandParser.on(BattlelineEvent[BattlelineEvent.Play],
() => console.log(strategyRunner.onPlay())
);
// Main game loop. Parse incoming events and generate responses
const lineReader = readline.createInterface({
input: process.stdin,
output: process.stdout
});
lineReader.on("line", line => {
commandParser.parseEvent(line);
});
| Add main program entry point and initialize components | feat(Index): Add main program entry point and initialize components
| TypeScript | mit | grantpatten/battleline-ai,grantpatten/battleline-ai | ---
+++
@@ -0,0 +1,47 @@
+import * as readline from "readline";
+import {CommandParser, BattlelineEvent, Position, Card} from "./command_parser";
+import {StrategyRunner} from "./strategy_runner";
+import {RandomStrategy} from "./random_strategy";
+
+// Parse all commands as the enter the system
+const commandParser = new CommandParser();
+
+// Configure the strategies
+const strategy = new RandomStrategy();
+const strategyRunner = new StrategyRunner(strategy);
+
+// Connect the strategy runner to incoming commands
+// All returned values are written to stdout
+commandParser.on(BattlelineEvent[BattlelineEvent.NameRequest],
+ (position: Position) => console.log(strategyRunner.onNameRequest(position))
+);
+
+commandParser.on(BattlelineEvent[BattlelineEvent.Colors],
+ (colors: string[]) => strategyRunner.onColors(colors)
+);
+
+commandParser.on(BattlelineEvent[BattlelineEvent.Hand],
+ (cards: Card[]) => strategyRunner.onHand(cards)
+);
+
+commandParser.on(BattlelineEvent[BattlelineEvent.Claim],
+ (claimStatus: Position[]) => strategyRunner.onClaim(claimStatus)
+);
+
+commandParser.on(BattlelineEvent[BattlelineEvent.Flag],
+ (flagNum: number, position: Position, cards: Card[]) => strategyRunner.onFlag(flagNum, position, cards)
+);
+
+commandParser.on(BattlelineEvent[BattlelineEvent.Play],
+ () => console.log(strategyRunner.onPlay())
+);
+
+// Main game loop. Parse incoming events and generate responses
+const lineReader = readline.createInterface({
+ input: process.stdin,
+ output: process.stdout
+});
+
+lineReader.on("line", line => {
+ commandParser.parseEvent(line);
+}); |
|
845895559059dc4f34ad1329942803187e18902c | server/src/utils.ts | server/src/utils.ts |
/*#######.
########",#:
#########',##".
##'##'## .##',##.
## ## ## # ##",#.
## ## ## ## ##'
## ## ## :##
## ## ##*/
import { readFile as readFileAsync } from 'fs'
export const readFile = (filePath: string) =>
new Promise<Buffer>((resolve, reject) => {
readFileAsync(filePath, (err, data) => (err ? reject(err) : resolve(data)))
})
| Add custom promisified Node library functions | Add custom promisified Node library functions
| TypeScript | mit | kube/vscode-clang-complete,kube/vscode-clang-complete | ---
+++
@@ -0,0 +1,16 @@
+
+ /*#######.
+ ########",#:
+ #########',##".
+ ##'##'## .##',##.
+ ## ## ## # ##",#.
+ ## ## ## ## ##'
+ ## ## ## :##
+ ## ## ##*/
+
+import { readFile as readFileAsync } from 'fs'
+
+export const readFile = (filePath: string) =>
+ new Promise<Buffer>((resolve, reject) => {
+ readFileAsync(filePath, (err, data) => (err ? reject(err) : resolve(data)))
+ }) |
|
6cc70e918bc4c1619b86816c840e0b62727a2416 | test/property-decorators/logger.spec.ts | test/property-decorators/logger.spec.ts | import { LoggerProperty } from './../../src/';
describe('LoggerMethod decorator', () => {
beforeEach(() => {
spyOn(console, 'log');
});
it('should output log trace for "set" method (without annotation, default behaviour)', () => {
class TestClassProperty {
@LoggerProperty()
name: string;
}
let testClass = new TestClassProperty();
testClass.name = 'My name';
expect(console.log).toHaveBeenCalled();
expect(console.log).toHaveBeenCalledTimes(1);
});
it('should output log trace for "get" method (without annotation, default behaviour)', () => {
let testName = 'My name';
class TestClassProperty {
@LoggerProperty()
name: string = testName;
}
let testClass = new TestClassProperty();
expect(testClass.name).toEqual(testName);
expect(console.log).toHaveBeenCalled();
expect(console.log).toHaveBeenCalledTimes(2); // One for setting the name, another for getting the value
});
it('should not output any traces for getting/setting a value', () => {
let testName = 'My name';
class TestClassProperty {
@LoggerProperty({ getter: false, setter: false })
name: string = testName;
}
let testClass = new TestClassProperty();
expect(testClass.name).toEqual(testName);
expect(console.log).not.toHaveBeenCalled();
expect(console.log).toHaveBeenCalledTimes(0);
});
it('should output trace with a prefix for setting a value', () => {
let prefixLog = '[TEST-TRACE]';
let testName = 'My name';
class TestClassProperty {
@LoggerProperty({ prefix: prefixLog })
name: string = testName;
}
let testClass = new TestClassProperty();
expect(console.log).toHaveBeenCalled();
expect(console.log).toHaveBeenCalledWith(`${prefixLog} Setting value for field "name":`, testName);
});
}); | Add unit tests for property logger | Add unit tests for property logger
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -0,0 +1,60 @@
+import { LoggerProperty } from './../../src/';
+
+describe('LoggerMethod decorator', () => {
+
+ beforeEach(() => {
+ spyOn(console, 'log');
+ });
+
+ it('should output log trace for "set" method (without annotation, default behaviour)', () => {
+ class TestClassProperty {
+ @LoggerProperty()
+ name: string;
+ }
+
+ let testClass = new TestClassProperty();
+ testClass.name = 'My name';
+ expect(console.log).toHaveBeenCalled();
+ expect(console.log).toHaveBeenCalledTimes(1);
+ });
+
+ it('should output log trace for "get" method (without annotation, default behaviour)', () => {
+ let testName = 'My name';
+ class TestClassProperty {
+ @LoggerProperty()
+ name: string = testName;
+ }
+
+ let testClass = new TestClassProperty();
+ expect(testClass.name).toEqual(testName);
+ expect(console.log).toHaveBeenCalled();
+ expect(console.log).toHaveBeenCalledTimes(2); // One for setting the name, another for getting the value
+ });
+
+ it('should not output any traces for getting/setting a value', () => {
+ let testName = 'My name';
+ class TestClassProperty {
+ @LoggerProperty({ getter: false, setter: false })
+ name: string = testName;
+ }
+
+ let testClass = new TestClassProperty();
+ expect(testClass.name).toEqual(testName);
+ expect(console.log).not.toHaveBeenCalled();
+ expect(console.log).toHaveBeenCalledTimes(0);
+ });
+
+ it('should output trace with a prefix for setting a value', () => {
+ let prefixLog = '[TEST-TRACE]';
+ let testName = 'My name';
+ class TestClassProperty {
+ @LoggerProperty({ prefix: prefixLog })
+ name: string = testName;
+ }
+
+ let testClass = new TestClassProperty();
+ expect(console.log).toHaveBeenCalled();
+ expect(console.log).toHaveBeenCalledWith(`${prefixLog} Setting value for field "name":`, testName);
+ });
+
+}); |
|
020a8b00e9cbe207497112e700411cd421a0c3b7 | packages/ionic/test/horizontal-layout.spec.ts | packages/ionic/test/horizontal-layout.spec.ts | /*
The MIT License
Copyright (c) 2018 EclipseSource Munich
https://github.com/eclipsesource/jsonforms
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { TestBed } from '@angular/core/testing';
import { JsonFormsOutlet } from '@jsonforms/angular';
import { IonicModule, Platform } from 'ionic-angular';
import { PlatformMock } from '../test-config/mocks-ionic';
import { NgRedux } from '@angular-redux/store';
import { MockNgRedux } from '@angular-redux/store/testing';
import { HorizontalLayoutRenderer } from '../src';
describe('Horizontal layout', () => {
let fixture;
let component;
const data = { foo: true };
const schema = {
type: 'object',
properties: {
foo: {
type: 'boolean'
}
}
};
const uischema = {
type: 'HorizontalLayout',
elements: [{
type: 'Control',
scope: '#/properties/foo'
}]
};
beforeEach((() => {
TestBed.configureTestingModule({
declarations: [
JsonFormsOutlet,
HorizontalLayoutRenderer
],
imports: [
IonicModule.forRoot(HorizontalLayoutRenderer)
],
providers: [
{provide: Platform, useClass: PlatformMock},
{provide: NgRedux, useFactory: MockNgRedux.getInstance}
]
}).compileComponents();
MockNgRedux.reset();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HorizontalLayoutRenderer);
component = fixture.componentInstance;
});
it('add elements', () => {
const mockSubStore = MockNgRedux.getSelectorStub();
component.uischema = uischema;
mockSubStore.next({
jsonforms: {
core: {
data,
schema,
}
}
});
mockSubStore.complete();
component.ngOnInit();
MockNgRedux.reset();
component.uischema = {
type: 'HorizontalLayout',
elements: [
...uischema.elements,
{
type: 'Control',
scope: '#properties/bar'
}
]
};
fixture.detectChanges();
expect(component.uischema.elements.length).toBe(2);
});
});
| Add test for horizontal layout | Add test for horizontal layout
| TypeScript | mit | qb-project/jsonforms,qb-project/jsonforms,qb-project/jsonforms | ---
+++
@@ -0,0 +1,105 @@
+/*
+ The MIT License
+
+ Copyright (c) 2018 EclipseSource Munich
+ https://github.com/eclipsesource/jsonforms
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+*/
+import { TestBed } from '@angular/core/testing';
+import { JsonFormsOutlet } from '@jsonforms/angular';
+import { IonicModule, Platform } from 'ionic-angular';
+import { PlatformMock } from '../test-config/mocks-ionic';
+import { NgRedux } from '@angular-redux/store';
+import { MockNgRedux } from '@angular-redux/store/testing';
+import { HorizontalLayoutRenderer } from '../src';
+
+describe('Horizontal layout', () => {
+ let fixture;
+ let component;
+
+ const data = { foo: true };
+ const schema = {
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'boolean'
+ }
+ }
+ };
+ const uischema = {
+ type: 'HorizontalLayout',
+ elements: [{
+ type: 'Control',
+ scope: '#/properties/foo'
+ }]
+ };
+
+ beforeEach((() => {
+ TestBed.configureTestingModule({
+ declarations: [
+ JsonFormsOutlet,
+ HorizontalLayoutRenderer
+ ],
+ imports: [
+ IonicModule.forRoot(HorizontalLayoutRenderer)
+ ],
+ providers: [
+ {provide: Platform, useClass: PlatformMock},
+ {provide: NgRedux, useFactory: MockNgRedux.getInstance}
+ ]
+ }).compileComponents();
+
+ MockNgRedux.reset();
+ }));
+
+ beforeEach(() => {
+ fixture = TestBed.createComponent(HorizontalLayoutRenderer);
+ component = fixture.componentInstance;
+ });
+
+ it('add elements', () => {
+ const mockSubStore = MockNgRedux.getSelectorStub();
+ component.uischema = uischema;
+
+ mockSubStore.next({
+ jsonforms: {
+ core: {
+ data,
+ schema,
+ }
+ }
+ });
+ mockSubStore.complete();
+ component.ngOnInit();
+ MockNgRedux.reset();
+ component.uischema = {
+ type: 'HorizontalLayout',
+ elements: [
+ ...uischema.elements,
+ {
+ type: 'Control',
+ scope: '#properties/bar'
+ }
+ ]
+ };
+ fixture.detectChanges();
+ expect(component.uischema.elements.length).toBe(2);
+ });
+}); |
|
b30795109f03950205536425095c7fbb7e013fc7 | server/libs/api/mail-functions.ts | server/libs/api/mail-functions.ts | ///<reference path="../../../typings/globals/nodemailer/index.d.ts"/>
import { Router, Response, Request, NextFunction } from "express";
import * as nodemailer from "nodemailer"
export class MailFunctions {
sendMail(recipientMail, subject, text, callback) {
let transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: '[email protected]',
pass: 'devalpha'
}
});
let mailOptions = {
from: '<[email protected]> Examen Email Verification',
to: recipientMail,
subject: subject,
text: text
}
transporter.sendMail(mailOptions, (error, info) => {
callback(error, info);
})
}
} | Add mail function as seperate mailing service provider | Add mail function as seperate mailing service provider
| TypeScript | mit | shavindraSN/examen,shavindraSN/examen,shavindraSN/examen | ---
+++
@@ -0,0 +1,26 @@
+///<reference path="../../../typings/globals/nodemailer/index.d.ts"/>
+
+import { Router, Response, Request, NextFunction } from "express";
+import * as nodemailer from "nodemailer"
+
+export class MailFunctions {
+ sendMail(recipientMail, subject, text, callback) {
+ let transporter = nodemailer.createTransport({
+ service: 'Gmail',
+ auth: {
+ user: '[email protected]',
+ pass: 'devalpha'
+ }
+ });
+ let mailOptions = {
+ from: '<[email protected]> Examen Email Verification',
+ to: recipientMail,
+ subject: subject,
+ text: text
+ }
+
+ transporter.sendMail(mailOptions, (error, info) => {
+ callback(error, info);
+ })
+ }
+} |
|
37bef945e199661c157abcfd44c13ece389524ef | test/unit/core/configuration/project-configuration-utils.spec.ts | test/unit/core/configuration/project-configuration-utils.spec.ts | import {ProjectConfigurationUtils} from '../../../../app/core/configuration/project-configuration-utils';
import {ConfigurationDefinition} from '../../../../app/core/configuration/boot/configuration-definition';
describe('ProjectConfigurationUtils', () => {
it('initTypes', () => {
const confDef: ConfigurationDefinition = {
relations: [],
identifier: '',
types: [{
type: 'A',
parent: 'P'
},{
type: 'P'
}]
};
const result = ProjectConfigurationUtils.initTypes(confDef);
expect(result['A'].name).toEqual('A');
expect(result['P'].name).toEqual('P');
});
}); | Add minimal test for initTypes | Add minimal test for initTypes
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -0,0 +1,24 @@
+import {ProjectConfigurationUtils} from '../../../../app/core/configuration/project-configuration-utils';
+import {ConfigurationDefinition} from '../../../../app/core/configuration/boot/configuration-definition';
+
+describe('ProjectConfigurationUtils', () => {
+
+ it('initTypes', () => {
+
+ const confDef: ConfigurationDefinition = {
+ relations: [],
+ identifier: '',
+ types: [{
+ type: 'A',
+ parent: 'P'
+ },{
+ type: 'P'
+ }]
+ };
+
+ const result = ProjectConfigurationUtils.initTypes(confDef);
+
+ expect(result['A'].name).toEqual('A');
+ expect(result['P'].name).toEqual('P');
+ });
+}); |
|
21d4ebf547894cad8aba149cf0eb699060926be4 | e2e/steps/datasets-list.ts | e2e/steps/datasets-list.ts | import { $$, steps } from '../support/world';
steps(({Then}) => {
Then(/^the datasets should be sorted by date in descending order$/, () => {
return $$('.datasets-list-row').getText().then(rows => {
const timestamp = row => new Date(row.split('\n')[0]).getTime();
rows.length.should.be.above(0);
(rows as any).reduce((last, next) => {
timestamp(next).should.be.at.most(timestamp(last));
return next;
});
});
});
});
| Add e2e step to test the list of datasets arranged by date | Add e2e step to test the list of datasets arranged by date
| TypeScript | bsd-3-clause | cumulous/web,cumulous/web,cumulous/web,cumulous/web | ---
+++
@@ -0,0 +1,14 @@
+import { $$, steps } from '../support/world';
+
+steps(({Then}) => {
+ Then(/^the datasets should be sorted by date in descending order$/, () => {
+ return $$('.datasets-list-row').getText().then(rows => {
+ const timestamp = row => new Date(row.split('\n')[0]).getTime();
+ rows.length.should.be.above(0);
+ (rows as any).reduce((last, next) => {
+ timestamp(next).should.be.at.most(timestamp(last));
+ return next;
+ });
+ });
+ });
+}); |
|
3eefb1834c363a730287b599ca46c935a3e3cc3a | spec/dimensions/packets/packetreaderspec.ts | spec/dimensions/packets/packetreaderspec.ts | import PacketReader from 'dimensions/packets/packetreader';
describe("packetreader", () => {
let reader: PacketReader;
beforeEach(() => {
reader = new PacketReader("02000505");
});
it("should correctly remove the packet length and type", () => {
expect(reader.data).toEqual("05");
});
it("should correctly store the type of the packet", () => {
expect(reader.type).toEqual(5);
});
}); | Write tests for packet reader | Write tests for packet reader
| TypeScript | mit | popstarfreas/Dimensions,popstarfreas/Dimensions,popstarfreas/Dimensions | ---
+++
@@ -0,0 +1,17 @@
+import PacketReader from 'dimensions/packets/packetreader';
+
+describe("packetreader", () => {
+ let reader: PacketReader;
+
+ beforeEach(() => {
+ reader = new PacketReader("02000505");
+ });
+
+ it("should correctly remove the packet length and type", () => {
+ expect(reader.data).toEqual("05");
+ });
+
+ it("should correctly store the type of the packet", () => {
+ expect(reader.type).toEqual(5);
+ });
+}); |
|
dd75d76d8cad8718337697b711caad8e5cc42890 | TestFiles/FormatTestLocations.ts | TestFiles/FormatTestLocations.ts | import 'reflect-metadata';
import { UtilService } from '../src/app/shared/util.service';
import xmljs = require('xml-js')
const a = [
{
"n_nit": "10117685",
"Ced_Vendedor": "4514347",
"ss_codigo": "!11127",
"NombreSucursal": "W.H. DISTRIBUCIONES",
"ss_direccion": "CL 14 05 05",
"Cod_Dpto": "66",
"Cod_Ciudad": "66001",
"ss_telefono": "3348413"
},
{
"n_nit": "10542042",
"Ced_Vendedor": "94370341",
"ss_codigo": "!10641",
"NombreSucursal": "LECHES Y PAÑALES MELISSA",
"ss_direccion": "CR 17 07 A 06",
"Cod_Dpto": "19",
"Cod_Ciudad": "19001",
"ss_telefono": "8365402"
}
]
const format: MapFormat = {
to: 'partnerLocations',
type: 'assign',
addChildren: [ {
to: 'query',
// tslint:disable-next-line:max-line-length
defaultVal: 'mutation ($partnerLocations: [upsertPartnerLocationsArgs]) { upsertPartnerLocations(partnerLocations: $partnerLocations) { c_bpartner_id c_bpartner_location_id phone name } }'
}],
children: {
'partnerLocations': {
to: 'variables.partnerLocations',
type: 'array',
childrenArray: {
type: 'map',
isPick: true,
children: {
n_nit: { to: 'partner.value' },
Ced_Vendedor: { to: 'seller.value' },
Cod_Dpto: { to: 'department.code' },
Cod_Ciudad: { to: 'city.code' },
ss_codigo: { to: 'code' },
NombreSucursal: { to: 'name' },
ss_direccion: { to: 'address' },
ss_telefono: { to: 'phone' },
}
}
}
}
}
const result = UtilService.formatJson(a, format)
JSON.stringify(result, null, 2)/*?*/
// const xml = xmljs.js2xml(result, {
// compact: true,
// })
// console.log(xml)
| Add JSON Format for Locations example | Add JSON Format for Locations example
| TypeScript | mit | luchillo17/Electron-Webpack,luchillo17/Electron-Webpack,luchillo17/Electron-Webpack | ---
+++
@@ -0,0 +1,63 @@
+import 'reflect-metadata';
+import { UtilService } from '../src/app/shared/util.service';
+import xmljs = require('xml-js')
+
+const a = [
+ {
+ "n_nit": "10117685",
+ "Ced_Vendedor": "4514347",
+ "ss_codigo": "!11127",
+ "NombreSucursal": "W.H. DISTRIBUCIONES",
+ "ss_direccion": "CL 14 05 05",
+ "Cod_Dpto": "66",
+ "Cod_Ciudad": "66001",
+ "ss_telefono": "3348413"
+ },
+ {
+ "n_nit": "10542042",
+ "Ced_Vendedor": "94370341",
+ "ss_codigo": "!10641",
+ "NombreSucursal": "LECHES Y PAÑALES MELISSA",
+ "ss_direccion": "CR 17 07 A 06",
+ "Cod_Dpto": "19",
+ "Cod_Ciudad": "19001",
+ "ss_telefono": "8365402"
+ }
+]
+
+const format: MapFormat = {
+ to: 'partnerLocations',
+ type: 'assign',
+ addChildren: [ {
+ to: 'query',
+ // tslint:disable-next-line:max-line-length
+ defaultVal: 'mutation ($partnerLocations: [upsertPartnerLocationsArgs]) { upsertPartnerLocations(partnerLocations: $partnerLocations) { c_bpartner_id c_bpartner_location_id phone name } }'
+ }],
+ children: {
+ 'partnerLocations': {
+ to: 'variables.partnerLocations',
+ type: 'array',
+ childrenArray: {
+ type: 'map',
+ isPick: true,
+ children: {
+ n_nit: { to: 'partner.value' },
+ Ced_Vendedor: { to: 'seller.value' },
+ Cod_Dpto: { to: 'department.code' },
+ Cod_Ciudad: { to: 'city.code' },
+ ss_codigo: { to: 'code' },
+ NombreSucursal: { to: 'name' },
+ ss_direccion: { to: 'address' },
+ ss_telefono: { to: 'phone' },
+ }
+ }
+ }
+ }
+}
+
+const result = UtilService.formatJson(a, format)
+JSON.stringify(result, null, 2)/*?*/
+// const xml = xmljs.js2xml(result, {
+// compact: true,
+// })
+// console.log(xml) |
|
f73392c13b22f6465467058feb1ac8d4df708c23 | ui/src/shared/parsing/lastValues.ts | ui/src/shared/parsing/lastValues.ts | import _ from 'lodash'
interface Result {
lastValues: number[]
series: string[]
}
interface Series {
name: string
values: number[] | null
columns: string[] | null
}
interface TimeSeriesResult {
series: Series[]
}
export interface TimeSeriesResponse {
response: {
result: TimeSeriesResult[]
}
}
export default function(
timeSeriesResponse: TimeSeriesResponse[] | null
): Result {
const values = _.get(
timeSeriesResponse,
['0', 'response', 'results', '0', 'series', '0', 'values'],
[['', '']]
)
const series = _.get(
timeSeriesResponse,
['0', 'response', 'results', '0', 'series', '0', 'columns'],
['', '']
).slice(1)
const lastValues = values[values.length - 1].slice(1) // remove time with slice 1
return {lastValues, series}
}
| import _ from 'lodash'
interface Result {
lastValues: number[]
series: string[]
}
interface Series {
name: string
values: number[] | null
columns: string[] | null
}
interface TimeSeriesResult {
series: Series[]
}
export interface TimeSeriesResponse {
response: {
results: TimeSeriesResult[]
}
}
export default function(
timeSeriesResponse: TimeSeriesResponse[] | null
): Result {
const values = _.get(
timeSeriesResponse,
['0', 'response', 'results', '0', 'series', '0', 'values'],
[['', '']]
)
const series = _.get(
timeSeriesResponse,
['0', 'response', 'results', '0', 'series', '0', 'columns'],
['', '']
).slice(1)
const lastValues = values[values.length - 1].slice(1) // remove time with slice 1
return {lastValues, series}
}
| Fix typescript results key for last values | Fix typescript results key for last values
| TypeScript | mit | li-ang/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb | ---
+++
@@ -17,7 +17,7 @@
export interface TimeSeriesResponse {
response: {
- result: TimeSeriesResult[]
+ results: TimeSeriesResult[]
}
}
|
0060b4d66332adb2fc5eb99b84f3e2095d176d58 | tests/cases/fourslash/signatureHelpThis.ts | tests/cases/fourslash/signatureHelpThis.ts | /// <reference path='fourslash.ts' />
////class Foo<T> {
//// public implicitAny(n: number) {
//// }
//// public explicitThis(this: this, n: number) {
//// console.log(this);
//// }
//// public explicitClass(this: Foo<T>, n: number) {
//// console.log(this);
//// }
////}
////
////function implicitAny(x: number): void {
//// return this;
////}
////function explicitVoid(this: void, x: number): void {
//// return this;
////}
////function explicitLiteral(this: { n: number }, x: number): void {
//// console.log(this);
////}
////let foo = new Foo<number>();
////foo.implicitAny(/*1*/);
////foo.explicitThis(/*2*/);
////foo.explicitClass(/*3*/);
////implicitAny(/*4*/12);
////explicitVoid(/*5*/13);
////let o = { n: 14, m: explicitLiteral };
////o.m(/*6*/);
goTo.marker('1');
verify.currentParameterHelpArgumentNameIs("n");
goTo.marker('2');
verify.currentParameterHelpArgumentNameIs("n");
goTo.marker('3');
verify.currentParameterHelpArgumentNameIs("n");
goTo.marker('4');
verify.currentParameterHelpArgumentNameIs("x");
goTo.marker('5');
verify.currentParameterHelpArgumentNameIs("x");
goTo.marker('6');
verify.currentParameterHelpArgumentNameIs("x");
| Test that signature help doesn't show 'this' | Test that signature help doesn't show 'this'
| TypeScript | apache-2.0 | ziacik/TypeScript,Eyas/TypeScript,Microsoft/TypeScript,jwbay/TypeScript,plantain-00/TypeScript,kpreisser/TypeScript,kpreisser/TypeScript,jeremyepling/TypeScript,weswigham/TypeScript,mihailik/TypeScript,donaldpipowitch/TypeScript,Microsoft/TypeScript,ziacik/TypeScript,DLehenbauer/TypeScript,erikmcc/TypeScript,vilic/TypeScript,jwbay/TypeScript,RyanCavanaugh/TypeScript,erikmcc/TypeScript,donaldpipowitch/TypeScript,basarat/TypeScript,jeremyepling/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,vilic/TypeScript,Eyas/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,kitsonk/TypeScript,alexeagle/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,chuckjaz/TypeScript,DLehenbauer/TypeScript,synaptek/TypeScript,jwbay/TypeScript,minestarks/TypeScript,jwbay/TypeScript,nojvek/TypeScript,mihailik/TypeScript,basarat/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,synaptek/TypeScript,kitsonk/TypeScript,TukekeSoft/TypeScript,mihailik/TypeScript,Microsoft/TypeScript,SaschaNaz/TypeScript,jeremyepling/TypeScript,RyanCavanaugh/TypeScript,ziacik/TypeScript,chuckjaz/TypeScript,plantain-00/TypeScript,microsoft/TypeScript,plantain-00/TypeScript,chuckjaz/TypeScript,thr0w/Thr0wScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,thr0w/Thr0wScript,thr0w/Thr0wScript,vilic/TypeScript,erikmcc/TypeScript,synaptek/TypeScript,basarat/TypeScript,Eyas/TypeScript,minestarks/TypeScript,thr0w/Thr0wScript,synaptek/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,microsoft/TypeScript,ziacik/TypeScript,plantain-00/TypeScript,erikmcc/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,TukekeSoft/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,mihailik/TypeScript,chuckjaz/TypeScript,TukekeSoft/TypeScript,vilic/TypeScript,Eyas/TypeScript,nojvek/TypeScript,DLehenbauer/TypeScript,DLehenbauer/TypeScript,kpreisser/TypeScript | ---
+++
@@ -0,0 +1,43 @@
+/// <reference path='fourslash.ts' />
+////class Foo<T> {
+//// public implicitAny(n: number) {
+//// }
+//// public explicitThis(this: this, n: number) {
+//// console.log(this);
+//// }
+//// public explicitClass(this: Foo<T>, n: number) {
+//// console.log(this);
+//// }
+////}
+////
+////function implicitAny(x: number): void {
+//// return this;
+////}
+////function explicitVoid(this: void, x: number): void {
+//// return this;
+////}
+////function explicitLiteral(this: { n: number }, x: number): void {
+//// console.log(this);
+////}
+////let foo = new Foo<number>();
+////foo.implicitAny(/*1*/);
+////foo.explicitThis(/*2*/);
+////foo.explicitClass(/*3*/);
+////implicitAny(/*4*/12);
+////explicitVoid(/*5*/13);
+////let o = { n: 14, m: explicitLiteral };
+////o.m(/*6*/);
+
+
+goTo.marker('1');
+verify.currentParameterHelpArgumentNameIs("n");
+goTo.marker('2');
+verify.currentParameterHelpArgumentNameIs("n");
+goTo.marker('3');
+verify.currentParameterHelpArgumentNameIs("n");
+goTo.marker('4');
+verify.currentParameterHelpArgumentNameIs("x");
+goTo.marker('5');
+verify.currentParameterHelpArgumentNameIs("x");
+goTo.marker('6');
+verify.currentParameterHelpArgumentNameIs("x"); |
|
45fd54a60ec72813a876cc21dcd63913956bb891 | src/actions/watcherFolders.ts | src/actions/watcherFolders.ts | import { SELECT_WATCHER_FOLDER } from '../constants/index';
export interface SelectWatcherFolder {
readonly type: SELECT_WATCHER_FOLDER;
readonly folderId: string;
}
export const selectWatcherFolder = (folderId: string): SelectWatcherFolder => ({
type: SELECT_WATCHER_FOLDER,
folderId
});
| Add action creators for watcherFolder actions. | Add action creators for watcherFolder actions.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,11 @@
+import { SELECT_WATCHER_FOLDER } from '../constants/index';
+
+export interface SelectWatcherFolder {
+ readonly type: SELECT_WATCHER_FOLDER;
+ readonly folderId: string;
+}
+
+export const selectWatcherFolder = (folderId: string): SelectWatcherFolder => ({
+ type: SELECT_WATCHER_FOLDER,
+ folderId
+}); |
|
006003ae6b17b23e93fd89014a1a5b7bbb467d55 | src/utils/__tests__/clientUtils.node.tsx | src/utils/__tests__/clientUtils.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 {deconstructClientId, buildClientId} from '../clientUtils';
test('client id constructed correctly', () => {
const consoleErrorSpy = jest.spyOn(global.console, 'error');
const clientId = buildClientId({
app: 'Instagram',
os: 'iOS',
device: 'iPhone Simulator',
device_id: 'EC431B79-69F1-4705-9FE5-9AE5D96378E1',
});
expect(clientId).toBe(
'Instagram#iOS#iPhone Simulator#EC431B79-69F1-4705-9FE5-9AE5D96378E1',
);
expect(consoleErrorSpy).toHaveBeenCalledTimes(0);
});
test('client id deconstructed correctly', () => {
const deconstructedClientId = deconstructClientId(
'Instagram#iOS#iPhone Simulator#EC431B79-69F1-4705-9FE5-9AE5D96378E1',
);
expect(deconstructedClientId).toStrictEqual({
app: 'Instagram',
os: 'iOS',
device: 'iPhone Simulator',
device_id: 'EC431B79-69F1-4705-9FE5-9AE5D96378E1',
});
});
test('client id deconstruction error logged', () => {
const consoleErrorSpy = jest.spyOn(global.console, 'error');
const deconstructedClientId = deconstructClientId(
'Instagram#iPhone Simulator#EC431B79-69F1-4705-9FE5-9AE5D96378E1',
);
expect(deconstructedClientId).toStrictEqual({
app: 'Instagram',
os: 'iPhone Simulator',
device: 'EC431B79-69F1-4705-9FE5-9AE5D96378E1',
device_id: undefined,
});
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
});
| Add tests for client-id / app name parsing | Add tests for client-id / app name parsing
Summary: Add tests for client-id / app name parsing. We've had a lot of bugs here in the past. Get some good test coverage so we have some assurance the shared utils for it won't be broken.
Reviewed By: jknoxville
Differential Revision: D18830269
fbshipit-source-id: 07c9755bbeae28c48580f44453d4010d6d3830b0
| 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,50 @@
+/**
+ * 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 {deconstructClientId, buildClientId} from '../clientUtils';
+
+test('client id constructed correctly', () => {
+ const consoleErrorSpy = jest.spyOn(global.console, 'error');
+ const clientId = buildClientId({
+ app: 'Instagram',
+ os: 'iOS',
+ device: 'iPhone Simulator',
+ device_id: 'EC431B79-69F1-4705-9FE5-9AE5D96378E1',
+ });
+ expect(clientId).toBe(
+ 'Instagram#iOS#iPhone Simulator#EC431B79-69F1-4705-9FE5-9AE5D96378E1',
+ );
+ expect(consoleErrorSpy).toHaveBeenCalledTimes(0);
+});
+
+test('client id deconstructed correctly', () => {
+ const deconstructedClientId = deconstructClientId(
+ 'Instagram#iOS#iPhone Simulator#EC431B79-69F1-4705-9FE5-9AE5D96378E1',
+ );
+ expect(deconstructedClientId).toStrictEqual({
+ app: 'Instagram',
+ os: 'iOS',
+ device: 'iPhone Simulator',
+ device_id: 'EC431B79-69F1-4705-9FE5-9AE5D96378E1',
+ });
+});
+
+test('client id deconstruction error logged', () => {
+ const consoleErrorSpy = jest.spyOn(global.console, 'error');
+ const deconstructedClientId = deconstructClientId(
+ 'Instagram#iPhone Simulator#EC431B79-69F1-4705-9FE5-9AE5D96378E1',
+ );
+ expect(deconstructedClientId).toStrictEqual({
+ app: 'Instagram',
+ os: 'iPhone Simulator',
+ device: 'EC431B79-69F1-4705-9FE5-9AE5D96378E1',
+ device_id: undefined,
+ });
+ expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
+}); |
|
67cc169a9dcca4e6ea301451007573549abc5c59 | src/utils/databaseFilter.ts | src/utils/databaseFilter.ts | import { StatusFilterType } from 'types';
import { Map, Set } from 'immutable';
import { AppliedFilter, FilterType } from '@shopify/polaris';
const statusFilterTypeToLabel: Map<StatusFilterType, string> = Map([
['PENDING', 'Pending'],
['PAID', 'Paid'],
['APPROVED', 'Approved'],
['REJECTED', 'Rejected']
]);
export interface HitDatabaseFilter {
readonly key: 'STATUS';
readonly label: string;
readonly type: FilterType.Select;
readonly options: HitDatabaseFilterOption[];
}
export interface HitDatabaseFilterOption {
readonly value: StatusFilterType;
readonly label: string;
}
export interface AppliedHitDatabaseFilter {
readonly key: 'STATUS';
readonly value: StatusFilterType;
readonly label?: string;
}
export const availableFilters: HitDatabaseFilter[] = [
{
key: 'STATUS',
label: 'Status',
type: FilterType.Select,
options: statusFilterTypeToLabel.reduce(
(acc: HitDatabaseFilterOption[], cur: string, key: StatusFilterType) =>
acc.concat([
{
label: cur,
value: key
}
]),
[]
)
}
];
export const appliedFiltersToStatusFilterTypeSet = (
filters: AppliedHitDatabaseFilter[]
) =>
filters.reduce(
(acc, cur): Set<StatusFilterType> => acc.add(cur.value),
Set<StatusFilterType>([])
);
/**
* Generates the
* @param filters
*/
export const statusFiltersToAppliedFilterArray = (
filters: Set<StatusFilterType>
): AppliedFilter[] =>
filters.toArray().map((filter: StatusFilterType): AppliedFilter => ({
key: 'STATUS',
value: filter,
label: `Status: ${statusFilterTypeToLabel.get(filter)}`
}));
| Add utility functions for converting data in root state to comply with Polaris filter API. | Add utility functions for converting data in root state to comply with Polaris filter API.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,67 @@
+import { StatusFilterType } from 'types';
+import { Map, Set } from 'immutable';
+import { AppliedFilter, FilterType } from '@shopify/polaris';
+
+const statusFilterTypeToLabel: Map<StatusFilterType, string> = Map([
+ ['PENDING', 'Pending'],
+ ['PAID', 'Paid'],
+ ['APPROVED', 'Approved'],
+ ['REJECTED', 'Rejected']
+]);
+
+export interface HitDatabaseFilter {
+ readonly key: 'STATUS';
+ readonly label: string;
+ readonly type: FilterType.Select;
+ readonly options: HitDatabaseFilterOption[];
+}
+
+export interface HitDatabaseFilterOption {
+ readonly value: StatusFilterType;
+ readonly label: string;
+}
+
+export interface AppliedHitDatabaseFilter {
+ readonly key: 'STATUS';
+ readonly value: StatusFilterType;
+ readonly label?: string;
+}
+
+export const availableFilters: HitDatabaseFilter[] = [
+ {
+ key: 'STATUS',
+ label: 'Status',
+ type: FilterType.Select,
+ options: statusFilterTypeToLabel.reduce(
+ (acc: HitDatabaseFilterOption[], cur: string, key: StatusFilterType) =>
+ acc.concat([
+ {
+ label: cur,
+ value: key
+ }
+ ]),
+ []
+ )
+ }
+];
+
+export const appliedFiltersToStatusFilterTypeSet = (
+ filters: AppliedHitDatabaseFilter[]
+) =>
+ filters.reduce(
+ (acc, cur): Set<StatusFilterType> => acc.add(cur.value),
+ Set<StatusFilterType>([])
+ );
+
+/**
+ * Generates the
+ * @param filters
+ */
+export const statusFiltersToAppliedFilterArray = (
+ filters: Set<StatusFilterType>
+): AppliedFilter[] =>
+ filters.toArray().map((filter: StatusFilterType): AppliedFilter => ({
+ key: 'STATUS',
+ value: filter,
+ label: `Status: ${statusFilterTypeToLabel.get(filter)}`
+ })); |
|
559d42c26a7ff92f53dbf17b78f1d21c7070212b | ui/src/utils/wrappers.ts | ui/src/utils/wrappers.ts | import _ from 'lodash'
export function getNested<T = any>(obj: any, path: string, fallack: T): T {
return _.get<T>(obj, path, fallack)
}
| import _ from 'lodash'
export function getNested<T = any>(obj: any, path: string, fallback: T): T {
return _.get<T>(obj, path, fallback)
}
| Correct spelling of 'fallack' to 'fallback' in getNested | Correct spelling of 'fallack' to 'fallback' in getNested
| TypeScript | mit | nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -1,5 +1,5 @@
import _ from 'lodash'
-export function getNested<T = any>(obj: any, path: string, fallack: T): T {
- return _.get<T>(obj, path, fallack)
+export function getNested<T = any>(obj: any, path: string, fallback: T): T {
+ return _.get<T>(obj, path, fallback)
} |
bf09c732d91232724c19c40c915a8a1ea8bf584e | src/Test/Ast/Config/Spoiler.ts | src/Test/Ast/Config/Spoiler.ts | import { expect } from 'chai'
import { Up } from '../../../index'
import { insideDocumentAndParagraph } from '../Helpers'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
import { SpoilerNode } from '../../../SyntaxNodes/SpoilerNode'
describe('The term that represents spoiler conventions', () => {
const up = new Up({
i18n: {
terms: { spoiler: 'ruins ending' }
}
})
it('comes from the "spoiler" config term ', () => {
expect(up.toAst('[ruins ending: Ash fights Gary]')).to.be.eql(
insideDocumentAndParagraph([
new SpoilerNode([
new PlainTextNode('Ash fights Gary')
])
]))
})
it('is always canse-insensivite', () => {
expect(up.toAst('[RUINS ENDING: Ash fights Gary]')).to.be.eql(
insideDocumentAndParagraph([
new SpoilerNode([
new PlainTextNode('Ash fights Gary')
])
]))
})
})
| Add 2 passing config tests | Add 2 passing config tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,32 @@
+import { expect } from 'chai'
+import { Up } from '../../../index'
+import { insideDocumentAndParagraph } from '../Helpers'
+import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
+import { SpoilerNode } from '../../../SyntaxNodes/SpoilerNode'
+
+
+describe('The term that represents spoiler conventions', () => {
+ const up = new Up({
+ i18n: {
+ terms: { spoiler: 'ruins ending' }
+ }
+ })
+
+ it('comes from the "spoiler" config term ', () => {
+ expect(up.toAst('[ruins ending: Ash fights Gary]')).to.be.eql(
+ insideDocumentAndParagraph([
+ new SpoilerNode([
+ new PlainTextNode('Ash fights Gary')
+ ])
+ ]))
+ })
+
+ it('is always canse-insensivite', () => {
+ expect(up.toAst('[RUINS ENDING: Ash fights Gary]')).to.be.eql(
+ insideDocumentAndParagraph([
+ new SpoilerNode([
+ new PlainTextNode('Ash fights Gary')
+ ])
+ ]))
+ })
+}) |
|
2f88959ac4e79fa5e053110f19933f8714796fc1 | src/Test/Html/Config/Outline.ts | src/Test/Html/Config/Outline.ts | import { expect } from 'chai'
import Up from '../../../index'
import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
import { HeadingNode } from '../../../SyntaxNodes/HeadingNode'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
describe('The ID of an element referenced by the table of contents', () => {
it('uses the config term for "outline"', () => {
const up = new Up({
i18n: {
terms: { outline: 'table of contents entry' }
}
})
const heading =
new HeadingNode([new PlainTextNode('I enjoy apples')], 1)
const documentNode =
new DocumentNode([heading], new DocumentNode.TableOfContents([heading]))
expect(up.toHtml(documentNode)).to.be.eql(
'<nav class="up-table-of-contents">'
+ '<h1>Table of Contents</h1>'
+ '<ul>'
+ '<li><h2><a href="#up-table-of-contents-entry-1">I enjoy apples</a></h2></li>'
+ '</ul>'
+ '</nav>'
+ '<h1 id="up-table-of-contents-entry-1">I enjoy apples</h1>')
})
}) | Add passing table of contents HTML test | Add passing table of contents HTML test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,31 @@
+import { expect } from 'chai'
+import Up from '../../../index'
+import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
+import { HeadingNode } from '../../../SyntaxNodes/HeadingNode'
+import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
+
+
+describe('The ID of an element referenced by the table of contents', () => {
+ it('uses the config term for "outline"', () => {
+ const up = new Up({
+ i18n: {
+ terms: { outline: 'table of contents entry' }
+ }
+ })
+
+ const heading =
+ new HeadingNode([new PlainTextNode('I enjoy apples')], 1)
+
+ const documentNode =
+ new DocumentNode([heading], new DocumentNode.TableOfContents([heading]))
+
+ expect(up.toHtml(documentNode)).to.be.eql(
+ '<nav class="up-table-of-contents">'
+ + '<h1>Table of Contents</h1>'
+ + '<ul>'
+ + '<li><h2><a href="#up-table-of-contents-entry-1">I enjoy apples</a></h2></li>'
+ + '</ul>'
+ + '</nav>'
+ + '<h1 id="up-table-of-contents-entry-1">I enjoy apples</h1>')
+ })
+}) |
|
b86a9a656cfbfbebff3e1ebff0ace086ebff8355 | src/lib/src/utilities/rxjs-lift-hack.ts | src/lib/src/utilities/rxjs-lift-hack.ts | // TODO: Remove this when RxJS releases a stable version with a correct declaration of `Subject`.
// https://github.com/ReactiveX/rxjs/issues/2539#issuecomment-312683629
import { Operator } from 'rxjs/Operator'
import { Observable } from 'rxjs/Observable';
declare module 'rxjs/Subject' {
interface Subject<T> {
lift<R>(operator: Operator<T, R>): Observable<R>
}
}
| Create hack for RXJS subject | chore: Create hack for RXJS subject
More here:
https://github.com/ReactiveX/rxjs/issues/2539#issuecomment-312683629
| TypeScript | mit | GetTerminus/terminus-ui,GetTerminus/terminus-ui,GetTerminus/terminus-ui,GetTerminus/terminus-ui | ---
+++
@@ -0,0 +1,10 @@
+// TODO: Remove this when RxJS releases a stable version with a correct declaration of `Subject`.
+// https://github.com/ReactiveX/rxjs/issues/2539#issuecomment-312683629
+import { Operator } from 'rxjs/Operator'
+import { Observable } from 'rxjs/Observable';
+
+declare module 'rxjs/Subject' {
+ interface Subject<T> {
+ lift<R>(operator: Operator<T, R>): Observable<R>
+ }
+} |
|
61dac30a2bc1d5d6109b6775853075bd6da6dfb4 | src/views/settingsScreen.tsx | src/views/settingsScreen.tsx | /**
* Created by archheretic on 19.04.17.
*/
/**
* Created by archheretic on 19.04.17.
*/
import * as React from "react";
import {
AppRegistry,
Text
} from "react-native";
import { StackNavigator } from "react-navigation";
import { TabNavigator } from "react-navigation";
export interface Props {
navigation: any;
}
export interface State {}
export class SettingsScreen extends React.Component<Props, State> {
render() {
return <Text>Innstillinger</Text>
}
}
| Add a new empty settings screen that will contain settings like how far away from the users location that parking lots should be shown in the app. | Add a new empty settings screen that will contain settings like how far away from the users location that parking lots should be shown in the app.
| TypeScript | mit | Archheretic/ParkingLotTrackerMobileApp,Archheretic/ParkingLotTrackerMobileApp,Archheretic/ParkingLotTrackerMobileApp,Archheretic/ParkingLotTrackerMobileApp | ---
+++
@@ -0,0 +1,25 @@
+/**
+ * Created by archheretic on 19.04.17.
+ */
+/**
+ * Created by archheretic on 19.04.17.
+ */
+import * as React from "react";
+import {
+ AppRegistry,
+ Text
+} from "react-native";
+import { StackNavigator } from "react-navigation";
+
+import { TabNavigator } from "react-navigation";
+
+export interface Props {
+ navigation: any;
+}
+
+export interface State {}
+export class SettingsScreen extends React.Component<Props, State> {
+ render() {
+ return <Text>Innstillinger</Text>
+ }
+} |
|
496f25e564a41406e8dade1f59ef15b2f58e7b17 | packages/shared/test/mail/helpers.spec.ts | packages/shared/test/mail/helpers.spec.ts | import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { clearFlag, hasFlag, setFlag, toggleFlag } from '@proton/shared/lib/mail/messages';
describe('hasFlag', () => {
it('should detect correctly that the message has a flag', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_SENT,
} as Partial<Message>;
expect(hasFlag(MESSAGE_FLAGS.FLAG_SENT)(message)).toBeTrue();
});
it('should detect correctly that the message has not a flag', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
} as Partial<Message>;
expect(hasFlag(MESSAGE_FLAGS.FLAG_SENT)(message)).toBeFalsy();
});
});
describe('setFlag', () => {
it('should set the message Flag', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_SENT,
} as Partial<Message>;
const newFlags = setFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message);
expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT);
});
});
describe('clearFlag', () => {
it('should clear the message flag', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT,
} as Partial<Message>;
const newFlags = clearFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message);
expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT);
});
});
describe('toggleFlag', () => {
it('should clear the message flag', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT,
} as Partial<Message>;
const newFlags = toggleFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message);
expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT);
});
});
| Add tests on has, set, clear and toggle flags MAILWEB-3468 | Add tests on has, set, clear and toggle flags
MAILWEB-3468
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -0,0 +1,54 @@
+import { Message } from '@proton/shared/lib/interfaces/mail/Message';
+import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
+import { clearFlag, hasFlag, setFlag, toggleFlag } from '@proton/shared/lib/mail/messages';
+
+describe('hasFlag', () => {
+ it('should detect correctly that the message has a flag', () => {
+ const message = {
+ Flags: MESSAGE_FLAGS.FLAG_SENT,
+ } as Partial<Message>;
+
+ expect(hasFlag(MESSAGE_FLAGS.FLAG_SENT)(message)).toBeTrue();
+ });
+
+ it('should detect correctly that the message has not a flag', () => {
+ const message = {
+ Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
+ } as Partial<Message>;
+
+ expect(hasFlag(MESSAGE_FLAGS.FLAG_SENT)(message)).toBeFalsy();
+ });
+});
+
+describe('setFlag', () => {
+ it('should set the message Flag', () => {
+ const message = {
+ Flags: MESSAGE_FLAGS.FLAG_SENT,
+ } as Partial<Message>;
+
+ const newFlags = setFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message);
+ expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT);
+ });
+});
+
+describe('clearFlag', () => {
+ it('should clear the message flag', () => {
+ const message = {
+ Flags: MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT,
+ } as Partial<Message>;
+
+ const newFlags = clearFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message);
+ expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT);
+ });
+});
+
+describe('toggleFlag', () => {
+ it('should clear the message flag', () => {
+ const message = {
+ Flags: MESSAGE_FLAGS.FLAG_SENT + MESSAGE_FLAGS.FLAG_RECEIPT_SENT,
+ } as Partial<Message>;
+
+ const newFlags = toggleFlag(MESSAGE_FLAGS.FLAG_RECEIPT_SENT)(message);
+ expect(newFlags).toEqual(MESSAGE_FLAGS.FLAG_SENT);
+ });
+}); |
|
5ff5d9588784bd790f67fc25cf5fce7d8a35ed1b | 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 * 2,
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;
| 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: theme.palette.primary.main
},
"&:hover": {
color: theme.palette.primary.main
},
borderBottom: "1px solid transparent",
cursor: "pointer",
display: "inline-block",
fontWeight: theme.typography.fontWeightRegular,
marginRight: theme.spacing.unit * 2,
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;
| Use color defined in theme | Use color defined in theme
| TypeScript | bsd-3-clause | mociepka/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor | ---
+++
@@ -16,10 +16,10 @@
borderBottomColor: theme.palette.primary.main
},
"&:focus": {
- color: "#5AB378"
+ color: theme.palette.primary.main
},
"&:hover": {
- color: "#5AB378"
+ color: theme.palette.primary.main
},
borderBottom: "1px solid transparent",
cursor: "pointer", |
4a1c0a9cdd066d0fc536b14c5c1b2d4f6d9c93a8 | src/migration/1544803202664-RenameEswatiniBackToSwaziland.ts | src/migration/1544803202664-RenameEswatiniBackToSwaziland.ts | import {MigrationInterface, QueryRunner} from "typeorm"
export class RenameEswatiniBackToSwaziland1544803202664 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
// If a Swaziland entity exists, we want to map it to Eswatini
// before renaming Eswatini to Swaziland.
await queryRunner.query(`
UPDATE data_values
SET entityId = (SELECT id FROM entities WHERE name = 'Eswatini')
WHERE entityId = (SELECT id FROM entities WHERE name = 'Swaziland')
`)
await queryRunner.query(`
DELETE FROM entities
WHERE name = 'Swaziland'
`)
await queryRunner.query(`
UPDATE entities
SET name = 'Swaziland'
WHERE name = 'Eswatini'
`)
await queryRunner.query(`
UPDATE country_name_tool_countrydata
SET owid_name = 'Swaziland'
WHERE owid_name = 'Eswatini'
`)
}
public async down(queryRunner: QueryRunner): Promise<any> {
}
}
| Rename 'Eswatini' back to 'Swaziland' | Rename 'Eswatini' back to 'Swaziland'
| TypeScript | mit | OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher | ---
+++
@@ -0,0 +1,32 @@
+import {MigrationInterface, QueryRunner} from "typeorm"
+
+export class RenameEswatiniBackToSwaziland1544803202664 implements MigrationInterface {
+
+ public async up(queryRunner: QueryRunner): Promise<any> {
+ // If a Swaziland entity exists, we want to map it to Eswatini
+ // before renaming Eswatini to Swaziland.
+ await queryRunner.query(`
+ UPDATE data_values
+ SET entityId = (SELECT id FROM entities WHERE name = 'Eswatini')
+ WHERE entityId = (SELECT id FROM entities WHERE name = 'Swaziland')
+ `)
+ await queryRunner.query(`
+ DELETE FROM entities
+ WHERE name = 'Swaziland'
+ `)
+ await queryRunner.query(`
+ UPDATE entities
+ SET name = 'Swaziland'
+ WHERE name = 'Eswatini'
+ `)
+ await queryRunner.query(`
+ UPDATE country_name_tool_countrydata
+ SET owid_name = 'Swaziland'
+ WHERE owid_name = 'Eswatini'
+ `)
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<any> {
+ }
+
+} |
|
327903befe9e06d605ffe9e9b14cd9a586c63b9d | tests/pos/loops/for-06.ts | tests/pos/loops/for-06.ts | function foo():void {
for (var x:number = 1; x < 3; x++) { }
}
function bar():void {
var x:number;
for (x = 1; x < 3; x++) { }
}
| Add another test for for-loop | Add another test for for-loop
| TypeScript | bsd-3-clause | UCSD-PL/RefScript,UCSD-PL/RefScript,UCSD-PL/RefScript | ---
+++
@@ -0,0 +1,8 @@
+function foo():void {
+ for (var x:number = 1; x < 3; x++) { }
+}
+
+function bar():void {
+ var x:number;
+ for (x = 1; x < 3; x++) { }
+} |
|
a47c47a3ed4a6a8172d185aaa9e1037361baee1f | src/Test/Ast/EdgeCases/SpoilerBlock.ts | src/Test/Ast/EdgeCases/SpoilerBlock.ts | import { expect } from 'chai'
import Up from '../../../index'
import { insideDocumentAndParagraph } from '../Helpers'
import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
import { CodeBlockNode } from '../../../SyntaxNodes/CodeBlockNode'
import { ParagraphNode } from '../../../SyntaxNodes/ParagraphNode'
import { LineBlockNode } from '../../../SyntaxNodes/LineBlockNode'
import { Line } from '../../../SyntaxNodes/Line'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
context("A spoiler block indicator does not produce a spoiler block node if it is", () => {
specify('the last line of the document', () => {
expect(Up.toAst('SPOILER:')).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('SPOILER:')
]))
})
specify('immediately followed by non-indented text', () => {
const text = `
Spoiler:
No!
Roses don't glow!
`
expect(Up.toAst('SPOILER:')).to.be.eql(
new DocumentNode([
new LineBlockNode([
new Line([new PlainTextNode('Spoiler:')]),
new Line([new PlainTextNode('No!')]),
new Line([new PlainTextNode("Roses don't glow!")]),
])
]))
})
specify('followed a blank line then a non-indented text', () => {
const text = `
Spoiler:
No!`
expect(Up.toAst('SPOILER:')).to.be.eql(
new DocumentNode([
new ParagraphNode([
new PlainTextNode('Spoiler:')
]),
new ParagraphNode([
new PlainTextNode('No!')
])
]))
})
}) | Add 3 failing spoiler block tests | Add 3 failing spoiler block tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,51 @@
+import { expect } from 'chai'
+import Up from '../../../index'
+import { insideDocumentAndParagraph } from '../Helpers'
+import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
+import { CodeBlockNode } from '../../../SyntaxNodes/CodeBlockNode'
+import { ParagraphNode } from '../../../SyntaxNodes/ParagraphNode'
+import { LineBlockNode } from '../../../SyntaxNodes/LineBlockNode'
+import { Line } from '../../../SyntaxNodes/Line'
+import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
+
+
+context("A spoiler block indicator does not produce a spoiler block node if it is", () => {
+ specify('the last line of the document', () => {
+ expect(Up.toAst('SPOILER:')).to.be.eql(
+ insideDocumentAndParagraph([
+ new PlainTextNode('SPOILER:')
+ ]))
+ })
+
+ specify('immediately followed by non-indented text', () => {
+ const text = `
+Spoiler:
+No!
+Roses don't glow!
+`
+ expect(Up.toAst('SPOILER:')).to.be.eql(
+ new DocumentNode([
+ new LineBlockNode([
+ new Line([new PlainTextNode('Spoiler:')]),
+ new Line([new PlainTextNode('No!')]),
+ new Line([new PlainTextNode("Roses don't glow!")]),
+ ])
+ ]))
+ })
+
+ specify('followed a blank line then a non-indented text', () => {
+ const text = `
+Spoiler:
+
+No!`
+ expect(Up.toAst('SPOILER:')).to.be.eql(
+ new DocumentNode([
+ new ParagraphNode([
+ new PlainTextNode('Spoiler:')
+ ]),
+ new ParagraphNode([
+ new PlainTextNode('No!')
+ ])
+ ]))
+ })
+}) |
|
106ce79244e18f24a353f7715d9e03fdf8198f9e | app/src/ui/cherry-pick/confirm-cherry-pick-abort-dialog.tsx | app/src/ui/cherry-pick/confirm-cherry-pick-abort-dialog.tsx | import * as React from 'react'
import { Dialog, DialogContent, DialogFooter } from '../dialog'
import { Ref } from '../lib/ref'
import { OkCancelButtonGroup } from '../dialog/ok-cancel-button-group'
import { ConfirmAbortStep } from '../../models/cherry-pick'
interface IConfirmCherryPickAbortDialogProps {
readonly step: ConfirmAbortStep
readonly commitCount: number
readonly onReturnToConflicts: (step: ConfirmAbortStep) => void
readonly onConfirmAbort: () => Promise<void>
}
interface IConfirmCherryPickAbortDialogState {
readonly isAborting: boolean
}
export class ConfirmCherryPickAbortDialog extends React.Component<
IConfirmCherryPickAbortDialogProps,
IConfirmCherryPickAbortDialogState
> {
public constructor(props: IConfirmCherryPickAbortDialogProps) {
super(props)
this.state = {
isAborting: false,
}
}
private onSubmit = async () => {
this.setState({
isAborting: true,
})
await this.props.onConfirmAbort()
this.setState({
isAborting: false,
})
}
private onCancel = async () => {
await this.props.onReturnToConflicts(this.props.step)
}
private renderTextContent() {
const { commitCount, step } = this.props
const { targetBranchName } = step.conflictState
const pluralize = commitCount > 1 ? 'commits' : 'commit'
const confirm = (
<p>
{`Are you sure you want to abort cherry picking ${commitCount} ${pluralize}`}
{' onto '}
<Ref>{targetBranchName}</Ref>?
</p>
)
return (
<div className="column-left">
{confirm}
<p>
Aborting this cherry pick will take you back to the original branch
you started on and the conflicts you have already resolved will be
discarded.
</p>
</div>
)
}
public render() {
return (
<Dialog
id="abort-merge-warning"
title={
__DARWIN__ ? 'Confirm Abort Cherry Pick' : 'Confirm abort cherry pick'
}
onDismissed={this.onCancel}
onSubmit={this.onSubmit}
disabled={this.state.isAborting}
type="warning"
>
<DialogContent>{this.renderTextContent()}</DialogContent>
<DialogFooter>
<OkCancelButtonGroup
destructive={true}
okButtonText={
__DARWIN__ ? 'Abort Cherry Pick' : 'Abort cherry pick'
}
/>
</DialogFooter>
</Dialog>
)
}
}
| Create Cherry Pick Confirmation Dialog | Create Cherry Pick Confirmation Dialog
| TypeScript | mit | desktop/desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,say25/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,j-f1/forked-desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop | ---
+++
@@ -0,0 +1,96 @@
+import * as React from 'react'
+
+import { Dialog, DialogContent, DialogFooter } from '../dialog'
+import { Ref } from '../lib/ref'
+import { OkCancelButtonGroup } from '../dialog/ok-cancel-button-group'
+import { ConfirmAbortStep } from '../../models/cherry-pick'
+
+interface IConfirmCherryPickAbortDialogProps {
+ readonly step: ConfirmAbortStep
+ readonly commitCount: number
+
+ readonly onReturnToConflicts: (step: ConfirmAbortStep) => void
+ readonly onConfirmAbort: () => Promise<void>
+}
+
+interface IConfirmCherryPickAbortDialogState {
+ readonly isAborting: boolean
+}
+
+export class ConfirmCherryPickAbortDialog extends React.Component<
+ IConfirmCherryPickAbortDialogProps,
+ IConfirmCherryPickAbortDialogState
+> {
+ public constructor(props: IConfirmCherryPickAbortDialogProps) {
+ super(props)
+ this.state = {
+ isAborting: false,
+ }
+ }
+
+ private onSubmit = async () => {
+ this.setState({
+ isAborting: true,
+ })
+
+ await this.props.onConfirmAbort()
+
+ this.setState({
+ isAborting: false,
+ })
+ }
+
+ private onCancel = async () => {
+ await this.props.onReturnToConflicts(this.props.step)
+ }
+
+ private renderTextContent() {
+ const { commitCount, step } = this.props
+ const { targetBranchName } = step.conflictState
+
+ const pluralize = commitCount > 1 ? 'commits' : 'commit'
+ const confirm = (
+ <p>
+ {`Are you sure you want to abort cherry picking ${commitCount} ${pluralize}`}
+ {' onto '}
+ <Ref>{targetBranchName}</Ref>?
+ </p>
+ )
+
+ return (
+ <div className="column-left">
+ {confirm}
+ <p>
+ Aborting this cherry pick will take you back to the original branch
+ you started on and the conflicts you have already resolved will be
+ discarded.
+ </p>
+ </div>
+ )
+ }
+
+ public render() {
+ return (
+ <Dialog
+ id="abort-merge-warning"
+ title={
+ __DARWIN__ ? 'Confirm Abort Cherry Pick' : 'Confirm abort cherry pick'
+ }
+ onDismissed={this.onCancel}
+ onSubmit={this.onSubmit}
+ disabled={this.state.isAborting}
+ type="warning"
+ >
+ <DialogContent>{this.renderTextContent()}</DialogContent>
+ <DialogFooter>
+ <OkCancelButtonGroup
+ destructive={true}
+ okButtonText={
+ __DARWIN__ ? 'Abort Cherry Pick' : 'Abort cherry pick'
+ }
+ />
+ </DialogFooter>
+ </Dialog>
+ )
+ }
+} |
|
116d75f939011dc7476b56dcfd5015e8ccdda8c1 | test-helpers/matchers.ts | test-helpers/matchers.ts | beforeEach(() => {
jasmine.addMatchers({
toContainText: function() {
return {
compare: function(actual, expectedText) {
let actualText = actual.textContent;
return {
pass: actualText.indexOf(expectedText) > -1,
get message() { return 'Expected ' + actualText + ' to contain ' + expectedText; }
};
}
};
}
});
});
| beforeEach(() => {
jasmine.addMatchers({
toContainText: () => {
return {
compare: (actual, expectedText) => {
let actualText = actual.textContent;
return {
pass: actualText.indexOf(expectedText) > -1,
get message() { return 'Expected ' + actualText + ' to contain ' + expectedText; }
};
}
};
}
});
});
| Refactor matcher: use arrow function | Refactor matcher: use arrow function
| TypeScript | mit | westlab/door-front,antonybudianto/angular2-starter,foxjazz/eveview,foxjazz/memberbase,westlab/door-front,dabcat/myapp-angular2,jasoncbuehler/mohits_awesome_chat_app,jasoncbuehler/mohits_awesome_chat_app,Michael-xxxx/angular2-starter,foxjazz/eveview,westlab/door-front,NiallBrickell/angular2-starter,Michael-xxxx/angular2-starter,dabcat/myapp-angular2,antonybudianto/angular2-starter,NiallBrickell/angular2-starter,foxjazz/eveview,jasoncbuehler/mohits_awesome_chat_app,bitcoinZephyr/bitcoinZephyr.github.io,bitcoinZephyr/bitcoinZephyr.github.io,dabcat/myapp-angular2,antonybudianto/angular2-starter,bitcoinZephyr/bitcoinZephyr.github.io,foxjazz/memberbase,foxjazz/memberbase,NiallBrickell/angular2-starter,Michael-xxxx/angular2-starter | ---
+++
@@ -1,8 +1,8 @@
beforeEach(() => {
jasmine.addMatchers({
- toContainText: function() {
+ toContainText: () => {
return {
- compare: function(actual, expectedText) {
+ compare: (actual, expectedText) => {
let actualText = actual.textContent;
return {
pass: actualText.indexOf(expectedText) > -1, |
656ea7cf9d2db58c7e69c2bd82b420bacc39b280 | tests/test-components/FileItem.spec.tsx | tests/test-components/FileItem.spec.tsx | import {
FileItem,
IFileItemProps
} from '../../src/components/FileItem';
import * as React from 'react';
import 'jest';
import { shallow } from "enzyme";
describe('FileItem', () => {
const props: IFileItemProps = {
topRepoPath: '',
file: {
to: 'some/file/path/file-name'
},
stage: '',
app: null,
refresh: null,
moveFile: () => {},
discardFile: () => {},
moveFileIconClass: () => {},
moveFileIconSelectedClass: 'string',
moveFileTitle: '',
openFile: () => {},
extractFilename: () => {},
contextMenu: () => {},
parseFileExtension: () => {},
parseSelectedFileExtension: () => {},
selectedFile: 0,
updateSelectedFile: () => {},
fileIndex: 0,
selectedStage: '',
selectedDiscardFile: 0,
updateSelectedDiscardFile: () => {},
disableFile: false,
toggleDisableFiles: () => {},
sideBarExpanded: false,
currentTheme: ''
};
describe("#render()", () => {
const component = shallow(<FileItem {...props} />);
it("should display the full path on hover", () => {
expect(
component.find('[title="some/file/path/file-name"]')
).toHaveLength(1);
});
});
}); | Add test file hover file item | Add test file hover file item
| TypeScript | bsd-3-clause | jupyterlab/jupyterlab-git,jupyterlab/jupyterlab-git,jupyterlab/jupyterlab-git | ---
+++
@@ -0,0 +1,49 @@
+import {
+ FileItem,
+ IFileItemProps
+} from '../../src/components/FileItem';
+import * as React from 'react';
+import 'jest';
+import { shallow } from "enzyme";
+
+
+describe('FileItem', () => {
+ const props: IFileItemProps = {
+ topRepoPath: '',
+ file: {
+ to: 'some/file/path/file-name'
+ },
+ stage: '',
+ app: null,
+ refresh: null,
+ moveFile: () => {},
+ discardFile: () => {},
+ moveFileIconClass: () => {},
+ moveFileIconSelectedClass: 'string',
+ moveFileTitle: '',
+ openFile: () => {},
+ extractFilename: () => {},
+ contextMenu: () => {},
+ parseFileExtension: () => {},
+ parseSelectedFileExtension: () => {},
+ selectedFile: 0,
+ updateSelectedFile: () => {},
+ fileIndex: 0,
+ selectedStage: '',
+ selectedDiscardFile: 0,
+ updateSelectedDiscardFile: () => {},
+ disableFile: false,
+ toggleDisableFiles: () => {},
+ sideBarExpanded: false,
+ currentTheme: ''
+ };
+
+ describe("#render()", () => {
+ const component = shallow(<FileItem {...props} />);
+ it("should display the full path on hover", () => {
+ expect(
+ component.find('[title="some/file/path/file-name"]')
+ ).toHaveLength(1);
+ });
+ });
+}); |
|
1db708814222fc07c31c92dc256ef59a04029967 | tests/cases/fourslash/invertedCloduleAfterQuickInfo.ts | tests/cases/fourslash/invertedCloduleAfterQuickInfo.ts | /// <reference path="fourslash.ts" />
////module M {
//// module A {
//// var o;
//// }
//// class A {
//// /**/c
//// }
////}
goTo.marker();
verify.quickInfoExists();
// Bug 823365
// verify.numberOfErrorsInCurrentFile(1); // We get no errors | Add test for inverted clodule | Add test for inverted clodule
| TypeScript | apache-2.0 | hippich/typescript,fdecampredon/jsx-typescript-old-version,popravich/typescript,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts,hippich/typescript,hippich/typescript,popravich/typescript,popravich/typescript | ---
+++
@@ -0,0 +1,15 @@
+/// <reference path="fourslash.ts" />
+
+////module M {
+//// module A {
+//// var o;
+//// }
+//// class A {
+//// /**/c
+//// }
+////}
+
+goTo.marker();
+verify.quickInfoExists();
+// Bug 823365
+// verify.numberOfErrorsInCurrentFile(1); // We get no errors |
|
6d95231c0cc06d62614ef70a9ccdaaa4ee60b942 | spec/flux-reduce-store-spec.ts | spec/flux-reduce-store-spec.ts | import { FluxReduceStore } from '../lib/flux-reduce-store';
import { StoreError } from '../lib/flux-store';
describe('FluxReduceStore', () => {
let store: TestReduceStore;
let dispatcher;
beforeEach(() => {
dispatcher = {
register: () => { },
isDispatching: () => true
}
store = new TestReduceStore(dispatcher);
});
describe('#getState', () => {
it('should return the initial state', () => {
expect(store.getState()).toEqual({ foo: 'initial' });
});
it('should return up-to-date state after modifications', () => {
store.reduceResult = { foo: 'bar' };
store.invokeOnDispatch({ foo: 'bar' });
expect(store.getState()).toEqual({ foo: 'bar' });
});
});
describe('#areEqual', () => {
it('should return true for reference equality', () => {
let a = { foo: 'bar' };
let b = a;
expect(store.areEqual(a, b)).toEqual(true);
});
it('should return false for object equality', () => {
let a = { foo: 'bar' };
let b = { foo: 'bar' };
expect(store.areEqual(a, b)).toEqual(false);
});
});
describe('#_invokeOnDispatch', () => {
it('should throw if reduce returns undefined', () => {
store.reduceResult = undefined;
expect(() => store.invokeOnDispatch(42)).toThrowError(StoreError);
});
it('should take no action if no change has occurred', () => {
let cb = jasmine.createSpy('cb');
store.reduceResult = store.getState();
store.addListener(cb);
store.invokeOnDispatch(store.reduceResult);
expect(cb).not.toHaveBeenCalled();
});
it('should invoke callbacks if change has occurred', () => {
let cb = jasmine.createSpy('cb');
store.reduceResult = { foo: 'changed' };
store.addListener(cb);
store.invokeOnDispatch(store.reduceResult);
expect(cb).toHaveBeenCalled();
});
});
});
class TestReduceStore extends FluxReduceStore<TestObj> {
reduceResult: TestObj;
getInitialState(): TestObj {
return { foo: 'initial' };
}
reduce(state: TestObj, action: any): TestObj {
return this.reduceResult;
}
invokeOnDispatch(payload): void {
this._invokeOnDispatch(payload);
}
}
interface TestObj {
foo: string;
}
| Add tests for reduce store | Add tests for reduce store
| TypeScript | mit | delta62/flux-lite,delta62/flux-lite | ---
+++
@@ -0,0 +1,85 @@
+import { FluxReduceStore } from '../lib/flux-reduce-store';
+import { StoreError } from '../lib/flux-store';
+
+describe('FluxReduceStore', () => {
+ let store: TestReduceStore;
+ let dispatcher;
+
+ beforeEach(() => {
+ dispatcher = {
+ register: () => { },
+ isDispatching: () => true
+ }
+ store = new TestReduceStore(dispatcher);
+ });
+
+ describe('#getState', () => {
+ it('should return the initial state', () => {
+ expect(store.getState()).toEqual({ foo: 'initial' });
+ });
+
+ it('should return up-to-date state after modifications', () => {
+ store.reduceResult = { foo: 'bar' };
+ store.invokeOnDispatch({ foo: 'bar' });
+ expect(store.getState()).toEqual({ foo: 'bar' });
+ });
+ });
+
+ describe('#areEqual', () => {
+ it('should return true for reference equality', () => {
+ let a = { foo: 'bar' };
+ let b = a;
+ expect(store.areEqual(a, b)).toEqual(true);
+ });
+
+ it('should return false for object equality', () => {
+ let a = { foo: 'bar' };
+ let b = { foo: 'bar' };
+ expect(store.areEqual(a, b)).toEqual(false);
+ });
+ });
+
+ describe('#_invokeOnDispatch', () => {
+ it('should throw if reduce returns undefined', () => {
+ store.reduceResult = undefined;
+ expect(() => store.invokeOnDispatch(42)).toThrowError(StoreError);
+ });
+
+ it('should take no action if no change has occurred', () => {
+ let cb = jasmine.createSpy('cb');
+ store.reduceResult = store.getState();
+ store.addListener(cb);
+ store.invokeOnDispatch(store.reduceResult);
+ expect(cb).not.toHaveBeenCalled();
+ });
+
+ it('should invoke callbacks if change has occurred', () => {
+ let cb = jasmine.createSpy('cb');
+ store.reduceResult = { foo: 'changed' };
+ store.addListener(cb);
+ store.invokeOnDispatch(store.reduceResult);
+ expect(cb).toHaveBeenCalled();
+ });
+ });
+});
+
+class TestReduceStore extends FluxReduceStore<TestObj> {
+
+ reduceResult: TestObj;
+
+ getInitialState(): TestObj {
+ return { foo: 'initial' };
+ }
+
+ reduce(state: TestObj, action: any): TestObj {
+ return this.reduceResult;
+ }
+
+ invokeOnDispatch(payload): void {
+ this._invokeOnDispatch(payload);
+ }
+}
+
+interface TestObj {
+ foo: string;
+} |
|
242f0959da49cd5d7a365910cb95cabea9a472ac | src/debug/flutter_test.ts | src/debug/flutter_test.ts | interface Notification {
type: string;
time: number;
}
interface StartNotification extends Notification {
protocolVersion: string;
runnerVersion?: string;
}
interface AllSuitesNotification extends Notification {
count: number;
}
interface SuiteNotification extends Notification {
suite: Suite;
}
interface Suite {
id: number;
platform: string;
path: string;
}
interface TestNotification extends Notification {
test: Test;
}
interface Item {
id: number;
name?: string;
suiteID: number;
metadata: Metadata;
line?: number;
column?: number;
url?: string;
}
interface Test extends Item {
groupIDs: Group[];
}
interface Metadata {
skip: boolean;
skipReason?: string;
}
interface TestDoneNotification extends Notification {
testID: number;
result: string;
skipped: boolean;
hidden: boolean;
}
interface GroupNotification extends Notification {
group: Group;
}
interface Group extends Item {
parentID?: number;
testCount: number;
}
interface TestStartNotification extends Notification {
test: Test;
}
interface TestDoneNotification extends Notification {
testID: number;
result: string;
skipped: boolean;
hidden: boolean;
}
interface DoneNotification extends Notification {
success: boolean;
}
| Create types for `flutter test` | Create types for `flutter test`
See #636.
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -0,0 +1,76 @@
+interface Notification {
+ type: string;
+ time: number;
+}
+
+interface StartNotification extends Notification {
+ protocolVersion: string;
+ runnerVersion?: string;
+}
+interface AllSuitesNotification extends Notification {
+ count: number;
+}
+
+interface SuiteNotification extends Notification {
+ suite: Suite;
+}
+
+interface Suite {
+ id: number;
+ platform: string;
+ path: string;
+}
+
+interface TestNotification extends Notification {
+ test: Test;
+}
+
+interface Item {
+ id: number;
+ name?: string;
+ suiteID: number;
+ metadata: Metadata;
+ line?: number;
+ column?: number;
+ url?: string;
+}
+
+interface Test extends Item {
+ groupIDs: Group[];
+}
+
+interface Metadata {
+ skip: boolean;
+ skipReason?: string;
+}
+
+interface TestDoneNotification extends Notification {
+ testID: number;
+ result: string;
+ skipped: boolean;
+ hidden: boolean;
+}
+
+interface GroupNotification extends Notification {
+ group: Group;
+}
+
+interface Group extends Item {
+ parentID?: number;
+ testCount: number;
+}
+
+interface TestStartNotification extends Notification {
+ test: Test;
+}
+
+interface TestDoneNotification extends Notification {
+ testID: number;
+ result: string;
+ skipped: boolean;
+ hidden: boolean;
+}
+
+interface DoneNotification extends Notification {
+ success: boolean;
+} |
|
29bacf4901012d9a5538963894325f5537592cf2 | cli/clipboard_test.ts | cli/clipboard_test.ts | import clipboard = require('./clipboard');
import testLib = require('../lib/test');
var clip = clipboard.createPlatformClipboard();
testLib.addAsyncTest('get/set/clear', (assert) => {
clip.setData('hello world').then(() => {
return clip.getData();
})
.then((content) => {
assert.equal(content, 'hello world');
return clip.clear();
})
.then(() => {
return clip.getData();
})
.then((content) => {
assert.equal(content, '');
testLib.continueTests();
})
.done();
});
testLib.runTests();
| Add unit test for platform clipboard implementation | Add unit test for platform clipboard implementation
| TypeScript | bsd-3-clause | robertknight/passcards,robertknight/passcards,robertknight/passcards,robertknight/passcards | ---
+++
@@ -0,0 +1,24 @@
+import clipboard = require('./clipboard');
+import testLib = require('../lib/test');
+
+var clip = clipboard.createPlatformClipboard();
+
+testLib.addAsyncTest('get/set/clear', (assert) => {
+ clip.setData('hello world').then(() => {
+ return clip.getData();
+ })
+ .then((content) => {
+ assert.equal(content, 'hello world');
+ return clip.clear();
+ })
+ .then(() => {
+ return clip.getData();
+ })
+ .then((content) => {
+ assert.equal(content, '');
+ testLib.continueTests();
+ })
+ .done();
+});
+
+testLib.runTests(); |
|
ad6df613ec4de34581f875808842927f65d7f0b4 | types/promise-polyfill/promise-polyfill-tests.ts | types/promise-polyfill/promise-polyfill-tests.ts | const prom1 = new Promise<number>((resolve, reject) => {
resolve(12);
});
const prom2 = new Promise<string>((resolve, reject) => {
reject('an error');
}).then((val) => {
console.log(val);
return val;
}).catch((err) => {
console.error(err);
});
Promise.all([prom1, prom2])
.then(result => {
console.log(result);
}, (exception) => console.error(exception))
.catch((ex) => console.error(ex));
| import Promise from "promise-polyfill";
const prom1 = new Promise<number>((resolve, reject) => {
resolve(12);
});
const prom2 = new Promise<string>((resolve, reject) => {
reject('an error');
}).then((val) => {
console.log(val);
return val;
}).catch((err) => {
console.error(err);
});
Promise.all([prom1, prom2])
.then(result => {
console.log(result);
}, (exception) => console.error(exception))
.catch((ex) => console.error(ex));
| Add missing import to test file. | Add missing import to test file.
The tests weren't really testing promise-polyfill at all, they were
testing TypeScript's built-in Promise type.
| TypeScript | mit | borisyankov/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped | ---
+++
@@ -1,3 +1,5 @@
+import Promise from "promise-polyfill";
+
const prom1 = new Promise<number>((resolve, reject) => {
resolve(12);
}); |
a9c4e58b08f6534d16b81205d7f54fa0ec3d9fb3 | app/src/lib/git/checkout-index.ts | app/src/lib/git/checkout-index.ts | import { git } from './core'
import { Repository } from '../../models/repository'
export async function checkoutIndex(repository: Repository, paths: ReadonlyArray<string>) {
if (!paths.length) {
return
}
await git([ 'checkout-index', '-f', '-u', '--stdin', '-z' ], repository.path, 'checkoutIndex', {
stdin: paths.join('\0'),
})
}
| Add a function for updating the working directory from the index | Add a function for updating the working directory from the index
| TypeScript | mit | artivilla/desktop,kactus-io/kactus,desktop/desktop,hjobrien/desktop,hjobrien/desktop,j-f1/forked-desktop,j-f1/forked-desktop,gengjiawen/desktop,say25/desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,gengjiawen/desktop,say25/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,j-f1/forked-desktop,hjobrien/desktop,shiftkey/desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,say25/desktop,gengjiawen/desktop,shiftkey/desktop,kactus-io/kactus,hjobrien/desktop,desktop/desktop,shiftkey/desktop | ---
+++
@@ -0,0 +1,12 @@
+import { git } from './core'
+import { Repository } from '../../models/repository'
+
+export async function checkoutIndex(repository: Repository, paths: ReadonlyArray<string>) {
+ if (!paths.length) {
+ return
+ }
+
+ await git([ 'checkout-index', '-f', '-u', '--stdin', '-z' ], repository.path, 'checkoutIndex', {
+ stdin: paths.join('\0'),
+ })
+} |
|
39a03a39dab15f8c6e954da87f38a38685aa6a9c | src/Test/Ast/Config/Chart.ts | src/Test/Ast/Config/Chart.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 chart conventions', () => {
const up = new Up({
i18n: {
terms: { chart: 'data' }
}
})
it('comes from the "chart" config term', () => {
const text = `
Data:
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 TableNode.Header.Cell([new PlainTextNode('Release Date')])
]), [
new TableNode.Row([
new TableNode.Row.Cell([new PlainTextNode('1995')])
], new TableNode.Header.Cell([new PlainTextNode('Chrono Trigger')])),
new TableNode.Row([
new TableNode.Row.Cell([new PlainTextNode('1999')])
], new TableNode.Header.Cell([new PlainTextNode('Chrono Cross')]))
])
]))
})
it('is case-insensitive even when custom', () => {
const uppercase = `
Data:
Release Date
Chrono Trigger; 1995
Chrono Cross; 1999`
const mixedCase = `
dAtA:
Release Date
Chrono Trigger; 1995
Chrono Cross; 1999`
expect(up.toAst(uppercase)).to.be.eql(up.toAst(mixedCase))
})
})
| Add 2 passing chart tests | Add 2 passing chart tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,57 @@
+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 chart conventions', () => {
+ const up = new Up({
+ i18n: {
+ terms: { chart: 'data' }
+ }
+ })
+
+ it('comes from the "chart" config term', () => {
+ const text = `
+Data:
+
+ 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 TableNode.Header.Cell([new PlainTextNode('Release Date')])
+ ]), [
+ new TableNode.Row([
+ new TableNode.Row.Cell([new PlainTextNode('1995')])
+ ], new TableNode.Header.Cell([new PlainTextNode('Chrono Trigger')])),
+ new TableNode.Row([
+ new TableNode.Row.Cell([new PlainTextNode('1999')])
+ ], new TableNode.Header.Cell([new PlainTextNode('Chrono Cross')]))
+ ])
+ ]))
+ })
+
+ it('is case-insensitive even when custom', () => {
+ const uppercase = `
+Data:
+
+ Release Date
+Chrono Trigger; 1995
+Chrono Cross; 1999`
+
+ const mixedCase = `
+dAtA:
+
+ Release Date
+Chrono Trigger; 1995
+Chrono Cross; 1999`
+
+ expect(up.toAst(uppercase)).to.be.eql(up.toAst(mixedCase))
+ })
+}) |
|
f27a6ec5d64893c1c767aa8dcddeeeabf095f80c | src/modal/container-modal/index.ts | src/modal/container-modal/index.ts | /*
MIT License
Copyright (c) 2017 Temainfo Sistemas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TlContainerModal } from './container-modal';
export * from './container-modal';
@NgModule( {
imports: [
CommonModule,
],
declarations: [
TlContainerModal
],
exports: [
TlContainerModal
],
} )
export class ContainerModalModule {}
| Create an module for container modal. | feat(containermodal): Create an module for container modal.
| TypeScript | mit | TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui | ---
+++
@@ -0,0 +1,39 @@
+/*
+ MIT License
+
+ Copyright (c) 2017 Temainfo Sistemas
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ */
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { TlContainerModal } from './container-modal';
+
+export * from './container-modal';
+
+@NgModule( {
+ imports: [
+ CommonModule,
+ ],
+ declarations: [
+ TlContainerModal
+ ],
+ exports: [
+ TlContainerModal
+ ],
+} )
+export class ContainerModalModule {} |
|
892ed5f3af7e111a958411f47945a80d3025512a | src/constants/editors.ts | src/constants/editors.ts | export const ANDROIDSTUDIO = "ANDROIDSTUDIO";
export const ATOM = "ATOM";
export const CHROME = "CHROME";
export const ECLIPSE = "ECLIPSE";
export const SUBLIMETEXT2 = "SUBLIMETEXT2";
export const SUBLIMETEXT3 = "SUBLIMETEXT3";
export const VIM = "VIM";
export const VSCODE = "VSCODE";
export const XCODE = "XCODE";
| Create a constants folder for each type of editor | Create a constants folder for each type of editor
| TypeScript | bsd-3-clause | wakatime/desktop,wakatime/desktop,wakatime/wakatime-desktop,wakatime/desktop,wakatime/wakatime-desktop | ---
+++
@@ -0,0 +1,9 @@
+export const ANDROIDSTUDIO = "ANDROIDSTUDIO";
+export const ATOM = "ATOM";
+export const CHROME = "CHROME";
+export const ECLIPSE = "ECLIPSE";
+export const SUBLIMETEXT2 = "SUBLIMETEXT2";
+export const SUBLIMETEXT3 = "SUBLIMETEXT3";
+export const VIM = "VIM";
+export const VSCODE = "VSCODE";
+export const XCODE = "XCODE"; |
|
e78496d5ca0999d4c75979c6f889db193e25164d | src/core/dummies.ts | src/core/dummies.ts | import { Dummy, TextDummy, TypesDummy } from '../../test/helpers';
import { VcsAuthenticationInfo, VcsAuthenticationTypes } from './vcs';
export class VcsAuthenticationInfoDummy extends Dummy<VcsAuthenticationInfo> {
private type = new TypesDummy<VcsAuthenticationTypes>([
VcsAuthenticationTypes.BASIC,
VcsAuthenticationTypes.OAUTH2_TOKEN,
]);
private authorizationHeader = new TextDummy('AuthorizationHeader');
private providerName = new TextDummy('provider');
private userName = new TextDummy('username');
private password = new TextDummy('password');
private token = new TextDummy('token');
create(type?: VcsAuthenticationTypes): VcsAuthenticationInfo {
return {
type: type ? type : this.type.create(),
authorizationHeader: this.authorizationHeader.create(),
providerName: this.providerName.create(),
username: this.userName.create(),
password: this.password.create(),
token: this.token.create(),
};
}
}
| Add vcs authentication info dummy | Add vcs authentication info dummy
| TypeScript | mit | seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary | ---
+++
@@ -0,0 +1,26 @@
+import { Dummy, TextDummy, TypesDummy } from '../../test/helpers';
+import { VcsAuthenticationInfo, VcsAuthenticationTypes } from './vcs';
+
+
+export class VcsAuthenticationInfoDummy extends Dummy<VcsAuthenticationInfo> {
+ private type = new TypesDummy<VcsAuthenticationTypes>([
+ VcsAuthenticationTypes.BASIC,
+ VcsAuthenticationTypes.OAUTH2_TOKEN,
+ ]);
+ private authorizationHeader = new TextDummy('AuthorizationHeader');
+ private providerName = new TextDummy('provider');
+ private userName = new TextDummy('username');
+ private password = new TextDummy('password');
+ private token = new TextDummy('token');
+
+ create(type?: VcsAuthenticationTypes): VcsAuthenticationInfo {
+ return {
+ type: type ? type : this.type.create(),
+ authorizationHeader: this.authorizationHeader.create(),
+ providerName: this.providerName.create(),
+ username: this.userName.create(),
+ password: this.password.create(),
+ token: this.token.create(),
+ };
+ }
+} |
|
784fda028e6369bfc2983d6e12bf5eacfe464172 | app/test/unit/promise-test.ts | app/test/unit/promise-test.ts | import { timeout, sleep } from '../../src/lib/promise'
jest.useFakeTimers()
describe('timeout', () => {
it('falls back to the fallback value if promise takes too long', async () => {
const promise = timeout(sleep(1000).then(() => 'foo'), 500, 'bar')
jest.advanceTimersByTime(500)
expect(await promise).toBe('bar')
})
it('returns the promise result if it finishes in time', async () => {
const promise = timeout(Promise.resolve('foo'), 500, 'bar')
jest.advanceTimersByTime(500)
expect(await promise).toBe('foo')
})
})
| Add some smoke tests for timeout() | Add some smoke tests for timeout()
Co-Authored-By: Rafael Oleza <2cf5b502deae2e387c60721eb8244c243cb5c4e1@users.noreply.github.com>
| TypeScript | mit | desktop/desktop,kactus-io/kactus,say25/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,shiftkey/desktop,artivilla/desktop | ---
+++
@@ -0,0 +1,17 @@
+import { timeout, sleep } from '../../src/lib/promise'
+
+jest.useFakeTimers()
+
+describe('timeout', () => {
+ it('falls back to the fallback value if promise takes too long', async () => {
+ const promise = timeout(sleep(1000).then(() => 'foo'), 500, 'bar')
+ jest.advanceTimersByTime(500)
+ expect(await promise).toBe('bar')
+ })
+
+ it('returns the promise result if it finishes in time', async () => {
+ const promise = timeout(Promise.resolve('foo'), 500, 'bar')
+ jest.advanceTimersByTime(500)
+ expect(await promise).toBe('foo')
+ })
+}) |
|
e3289e2218d2566ce56baa50ec0561efd1a6cba0 | packages/shared/lib/api/features.ts | packages/shared/lib/api/features.ts | export const getFeature = (featureCode: string) => ({
url: `core/v4/features/${featureCode}`,
method: 'get',
});
export const updateFeatureValue = (featureCode: string, Value: any) => ({
url: `core/v4/features/${featureCode}/value`,
method: 'put',
data: { Value },
});
| Save BF modal state with API | [BF2020-57] Save BF modal state with API
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -0,0 +1,10 @@
+export const getFeature = (featureCode: string) => ({
+ url: `core/v4/features/${featureCode}`,
+ method: 'get',
+});
+
+export const updateFeatureValue = (featureCode: string, Value: any) => ({
+ url: `core/v4/features/${featureCode}/value`,
+ method: 'put',
+ data: { Value },
+}); |
|
9b01783e2d6cf94ec0aa720b6e1ef6f03c59e1ba | tests/cases/fourslash/renameImportOfExportEquals.ts | tests/cases/fourslash/renameImportOfExportEquals.ts | /// <reference path='fourslash.ts' />
////declare namespace N {
//// export var x: number;
////}
////declare module "mod" {
//// export = N;
////}
////declare module "test" {
//// import * as [|N|] from "mod";
//// export { [|N|] }; // Renaming N here would rename
////}
let ranges = test.ranges()
for (let range of ranges) {
goTo.position(range.start);
verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false);
}
| Add test for renaming accorss modules using export= | Add test for renaming accorss modules using export=
| TypeScript | apache-2.0 | thr0w/Thr0wScript,jeremyepling/TypeScript,synaptek/TypeScript,microsoft/TypeScript,fabioparra/TypeScript,donaldpipowitch/TypeScript,yortus/TypeScript,AbubakerB/TypeScript,alexeagle/TypeScript,SaschaNaz/TypeScript,DLehenbauer/TypeScript,basarat/TypeScript,mmoskal/TypeScript,minestarks/TypeScript,weswigham/TypeScript,nojvek/TypeScript,vilic/TypeScript,weswigham/TypeScript,kpreisser/TypeScript,blakeembrey/TypeScript,plantain-00/TypeScript,samuelhorwitz/typescript,nojvek/TypeScript,samuelhorwitz/typescript,chuckjaz/TypeScript,kimamula/TypeScript,microsoft/TypeScript,yortus/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,DLehenbauer/TypeScript,AbubakerB/TypeScript,mihailik/TypeScript,jwbay/TypeScript,mmoskal/TypeScript,blakeembrey/TypeScript,erikmcc/TypeScript,donaldpipowitch/TypeScript,RyanCavanaugh/TypeScript,Eyas/TypeScript,chuckjaz/TypeScript,mihailik/TypeScript,kitsonk/TypeScript,Microsoft/TypeScript,kpreisser/TypeScript,Eyas/TypeScript,ziacik/TypeScript,AbubakerB/TypeScript,erikmcc/TypeScript,nycdotnet/TypeScript,jeremyepling/TypeScript,DLehenbauer/TypeScript,plantain-00/TypeScript,fabioparra/TypeScript,jwbay/TypeScript,nojvek/TypeScript,thr0w/Thr0wScript,basarat/TypeScript,synaptek/TypeScript,samuelhorwitz/typescript,donaldpipowitch/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,minestarks/TypeScript,kpreisser/TypeScript,thr0w/Thr0wScript,TukekeSoft/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,AbubakerB/TypeScript,Eyas/TypeScript,plantain-00/TypeScript,plantain-00/TypeScript,nycdotnet/TypeScript,basarat/TypeScript,alexeagle/TypeScript,Microsoft/TypeScript,blakeembrey/TypeScript,mmoskal/TypeScript,evgrud/TypeScript,yortus/TypeScript,mmoskal/TypeScript,jwbay/TypeScript,jeremyepling/TypeScript,weswigham/TypeScript,samuelhorwitz/typescript,synaptek/TypeScript,nycdotnet/TypeScript,basarat/TypeScript,kimamula/TypeScript,RyanCavanaugh/TypeScript,evgrud/TypeScript,mihailik/TypeScript,RyanCavanaugh/TypeScript,evgrud/TypeScript,vilic/TypeScript,vilic/TypeScript,minestarks/TypeScript,chuckjaz/TypeScript,SaschaNaz/TypeScript,jwbay/TypeScript,ziacik/TypeScript,vilic/TypeScript,ziacik/TypeScript,chuckjaz/TypeScript,blakeembrey/TypeScript,microsoft/TypeScript,fabioparra/TypeScript,erikmcc/TypeScript,Eyas/TypeScript,erikmcc/TypeScript,thr0w/Thr0wScript,mihailik/TypeScript,yortus/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,nycdotnet/TypeScript,TukekeSoft/TypeScript,ziacik/TypeScript,synaptek/TypeScript,fabioparra/TypeScript,Microsoft/TypeScript,kimamula/TypeScript,evgrud/TypeScript,kimamula/TypeScript | ---
+++
@@ -0,0 +1,18 @@
+/// <reference path='fourslash.ts' />
+
+////declare namespace N {
+//// export var x: number;
+////}
+////declare module "mod" {
+//// export = N;
+////}
+////declare module "test" {
+//// import * as [|N|] from "mod";
+//// export { [|N|] }; // Renaming N here would rename
+////}
+
+let ranges = test.ranges()
+for (let range of ranges) {
+ goTo.position(range.start);
+ verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false);
+} |
|
c5ac39421d664f5db895b7abc674a26a75caf427 | test/property-decorators/max.spec.ts | test/property-decorators/max.spec.ts | import { Max } from './../../src/';
describe('LoggerMethod decorator', () => {
it('should assign a valid value (less than max value)', () => {
class TestClassMaxValue {
@Max(10)
myNumber: number;
}
let testClass = new TestClassMaxValue();
let valueToAssign = 10;
testClass.myNumber = valueToAssign;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
class TestClassMaxValue {
@Max(10)
myNumber: number;
}
let testClass = new TestClassMaxValue();
testClass.myNumber = 20;
expect(testClass.myNumber).toBeNull();
});
it('should protect the previous value when assign an invalid value (greater than max value)', () => {
class TestClassMaxValue {
@Max(10, true)
myNumber: number;
}
let testClass = new TestClassMaxValue();
let valueToAssign = 10;
testClass.myNumber = valueToAssign;
testClass.myNumber = 20;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should throw an error when the value assigned is invalid', () => {
let exceptionMsg = 'Invalid min value assigned!';
class TestClassMaxValue {
@Max(10, false, exceptionMsg)
myNumber: number;
}
let testClass = new TestClassMaxValue();
expect(() => testClass.myNumber = 20).toThrowError(exceptionMsg);
});
}); | Add unit tests for max decorator | Add unit tests for max decorator
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -0,0 +1,52 @@
+import { Max } from './../../src/';
+
+describe('LoggerMethod decorator', () => {
+
+ it('should assign a valid value (less than max value)', () => {
+ class TestClassMaxValue {
+ @Max(10)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMaxValue();
+ let valueToAssign = 10;
+ testClass.myNumber = valueToAssign;
+ expect(testClass.myNumber).toEqual(valueToAssign);
+ });
+
+ it('should assign null to the property (default value, protect = false) without throw an exception', () => {
+ class TestClassMaxValue {
+ @Max(10)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMaxValue();
+ testClass.myNumber = 20;
+ expect(testClass.myNumber).toBeNull();
+ });
+
+ it('should protect the previous value when assign an invalid value (greater than max value)', () => {
+ class TestClassMaxValue {
+ @Max(10, true)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMaxValue();
+ let valueToAssign = 10;
+ testClass.myNumber = valueToAssign;
+ testClass.myNumber = 20;
+ expect(testClass.myNumber).toEqual(valueToAssign);
+ });
+
+ it('should throw an error when the value assigned is invalid', () => {
+ let exceptionMsg = 'Invalid min value assigned!';
+ class TestClassMaxValue {
+ @Max(10, false, exceptionMsg)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMaxValue();
+ expect(() => testClass.myNumber = 20).toThrowError(exceptionMsg);
+ });
+
+}); |
|
2362dd4facb2e2f55a663f1b2b556a1773490eb3 | tests/cases/fourslash/quickInfoJSDocBackticks.ts | tests/cases/fourslash/quickInfoJSDocBackticks.ts | ///<reference path="fourslash.ts" />
// @noEmit: true
// @allowJs: true
// @checkJs: true
// @strict: true
// @Filename: jsdocParseMatchingBackticks.js
/////**
//// * `@param` initial at-param is OK in title comment
//// * @param {string} x hi there `@param`
//// * @param {string} y hi there `@ * param
//// * this is the margin
//// */
////export function f(x, y) {
//// return x/*x*/ + y/*y*/
////}
////f/*f*/
goTo.marker("f");
verify.quickInfoIs("function f(x: string, y: string): string", "`@param` initial at-param is OK in title comment");
goTo.marker("x");
verify.quickInfoIs("(parameter) x: string", "hi there `@param`");
goTo.marker("y");
verify.quickInfoIs("(parameter) y: string", "hi there `@ * param\nthis is the margin");
| Add fourslash test of jsdoc backtick parsing | Add fourslash test of jsdoc backtick parsing
| TypeScript | apache-2.0 | Microsoft/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,microsoft/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,microsoft/TypeScript,kitsonk/TypeScript,weswigham/TypeScript,minestarks/TypeScript,kpreisser/TypeScript,Microsoft/TypeScript,Microsoft/TypeScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,alexeagle/TypeScript,weswigham/TypeScript,kpreisser/TypeScript | ---
+++
@@ -0,0 +1,25 @@
+///<reference path="fourslash.ts" />
+
+// @noEmit: true
+// @allowJs: true
+// @checkJs: true
+// @strict: true
+// @Filename: jsdocParseMatchingBackticks.js
+
+/////**
+//// * `@param` initial at-param is OK in title comment
+//// * @param {string} x hi there `@param`
+//// * @param {string} y hi there `@ * param
+//// * this is the margin
+//// */
+////export function f(x, y) {
+//// return x/*x*/ + y/*y*/
+////}
+////f/*f*/
+
+goTo.marker("f");
+verify.quickInfoIs("function f(x: string, y: string): string", "`@param` initial at-param is OK in title comment");
+goTo.marker("x");
+verify.quickInfoIs("(parameter) x: string", "hi there `@param`");
+goTo.marker("y");
+verify.quickInfoIs("(parameter) y: string", "hi there `@ * param\nthis is the margin"); |
|
97957dff5b8b36da3c63a5b5c600d9a68b98888a | src/crawlers/elpaisbrasil.ts | src/crawlers/elpaisbrasil.ts | import * as cheerio from 'cheerio';
import * as prettyjson from 'prettyjson';
import * as requestPromise from 'request-promise';
import { ICrawlerInfo } from './../types/crawler-info';
const url: string = 'https://brasil.elpais.com/';
export let getNews = html => {
let $ = cheerio.load(html);
let arr = [];
$('.articulo-titulo a')
.each((index, item) => arr.push({
title: $(item).text(),
}));
return arr;
};
const crawlerInfo: ICrawlerInfo = {
get: () => {
requestPromise(url)
.then(getNews)
.then(prettyjson.render)
.then(console.log);
},
url,
};
export default crawlerInfo;
| Add El País Brasil website | Add El País Brasil website
| TypeScript | mit | mateusduraes/crawler-br-news,mateusduraes/crawler-br-news | ---
+++
@@ -0,0 +1,28 @@
+import * as cheerio from 'cheerio';
+import * as prettyjson from 'prettyjson';
+import * as requestPromise from 'request-promise';
+import { ICrawlerInfo } from './../types/crawler-info';
+
+const url: string = 'https://brasil.elpais.com/';
+
+export let getNews = html => {
+ let $ = cheerio.load(html);
+ let arr = [];
+ $('.articulo-titulo a')
+ .each((index, item) => arr.push({
+ title: $(item).text(),
+ }));
+ return arr;
+};
+
+const crawlerInfo: ICrawlerInfo = {
+ get: () => {
+ requestPromise(url)
+ .then(getNews)
+ .then(prettyjson.render)
+ .then(console.log);
+ },
+ url,
+};
+
+export default crawlerInfo; |
|
e445e012c4fe9a3673204988491266a41d56fd7a | tests/cases/fourslash/syntacticClassificationsDocComment4.ts | tests/cases/fourslash/syntacticClassificationsDocComment4.ts | /// <reference path="fourslash.ts"/>
//// /** @param {number} p1 */
//// function foo(p1) {}
var c = classification;
verify.syntacticClassificationsAre(
c.comment("/** "),
c.punctuation("@"),
c.docCommentTagName("param"),
c.comment(" "),
c.punctuation("{"),
c.keyword("number"),
c.punctuation("}"),
c.comment(" "),
c.parameterName("p1"),
c.comment(" */"),
c.keyword("function"),
c.identifier("foo"),
c.punctuation("("),
c.parameterName("p1"),
c.punctuation(")"),
c.punctuation("{"),
c.punctuation("}"));
| Add test for jsdoc syntactic classification for function declaration | Add test for jsdoc syntactic classification for function declaration
| TypeScript | apache-2.0 | jeremyepling/TypeScript,Eyas/TypeScript,weswigham/TypeScript,chuckjaz/TypeScript,vilic/TypeScript,chuckjaz/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,kpreisser/TypeScript,Microsoft/TypeScript,mihailik/TypeScript,basarat/TypeScript,microsoft/TypeScript,DLehenbauer/TypeScript,erikmcc/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,jeremyepling/TypeScript,jwbay/TypeScript,TukekeSoft/TypeScript,basarat/TypeScript,jwbay/TypeScript,weswigham/TypeScript,RyanCavanaugh/TypeScript,erikmcc/TypeScript,alexeagle/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,Microsoft/TypeScript,thr0w/Thr0wScript,Eyas/TypeScript,jwbay/TypeScript,donaldpipowitch/TypeScript,alexeagle/TypeScript,mihailik/TypeScript,jwbay/TypeScript,Eyas/TypeScript,microsoft/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,synaptek/TypeScript,minestarks/TypeScript,synaptek/TypeScript,minestarks/TypeScript,TukekeSoft/TypeScript,erikmcc/TypeScript,chuckjaz/TypeScript,thr0w/Thr0wScript,Eyas/TypeScript,weswigham/TypeScript,chuckjaz/TypeScript,kpreisser/TypeScript,DLehenbauer/TypeScript,donaldpipowitch/TypeScript,kpreisser/TypeScript,vilic/TypeScript,DLehenbauer/TypeScript,SaschaNaz/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,synaptek/TypeScript,basarat/TypeScript,TukekeSoft/TypeScript,vilic/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,mihailik/TypeScript,thr0w/Thr0wScript,basarat/TypeScript,thr0w/Thr0wScript,SaschaNaz/TypeScript,vilic/TypeScript,mihailik/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,microsoft/TypeScript,erikmcc/TypeScript,jeremyepling/TypeScript | ---
+++
@@ -0,0 +1,24 @@
+/// <reference path="fourslash.ts"/>
+
+//// /** @param {number} p1 */
+//// function foo(p1) {}
+
+var c = classification;
+verify.syntacticClassificationsAre(
+ c.comment("/** "),
+ c.punctuation("@"),
+ c.docCommentTagName("param"),
+ c.comment(" "),
+ c.punctuation("{"),
+ c.keyword("number"),
+ c.punctuation("}"),
+ c.comment(" "),
+ c.parameterName("p1"),
+ c.comment(" */"),
+ c.keyword("function"),
+ c.identifier("foo"),
+ c.punctuation("("),
+ c.parameterName("p1"),
+ c.punctuation(")"),
+ c.punctuation("{"),
+ c.punctuation("}")); |
|
407c8df39bd4cb49d0c9982fbdf2f0c404392a72 | test/browser/importer.spec.ts | test/browser/importer.spec.ts | import {Importer} from "../../app/import/importer";
import {Parser, ParserResult} from "../../app/import/parser";
import {Observable} from "rxjs/Observable";
/**
* @author Daniel de Oliveira
*/
export function main() {
let mockReader;
let mockParser;
let importer;
beforeEach(()=>{
mockReader = jasmine.createSpyObj('reader',['read']);
mockReader.read.and.callFake(function() {return Promise.resolve();});
mockParser = jasmine.createSpyObj('parser',['parse']);
mockParser.parse.and.callFake(function() {return Observable.create(observer => {
observer.next({
document: {
resource: {type:"object",id:"abc",relations:{}}
},
messages: []
});
observer.complete();
})});
let mockDatastore = jasmine.createSpyObj('datastore', ['create']);
let mockValidator = jasmine.createSpyObj('validator', ['validate']);
mockValidator.validate.and.callFake(function() {return Promise.resolve();});
importer = new Importer(mockDatastore,mockValidator);
});
describe('Importer', () => {
it('should do something',
function (done) {
importer.importResources(mockReader,mockParser)
.then(()=>{
done();
})
.catch(()=>{
fail();
done();
})
}
);
})
} | Set up importer test harness. | Set up importer test harness.
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -0,0 +1,48 @@
+import {Importer} from "../../app/import/importer";
+import {Parser, ParserResult} from "../../app/import/parser";
+import {Observable} from "rxjs/Observable";
+
+
+/**
+ * @author Daniel de Oliveira
+ */
+export function main() {
+
+ let mockReader;
+ let mockParser;
+ let importer;
+
+ beforeEach(()=>{
+ mockReader = jasmine.createSpyObj('reader',['read']);
+ mockReader.read.and.callFake(function() {return Promise.resolve();});
+ mockParser = jasmine.createSpyObj('parser',['parse']);
+ mockParser.parse.and.callFake(function() {return Observable.create(observer => {
+ observer.next({
+ document: {
+ resource: {type:"object",id:"abc",relations:{}}
+ },
+ messages: []
+ });
+ observer.complete();
+ })});
+ let mockDatastore = jasmine.createSpyObj('datastore', ['create']);
+ let mockValidator = jasmine.createSpyObj('validator', ['validate']);
+ mockValidator.validate.and.callFake(function() {return Promise.resolve();});
+ importer = new Importer(mockDatastore,mockValidator);
+ });
+
+ describe('Importer', () => {
+ it('should do something',
+ function (done) {
+ importer.importResources(mockReader,mockParser)
+ .then(()=>{
+ done();
+ })
+ .catch(()=>{
+ fail();
+ done();
+ })
+ }
+ );
+ })
+} |
|
3dae6624fa5dccdb8785fd0bfb13dcb58f0fbb4a | packages/web-client/tests/unit/models/workflow/workflow-postable-test.ts | packages/web-client/tests/unit/models/workflow/workflow-postable-test.ts | import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { Workflow } from '@cardstack/web-client/models/workflow';
import { WorkflowPostable } from '@cardstack/web-client/models/workflow/workflow-postable';
import { Participant } from '../../../../app/models/workflow/workflow-postable';
module('Unit | WorkflowPostable model', function (hooks) {
setupTest(hooks);
class ConcreteWorkflow extends Workflow {}
let participant: Participant;
hooks.beforeEach(function () {
participant = { name: 'cardbot' };
});
test('isComplete starts off as false', function (assert) {
let subject = new WorkflowPostable(participant);
assert.equal(subject.isComplete, false);
});
test('passing includeIf sets up method', function (assert) {
let subject = new WorkflowPostable(participant);
assert.ok(!subject.includeIf);
subject = new WorkflowPostable(participant, () => {
return true;
});
assert.ok(subject.includeIf);
assert.ok(subject.includeIf!());
});
test('passed participant is available as property', function (assert) {
let subject = new WorkflowPostable(participant);
assert.strictEqual(subject.author, participant);
});
test('setWorkflow does exactly that', function (assert) {
let workflow = new ConcreteWorkflow({});
let subject = new WorkflowPostable(participant);
subject.setWorkflow(workflow);
assert.strictEqual(subject.workflow, workflow);
});
});
| Add unit test coverage for WorkflowPostable | Add unit test coverage for WorkflowPostable
| TypeScript | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack | ---
+++
@@ -0,0 +1,43 @@
+import { module, test } from 'qunit';
+import { setupTest } from 'ember-qunit';
+import { Workflow } from '@cardstack/web-client/models/workflow';
+import { WorkflowPostable } from '@cardstack/web-client/models/workflow/workflow-postable';
+import { Participant } from '../../../../app/models/workflow/workflow-postable';
+
+module('Unit | WorkflowPostable model', function (hooks) {
+ setupTest(hooks);
+
+ class ConcreteWorkflow extends Workflow {}
+
+ let participant: Participant;
+ hooks.beforeEach(function () {
+ participant = { name: 'cardbot' };
+ });
+
+ test('isComplete starts off as false', function (assert) {
+ let subject = new WorkflowPostable(participant);
+ assert.equal(subject.isComplete, false);
+ });
+
+ test('passing includeIf sets up method', function (assert) {
+ let subject = new WorkflowPostable(participant);
+ assert.ok(!subject.includeIf);
+ subject = new WorkflowPostable(participant, () => {
+ return true;
+ });
+ assert.ok(subject.includeIf);
+ assert.ok(subject.includeIf!());
+ });
+
+ test('passed participant is available as property', function (assert) {
+ let subject = new WorkflowPostable(participant);
+ assert.strictEqual(subject.author, participant);
+ });
+
+ test('setWorkflow does exactly that', function (assert) {
+ let workflow = new ConcreteWorkflow({});
+ let subject = new WorkflowPostable(participant);
+ subject.setWorkflow(workflow);
+ assert.strictEqual(subject.workflow, workflow);
+ });
+}); |
|
afcc5879000f3f56304f6d251cd16ec9bb006bc8 | src/pages/settings/settings.spec.ts | src/pages/settings/settings.spec.ts | import { TestBed, inject, async, ComponentFixture } from '@angular/core/testing';
import { SettingsPage } from './settings';
import { App, Config, Form, IonicModule, Keyboard, Haptic, GestureController, DomController, NavController, Platform, NavParams } from 'ionic-angular';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SettingService } from '../../providers/setting-service';
import { ConfigMock, PlatformMock, NavParamsMock, AppMock, StorageMock } from '../../mocks/mocks';
import { Storage } from '@ionic/storage';
describe('Page: Settings', () => {
let fixture: ComponentFixture<SettingsPage> = null;
let page: SettingsPage = null;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SettingsPage],
providers: [
App, DomController, Form, Keyboard, NavController, SettingService, Haptic, GestureController,
{ provide: App, useClass: AppMock },
{ provide: Config, useClass: ConfigMock },
{ provide: Platform, useClass: PlatformMock },
{ provide: NavParams, useClass: NavParamsMock },
{ provide: Storage, useClass: StorageMock }
],
imports: [FormsModule, IonicModule, ReactiveFormsModule]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(SettingsPage);
page = fixture.componentInstance;
fixture.detectChanges();
});
}));
afterEach(() => {
fixture.destroy();
});
it('SettingService called when toggling show rest url field', inject([SettingService], (settingService: SettingService) => {
spyOn(settingService, 'setShowRestUrlField').and.callThrough();
page.isShowRestUrlField = true;
page.notify();
expect(settingService.setShowRestUrlField).toHaveBeenCalledWith(true);
page.isShowRestUrlField = false;
page.notify();
expect(settingService.setShowRestUrlField).toHaveBeenCalledWith(false);
}));
it('SettingService is initialized correctly', async(inject([SettingService], (settingService: SettingService) => {
settingService.isShowRestUrlField().subscribe(val => expect(page.isShowRestUrlField).toBe(val));
})));
});
| Add unit test for setting page | Add unit test for setting page
| TypeScript | mit | IMSmobile/app,IMSmobile/app,IMSmobile/app,IMSmobile/app | ---
+++
@@ -0,0 +1,55 @@
+import { TestBed, inject, async, ComponentFixture } from '@angular/core/testing';
+import { SettingsPage } from './settings';
+import { App, Config, Form, IonicModule, Keyboard, Haptic, GestureController, DomController, NavController, Platform, NavParams } from 'ionic-angular';
+import { FormsModule, ReactiveFormsModule } from '@angular/forms';
+import { SettingService } from '../../providers/setting-service';
+import { ConfigMock, PlatformMock, NavParamsMock, AppMock, StorageMock } from '../../mocks/mocks';
+import { Storage } from '@ionic/storage';
+
+
+describe('Page: Settings', () => {
+
+ let fixture: ComponentFixture<SettingsPage> = null;
+ let page: SettingsPage = null;
+
+ beforeEach(async(() => {
+
+ TestBed.configureTestingModule({
+
+ declarations: [SettingsPage],
+
+ providers: [
+ App, DomController, Form, Keyboard, NavController, SettingService, Haptic, GestureController,
+ { provide: App, useClass: AppMock },
+ { provide: Config, useClass: ConfigMock },
+ { provide: Platform, useClass: PlatformMock },
+ { provide: NavParams, useClass: NavParamsMock },
+ { provide: Storage, useClass: StorageMock }
+ ],
+ imports: [FormsModule, IonicModule, ReactiveFormsModule]
+ }).compileComponents().then(() => {
+ fixture = TestBed.createComponent(SettingsPage);
+ page = fixture.componentInstance;
+ fixture.detectChanges();
+ });
+ }));
+
+ afterEach(() => {
+ fixture.destroy();
+ });
+
+ it('SettingService called when toggling show rest url field', inject([SettingService], (settingService: SettingService) => {
+ spyOn(settingService, 'setShowRestUrlField').and.callThrough();
+ page.isShowRestUrlField = true;
+ page.notify();
+ expect(settingService.setShowRestUrlField).toHaveBeenCalledWith(true);
+
+ page.isShowRestUrlField = false;
+ page.notify();
+ expect(settingService.setShowRestUrlField).toHaveBeenCalledWith(false);
+ }));
+
+ it('SettingService is initialized correctly', async(inject([SettingService], (settingService: SettingService) => {
+ settingService.isShowRestUrlField().subscribe(val => expect(page.isShowRestUrlField).toBe(val));
+ })));
+}); |
|
7ca5f08331c471d91b5c8f2bb85d81a9342e7110 | src/Test/Ast/TableOfContents.ts | src/Test/Ast/TableOfContents.ts | import { expect } from 'chai'
import Up from '../../index'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
/*import { StressNode } from '../../SyntaxNodes/StressNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'*/
import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
context("When the 'createTableOfContents' config setting isn't specified as true", () => {
specify("the document isn't given a table of contents", () => {
const markup = `
I enjoy apples
==============`
const tableOfContents: DocumentNode.TableOfContents = undefined
expect(Up.toAst(markup)).to.be.eql(
new DocumentNode([
new HeadingNode([new PlainTextNode('I enjoy apples')], 1),
], tableOfContents))
})
})
| Add passing table of contents test | Add passing table of contents test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,24 @@
+import { expect } from 'chai'
+import Up from '../../index'
+import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+/*import { StressNode } from '../../SyntaxNodes/StressNode'
+import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
+import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'*/
+import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
+
+
+context("When the 'createTableOfContents' config setting isn't specified as true", () => {
+ specify("the document isn't given a table of contents", () => {
+ const markup = `
+I enjoy apples
+==============`
+
+ const tableOfContents: DocumentNode.TableOfContents = undefined
+
+ expect(Up.toAst(markup)).to.be.eql(
+ new DocumentNode([
+ new HeadingNode([new PlainTextNode('I enjoy apples')], 1),
+ ], tableOfContents))
+ })
+}) |
|
89873454861b8941bd3e63d13fb670a3fece64a4 | Server/config/vorlon.logconfig.ts | Server/config/vorlon.logconfig.ts | import fs = require("fs");
import path = require("path");
export module VORLON {
export class LogConfig {
public vorlonLogFile: string;
public exceptionsLogFile: string;
public enableConsole: boolean;
public level: string;
public constructor() {
var configurationFile: string = fs.readFileSync(path.join(__dirname, "../config.json"), "utf8");
var configurationString = configurationFile.toString().replace(/^\uFEFF/, '');
var configuration = JSON.parse(configurationString);
if (configuration.logs) {
var logConfig = configuration.logs;
var filePath = logConfig.filePath ? logConfig.filePath : path.join(__dirname, "../");
var vorlonjsFile = logConfig.vorlonLogFileName ? logConfig.vorlonLogFileName : "vorlonjs.log";
var exceptionFile = logConfig.exceptionsLogFileName ? logConfig.exceptionsLogFileName : "exceptions.log";
this.vorlonLogFile = path.join(filePath, vorlonjsFile);
this.exceptionsLogFile = path.join(filePath, exceptionFile);
this.enableConsole = logConfig.enableConsole;
this.level = logConfig.level ? logConfig.level : "info";
}
else {
this.vorlonLogFile = path.join(__dirname, "../vorlonjs.log");
this.exceptionsLogFile = path.join(__dirname, "../exceptions.log");
this.enableConsole = true;
this.level = "info";
}
}
}
} | import fs = require("fs");
import path = require("path");
export module VORLON {
export class LogConfig {
public vorlonLogFile: string;
public exceptionsLogFile: string;
public enableConsole: boolean;
public level: string;
public constructor() {
var configurationFile: string = fs.readFileSync(path.join(__dirname, "../config.json"), "utf8");
var configurationString = configurationFile.toString().replace(/^\uFEFF/, '');
var configuration = JSON.parse(configurationString);
if (configuration.logs) {
var logConfig = configuration.logs;
var filePath = logConfig.filePath ? logConfig.filePath : path.join(__dirname, "../");
var vorlonjsFile = logConfig.vorlonLogFileName ? logConfig.vorlonLogFileName : "vorlonjs.log";
var exceptionFile = logConfig.exceptionsLogFileName ? logConfig.exceptionsLogFileName : "exceptions.log";
this.vorlonLogFile = path.join(filePath, vorlonjsFile);
this.exceptionsLogFile = path.join(filePath, exceptionFile);
this.enableConsole = logConfig.enableConsole;
this.level = logConfig.level ? logConfig.level : "warn";
}
else {
this.vorlonLogFile = path.join(__dirname, "../vorlonjs.log");
this.exceptionsLogFile = path.join(__dirname, "../exceptions.log");
this.enableConsole = true;
this.level = "warn";
}
}
}
} | Change log level to warn by default | Change log level to warn by default
| TypeScript | mit | lahloumehdi/Vorlonjs,RaphaelLichan/Vorlonjs,gleborgne/Vorlonjs,SpencerRothschild/Vorlonjs,RaphaelLichan/Vorlonjs,SpencerRothschild/Vorlonjs,sayar/Vorlonjs,sayar/Vorlonjs,gleborgne/Vorlonjs,sayar/Vorlonjs,gleborgne/Vorlonjs,SpencerRothschild/Vorlonjs,lahloumehdi/Vorlonjs,lahloumehdi/Vorlonjs,SpencerRothschild/Vorlonjs,RaphaelLichan/Vorlonjs,lahloumehdi/Vorlonjs,sayar/Vorlonjs,RaphaelLichan/Vorlonjs,gleborgne/Vorlonjs | ---
+++
@@ -21,13 +21,13 @@
this.vorlonLogFile = path.join(filePath, vorlonjsFile);
this.exceptionsLogFile = path.join(filePath, exceptionFile);
this.enableConsole = logConfig.enableConsole;
- this.level = logConfig.level ? logConfig.level : "info";
+ this.level = logConfig.level ? logConfig.level : "warn";
}
else {
this.vorlonLogFile = path.join(__dirname, "../vorlonjs.log");
this.exceptionsLogFile = path.join(__dirname, "../exceptions.log");
this.enableConsole = true;
- this.level = "info";
+ this.level = "warn";
}
}
} |
6c223cc2cfd8961f29cca94db368ee4f6c36abe4 | src/workspacefolder-quickpick.ts | src/workspacefolder-quickpick.ts | import * as vscode from 'vscode';
class WorkspaceFolderQuickPickItem implements vscode.QuickPickItem {
description = "";
detail = "";
public get label(): string {
return this.folder.name;
}
constructor(public folder: vscode.WorkspaceFolder) {}
}
export interface WorkspaceFolderQuickPickOptions {
placeHolder?: string;
}
export async function workspaceFolderQuickPick(options: WorkspaceFolderQuickPickOptions = {}): Promise<vscode.WorkspaceFolder> {
if (vscode.workspace.workspaceFolders.length === 0)
return undefined;
if (vscode.workspace.workspaceFolders.length === 1)
return vscode.workspace.workspaceFolders[0];
let picks = vscode.workspace.workspaceFolders.map((f) => new WorkspaceFolderQuickPickItem(f));
let folderPick = await vscode.window.showQuickPick(picks, {
placeHolder: options.placeHolder
});
if (!folderPick)
return undefined;
return folderPick.folder;
} | Add helper to quick pick workspace folder | Add helper to quick pick workspace folder
| TypeScript | mpl-2.0 | hashicorp/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform | ---
+++
@@ -0,0 +1,33 @@
+import * as vscode from 'vscode';
+
+class WorkspaceFolderQuickPickItem implements vscode.QuickPickItem {
+ description = "";
+ detail = "";
+
+ public get label(): string {
+ return this.folder.name;
+ }
+
+ constructor(public folder: vscode.WorkspaceFolder) {}
+}
+
+export interface WorkspaceFolderQuickPickOptions {
+ placeHolder?: string;
+}
+
+export async function workspaceFolderQuickPick(options: WorkspaceFolderQuickPickOptions = {}): Promise<vscode.WorkspaceFolder> {
+ if (vscode.workspace.workspaceFolders.length === 0)
+ return undefined;
+
+ if (vscode.workspace.workspaceFolders.length === 1)
+ return vscode.workspace.workspaceFolders[0];
+
+ let picks = vscode.workspace.workspaceFolders.map((f) => new WorkspaceFolderQuickPickItem(f));
+ let folderPick = await vscode.window.showQuickPick(picks, {
+ placeHolder: options.placeHolder
+ });
+ if (!folderPick)
+ return undefined;
+
+ return folderPick.folder;
+} |
|
5ba416897c98c20ae2b15e92a121032949496de5 | src/public/search/SearchProviderInterfaces.ts | src/public/search/SearchProviderInterfaces.ts | /*********************************************************
* Copyright (c) 2018 datavisyn GmbH, http://datavisyn.io
*
* This file is property of datavisyn.
* Code and any other files associated with this project
* may not be copied and/or distributed without permission.
*
* Proprietary and confidential. No warranty.
*
*********************************************************/
import {IPluginDesc} from 'phovea_core/src/plugin';
import {IDType} from 'phovea_core/src/idtype';
/**
* a search result
*/
export interface IResult {
/**
* id of this result
*/
readonly _id: number;
/**
* the name for _id
*/
readonly id: string;
/**
* label of this result
*/
readonly text: string;
readonly idType?: IDType;
}
/**
* a search provider extension provides
*/
export interface ISearchProvider {
/**
* performs the search
* @param {string} query the query to search can be ''
* @param {number} page the page starting with 0 = first page
* @param {number} pageSize the size of a page
* @returns {Promise<{ more: boolean, items: IResult[] }>} list of results along with a hint whether more are available
*/
search(query: string, page: number, pageSize: number): Promise<{ more: boolean, items: IResult[] }>;
/**
* validates the given fully queries and returns the matching result subsets
* @param {string[]} query the list of tokens to validate
* @returns {Promise<IResult[]>} a list of valid results
*/
validate(query: string[]): Promise<IResult[]>;
/**
* returns the html to be used for showing this result
* @param {IResult} item
* @param {HTMLElement} node
* @param {string} mode the kind of formatting that should be done for a result in the dropdown or for an selected item
* @param {string} currentSearchQuery optional the current search query as a regular expression in which the first group is the matched subset
* @returns {string} the formatted html text
*/
format?(item: IResult, node: HTMLElement, mode: 'result'|'selection', currentSearchQuery?: RegExp): string;
produces?(idType: IDType): boolean;
}
/**
* additional plugin description fields as defined in phovea.js
*/
export interface ISearchProviderDesc extends IPluginDesc {
/**
* id type this provider returns
*/
idType: string;
/**
* name of this search provider (used for the checkbox)
*/
name: string;
}
| Move `IResult`, `ISearchProvider`, and `ISearchProviderDesc` | Move `IResult`, `ISearchProvider`, and `ISearchProviderDesc`
to new folder _src/public/search/_ in tdp_core
| TypeScript | bsd-3-clause | datavisyn/tdp_core,datavisyn/tdp_core,datavisyn/tdp_core,datavisyn/tdp_core | ---
+++
@@ -0,0 +1,82 @@
+/*********************************************************
+ * Copyright (c) 2018 datavisyn GmbH, http://datavisyn.io
+ *
+ * This file is property of datavisyn.
+ * Code and any other files associated with this project
+ * may not be copied and/or distributed without permission.
+ *
+ * Proprietary and confidential. No warranty.
+ *
+ *********************************************************/
+
+
+import {IPluginDesc} from 'phovea_core/src/plugin';
+import {IDType} from 'phovea_core/src/idtype';
+
+/**
+ * a search result
+ */
+export interface IResult {
+ /**
+ * id of this result
+ */
+ readonly _id: number;
+ /**
+ * the name for _id
+ */
+ readonly id: string;
+ /**
+ * label of this result
+ */
+ readonly text: string;
+
+ readonly idType?: IDType;
+}
+
+/**
+ * a search provider extension provides
+ */
+export interface ISearchProvider {
+ /**
+ * performs the search
+ * @param {string} query the query to search can be ''
+ * @param {number} page the page starting with 0 = first page
+ * @param {number} pageSize the size of a page
+ * @returns {Promise<{ more: boolean, items: IResult[] }>} list of results along with a hint whether more are available
+ */
+ search(query: string, page: number, pageSize: number): Promise<{ more: boolean, items: IResult[] }>;
+
+ /**
+ * validates the given fully queries and returns the matching result subsets
+ * @param {string[]} query the list of tokens to validate
+ * @returns {Promise<IResult[]>} a list of valid results
+ */
+ validate(query: string[]): Promise<IResult[]>;
+
+ /**
+ * returns the html to be used for showing this result
+ * @param {IResult} item
+ * @param {HTMLElement} node
+ * @param {string} mode the kind of formatting that should be done for a result in the dropdown or for an selected item
+ * @param {string} currentSearchQuery optional the current search query as a regular expression in which the first group is the matched subset
+ * @returns {string} the formatted html text
+ */
+ format?(item: IResult, node: HTMLElement, mode: 'result'|'selection', currentSearchQuery?: RegExp): string;
+
+ produces?(idType: IDType): boolean;
+}
+
+/**
+ * additional plugin description fields as defined in phovea.js
+ */
+export interface ISearchProviderDesc extends IPluginDesc {
+ /**
+ * id type this provider returns
+ */
+ idType: string;
+
+ /**
+ * name of this search provider (used for the checkbox)
+ */
+ name: string;
+} |
|
b761c62095a0f44ddf70ea984b953263123b1df3 | app/src/ui/lib/escape-regex.ts | app/src/ui/lib/escape-regex.ts | /**
* Converts the input string by escaping characters that have special meaning in
* regular expressions.
*
* From https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
*/
export function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
}
| Add a utility function for escaping regexes | Add a utility function for escaping regexes
| TypeScript | mit | BugTesterTest/desktops,desktop/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,hjobrien/desktop,gengjiawen/desktop,shiftkey/desktop,hjobrien/desktop,artivilla/desktop,say25/desktop,desktop/desktop,BugTesterTest/desktops,desktop/desktop,kactus-io/kactus,say25/desktop,say25/desktop,shiftkey/desktop,hjobrien/desktop,gengjiawen/desktop,artivilla/desktop,hjobrien/desktop,desktop/desktop,kactus-io/kactus,BugTesterTest/desktops,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,gengjiawen/desktop,kactus-io/kactus,gengjiawen/desktop,j-f1/forked-desktop,shiftkey/desktop,BugTesterTest/desktops,artivilla/desktop,j-f1/forked-desktop | ---
+++
@@ -0,0 +1,9 @@
+/**
+ * Converts the input string by escaping characters that have special meaning in
+ * regular expressions.
+ *
+ * From https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
+ */
+export function escapeRegExp(str: string) {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
+} |
|
1a5d5b758490f61e1163fdaf4f370bbc7dd1bf88 | tests/unit/models/setting-test.ts | tests/unit/models/setting-test.ts | import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { run } from '@ember/runloop';
module('Unit | Model | setting', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
let store = this.owner.lookup('service:store');
let model = run(() => store.createRecord('setting', {}));
assert.ok(model);
});
});
| Add test file for settings model | Add test file for settings model
| TypeScript | apache-2.0 | ExplorViz/explorviz-ui-frontend,ExplorViz/explorviz-ui-frontend,ExplorViz/explorviz-ui-frontend | ---
+++
@@ -0,0 +1,14 @@
+import { module, test } from 'qunit';
+import { setupTest } from 'ember-qunit';
+import { run } from '@ember/runloop';
+
+module('Unit | Model | setting', function(hooks) {
+ setupTest(hooks);
+
+ // Replace this with your real tests.
+ test('it exists', function(assert) {
+ let store = this.owner.lookup('service:store');
+ let model = run(() => store.createRecord('setting', {}));
+ assert.ok(model);
+ });
+}); |
|
e429b1a131348670bb40f3b9ba65ac94c18b326e | test/servicesSpec.ts | test/servicesSpec.ts | import * as angular from "angular";
import { UIRouter, trace } from "ui-router-core";
declare var inject;
var module = angular.mock.module;
describe('UI-Router services', () => {
var $uiRouterProvider: UIRouter, $uiRouter: UIRouter;
var providers;
var services;
beforeEach(module('ui.router', function(
_$uiRouterProvider_,
$urlMatcherFactoryProvider,
$urlRouterProvider,
$stateRegistryProvider,
$uiRouterGlobalsProvider,
$transitionsProvider,
$stateProvider,
) {
$uiRouterProvider = _$uiRouterProvider_;
expect($uiRouterProvider['router']).toBe($uiRouterProvider);
providers = {
$uiRouterProvider,
$urlMatcherFactoryProvider,
$urlRouterProvider,
$stateRegistryProvider,
$uiRouterGlobalsProvider,
$transitionsProvider,
$stateProvider,
};
}));
beforeEach(inject(function(
_$uiRouter_,
$urlMatcherFactory,
$urlRouter,
$stateRegistry,
$uiRouterGlobals,
$transitions,
$state,
$stateParams,
$templateFactory,
$view,
$trace,
) {
$uiRouter = _$uiRouter_;
services = {
$urlMatcherFactory,
$urlRouter,
$stateRegistry,
$uiRouterGlobals,
$transitions,
$state,
$stateParams,
$templateFactory,
$view,
$trace,
}
}));
it("Should expose ui-router providers from the UIRouter instance", () => {
expect(providers.$urlMatcherFactoryProvider).toBe($uiRouterProvider.urlMatcherFactory);
expect(providers.$urlRouterProvider).toBe($uiRouterProvider.urlRouterProvider);
expect(providers.$stateRegistryProvider).toBe($uiRouterProvider.stateRegistry);
expect(providers.$uiRouterGlobalsProvider).toBe($uiRouterProvider.globals);
expect(providers.$transitionsProvider).toBe($uiRouterProvider.transitionService);
expect(providers.$stateProvider).toBe($uiRouterProvider.stateProvider);
});
it("Should expose ui-router services from the UIRouter instance", () => {
expect($uiRouter).toBe($uiRouterProvider);
expect(services.$urlMatcherFactory).toBe($uiRouter.urlMatcherFactory);
expect(services.$urlRouter).toBe($uiRouter.urlRouter);
expect(services.$stateRegistry).toBe($uiRouter.stateRegistry);
expect(services.$uiRouterGlobals).toBe($uiRouter.globals);
expect(services.$transitions).toBe($uiRouter.transitionService);
expect(services.$state).toBe($uiRouter.stateService);
expect(services.$stateParams).toBe($uiRouter.globals.params);
expect(services.$templateFactory.constructor.name).toBe("TemplateFactory");
expect(services.$view).toBe($uiRouter.viewService);
expect(services.$trace).toBe(trace);
});
}); | Check each provider and service is injected | test(Services): Check each provider and service is injected
| TypeScript | mit | angular-ui/ui-router,codersongs/codersongs.github.io,codersongs/codersongs.github.io,mattlewis92/ui-router,fpipita/ui-router,fpipita/ui-router,fpipita/ui-router,mattlewis92/ui-router,angular-ui/ui-router,angular-ui/ui-router | ---
+++
@@ -0,0 +1,87 @@
+import * as angular from "angular";
+import { UIRouter, trace } from "ui-router-core";
+
+declare var inject;
+
+var module = angular.mock.module;
+describe('UI-Router services', () => {
+ var $uiRouterProvider: UIRouter, $uiRouter: UIRouter;
+ var providers;
+ var services;
+
+ beforeEach(module('ui.router', function(
+ _$uiRouterProvider_,
+ $urlMatcherFactoryProvider,
+ $urlRouterProvider,
+ $stateRegistryProvider,
+ $uiRouterGlobalsProvider,
+ $transitionsProvider,
+ $stateProvider,
+ ) {
+ $uiRouterProvider = _$uiRouterProvider_;
+
+ expect($uiRouterProvider['router']).toBe($uiRouterProvider);
+
+ providers = {
+ $uiRouterProvider,
+ $urlMatcherFactoryProvider,
+ $urlRouterProvider,
+ $stateRegistryProvider,
+ $uiRouterGlobalsProvider,
+ $transitionsProvider,
+ $stateProvider,
+ };
+ }));
+
+ beforeEach(inject(function(
+ _$uiRouter_,
+ $urlMatcherFactory,
+ $urlRouter,
+ $stateRegistry,
+ $uiRouterGlobals,
+ $transitions,
+ $state,
+ $stateParams,
+ $templateFactory,
+ $view,
+ $trace,
+ ) {
+ $uiRouter = _$uiRouter_;
+
+ services = {
+ $urlMatcherFactory,
+ $urlRouter,
+ $stateRegistry,
+ $uiRouterGlobals,
+ $transitions,
+ $state,
+ $stateParams,
+ $templateFactory,
+ $view,
+ $trace,
+ }
+ }));
+
+ it("Should expose ui-router providers from the UIRouter instance", () => {
+ expect(providers.$urlMatcherFactoryProvider).toBe($uiRouterProvider.urlMatcherFactory);
+ expect(providers.$urlRouterProvider).toBe($uiRouterProvider.urlRouterProvider);
+ expect(providers.$stateRegistryProvider).toBe($uiRouterProvider.stateRegistry);
+ expect(providers.$uiRouterGlobalsProvider).toBe($uiRouterProvider.globals);
+ expect(providers.$transitionsProvider).toBe($uiRouterProvider.transitionService);
+ expect(providers.$stateProvider).toBe($uiRouterProvider.stateProvider);
+ });
+
+ it("Should expose ui-router services from the UIRouter instance", () => {
+ expect($uiRouter).toBe($uiRouterProvider);
+ expect(services.$urlMatcherFactory).toBe($uiRouter.urlMatcherFactory);
+ expect(services.$urlRouter).toBe($uiRouter.urlRouter);
+ expect(services.$stateRegistry).toBe($uiRouter.stateRegistry);
+ expect(services.$uiRouterGlobals).toBe($uiRouter.globals);
+ expect(services.$transitions).toBe($uiRouter.transitionService);
+ expect(services.$state).toBe($uiRouter.stateService);
+ expect(services.$stateParams).toBe($uiRouter.globals.params);
+ expect(services.$templateFactory.constructor.name).toBe("TemplateFactory");
+ expect(services.$view).toBe($uiRouter.viewService);
+ expect(services.$trace).toBe(trace);
+ });
+}); |
|
40d9f58db76aa3aa1adf1f9e8eabba0c0ecf8c49 | src/test/model-utils.spec.ts | src/test/model-utils.spec.ts | import {fdescribe,describe,expect,fit,it,xit, inject,beforeEach, beforeEachProviders} from 'angular2/testing';
import {provide} from "angular2/core";
import {IdaiFieldObject} from "../app/model/idai-field-object";
import {ModelUtils} from "../app/model/model-utils";
/**
* @author Jan G. Wieners
*/
export function main() {
describe('ModelUtils', () => {
fit('should clone an IdaiFieldObject with all of its properties',
function(){
var initialObject = {
"identifier": "ob1",
"title": "Title",
"synced": 0,
"valid": true,
"type": "Object"
};
var clonedObject = ModelUtils.clone(initialObject);
//clonedObject.identifier = "obNew"; // make test fail
expect(clonedObject).toEqual(initialObject);
}
);
})
} | Add test for deep cloning objects. | Add test for deep cloning objects.
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -0,0 +1,29 @@
+import {fdescribe,describe,expect,fit,it,xit, inject,beforeEach, beforeEachProviders} from 'angular2/testing';
+import {provide} from "angular2/core";
+import {IdaiFieldObject} from "../app/model/idai-field-object";
+import {ModelUtils} from "../app/model/model-utils";
+
+/**
+ * @author Jan G. Wieners
+ */
+export function main() {
+ describe('ModelUtils', () => {
+
+ fit('should clone an IdaiFieldObject with all of its properties',
+ function(){
+
+ var initialObject = {
+ "identifier": "ob1",
+ "title": "Title",
+ "synced": 0,
+ "valid": true,
+ "type": "Object"
+ };
+ var clonedObject = ModelUtils.clone(initialObject);
+
+ //clonedObject.identifier = "obNew"; // make test fail
+ expect(clonedObject).toEqual(initialObject);
+ }
+ );
+ })
+} |
|
0442291ac04a0c62c5b8c63377b39bd4a60f5292 | src/datastore/postgres/schema/v5.ts | src/datastore/postgres/schema/v5.ts | import { IDatabase } from "pg-promise";
// tslint:disable-next-line: no-any
export async function runSchema(db: IDatabase<any>) {
// Create schema
await db.none(`
CREATE TABLE metrics_users (
user_id TEXT NOT NULL,
remote BOOLEAN,
puppeted BOOLEAN
);
CREATE TYPE room_type AS ENUM ('user', 'channel');
CREATE TABLE metrics_rooms (
room_id TEXT NOT NULL,
type room_type
);
CREATE TABLE metrics_user_room_activities (
user_id TEXT NOT NULL,
room_id TEXT NOT NULL,
date DATE,
CONSTRAINT cons_user_room_activities_unique UNIQUE(user_id, room_id, date)
);
`);
}
| Add database schema for the metrics | Add database schema for the metrics
| TypeScript | apache-2.0 | matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack | ---
+++
@@ -0,0 +1,26 @@
+import { IDatabase } from "pg-promise";
+
+// tslint:disable-next-line: no-any
+export async function runSchema(db: IDatabase<any>) {
+ // Create schema
+ await db.none(`
+ CREATE TABLE metrics_users (
+ user_id TEXT NOT NULL,
+ remote BOOLEAN,
+ puppeted BOOLEAN
+ );
+
+ CREATE TYPE room_type AS ENUM ('user', 'channel');
+ CREATE TABLE metrics_rooms (
+ room_id TEXT NOT NULL,
+ type room_type
+ );
+
+ CREATE TABLE metrics_user_room_activities (
+ user_id TEXT NOT NULL,
+ room_id TEXT NOT NULL,
+ date DATE,
+ CONSTRAINT cons_user_room_activities_unique UNIQUE(user_id, room_id, date)
+ );
+ `);
+} |
|
be2ae055909b5dd2c2b8c87266ef42bec8f64ea9 | test/Documents/Queries/HashCalculatorTest.ts | test/Documents/Queries/HashCalculatorTest.ts | import * as assert from "assert";
import { HashCalculator } from "../../../src/Documents/Queries/HashCalculator";
import { TypesAwareObjectMapper } from "../../../src/Mapping/ObjectMapper";
const mockObjectMapper = {
toObjectLiteral: obj => obj.toString()
} as TypesAwareObjectMapper;
const hash = data => {
const calculator = new HashCalculator();
calculator.write(data, mockObjectMapper);
return calculator.getHash();
}
describe('Hash calculator tests', () => {
it('Calculates the same hash for the same object', async () => {
const obj = {
boolean: true,
function: () => {
console.log('No-op')
},
number: 4,
object: {
property: 'value'
},
string: 'hello',
symbol: Symbol('world'),
undefined: undefined,
};
assert.equal(hash(obj), hash(obj));
assert.equal(hash(obj), hash({ ...obj }));
});
it('Calculates different hashes for different types', async () => {
assert.notEqual(hash(1), hash(true))
assert.notEqual(hash('1'), hash(true))
assert.notEqual(hash(1), hash('1'))
});
it('Calculates different hashes for different numbers', async () => {
assert.notEqual(hash(1), hash(257));
assert.notEqual(hash(86400), hash(0));
});
});
| Add tests for hash calculator | Add tests for hash calculator
| TypeScript | mit | ravendb/ravendb-nodejs-client,ravendb/ravendb-nodejs-client | ---
+++
@@ -0,0 +1,46 @@
+import * as assert from "assert";
+
+import { HashCalculator } from "../../../src/Documents/Queries/HashCalculator";
+import { TypesAwareObjectMapper } from "../../../src/Mapping/ObjectMapper";
+
+const mockObjectMapper = {
+ toObjectLiteral: obj => obj.toString()
+} as TypesAwareObjectMapper;
+
+const hash = data => {
+ const calculator = new HashCalculator();
+ calculator.write(data, mockObjectMapper);
+ return calculator.getHash();
+}
+
+describe('Hash calculator tests', () => {
+ it('Calculates the same hash for the same object', async () => {
+ const obj = {
+ boolean: true,
+ function: () => {
+ console.log('No-op')
+ },
+ number: 4,
+ object: {
+ property: 'value'
+ },
+ string: 'hello',
+ symbol: Symbol('world'),
+ undefined: undefined,
+ };
+
+ assert.equal(hash(obj), hash(obj));
+ assert.equal(hash(obj), hash({ ...obj }));
+ });
+
+ it('Calculates different hashes for different types', async () => {
+ assert.notEqual(hash(1), hash(true))
+ assert.notEqual(hash('1'), hash(true))
+ assert.notEqual(hash(1), hash('1'))
+ });
+
+ it('Calculates different hashes for different numbers', async () => {
+ assert.notEqual(hash(1), hash(257));
+ assert.notEqual(hash(86400), hash(0));
+ });
+}); |
|
20bd66d808c1ea5caa617d199e6b808b4f815a8d | airtable-custom-form/src/syncFileToS3.tsx | airtable-custom-form/src/syncFileToS3.tsx | // tslint:disable:no-any no-console
import * as AWS from 'aws-sdk';
const BUCKET_NAME = 'l4gg-timeline.ajhyndman.com';
const REGION = 'us-east-1';
const IDENTITY_POOL_ID = 'us-east-1:fa5d5bd8-abdc-4846-a62a-6f4fd6add035';
AWS.config.update({
region: REGION,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: IDENTITY_POOL_ID,
}),
});
const s3 = new AWS.S3({
apiVersion: '2006-03-01',
params: { Bucket: BUCKET_NAME },
});
function syncFileToS3(file: File): Promise<string> {
return new Promise((resolve, reject) => {
s3.upload(
{
ACL: 'public-read',
Bucket: BUCKET_NAME,
Body: file,
Key: encodeURIComponent(file.name),
},
(err, data) => {
if (err) {
reject(err);
} else {
console.log('successful image upload:', data);
resolve(data.Location);
}
},
);
});
}
export default syncFileToS3;
| Implement S3 sync file helper | Implement S3 sync file helper
| TypeScript | mit | L4GG/timeline,L4GG/timeline,L4GG/timeline | ---
+++
@@ -0,0 +1,41 @@
+// tslint:disable:no-any no-console
+import * as AWS from 'aws-sdk';
+
+const BUCKET_NAME = 'l4gg-timeline.ajhyndman.com';
+const REGION = 'us-east-1';
+const IDENTITY_POOL_ID = 'us-east-1:fa5d5bd8-abdc-4846-a62a-6f4fd6add035';
+
+AWS.config.update({
+ region: REGION,
+ credentials: new AWS.CognitoIdentityCredentials({
+ IdentityPoolId: IDENTITY_POOL_ID,
+ }),
+});
+
+const s3 = new AWS.S3({
+ apiVersion: '2006-03-01',
+ params: { Bucket: BUCKET_NAME },
+});
+
+function syncFileToS3(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ s3.upload(
+ {
+ ACL: 'public-read',
+ Bucket: BUCKET_NAME,
+ Body: file,
+ Key: encodeURIComponent(file.name),
+ },
+ (err, data) => {
+ if (err) {
+ reject(err);
+ } else {
+ console.log('successful image upload:', data);
+ resolve(data.Location);
+ }
+ },
+ );
+ });
+}
+
+export default syncFileToS3; |
|
e45a98137ecc7363af36721046358e1da5331fad | server/libs/api/subject-functions.ts | server/libs/api/subject-functions.ts | ///<reference path="../../../typings/globals/mysql/index.d.ts"/>
import * as mysql from 'mysql';
import { Subject } from '../../../client/sharedClasses/subject';
export class SubjectFunctions {
/**
* Callback for responding with available subject names from the Database as a JSON object
*
* @callback sendResponse
* @param {object} rows - Rows return from the query
*/
/**
* Method get available subject list from the database.
*
* @param {mysql.IConnection} connection - Connection object that has connection metadata
* @param {sendResponse} callback - Response rows as JSON to the request
*
*/
getAvailableSubjects(connection: mysql.IConnection, callback) {
let query = 'call sp_get_available_subjects()';
connection.query(query, (err, rows) => {
let subjects: Subject[] = [];
for(let subject of rows[0]) {
subjects.push(subject)
}
callback(subjects)
});
}
} | Add subject functions - Support API functions | Add subject functions
- Support API functions
| TypeScript | mit | shavindraSN/examen,shavindraSN/examen,shavindraSN/examen | ---
+++
@@ -0,0 +1,32 @@
+///<reference path="../../../typings/globals/mysql/index.d.ts"/>
+import * as mysql from 'mysql';
+import { Subject } from '../../../client/sharedClasses/subject';
+
+export class SubjectFunctions {
+
+ /**
+ * Callback for responding with available subject names from the Database as a JSON object
+ *
+ * @callback sendResponse
+ * @param {object} rows - Rows return from the query
+ */
+
+ /**
+ * Method get available subject list from the database.
+ *
+ * @param {mysql.IConnection} connection - Connection object that has connection metadata
+ * @param {sendResponse} callback - Response rows as JSON to the request
+ *
+ */
+ getAvailableSubjects(connection: mysql.IConnection, callback) {
+ let query = 'call sp_get_available_subjects()';
+ connection.query(query, (err, rows) => {
+ let subjects: Subject[] = [];
+
+ for(let subject of rows[0]) {
+ subjects.push(subject)
+ }
+ callback(subjects)
+ });
+ }
+} |
|
4d247a4827340d71d549ebbd718b91c069b7110e | script/find-trickline-exe.ts | script/find-trickline-exe.ts | import * as fs from 'fs';
import * as path from 'path';
const rootDir = path.dirname(require.resolve('../package.json'));
if (!fs.existsSync(path.join(rootDir, 'out'))) {
throw new Error('Package the app first!');
}
const dirName = fs.readdirSync(path.join(rootDir, 'out'))
.find(x => !!x.match(/^.+-.+-.+$/));
if (!dirName) {
throw new Error('Package the app first!');
}
const [packageId, platform] = dirName.split('-');
switch(platform) {
case 'win32':
console.log(path.join(rootDir, 'out', dirName, `${packageId}.exe`));
break;
case 'linux':
console.log(path.join(rootDir, 'out', dirName, `${packageId}`));
break;
case 'darwin':
console.log(path.join(rootDir, 'out', dirName, `${packageId}.app`, 'Contents', 'MacOS', packageId));
break;
} | Add a script which just dumps the path to the trickline exe | Add a script which just dumps the path to the trickline exe
| TypeScript | bsd-3-clause | paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline | ---
+++
@@ -0,0 +1,28 @@
+import * as fs from 'fs';
+import * as path from 'path';
+
+const rootDir = path.dirname(require.resolve('../package.json'));
+
+if (!fs.existsSync(path.join(rootDir, 'out'))) {
+ throw new Error('Package the app first!');
+}
+
+const dirName = fs.readdirSync(path.join(rootDir, 'out'))
+ .find(x => !!x.match(/^.+-.+-.+$/));
+
+if (!dirName) {
+ throw new Error('Package the app first!');
+}
+
+const [packageId, platform] = dirName.split('-');
+switch(platform) {
+case 'win32':
+ console.log(path.join(rootDir, 'out', dirName, `${packageId}.exe`));
+ break;
+case 'linux':
+ console.log(path.join(rootDir, 'out', dirName, `${packageId}`));
+ break;
+case 'darwin':
+ console.log(path.join(rootDir, 'out', dirName, `${packageId}.app`, 'Contents', 'MacOS', packageId));
+ break;
+} |
|
cacd7705f88a96ec62163ab78229e0479bb57e85 | functions/src/__tests__/patch/validators.ts | functions/src/__tests__/patch/validators.ts | import { required, failure, success } from '../../patch/validator'
describe('validators', () => {
describe('required', () => {
it('failure on undefined values', () => {
const result = required(undefined)
expect(result).toEqual(failure('Required'))
})
it('failure on null values', () => {
const result = required(null)
expect(result).toEqual(failure('Required'))
})
it('success on falsy values', () => {
const result = required(0)
expect(result).toEqual(success())
})
it('success on truthy values', () => {
const result = required('Hello world!')
expect(result).toEqual(success())
})
})
})
| Add test for required validator | Add test for required validator
| TypeScript | apache-2.0 | squanchy-dev/squanchy-firebase,squanchy-dev/squanchy-firebase | ---
+++
@@ -0,0 +1,25 @@
+import { required, failure, success } from '../../patch/validator'
+
+describe('validators', () => {
+ describe('required', () => {
+ it('failure on undefined values', () => {
+ const result = required(undefined)
+ expect(result).toEqual(failure('Required'))
+ })
+
+ it('failure on null values', () => {
+ const result = required(null)
+ expect(result).toEqual(failure('Required'))
+ })
+
+ it('success on falsy values', () => {
+ const result = required(0)
+ expect(result).toEqual(success())
+ })
+
+ it('success on truthy values', () => {
+ const result = required('Hello world!')
+ expect(result).toEqual(success())
+ })
+ })
+}) |
|
97a54e6c5d8b7b13ad2865ccd9341d6594835e36 | Demo/Types/StudyEventArgs.ts | Demo/Types/StudyEventArgs.ts | class StudyEventArgs {
constructor(study: StudyParams) {
this._studyParams = study;
}
private _studyParams: StudyParams;
public get StudyParams(): StudyParams{
return this._studyParams;
};
public set StudyParams(instance: StudyParams) {
this._studyParams = instance;
};
} | Include missing file and Fix build error | Include missing file and Fix build error
| TypeScript | mit | Zaid-Safadi/dicom-webJS | ---
+++
@@ -0,0 +1,14 @@
+class StudyEventArgs {
+ constructor(study: StudyParams) {
+ this._studyParams = study;
+ }
+
+ private _studyParams: StudyParams;
+
+ public get StudyParams(): StudyParams{
+ return this._studyParams;
+ };
+ public set StudyParams(instance: StudyParams) {
+ this._studyParams = instance;
+ };
+} |
|
eaf6a9651421405ea14a837fb39606de8814a32a | src/app/gallery/mocks/mock-data.ts | src/app/gallery/mocks/mock-data.ts | import { AlbumInfo } from '../album-info';
export const MOCK_ALBUMDATA: AlbumInfo = {
albumId: 1,
title: 'title',
name: 'name',
description: 'description',
imagesInAlbum: 8,
imagesPerPage: 4,
totalPages: 2,
iconUrl: 'http://url/jpg.jpg'
};
export const MOCK_IMAGEDATA = {
id: 1,
title: 'img_title',
date: 123456789,
description: 'img_desc',
thumbnail: 'http://localhost/thumb.jpg',
src: 'http://localhost/img.jpg',
containingAlbums: [
{name: 'name', title: 'album name'},
{name: 'name2', title: 'album name 2'}
],
featured: false
};
| Refactor gallery mock data for tests | Refactor gallery mock data for tests
| TypeScript | apache-2.0 | jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog | ---
+++
@@ -0,0 +1,26 @@
+import { AlbumInfo } from '../album-info';
+
+export const MOCK_ALBUMDATA: AlbumInfo = {
+ albumId: 1,
+ title: 'title',
+ name: 'name',
+ description: 'description',
+ imagesInAlbum: 8,
+ imagesPerPage: 4,
+ totalPages: 2,
+ iconUrl: 'http://url/jpg.jpg'
+};
+
+export const MOCK_IMAGEDATA = {
+ id: 1,
+ title: 'img_title',
+ date: 123456789,
+ description: 'img_desc',
+ thumbnail: 'http://localhost/thumb.jpg',
+ src: 'http://localhost/img.jpg',
+ containingAlbums: [
+ {name: 'name', title: 'album name'},
+ {name: 'name2', title: 'album name 2'}
+ ],
+ featured: false
+}; |
|
76685240e688f6083d7a674f0cb25a959cf0e401 | test/src/testcomm.ts | test/src/testcomm.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import expect = require('expect.js');
import { IComm, ICommInfo, ICommManager } from '../../lib/icomm';
import { IKernel } from '../../lib/ikernel';
import { startNewKernel } from '../../lib/kernel';
import { RequestHandler, expectFailure } from './utils';
describe('jupyter.services - Comm', () => {
});
| Add a stub for comm tests | Add a stub for comm tests
| TypeScript | bsd-3-clause | jupyter/jupyter-js-services,blink1073/jupyter-js-services,jupyterlab/services,minrk/jupyter-js-services,blink1073/services,blink1073/services,blink1073/jupyter-js-services,blink1073/jupyter-js-services,jupyter/jupyter-js-services,blink1073/services,jupyter/jupyter-js-services,jupyterlab/services,minrk/jupyter-js-services,blink1073/services,minrk/jupyter-js-services,jupyter/jupyter-js-services,blink1073/jupyter-js-services,jupyterlab/services,jupyterlab/services,minrk/jupyter-js-services | ---
+++
@@ -0,0 +1,19 @@
+// Copyright (c) Jupyter Development Team.
+// Distributed under the terms of the Modified BSD License.
+'use strict';
+
+import expect = require('expect.js');
+
+import { IComm, ICommInfo, ICommManager } from '../../lib/icomm';
+
+import { IKernel } from '../../lib/ikernel';
+
+import { startNewKernel } from '../../lib/kernel';
+
+import { RequestHandler, expectFailure } from './utils';
+
+
+
+describe('jupyter.services - Comm', () => {
+
+}); |
|
7229192eaeee97f043626a75f88774dee6819d2f | src/Test/Ast/Config/Video.ts | src/Test/Ast/Config/Video.ts | import { expect } from 'chai'
import { Up } from '../../../index'
import { insideDocumentAndParagraph } from '../Helpers'
import { VideoNode } from '../../../SyntaxNodes/VideoNode'
import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
describe('The term that represents video conventions', () => {
const up = new Up({
i18n: {
terms: { video: 'watch' }
}
})
it('comes from the "video" config term', () => {
const text = '[watch: Nevada caucus footage -> https://example.com/video.webm]'
expect(up.toAst(text)).to.be.eql(
new DocumentNode([
new VideoNode('Nevada caucus footage', 'https://example.com/video.webm')
])
)
})
it('is always case insensitive', () => {
const text = '[WATCH: Nevada caucus footage -> https://example.com/video.webm]'
expect(up.toAst(text)).to.be.eql(
new DocumentNode([
new VideoNode('Nevada caucus footage', 'https://example.com/video.webm')
])
)
})
})
| Add 2 config tests, 1 passing and 1 failing | Add 2 config tests, 1 passing and 1 failing
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,34 @@
+import { expect } from 'chai'
+import { Up } from '../../../index'
+import { insideDocumentAndParagraph } from '../Helpers'
+import { VideoNode } from '../../../SyntaxNodes/VideoNode'
+import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
+
+
+describe('The term that represents video conventions', () => {
+ const up = new Up({
+ i18n: {
+ terms: { video: 'watch' }
+ }
+ })
+
+ it('comes from the "video" config term', () => {
+ const text = '[watch: Nevada caucus footage -> https://example.com/video.webm]'
+
+ expect(up.toAst(text)).to.be.eql(
+ new DocumentNode([
+ new VideoNode('Nevada caucus footage', 'https://example.com/video.webm')
+ ])
+ )
+ })
+
+ it('is always case insensitive', () => {
+ const text = '[WATCH: Nevada caucus footage -> https://example.com/video.webm]'
+
+ expect(up.toAst(text)).to.be.eql(
+ new DocumentNode([
+ new VideoNode('Nevada caucus footage', 'https://example.com/video.webm')
+ ])
+ )
+ })
+}) |
|
4cce2b54a5c7a4645937fc398c0c4b0d1d30d446 | src/common-ui/components/pioneer-plan-banner.tsx | src/common-ui/components/pioneer-plan-banner.tsx | import * as React from 'react'
import styled from 'styled-components'
import { PrimaryAction } from 'src/common-ui/components/design-library/actions/PrimaryAction'
import { SecondaryAction } from 'src/common-ui/components/design-library/actions/SecondaryAction'
import Icon from '@worldbrain/memex-common/lib/common-ui/components/icon'
import ButtonTooltip from '@worldbrain/memex-common/lib/common-ui/components/button-tooltip'
const PioneerPlanContainer = styled.div`
display: flex;
padding: 10px 15px;
justify-content: space-between;
align-items: center;
background: #f0f0f0;
border-radius: 3px;
margin-bottom: 30px;
width: 780px;
`
const PioneerPlanContentBox = styled.div`
display: flex;
flex-direction: column;
`
const PioneerPlanTitle = styled.div`
font-weight: bold;
font-size: 14px;
`
const PioneerPlanDescription = styled.div`
font-size: 12px;
`
const PioneerPlanButtonBox = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
gap: 5px;
margin-right: -5px;
`
const PioneerPlanLearnMoreButton = styled(SecondaryAction)``
const PioneerPlanUpgradeButton = styled(PrimaryAction)``
export interface Props {
upgradeUrl?: string
moreInfoUrl?: string
onHideClick?: React.MouseEventHandler
}
const PioneerPlanBanner = ({
onHideClick,
moreInfoUrl = 'https://worldbrain.io/announcements/pioneer-plan',
upgradeUrl = process.env.NODE_ENV === 'production'
? 'https://buy.stripe.com/4gw3fpg3i6i534IcMM'
: 'https://buy.stripe.com/test_8wMdU4cm4frH4SY144',
}: Props) => (
<PioneerPlanContainer>
<PioneerPlanContentBox>
<PioneerPlanTitle>
Support Memex with the Pioneer Plan
</PioneerPlanTitle>
<PioneerPlanDescription>
Memex is about to change. Become an early supporter and get a
35% discount.
</PioneerPlanDescription>
</PioneerPlanContentBox>
<PioneerPlanButtonBox>
<PioneerPlanLearnMoreButton
label="Learn More"
onClick={() => window.open(moreInfoUrl)}
/>
<PioneerPlanUpgradeButton
label="Upgrade"
onClick={() => window.open(upgradeUrl)}
/>
{onHideClick && (
<ButtonTooltip
position="bottom"
tooltipText="Find this message again in your account settings."
>
<Icon icon="removeX" height="12px" onClick={onHideClick} />
</ButtonTooltip>
)}
</PioneerPlanButtonBox>
</PioneerPlanContainer>
)
export default PioneerPlanBanner
| Create re-usable pioneer plan banner component | Create re-usable pioneer plan banner component
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -0,0 +1,89 @@
+import * as React from 'react'
+import styled from 'styled-components'
+
+import { PrimaryAction } from 'src/common-ui/components/design-library/actions/PrimaryAction'
+import { SecondaryAction } from 'src/common-ui/components/design-library/actions/SecondaryAction'
+import Icon from '@worldbrain/memex-common/lib/common-ui/components/icon'
+import ButtonTooltip from '@worldbrain/memex-common/lib/common-ui/components/button-tooltip'
+
+const PioneerPlanContainer = styled.div`
+ display: flex;
+ padding: 10px 15px;
+ justify-content: space-between;
+ align-items: center;
+ background: #f0f0f0;
+ border-radius: 3px;
+ margin-bottom: 30px;
+ width: 780px;
+`
+const PioneerPlanContentBox = styled.div`
+ display: flex;
+ flex-direction: column;
+`
+
+const PioneerPlanTitle = styled.div`
+ font-weight: bold;
+ font-size: 14px;
+`
+
+const PioneerPlanDescription = styled.div`
+ font-size: 12px;
+`
+
+const PioneerPlanButtonBox = styled.div`
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 5px;
+ margin-right: -5px;
+`
+
+const PioneerPlanLearnMoreButton = styled(SecondaryAction)``
+
+const PioneerPlanUpgradeButton = styled(PrimaryAction)``
+
+export interface Props {
+ upgradeUrl?: string
+ moreInfoUrl?: string
+ onHideClick?: React.MouseEventHandler
+}
+
+const PioneerPlanBanner = ({
+ onHideClick,
+ moreInfoUrl = 'https://worldbrain.io/announcements/pioneer-plan',
+ upgradeUrl = process.env.NODE_ENV === 'production'
+ ? 'https://buy.stripe.com/4gw3fpg3i6i534IcMM'
+ : 'https://buy.stripe.com/test_8wMdU4cm4frH4SY144',
+}: Props) => (
+ <PioneerPlanContainer>
+ <PioneerPlanContentBox>
+ <PioneerPlanTitle>
+ Support Memex with the Pioneer Plan
+ </PioneerPlanTitle>
+ <PioneerPlanDescription>
+ Memex is about to change. Become an early supporter and get a
+ 35% discount.
+ </PioneerPlanDescription>
+ </PioneerPlanContentBox>
+ <PioneerPlanButtonBox>
+ <PioneerPlanLearnMoreButton
+ label="Learn More"
+ onClick={() => window.open(moreInfoUrl)}
+ />
+ <PioneerPlanUpgradeButton
+ label="Upgrade"
+ onClick={() => window.open(upgradeUrl)}
+ />
+ {onHideClick && (
+ <ButtonTooltip
+ position="bottom"
+ tooltipText="Find this message again in your account settings."
+ >
+ <Icon icon="removeX" height="12px" onClick={onHideClick} />
+ </ButtonTooltip>
+ )}
+ </PioneerPlanButtonBox>
+ </PioneerPlanContainer>
+)
+
+export default PioneerPlanBanner |
|
6fe95608e0e629fae10fbdabc846554919c66d28 | src/coalesce-vue-vuetify2/src/build.ts | src/coalesce-vue-vuetify2/src/build.ts | /** Component name resolver for unplugin-vue-components. */
export function CoalesceVuetifyResolver() {
return {
type: "component",
resolve: (name: string) => {
if (name.match(/^C[A-Z]/))
return { name, from: "coalesce-vue-vuetify/lib" };
},
} as const;
}
| /** Component name resolver for unplugin-vue-components. */
let moduleName: Promise<string>;
export function CoalesceVuetifyResolver() {
moduleName = (async () => {
// See if coalesce-vue-vuetify2 was aliased in package.json as coalesce-vue-vuetify.
// We have to do so in a way that will work in both ESM and CJS.
if ("require" in global) {
try {
require.resolve("coalesce-vue-vuetify");
return "coalesce-vue-vuetify";
} catch {}
} else {
try {
if (await import.meta.resolve?.("coalesce-vue-vuetify"))
return "coalesce-vue-vuetify";
} catch {}
}
return "coalesce-vue-vuetify2";
})();
return {
type: "component",
resolve: async (name: string) => {
if (name.match(/^C[A-Z]/))
return { name, from: (await moduleName) + "/lib" };
},
} as const;
}
| Make CoalesceVuetifyResolver automatically detect if coalesce-vue-vuetify2 was aliased as coalesce-vue-vuetify via package.json | Make CoalesceVuetifyResolver automatically detect if coalesce-vue-vuetify2 was aliased as coalesce-vue-vuetify via package.json
| TypeScript | apache-2.0 | IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce | ---
+++
@@ -1,11 +1,30 @@
/** Component name resolver for unplugin-vue-components. */
+let moduleName: Promise<string>;
export function CoalesceVuetifyResolver() {
+ moduleName = (async () => {
+ // See if coalesce-vue-vuetify2 was aliased in package.json as coalesce-vue-vuetify.
+ // We have to do so in a way that will work in both ESM and CJS.
+
+ if ("require" in global) {
+ try {
+ require.resolve("coalesce-vue-vuetify");
+ return "coalesce-vue-vuetify";
+ } catch {}
+ } else {
+ try {
+ if (await import.meta.resolve?.("coalesce-vue-vuetify"))
+ return "coalesce-vue-vuetify";
+ } catch {}
+ }
+ return "coalesce-vue-vuetify2";
+ })();
+
return {
type: "component",
- resolve: (name: string) => {
+ resolve: async (name: string) => {
if (name.match(/^C[A-Z]/))
- return { name, from: "coalesce-vue-vuetify/lib" };
+ return { name, from: (await moduleName) + "/lib" };
},
} as const;
} |
5f5096c9d1667e17c8ad5ff7dd0a3065b826b41b | src/collections/collections.component.spec.ts | src/collections/collections.component.spec.ts | import { Observable } from 'rxjs';
import { provide } from '@angular/core';
import {
describe, it, inject, beforeEachProviders, expect
} from '@angular/core/testing';
import { CollectionService } from './collection.service.ts';
import { CollectionsComponent } from './collections.component.ts';
import { HelpService } from '../common/help.service.ts';
class CollectionServiceStub {
getCollections(project: string): Observable<Object[]> {
let values = [{name: 'Sarcoma'}, {name: 'Breast'}];
return Observable.create((subscriber) => subscriber.next(values));
}
}
class HelpServiceStub {
}
beforeEachProviders(() => {
return [
CollectionsComponent,
provide(CollectionService, {useClass: CollectionServiceStub}),
provide(HelpService, {useClass: HelpServiceStub})
];
});
// This test is better suited for E2E testing, but confirms that we
// can test an observable component property with injected stubs and
// simulated init.
describe('Collections', () => {
it('should sort the collections', inject(
[CollectionService, HelpService, CollectionsComponent],
(dataService: CollectionService, helpService: HelpService,
collections: CollectionsComponent) => {
// Manually init the component.
collections.ngOnInit();
// The sorted collections.
let expected;
dataService.getCollections().subscribe(colls => {
expected = colls.reverse();
});
collections.collections.subscribe(
actual => {
expect(actual, 'Collections are incorrect').to.eql(expected);
}
);
}
));
});
| Add a CollectionsComponent test suite. | Add a CollectionsComponent test suite.
| TypeScript | bsd-2-clause | ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile | ---
+++
@@ -0,0 +1,51 @@
+import { Observable } from 'rxjs';
+import { provide } from '@angular/core';
+import {
+ describe, it, inject, beforeEachProviders, expect
+} from '@angular/core/testing';
+
+import { CollectionService } from './collection.service.ts';
+import { CollectionsComponent } from './collections.component.ts';
+import { HelpService } from '../common/help.service.ts';
+
+class CollectionServiceStub {
+ getCollections(project: string): Observable<Object[]> {
+ let values = [{name: 'Sarcoma'}, {name: 'Breast'}];
+ return Observable.create((subscriber) => subscriber.next(values));
+ }
+}
+
+class HelpServiceStub {
+}
+
+beforeEachProviders(() => {
+ return [
+ CollectionsComponent,
+ provide(CollectionService, {useClass: CollectionServiceStub}),
+ provide(HelpService, {useClass: HelpServiceStub})
+ ];
+});
+
+// This test is better suited for E2E testing, but confirms that we
+// can test an observable component property with injected stubs and
+// simulated init.
+describe('Collections', () => {
+ it('should sort the collections', inject(
+ [CollectionService, HelpService, CollectionsComponent],
+ (dataService: CollectionService, helpService: HelpService,
+ collections: CollectionsComponent) => {
+ // Manually init the component.
+ collections.ngOnInit();
+ // The sorted collections.
+ let expected;
+ dataService.getCollections().subscribe(colls => {
+ expected = colls.reverse();
+ });
+ collections.collections.subscribe(
+ actual => {
+ expect(actual, 'Collections are incorrect').to.eql(expected);
+ }
+ );
+ }
+ ));
+}); |
|
359b1d65810ddfb0bd8944682e50264c6b8115f3 | client/src/app/admin/import.component.spec.ts | client/src/app/admin/import.component.spec.ts | import {ComponentFixture, TestBed, async} from "@angular/core/testing";
import { Observable } from "rxjs";
import {FormsModule} from "@angular/forms";
import {AdminService} from "./admin.service";
import {RouterTestingModule} from "@angular/router/testing";
import {NavbarComponent} from "../navbar/navbar.component";
import {ImportComponent} from "./import.component";
import {FileUploadComponent} from "./file-upload.component";
import { Http } from '@angular/http';
describe("Import Component", () => {
let importComponent: ImportComponent;
let fixture: ComponentFixture<ImportComponent>;
let mockHttp: {post: (string, any) => Observable<any>};
beforeEach(() => {
mockHttp = {
post: (str: string, a: any) => {
return Observable.of({json:() => "mockFileName"});
}
};
TestBed.configureTestingModule({
imports: [FormsModule, RouterTestingModule],
declarations: [ImportComponent, NavbarComponent, FileUploadComponent],
providers: [{provide: Http, useValue: mockHttp}]
});
});
beforeEach(
async(() => {
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent(ImportComponent);
importComponent = fixture.componentInstance;
fixture.detectChanges();
});
}));
it("can be initialized", () => {
expect(importComponent).toBeDefined();
});
it("can import a file", () => {
importComponent.fu.inputEl = {nativeElement: {files: {length: 1, item: (x) => "eh"}}};
importComponent.handleUpload();
expect(importComponent.filename).toEqual("mockFileName");
expect(importComponent.uploadAttempted).toEqual(true);
});
});
| Add tests for import component | Add tests for import component
| TypeScript | mit | UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2 | ---
+++
@@ -0,0 +1,52 @@
+import {ComponentFixture, TestBed, async} from "@angular/core/testing";
+import { Observable } from "rxjs";
+import {FormsModule} from "@angular/forms";
+import {AdminService} from "./admin.service";
+import {RouterTestingModule} from "@angular/router/testing";
+import {NavbarComponent} from "../navbar/navbar.component";
+import {ImportComponent} from "./import.component";
+import {FileUploadComponent} from "./file-upload.component";
+import { Http } from '@angular/http';
+
+describe("Import Component", () => {
+
+ let importComponent: ImportComponent;
+ let fixture: ComponentFixture<ImportComponent>;
+ let mockHttp: {post: (string, any) => Observable<any>};
+
+ beforeEach(() => {
+ mockHttp = {
+ post: (str: string, a: any) => {
+ return Observable.of({json:() => "mockFileName"});
+ }
+ };
+
+ TestBed.configureTestingModule({
+ imports: [FormsModule, RouterTestingModule],
+ declarations: [ImportComponent, NavbarComponent, FileUploadComponent],
+ providers: [{provide: Http, useValue: mockHttp}]
+ });
+
+ });
+
+ beforeEach(
+ async(() => {
+ TestBed.compileComponents().then(() => {
+ fixture = TestBed.createComponent(ImportComponent);
+ importComponent = fixture.componentInstance;
+ fixture.detectChanges();
+ });
+ }));
+
+ it("can be initialized", () => {
+ expect(importComponent).toBeDefined();
+ });
+
+ it("can import a file", () => {
+ importComponent.fu.inputEl = {nativeElement: {files: {length: 1, item: (x) => "eh"}}};
+ importComponent.handleUpload();
+ expect(importComponent.filename).toEqual("mockFileName");
+ expect(importComponent.uploadAttempted).toEqual(true);
+ });
+});
+ |
|
37089caa2777114ed2b350aa2468413daf2bbd1d | app/data/Crumpet.ts | app/data/Crumpet.ts |
type CrumpetType = "English" | "Scottish" | "Square" | "Pikelet";
export const CrumpetTypes = {
English: "English" as CrumpetType,
Scottish: "Scottish" as CrumpetType,
Square: "Square" as CrumpetType,
Pikelet: "Pikelet" as CrumpetType
};
export interface Crumpet {
name:string;
type:CrumpetType;
} | Define crumpet data. Note the patch for a lack of string based enums to be fixed in a future version of TypeScript. | Define crumpet data. Note the patch for a lack of string based enums to be fixed in a future version of TypeScript.
| TypeScript | unlicense | luketn/WonderCrumpet | ---
+++
@@ -0,0 +1,13 @@
+
+type CrumpetType = "English" | "Scottish" | "Square" | "Pikelet";
+export const CrumpetTypes = {
+ English: "English" as CrumpetType,
+ Scottish: "Scottish" as CrumpetType,
+ Square: "Square" as CrumpetType,
+ Pikelet: "Pikelet" as CrumpetType
+};
+
+export interface Crumpet {
+ name:string;
+ type:CrumpetType;
+} |
|
e94aa8681316af490984ac256fac90f1b02cf377 | src/helpers/getClosestElement.spec.ts | src/helpers/getClosestElement.spec.ts | import { getClosestElement } from './getClosestElement';
describe('getClosestElement', () => {
it('gets the closest ancestor matching the given selector', () => {
const ANCESTOR_ID = 'foo';
const ancestor = document.createElement('div');
ancestor.setAttribute('id', ANCESTOR_ID);
const descendant = document.createElement('div');
ancestor.appendChild(descendant);
expect(getClosestElement(descendant, `#${ANCESTOR_ID}`)).toEqual(
ancestor,
);
});
});
| import { getClosestElement } from './getClosestElement';
describe('getClosestElement', () => {
it('gets the closest ancestor matching the given selector', () => {
const ANCESTOR_ID = 'foo';
const ancestor = document.createElement('div');
ancestor.setAttribute('id', ANCESTOR_ID);
const descendant = document.createElement('div');
ancestor.appendChild(descendant);
expect(getClosestElement(descendant, `#${ANCESTOR_ID}`)).toEqual(
ancestor,
);
});
it('gets the closest ancestor several levels up', () => {
const ANCESTOR_ID = 'foo';
const DESCENDANT_ID = 'bar';
const ancestor = document.createElement('div');
ancestor.setAttribute('id', ANCESTOR_ID);
const middleMan = document.createElement('div');
const descendant = document.createElement('div');
descendant.setAttribute('id', DESCENDANT_ID);
middleMan.appendChild(descendant);
ancestor.appendChild(middleMan);
expect(getClosestElement(descendant, `#${ANCESTOR_ID}`)).toEqual(
ancestor,
);
});
it('no ancestor that matches selector', () => {
const ANCESTOR_ID = 'foo';
const DESCENDANT_ID = 'bar';
const ancestor = document.createElement('div');
const descendant = document.createElement('div');
descendant.setAttribute('id', DESCENDANT_ID);
ancestor.appendChild(descendant);
expect(getClosestElement(descendant, `#${ANCESTOR_ID}`)).toBeNull();
});
});
| Add a couple more tests for get closest element function | Add a couple more tests for get closest element function
| TypeScript | mit | springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion | ---
+++
@@ -15,4 +15,38 @@
ancestor,
);
});
+
+ it('gets the closest ancestor several levels up', () => {
+ const ANCESTOR_ID = 'foo';
+ const DESCENDANT_ID = 'bar';
+
+ const ancestor = document.createElement('div');
+ ancestor.setAttribute('id', ANCESTOR_ID);
+
+ const middleMan = document.createElement('div');
+
+ const descendant = document.createElement('div');
+ descendant.setAttribute('id', DESCENDANT_ID);
+
+ middleMan.appendChild(descendant);
+ ancestor.appendChild(middleMan);
+
+ expect(getClosestElement(descendant, `#${ANCESTOR_ID}`)).toEqual(
+ ancestor,
+ );
+ });
+
+ it('no ancestor that matches selector', () => {
+ const ANCESTOR_ID = 'foo';
+ const DESCENDANT_ID = 'bar';
+
+ const ancestor = document.createElement('div');
+
+ const descendant = document.createElement('div');
+ descendant.setAttribute('id', DESCENDANT_ID);
+
+ ancestor.appendChild(descendant);
+
+ expect(getClosestElement(descendant, `#${ANCESTOR_ID}`)).toBeNull();
+ });
}); |
bb1ac7d58548f95d5553f93bac4e5b805dabdcc2 | src/language/language.ts | src/language/language.ts | import * as _ from 'lodash';
/**
* Makes an array filled with a value.
*
* @method dup
* @param value {any} the array item value
* @param n {number} the array size
* @return the array of size *n* filled with *value*
*/
function dup(value: any, n: number) {
return _.fill(new Array(n), value);
}
export { dup };
| Add the dup utility function. | Add the dup utility function.
| TypeScript | bsd-2-clause | ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile | ---
+++
@@ -0,0 +1,15 @@
+import * as _ from 'lodash';
+
+/**
+ * Makes an array filled with a value.
+ *
+ * @method dup
+ * @param value {any} the array item value
+ * @param n {number} the array size
+ * @return the array of size *n* filled with *value*
+ */
+function dup(value: any, n: number) {
+ return _.fill(new Array(n), value);
+}
+
+export { dup }; |
|
8ba11eae235679b9373954119db4f99694f8ea48 | packages/commutable/__tests__/notebook.spec.ts | packages/commutable/__tests__/notebook.spec.ts | import Immutable from "immutable";
import { fromJS, parseNotebook, toJS } from "../src/notebook";
import { makeNotebookRecord } from "../src/structures";
describe("parseNotebook", () => {
it("parses a string notebook", () => {
const notebook = `{
"cells": [],
"metadata": {
"kernel_info": {
"name": "python3"
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
},
"nteract": {
"version": "[email protected]"
},
"title": "Introduce nteract"
},
"nbformat": 4,
"nbformat_minor": 0
}`;
const result = parseNotebook(notebook);
expect(result.nbformat).toBe(4);
expect(result.nbformat_minor).toBe(0);
});
});
describe("toJS", () => {
it("throws an error if the notebook version is invalid", () => {
const notebook = Immutable.Map({
nbformat: 5,
nbformat_minor: 0
});
const invocation = () => toJS(notebook);
expect(invocation).toThrowError(
"Only notebook formats 3 and 4 are supported!"
);
});
});
describe("fromJS", () => {
it("throws an error if given notebook is not immutable structure", () => {
const notebook = "";
const invocation = () => fromJS(notebook);
expect(invocation).toThrowError("This notebook format is not supported");
});
it("returns same notebook if it is already Immutable", () => {
const notebook = makeNotebookRecord();
const result = fromJS(notebook);
expect(result).toEqual(notebook);
});
});
| Add tests for notebook sub-module in commutable | Add tests for notebook sub-module in commutable
| TypeScript | bsd-3-clause | nteract/composition,nteract/composition,nteract/composition,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract | ---
+++
@@ -0,0 +1,69 @@
+import Immutable from "immutable";
+
+import { fromJS, parseNotebook, toJS } from "../src/notebook";
+import { makeNotebookRecord } from "../src/structures";
+
+describe("parseNotebook", () => {
+ it("parses a string notebook", () => {
+ const notebook = `{
+ "cells": [],
+ "metadata": {
+ "kernel_info": {
+ "name": "python3"
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.7.2"
+ },
+ "nteract": {
+ "version": "[email protected]"
+ },
+ "title": "Introduce nteract"
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}`;
+ const result = parseNotebook(notebook);
+ expect(result.nbformat).toBe(4);
+ expect(result.nbformat_minor).toBe(0);
+ });
+});
+
+describe("toJS", () => {
+ it("throws an error if the notebook version is invalid", () => {
+ const notebook = Immutable.Map({
+ nbformat: 5,
+ nbformat_minor: 0
+ });
+ const invocation = () => toJS(notebook);
+ expect(invocation).toThrowError(
+ "Only notebook formats 3 and 4 are supported!"
+ );
+ });
+});
+
+describe("fromJS", () => {
+ it("throws an error if given notebook is not immutable structure", () => {
+ const notebook = "";
+ const invocation = () => fromJS(notebook);
+ expect(invocation).toThrowError("This notebook format is not supported");
+ });
+ it("returns same notebook if it is already Immutable", () => {
+ const notebook = makeNotebookRecord();
+ const result = fromJS(notebook);
+ expect(result).toEqual(notebook);
+ });
+}); |
|
626453312b2ddd7758bbe430ee2939c2ee978aca | src/get.ts | src/get.ts | import { ReadConverter } from '../types/index'
import { readName, readValue } from './converter'
type GetReturn<T, R> = [T] extends [undefined]
? object & { [property: string]: string }
: R | undefined
export default function <T extends string | undefined>(
key: T,
converter: ReadConverter<any> = readValue
): GetReturn<T, typeof converter> {
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all.
const cookies: string[] =
document.cookie.length > 0 ? document.cookie.split('; ') : []
const jar: any = {}
for (let i = 0; i < cookies.length; i++) {
const parts: string[] = cookies[i].split('=')
const value: string = parts.slice(1).join('=')
try {
const foundKey: string = readName(parts[0])
jar[foundKey] = converter(value, foundKey)
if (key === foundKey) {
break
}
} catch (e) {}
}
return key != null ? jar[key] : jar
}
| import { ReadConverter } from '../types/index'
import { readName, readValue } from './converter'
type GetReturn<T, R> = [T] extends [undefined]
? object & { [property: string]: string }
: R | undefined
export default function <T extends string | undefined>(
key: T,
converter: ReadConverter<any> = readValue
): GetReturn<T, typeof converter> {
const scan = /(?:^|; )([^=]*)=([^;]*)/g
const jar: any = {}
let match
while ((match = scan.exec(document.cookie)) != null) {
try {
const foundKey = readName(match[1])
const value = converter(match[2], foundKey)
jar[foundKey] = value
if (key === foundKey) {
break
}
} catch (e) {}
}
return key != null ? jar[key] : jar
}
| Change cookie lookup to using regex | Change cookie lookup to using regex
Now we don't need to consider an edge case in rather outdated Internet
Explorer we can safely use a regex for this task.
Also reduces the module size..
| TypeScript | mit | carhartl/js-cookie,carhartl/js-cookie | ---
+++
@@ -9,19 +9,14 @@
key: T,
converter: ReadConverter<any> = readValue
): GetReturn<T, typeof converter> {
- // To prevent the for loop in the first place assign an empty array
- // in case there are no cookies at all.
- const cookies: string[] =
- document.cookie.length > 0 ? document.cookie.split('; ') : []
+ const scan = /(?:^|; )([^=]*)=([^;]*)/g
const jar: any = {}
- for (let i = 0; i < cookies.length; i++) {
- const parts: string[] = cookies[i].split('=')
- const value: string = parts.slice(1).join('=')
-
+ let match
+ while ((match = scan.exec(document.cookie)) != null) {
try {
- const foundKey: string = readName(parts[0])
- jar[foundKey] = converter(value, foundKey)
-
+ const foundKey = readName(match[1])
+ const value = converter(match[2], foundKey)
+ jar[foundKey] = value
if (key === foundKey) {
break
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.