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
c220163f372e2320eb8b00c5e473dd42e69b9bbb
tools/tasks/seed/css-lint.ts
tools/tasks/seed/css-lint.ts
import * as gulp from 'gulp'; import * as gulpLoadPlugins from 'gulp-load-plugins'; import * as merge from 'merge-stream'; import * as reporter from 'postcss-reporter'; import * as stylelint from 'stylelint'; import * as doiuse from 'doiuse'; import * as colorguard from 'colorguard'; import {join} from 'path'; import {APP_SRC, APP_ASSETS, BROWSER_LIST, ENV} from '../../config'; const plugins = <any>gulpLoadPlugins(); const isProd = ENV === 'prod'; const processors = [ doiuse({ browsers: BROWSER_LIST, }), colorguard(), stylelint(), reporter({clearMessages: true}) ]; function lintComponentCss() { return gulp.src([ join(APP_SRC, '**', '*.css'), '!' + join(APP_SRC, 'assets', '**', '*.css') ]) .pipe(isProd ? plugins.cached('css-lint') : plugins.util.noop()) .pipe(plugins.postcss(processors)); } function lintExternalCss() { return gulp.src(getExternalCss().map(r => r.src)) .pipe(isProd ? plugins.cached('css-lint') : plugins.util.noop()) .pipe(plugins.postcss(processors)); } function getExternalCss() { return APP_ASSETS.filter(d => /\.css$/.test(d.src) && !d.vendor); } export = () => merge(lintComponentCss(), lintExternalCss());
import * as gulp from 'gulp'; import * as gulpLoadPlugins from 'gulp-load-plugins'; import * as merge from 'merge-stream'; import * as reporter from 'postcss-reporter'; import * as stylelint from 'stylelint'; import * as doiuse from 'doiuse'; import * as colorguard from 'colorguard'; import {join} from 'path'; import {APP_SRC, APP_ASSETS, ASSETS_SRC, BROWSER_LIST, ENV} from '../../config'; const plugins = <any>gulpLoadPlugins(); const isProd = ENV === 'prod'; const processors = [ doiuse({ browsers: BROWSER_LIST, }), colorguard(), stylelint(), reporter({clearMessages: true}) ]; function lintComponentCss() { return gulp.src([ join(APP_SRC, '**', '*.css'), '!' + join(ASSETS_SRC, '**', '*.css') ]) .pipe(isProd ? plugins.cached('css-lint') : plugins.util.noop()) .pipe(plugins.postcss(processors)); } function lintExternalCss() { return gulp.src(getExternalCss().map(r => r.src)) .pipe(isProd ? plugins.cached('css-lint') : plugins.util.noop()) .pipe(plugins.postcss(processors)); } function getExternalCss() { return APP_ASSETS.filter(d => /\.css$/.test(d.src) && !d.vendor); } export = () => merge(lintComponentCss(), lintExternalCss());
Use ASSET_SRC parameter from SeedConfig instead of reconstructing it
Fix(tools): Use ASSET_SRC parameter from SeedConfig instead of reconstructing it
TypeScript
mit
davewragg/agot-spa,fr-esco/angular-seed,alexmanning23/uafl-web,rtang03/fabric-seed,liuy97/angular2-material-seed,ysyun/angular-seed-stub-api-environment,suigezi/angular2-seed,nie-ine/raeber-website,jelgar1/fpl-api,osulp/oe-ng2-seed,MgCoders/angular-seed,NathanWalker/angular-seed-advanced,maniche04/ngIntranet,dspies/boot-angular2-seed,booleanVirus/POC,AnnaCasper/finance-tool,rvanmarkus/studio-eve,nlopezcenteno/angular2-seed,zertyz/angular-seed-advanced-spikes,CNSKnight/ng2-CNSKalc,JohnnyQQQQ/angular-seed-material2,ilvestoomas/angular-seed-advanced,idrabenia/angular2-crud,nlopezcenteno/angular2-seed,ronikurnia1/ClientApp,zertyz/observatorio-SUAS,llwt/angular-seed-advanced,dspies/boot-angular2-seed,CordanoCorey/growtell,mraible/angular2-tutorial,idready/Philosophers,lfarran/angular2-seed-advanced,OlivierVoyer/angular-seed-advanced,osulp/oe-ng2-seed,felipecamargo/ACSC-SBPL-M,CNSKnight/angular2-seed-advanced,Bigous/angular2-seed-ng2-highcharts,mgechev/angular2-seed,mgechev/angular-seed,nickaranz/robinhood-ui,mgechev/angular2-seed,ManasviA/Dashboard,CNSKnight/ng2-CNSKalc,Spencer-Lewis/BandBoard2,hookom/climbontheway,prabhatsharma/bwa2,billsworld/angular2-seed,AngularShowcase/angular2-seed-ng2-highcharts,Aurimas-Norkus/angular2-seed-arch,GeoscienceAustralia/gnss-site-manager,rtang03/fabric-seed,idready/Bloody-Prophety-NG2,lhoezee/faithreg1,deanQj/angular2-seed-bric,JohnCashmore/angular2-seed,tarlepp/angular2-seed,fart-one/monitor-ngx,NathanWalker/angular2-seed-advanced,zertyz/edificando-o-controle-interno,JLou/JandelouFront,Sn3b/angular-seed-advanced,larsnolden/MLB,Spencer-Lewis/BandBoard2,dmitriyse/angular2-seed,AWNICS/mesomeds-ng2,smartnosemm/angular2-seed-express,BlackMr/angular2seed2new,JLou/JandelouFront,alantreadway/homedash,pskaarup/marge,hookom/climbontheway,tctc91/angular2-wordpress-portfolio,watonyweng/angular-seed,mgechev/angular-seed,Karasuni/angular-seed,wenzelj/nativescript-angular,fr-esco/angular-seed,Sn3b/angular-seed-advanced,AngularShowcase/angular2-seed-ng2-highcharts,guilhebl/offer-web,nickaranz/robinhood-ui,rvanmarkus/studio-eve,dspies/boot-angular2-seed,JohnnyQQQQ/md-dashboard,rvanmarkus/studio-eve,shaggyshelar/Linkup,Bigous/angular2-seed-ng2-highcharts,zertyz/observatorio-SUAS-formularios,talentspear/a2-redux,vyakymenko/angular-seed-express,davidstellini/bvl-pay,jelgar1/fpl-api,ManasviA/Dashboard,hoangnguyenba/chatapp,m-abs/angular2-seed-advanced,radiorabe/raar-ui,lilia-simeonova/project-estimations,booleanVirus/POC,JLou/JandelouFront,oblong-antelope/oblong-web,felipecamargo/ACSC-SBPL-M,ysyun/angular-seed-stub-api-environment,rawnics/mesomeds-ng2,m-abs/angular2-seed-advanced,AWNICS/mesomeds-ng2,DallasAngularSuperHeroes/dash-ng2,NathanWalker/angular2-seed-advanced,christophersanson/js-demo-fe,larsnolden/MLB,zertyz/angular2-seed-advanced-spikes2,shaggyshelar/Linkup,larsnolden/MLB,alantreadway/homedash,billsworld/angular2-seed,ysyun/angular-seed-stub-api-environment,idready/Philosophers,nie-ine/raeber-website,Aurimas-Norkus/angular2-seed-arch,fart-one/monitor-ngx,Shyiy/angular-seed,sanastasiadis/angular-seed-openlayers,jigarpt/angular-seed-semi,trutoo/startatalk-native,deanQj/angular2-seed-bric,ronikurnia1/ClientApp,arun-awnics/mesomeds-ng2,sylviefiat/bdmer3,fredrikbergqvist/ng2.bergqvist.it,miltador/unichat,arun-awnics/mesomeds-ng2,pieczkus/whyblogfront,pieczkus/whyblogfront,nickaranz/robinhood-ui,dmitriyse/angular2-seed,NathanWalker/angular2-seed-advanced,chnoumis/angular2-seed-advanced,dmitriyse/angular2-seed,GeoscienceAustralia/gnss-site-manager,zertyz/angular2-seed-advanced-spikes2,ysyun/angular-seed-stub-api-environment,prabhatsharma/bwa2,rtang03/fabric-seed,rtang03/fabric-seed,alexmanning23/uafl-web,DallasAngularSuperHeroes/dash-ng2,MgCoders/angular-seed,natarajanmca11/angular2-seed,millea1/tips1,hoangnguyenba/chatapp,ManasviA/Dashboard,mraible/angular2-tutorial,trutoo/startatalk-native,NathanWalker/angular-seed-advanced,smartnosemm/angular2-seed-express,pocmanu/angular2-seed-advanced,pskaarup/marge,CordanoCorey/growtell,idrabenia/angular2-crud,abhibly/Angular2-Seed-Project,pieczkus/whyblogfront,vip32/eventfeedback,zertyz/angular-seed-advanced-spikes,AWNICS/mesomeds-ng2,pratheekhegde/a2-redux,JohnnyQQQQ/angular-seed-material2,BlackMr/angular2seed2new,deanQj/angular2-seed-bric,nlopezcenteno/angular2-seed,natarajanmca11/angular2-seed,zertyz/edificando-o-controle-interno,sanastasiadis/angular-seed-openlayers,davewragg/agot-spa,tobiaseisenschenk/data-cube,dspies/boot-angular2-seed,zertyz/observatorio-SUAS,talentspear/a2-redux,adobley/angular2-tdd-workshop,ronikurnia1/ClientApp,tiagomapmarques/angular-examples_books,suigezi/angular2-seed,ilvestoomas/angular-seed-advanced,sanastasiadis/angular-seed-openlayers,davidstellini/bvl-pay,rawnics/mesomeds-ng2,christophersanson/js-demo-fe,JohnnyQQQQ/md-dashboard,liuy97/angular2-material-seed,Nightapes/angular2-seed,nie-ine/raeber-website,tobiaseisenschenk/data-cube,tobiaseisenschenk/data-cube,abhibly/Angular2-Seed-Project,hoangnguyenba/chat-app,nie-ine/raeber-website,suigezi/angular2-seed,adobley/angular2-tdd-workshop,idready/Philosophers,Karasuni/angular-seed,billsworld/angular2-seed,prabhatsharma/bwa2,vip32/eventfeedback,arun-awnics/mesomeds-ng2,talentspear/a2-redux,zertyz/observatorio-SUAS,zertyz/angular2-seed-advanced-spikes2,JohnCashmore/angular2-seed,GeoscienceAustralia/gnss-site-manager,jasonlevinsohn/jarvis-dashboard,millea1/tips1,fart-one/monitor-ngx,hookom/climbontheway,CNSKnight/angular2-seed-advanced,pocmanu/angular2-seed-advanced,chnoumis/angular2-seed-advanced,JohnnyQQQQ/md-dashboard,mgechev/angular2-seed,ppanthony/angular-seed-tutorial,shaggyshelar/Linkup,llwt/angular-seed-advanced,lfarran/angular2-seed-advanced,lhoezee/faithreg1,MgCoders/angular-seed,Spencer-Lewis/BandBoard2,CNSKnight/angular2-seed-advanced,OlivierVoyer/angular-seed-advanced,OlivierVoyer/angular-seed-advanced,trevordaniels/ang2seed-advanced,ghsyeung/ng2-component-intro,m-abs/angular2-seed-advanced,vyakymenko/angular-seed-express,osulp/oe-ng2-seed,mraible/angular2-tutorial,radiorabe/raar-ui,rawnics/mesomeds-ng2,pskaarup/marge,oblong-antelope/oblong-web,Nightapes/angular2-seed,idrabenia/angular2-crud,felipecamargo/ACSC-SBPL-M,oblong-antelope/oblong-web,miltador/unichat,vip32/eventfeedback,TOKOFE/team-todo,alexmanning23/uafl-web,AnnaCasper/finance-tool,Aurimas-Norkus/angular2-seed-arch,adobley/angular2-tdd-workshop,zertyz/edificando-o-controle-interno,Shyiy/angular-seed,hoangnguyenba/chat-app,davewragg/agot-spa,ppanthony/angular-seed-tutorial,wenzelj/nativescript-angular,vip32/eventfeedback,alantreadway/homedash,ghsyeung/ng2-component-intro,guilhebl/offer-web,dmitriyse/angular2-seed,wenzelj/nativescript-angular,lfarran/angular2-seed-advanced,liuy97/angular2-material-seed,zertyz/observatorio-SUAS-formularios,rvanmarkus/studio-eve,DallasAngularSuperHeroes/dash-ng2,tarlepp/angular2-seed,Bigous/angular2-seed-ng2-highcharts,pratheekhegde/a2-redux,jasonlevinsohn/jarvis-dashboard,hoangnguyenba/chatapp,JohnnyQQQQ/angular-seed-material2,lilia-simeonova/project-estimations,origamyllc/Mangular,CNSKnight/ng2-CNSKalc,trevordaniels/ang2seed-advanced,zertyz/observatorio-SUAS-formularios,sylviefiat/bdmer3,pocmanu/angular2-seed-advanced,ManasviA/Dashboard,AnnaCasper/finance-tool,tarlepp/angular2-seed,origamyllc/Mangular,millea1/tips1,davidstellini/bvl-pay,maniche04/ngIntranet,Jimmysh/angular2-seed-advanced,NathanWalker/angular-seed-advanced,sylviefiat/bdmer3,Nightapes/angular2-seed,ghsyeung/ng2-component-intro,Sn3b/angular-seed-advanced,CordanoCorey/growtell,Shyiy/angular-seed,fredrikbergqvist/ng2.bergqvist.it,radiorabe/raar-ui,tiagomapmarques/angular-examples_books,abhibly/Angular2-Seed-Project,chnoumis/angular2-seed-advanced,TOKOFE/team-todo,trevordaniels/ang2seed-advanced,pratheekhegde/a2-redux,christophersanson/js-demo-fe,Karasuni/angular-seed,hookom/climbontheway,maniche04/ngIntranet,adobley/angular2-tdd-workshop,watonyweng/angular-seed,zertyz/observatorio-SUAS,ppanthony/angular-seed-tutorial,OlivierVoyer/angular-seed-advanced,Jimmysh/angular2-seed-advanced,llwt/angular-seed-advanced,miltador/unichat,MgCoders/angular-seed,natarajanmca11/angular2-seed,lilia-simeonova/project-estimations,idready/Bloody-Prophety-NG2,jigarpt/angular-seed-semi,radiorabe/raar-ui,booleanVirus/POC,ilvestoomas/angular-seed-advanced,TOKOFE/team-todo,trutoo/startatalk-native,jelgar1/fpl-api,tiagomapmarques/angular-examples_books,JohnCashmore/angular2-seed,smartnosemm/angular2-seed-express,tctc91/angular2-wordpress-portfolio,BlackMr/angular2seed2new,zertyz/angular-seed-advanced-spikes,vyakymenko/angular-seed-express,fr-esco/angular-seed,jigarpt/angular-seed-semi,AngularShowcase/angular2-seed-ng2-highcharts,jasonlevinsohn/jarvis-dashboard,lhoezee/faithreg1,fredrikbergqvist/ng2.bergqvist.it,Jimmysh/angular2-seed-advanced,idready/Bloody-Prophety-NG2,origamyllc/Mangular,guilhebl/offer-web,rtang03/fabric-seed,mgechev/angular-seed,hoangnguyenba/chat-app,tctc91/angular2-wordpress-portfolio
--- +++ @@ -6,7 +6,7 @@ import * as doiuse from 'doiuse'; import * as colorguard from 'colorguard'; import {join} from 'path'; -import {APP_SRC, APP_ASSETS, BROWSER_LIST, ENV} from '../../config'; +import {APP_SRC, APP_ASSETS, ASSETS_SRC, BROWSER_LIST, ENV} from '../../config'; const plugins = <any>gulpLoadPlugins(); const isProd = ENV === 'prod'; @@ -23,7 +23,7 @@ function lintComponentCss() { return gulp.src([ join(APP_SRC, '**', '*.css'), - '!' + join(APP_SRC, 'assets', '**', '*.css') + '!' + join(ASSETS_SRC, '**', '*.css') ]) .pipe(isProd ? plugins.cached('css-lint') : plugins.util.noop()) .pipe(plugins.postcss(processors));
9a4bd65b7e6e84a079493f47192ec07406e63a3f
src/app/home/login/login.component.stories.ts
src/app/home/login/login.component.stories.ts
import { of, throwError } from 'rxjs'; import { NgModule } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { storiesOf } from '@storybook/angular'; import { UserService } from '../../services/user.service'; import { LoginComponent } from './login.component'; const mockUserService = { initialiseSession: () => throwError(new Error('mock')) }; const mockRouter = { navigate: () => {} }; const mockActivatedRoute = { queryParams: of({}) }; const moduleMetadata: NgModule = { providers: [ { provide: UserService, useValue: mockUserService }, { provide: Router, useValue: mockRouter }, { provide: ActivatedRoute, useValue: mockActivatedRoute } ] }; storiesOf('Home', module).add('Login', () => ({ component: LoginComponent, moduleMetadata }));
Add story for login form
Add story for login form
TypeScript
apache-2.0
jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog
--- +++ @@ -0,0 +1,33 @@ +import { of, throwError } from 'rxjs'; + +import { NgModule } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { storiesOf } from '@storybook/angular'; + +import { UserService } from '../../services/user.service'; +import { LoginComponent } from './login.component'; + +const mockUserService = { + initialiseSession: () => throwError(new Error('mock')) +}; + +const mockRouter = { + navigate: () => {} +}; + +const mockActivatedRoute = { + queryParams: of({}) +}; + +const moduleMetadata: NgModule = { + providers: [ + { provide: UserService, useValue: mockUserService }, + { provide: Router, useValue: mockRouter }, + { provide: ActivatedRoute, useValue: mockActivatedRoute } + ] +}; + +storiesOf('Home', module).add('Login', () => ({ + component: LoginComponent, + moduleMetadata +}));
2a850abace3d4e411ced4c0d588e5f3c48c1708e
src/components/SearchBar/TimeNextSearch.tsx
src/components/SearchBar/TimeNextSearch.tsx
import * as React from 'react'; import { connect } from 'react-redux'; import { RootState } from '../../types'; import { Caption } from '@shopify/polaris'; interface Props { readonly timeNextSearch: Date | null; } interface State { readonly timeUntilNextSearch: number | null; } const mapState = (state: RootState): Props => ({ timeNextSearch: state.timeNextSearch }); class TimeNextSearch extends React.PureComponent<Props, State> { state = { timeUntilNextSearch: null }; private tickRate: number = 1000; private timerId: number; componentDidMount() { this.startTimer(); } componentWillReceiveProps(nextProps: Props) { if (nextProps.timeNextSearch) { clearInterval(this.timerId); this.startTimer(); } } private startTimer = () => { this.timerId = window.setInterval(() => this.tick(), this.tickRate); }; private calculateTimeUntilNextSearch = (nextSearch: Date): number => { return Math.max(nextSearch.valueOf() - Date.now(), 0); }; private tick = () => { if (this.props.timeNextSearch) { this.setState({ timeUntilNextSearch: this.calculateTimeUntilNextSearch( this.props.timeNextSearch ) }); } }; public render() { const { timeNextSearch } = this.props; return timeNextSearch ? ( <Caption>Next search in: {this.state.timeUntilNextSearch}</Caption> ) : ( <div /> ); } } export default connect(mapState)(TimeNextSearch);
Add component to display the time until the next scheduled search.
Add component to display the time until the next scheduled search.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -0,0 +1,62 @@ +import * as React from 'react'; +import { connect } from 'react-redux'; +import { RootState } from '../../types'; +import { Caption } from '@shopify/polaris'; + +interface Props { + readonly timeNextSearch: Date | null; +} + +interface State { + readonly timeUntilNextSearch: number | null; +} + +const mapState = (state: RootState): Props => ({ + timeNextSearch: state.timeNextSearch +}); + +class TimeNextSearch extends React.PureComponent<Props, State> { + state = { timeUntilNextSearch: null }; + private tickRate: number = 1000; + private timerId: number; + + componentDidMount() { + this.startTimer(); + } + + componentWillReceiveProps(nextProps: Props) { + if (nextProps.timeNextSearch) { + clearInterval(this.timerId); + this.startTimer(); + } + } + + private startTimer = () => { + this.timerId = window.setInterval(() => this.tick(), this.tickRate); + }; + + private calculateTimeUntilNextSearch = (nextSearch: Date): number => { + return Math.max(nextSearch.valueOf() - Date.now(), 0); + }; + + private tick = () => { + if (this.props.timeNextSearch) { + this.setState({ + timeUntilNextSearch: this.calculateTimeUntilNextSearch( + this.props.timeNextSearch + ) + }); + } + }; + + public render() { + const { timeNextSearch } = this.props; + return timeNextSearch ? ( + <Caption>Next search in: {this.state.timeUntilNextSearch}</Caption> + ) : ( + <div /> + ); + } +} + +export default connect(mapState)(TimeNextSearch);
89488f83171a0eb9118e825b86410cab88dca4c6
tests/cases/fourslash/navigationBarJsDoc.ts
tests/cases/fourslash/navigationBarJsDoc.ts
/// <reference path="fourslash.ts"/> // @Filename: foo.js /////** @typedef {(number|string)} NumberLike */ /////** @typedef {(string|number)} */ ////const x = 0; verify.navigationBar([ { "text": "NumberLike", "kind": "type" }, { "text": "x", "kind": "type" }, { "text": "x", "kind": "var" } ]);
Add test for jsdoc in navigation bar
Add test for jsdoc in navigation bar
TypeScript
apache-2.0
basarat/TypeScript,vilic/TypeScript,TukekeSoft/TypeScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,erikmcc/TypeScript,Eyas/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,jeremyepling/TypeScript,mihailik/TypeScript,mihailik/TypeScript,Microsoft/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,DLehenbauer/TypeScript,jeremyepling/TypeScript,mihailik/TypeScript,RyanCavanaugh/TypeScript,jeremyepling/TypeScript,weswigham/TypeScript,minestarks/TypeScript,synaptek/TypeScript,microsoft/TypeScript,donaldpipowitch/TypeScript,chuckjaz/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,SaschaNaz/TypeScript,DLehenbauer/TypeScript,mihailik/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,nojvek/TypeScript,synaptek/TypeScript,TukekeSoft/TypeScript,Eyas/TypeScript,DLehenbauer/TypeScript,Microsoft/TypeScript,jwbay/TypeScript,synaptek/TypeScript,jwbay/TypeScript,RyanCavanaugh/TypeScript,jwbay/TypeScript,basarat/TypeScript,chuckjaz/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,kitsonk/TypeScript,thr0w/Thr0wScript,RyanCavanaugh/TypeScript,vilic/TypeScript,microsoft/TypeScript,donaldpipowitch/TypeScript,basarat/TypeScript,DLehenbauer/TypeScript,TukekeSoft/TypeScript,minestarks/TypeScript,jwbay/TypeScript,thr0w/Thr0wScript,erikmcc/TypeScript,alexeagle/TypeScript,alexeagle/TypeScript,erikmcc/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,erikmcc/TypeScript,thr0w/Thr0wScript,Eyas/TypeScript,kitsonk/TypeScript,chuckjaz/TypeScript,chuckjaz/TypeScript,vilic/TypeScript,weswigham/TypeScript,thr0w/Thr0wScript,Eyas/TypeScript,donaldpipowitch/TypeScript
--- +++ @@ -0,0 +1,21 @@ +/// <reference path="fourslash.ts"/> + +// @Filename: foo.js +/////** @typedef {(number|string)} NumberLike */ +/////** @typedef {(string|number)} */ +////const x = 0; + +verify.navigationBar([ + { + "text": "NumberLike", + "kind": "type" + }, + { + "text": "x", + "kind": "type" + }, + { + "text": "x", + "kind": "var" + } +]);
d73b3126c003dbf63dd4e60525cf55a34effe9db
ui/src/shared/components/TemplateDrawer.tsx
ui/src/shared/components/TemplateDrawer.tsx
import React, {SFC, MouseEvent} from 'react' import OnClickOutside from 'react-onclickoutside' import classnames from 'classnames' import {Template} from 'src/types' interface Props { templates: Template[] selected: Template onMouseOverTempVar: ( template: Template ) => (e: MouseEvent<HTMLDivElement>) => void onClickTempVar: ( template: Template ) => (e: MouseEvent<HTMLDivElement>) => void } const TemplateDrawer: SFC<Props> = ({ templates, selected, onMouseOverTempVar, onClickTempVar, }) => ( <div className="template-drawer"> {templates.map(t => ( <div className={classnames('template-drawer--item', { 'template-drawer--selected': t.tempVar === selected.tempVar, })} onMouseOver={onMouseOverTempVar(t)} onClick={onClickTempVar(t)} key={t.tempVar} > {' '} {t.tempVar}{' '} </div> ))} </div> ) export default OnClickOutside(TemplateDrawer)
import React, {SFC, MouseEvent} from 'react' import OnClickOutside from 'react-onclickoutside' import classnames from 'classnames' import {Template} from 'src/types' interface Props { templates: Template[] selected: Template onMouseOverTempVar: ( template: Template ) => (e: MouseEvent<HTMLDivElement>) => void onClickTempVar: ( template: Template ) => (e: MouseEvent<HTMLDivElement>) => void } const TemplateDrawer: SFC<Props> = ({ templates, selected, onMouseOverTempVar, onClickTempVar, }) => ( <div className="template-drawer"> {templates.map(t => ( <div className={classnames('template-drawer--item', { 'template-drawer--selected': t.tempVar === selected.tempVar, })} onMouseOver={onMouseOverTempVar(t)} onMouseDown={onClickTempVar(t)} key={t.tempVar} > {' '} {t.tempVar}{' '} </div> ))} </div> ) export default OnClickOutside(TemplateDrawer)
Call onClickTempvar on mouseDown instead of MouseOver
Call onClickTempvar on mouseDown instead of MouseOver
TypeScript
mit
nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,li-ang/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb
--- +++ @@ -27,7 +27,7 @@ 'template-drawer--selected': t.tempVar === selected.tempVar, })} onMouseOver={onMouseOverTempVar(t)} - onClick={onClickTempVar(t)} + onMouseDown={onClickTempVar(t)} key={t.tempVar} > {' '}
5d5c99b4e618965f1fdc1113ac50983a1b0d665e
client/src/asPromise.ts
client/src/asPromise.ts
export function asPromise<T, A>(fn: (a: A, cb: (err: Error, data: T) => any) => any): (a: A) => Promise<T>; export function asPromise<T, A, B>(fn: (a: A, b: B, cb: (err: Error, data: T) => any) => any): (a: A, b: B) => Promise<T>; export function asPromise<T, A, B, C>(fn: (a: A, b: B, c: C, cb: (err: Error, data: T) => any) => any): (a: A, b: B, c: C) => Promise<T>; export function asPromise<T>(fn: (cb: (err: Error, data: T) => any) => any): () => Promise<T> { return function (...args: any[]) { const p = new Promise((resolve, reject) => { return fn.apply(this, [...args, (err: Error, data: any) => { if (err) { reject(err); } else { resolve(data); } }]); }); return p; }; }
Make converting node 4 calls to promises easier.
Make converting node 4 calls to promises easier.
TypeScript
mit
Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker,Jason-Rev/vscode-spell-checker
--- +++ @@ -0,0 +1,20 @@ + + + +export function asPromise<T, A>(fn: (a: A, cb: (err: Error, data: T) => any) => any): (a: A) => Promise<T>; +export function asPromise<T, A, B>(fn: (a: A, b: B, cb: (err: Error, data: T) => any) => any): (a: A, b: B) => Promise<T>; +export function asPromise<T, A, B, C>(fn: (a: A, b: B, c: C, cb: (err: Error, data: T) => any) => any): (a: A, b: B, c: C) => Promise<T>; +export function asPromise<T>(fn: (cb: (err: Error, data: T) => any) => any): () => Promise<T> { + return function (...args: any[]) { + const p = new Promise((resolve, reject) => { + return fn.apply(this, [...args, (err: Error, data: any) => { + if (err) { + reject(err); + } else { + resolve(data); + } + }]); + }); + return p; + }; +}
4897de1318acac29d974cb0015528373d8b63188
src/Test/Html/InlineDocument.ts
src/Test/Html/InlineDocument.ts
import { expect } from 'chai' import Up from '../../index' import { InlineUpDocument } from '../../SyntaxNodes/InlineUpDocument' describe('An empty inline document', () => { it('does not produce any HTML on its own', () => { expect(Up.toInlineHtml(new InlineUpDocument([]))).to.be.eql('') }) })
Add passing inline document HTML test
Add passing inline document HTML test
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,10 @@ +import { expect } from 'chai' +import Up from '../../index' +import { InlineUpDocument } from '../../SyntaxNodes/InlineUpDocument' + + +describe('An empty inline document', () => { + it('does not produce any HTML on its own', () => { + expect(Up.toInlineHtml(new InlineUpDocument([]))).to.be.eql('') + }) +})
91895dee9cb5bfa3b6d262ea9c2522c24c55df9e
ui/src/data_explorer/components/VisHeader.tsx
ui/src/data_explorer/components/VisHeader.tsx
import React, {PureComponent} from 'react' import {getDataForCSV} from 'src/data_explorer/apis' import VisHeaderTabs from 'src/data_explorer/components/VisHeaderTabs' import {OnToggleView} from 'src/data_explorer/components/VisHeaderTab' import {Source} from 'src/types' interface Props { source: Source views: string[] view: string query: any onToggleView: OnToggleView errorThrown: () => void } class VisHeader extends PureComponent<Props> { public render() { const {source, views, view, onToggleView, query, errorThrown} = this.props return ( <div className="graph-heading"> {!!views.length && ( <VisHeaderTabs view={view} views={views} currentView={view} onToggleView={onToggleView} /> )} {query && ( <div className="btn btn-sm btn-default dlcsv" onClick={getDataForCSV(source, query, errorThrown)} > <span className="icon download dlcsv" /> .csv </div> )} </div> ) } } export default VisHeader
import React, {PureComponent} from 'react' import {getDataForCSV} from 'src/data_explorer/apis' import RadioButtons, { RadioButton, } from 'src/reusable_ui/components/radio_buttons/RadioButtons' import {OnToggleView} from 'src/data_explorer/components/VisHeaderTab' import {Source} from 'src/types' interface Props { source: Source views: string[] view: string query: any onToggleView: OnToggleView errorThrown: () => void } class VisHeader extends PureComponent<Props> { public render() { return ( <div className="graph-heading"> {this.visTypeToggle} {this.downloadButton} </div> ) } private handleChangeVisType = (visType: RadioButton) => { const {onToggleView} = this.props const {text} = visType onToggleView(text) } private get visTypeToggle(): JSX.Element { const {views, view} = this.props const buttons = views.map(v => ({text: v})) const activeButton = {text: view} if (views.length) { return ( <RadioButtons buttons={buttons} activeButton={activeButton} onChange={this.handleChangeVisType} /> ) } return null } private get downloadButton(): JSX.Element { const {query, source, errorThrown} = this.props if (query) { return ( <div className="btn btn-sm btn-default dlcsv" onClick={getDataForCSV(source, query, errorThrown)} > <span className="icon download dlcsv" /> .CSV </div> ) } return null } } export default VisHeader
Replace DE viz tabs with RadioButtons component
Replace DE viz tabs with RadioButtons component
TypeScript
mit
influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,li-ang/influxdb,influxdata/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb
--- +++ @@ -1,6 +1,8 @@ import React, {PureComponent} from 'react' import {getDataForCSV} from 'src/data_explorer/apis' -import VisHeaderTabs from 'src/data_explorer/components/VisHeaderTabs' +import RadioButtons, { + RadioButton, +} from 'src/reusable_ui/components/radio_buttons/RadioButtons' import {OnToggleView} from 'src/data_explorer/components/VisHeaderTab' import {Source} from 'src/types' @@ -15,29 +17,57 @@ class VisHeader extends PureComponent<Props> { public render() { - const {source, views, view, onToggleView, query, errorThrown} = this.props - return ( <div className="graph-heading"> - {!!views.length && ( - <VisHeaderTabs - view={view} - views={views} - currentView={view} - onToggleView={onToggleView} - /> - )} - {query && ( - <div - className="btn btn-sm btn-default dlcsv" - onClick={getDataForCSV(source, query, errorThrown)} - > - <span className="icon download dlcsv" /> - .csv - </div> - )} + {this.visTypeToggle} + {this.downloadButton} </div> ) + } + + private handleChangeVisType = (visType: RadioButton) => { + const {onToggleView} = this.props + const {text} = visType + + onToggleView(text) + } + + private get visTypeToggle(): JSX.Element { + const {views, view} = this.props + + const buttons = views.map(v => ({text: v})) + + const activeButton = {text: view} + + if (views.length) { + return ( + <RadioButtons + buttons={buttons} + activeButton={activeButton} + onChange={this.handleChangeVisType} + /> + ) + } + + return null + } + + private get downloadButton(): JSX.Element { + const {query, source, errorThrown} = this.props + + if (query) { + return ( + <div + className="btn btn-sm btn-default dlcsv" + onClick={getDataForCSV(source, query, errorThrown)} + > + <span className="icon download dlcsv" /> + .CSV + </div> + ) + } + + return null } }
a60a101ea662409b32ed3f74b5ea4c96d2879ee4
vpatch.ts
vpatch.ts
/** * VPatch: the core type indicating changes between two VTrees. */ import VTree = require('vtree'); /** * Patches come in several flavors denoting the behavior of the * action of this patch on a VTree. */ export const enum Flavor { None, VText, VNode, Widget, Props, Order, Insert, Remove, Thunk } export class VPatch { constructor ( public flavor: Flavor , public vNode: any , public patch: any ) {} } export class VPatchSet { constructor ( public patches: Array<VPatch> , public tree0: VTree.VTree ) {} }
Introduce the basic patch types.
Introduce the basic patch types.
TypeScript
mit
tel/typescript-vdom
--- +++ @@ -0,0 +1,36 @@ +/** + * VPatch: the core type indicating changes between two VTrees. + */ + +import VTree = require('vtree'); + +/** + * Patches come in several flavors denoting the behavior of the + * action of this patch on a VTree. + */ +export const enum Flavor { + None, + VText, + VNode, + Widget, + Props, + Order, + Insert, + Remove, + Thunk +} + +export class VPatch { + constructor + ( public flavor: Flavor + , public vNode: any + , public patch: any + ) {} +} + +export class VPatchSet { + constructor + ( public patches: Array<VPatch> + , public tree0: VTree.VTree + ) {} +}
09fd55a41a8b67d5b8eece5e77879d58ef18eba4
lib/services/nativescript-cloud-extension-service.ts
lib/services/nativescript-cloud-extension-service.ts
import * as constants from "../constants"; export class NativescriptCloudExtensionService implements INativescriptCloudExtensionService { constructor(private $extensibilityService: IExtensibilityService, private $logger: ILogger) { } public install(): Promise<IExtensionData> { const installedExtensions = this.$extensibilityService.getInstalledExtensions(); if (!installedExtensions[constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME]) { return this.$extensibilityService.installExtension(constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME); } this.$logger.out(`Extension ${constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME} is already installed.`); } } $injector.register("nativescriptCloudExtensionService", NativescriptCloudExtensionService);
import * as constants from "../constants"; export class NativescriptCloudExtensionService implements INativescriptCloudExtensionService { constructor(private $extensibilityService: IExtensibilityService, private $logger: ILogger) { } public install(): Promise<IExtensionData> { const installedExtensions = this.$extensibilityService.getInstalledExtensions() || {}; if (!installedExtensions[constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME]) { return this.$extensibilityService.installExtension(constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME); } this.$logger.out(`Extension ${constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME} is already installed.`); } } $injector.register("nativescriptCloudExtensionService", NativescriptCloudExtensionService);
Fix cannot read `nativescript-cloud` of undefined error
Fix cannot read `nativescript-cloud` of undefined error
TypeScript
apache-2.0
NathanaelA/nativescript-cli,NathanaelA/nativescript-cli,NativeScript/nativescript-cli,NativeScript/nativescript-cli,NativeScript/nativescript-cli,NativeScript/nativescript-cli,NathanaelA/nativescript-cli,NathanaelA/nativescript-cli
--- +++ @@ -6,7 +6,7 @@ private $logger: ILogger) { } public install(): Promise<IExtensionData> { - const installedExtensions = this.$extensibilityService.getInstalledExtensions(); + const installedExtensions = this.$extensibilityService.getInstalledExtensions() || {}; if (!installedExtensions[constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME]) { return this.$extensibilityService.installExtension(constants.NATIVESCRIPT_CLOUD_EXTENSION_NAME); }
90a6117709aa6f8320c8e24287852879d631e582
front_end/src/app/setup/setup.component.spec.ts
front_end/src/app/setup/setup.component.spec.ts
import { SetupComponent } from './setup.component'; import { Observable } from 'rxjs/Observable'; let fixture: SetupComponent; let routerStub: any = { navigate(): void { } }; let setupServiceStup: any = { getChildrenByPhoneNumber() { return Observable.of([1, 2, 3]); } }; let rootServiceStub: any = { announceEvent(): void { } }; describe('SetupComponent', () => { beforeEach(() => { fixture = new SetupComponent(setupServiceStup, routerStub, rootServiceStub); }); describe('#ngOnInit', () => { }); describe('#reset', () => { beforeEach(() => { fixture.machineId = 'test-id'; }); it('should reset machineId to undefined', () => { expect(fixture.machineId).toEqual('test-id'); fixture.reset(); expect(fixture.machineId).toEqual(undefined); }); }); });
Add test around setup component's reset method.
Add test around setup component's reset method.
TypeScript
bsd-2-clause
crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin
--- +++ @@ -0,0 +1,43 @@ +import { SetupComponent } from './setup.component'; +import { Observable } from 'rxjs/Observable'; + +let fixture: SetupComponent; + +let routerStub: any = { + navigate(): void { + } +}; + +let setupServiceStup: any = { + getChildrenByPhoneNumber() { + return Observable.of([1, 2, 3]); + } +}; + +let rootServiceStub: any = { + announceEvent(): void { + } +}; + +describe('SetupComponent', () => { + + beforeEach(() => { + fixture = new SetupComponent(setupServiceStup, routerStub, rootServiceStub); + }); + + describe('#ngOnInit', () => { + }); + + describe('#reset', () => { + beforeEach(() => { + fixture.machineId = 'test-id'; + }); + + it('should reset machineId to undefined', () => { + expect(fixture.machineId).toEqual('test-id'); + fixture.reset(); + expect(fixture.machineId).toEqual(undefined); + }); + }); +}); +
6f4372c2d950bdcaa83ebda070c3c0a92a13d7f6
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
artivilla/desktop,kactus-io/kactus,shiftkey/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,desktop/desktop,say25/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,say25/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') + }) +})
39528878995e8baef3e3d4797a4a48078d1939d3
app/javascript/components/Pagination/Pagination.stories.tsx
app/javascript/components/Pagination/Pagination.stories.tsx
import React from 'react' import type { Story } from '@storybook/react' import Pagination from './' export default { title: 'components/Pagination', component: Pagination, decorators: [ (Story: Story) => ( <div style={{ padding: '2rem' }}> <Story /> </div> ) ] } export const Default = () => ( <Pagination buildUrl={({ page }) => `?page=${page}`} page={3} totalPages={7} /> )
Add Pagination component to storybook
Add Pagination component to storybook
TypeScript
agpl-3.0
skyderby/skyderby,skyderby/skyderby,skyderby/skyderby,skyderby/skyderby,skyderby/skyderby
--- +++ @@ -0,0 +1,20 @@ +import React from 'react' +import type { Story } from '@storybook/react' + +import Pagination from './' + +export default { + title: 'components/Pagination', + component: Pagination, + decorators: [ + (Story: Story) => ( + <div style={{ padding: '2rem' }}> + <Story /> + </div> + ) + ] +} + +export const Default = () => ( + <Pagination buildUrl={({ page }) => `?page=${page}`} page={3} totalPages={7} /> +)
04bc2e9995b417fd66530d1def93c7e068fbdd81
src/components/geo-map/geo-map.component.spec.ts
src/components/geo-map/geo-map.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { GeoMapComponent } from './geo-map.component'; import { GeoMapD3 } from '../../d3/geo-map.d3'; describe('GeoMapComponent', () => { let fixture: ComponentFixture<GeoMapComponent>; let component: GeoMapComponent; let geoMapD3: GeoMapD3; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ GeoMapComponent, ], }); fixture = TestBed.createComponent(GeoMapComponent); component = fixture.componentInstance; geoMapD3 = component.geoMapD3; }); it('should instantiate.', () => { expect(component).toBeInstanceOf(GeoMapComponent); }); it('should render d3 on init.', () => { spyOn(geoMapD3, 'render'); component.ngOnInit(); expect(geoMapD3.render).toHaveBeenCalled(); }); it('should clear d3 on destroy.', () => { spyOn(geoMapD3, 'clear'); component.ngOnDestroy(); expect(geoMapD3.clear).toHaveBeenCalled(); }); });
Add tests for geo map component
Add tests for geo map component
TypeScript
apache-2.0
googleinterns/guide-doge,googleinterns/guide-doge,googleinterns/guide-doge
--- +++ @@ -0,0 +1,36 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { GeoMapComponent } from './geo-map.component'; +import { GeoMapD3 } from '../../d3/geo-map.d3'; + +describe('GeoMapComponent', () => { + let fixture: ComponentFixture<GeoMapComponent>; + let component: GeoMapComponent; + let geoMapD3: GeoMapD3; + + beforeEach(() => { + TestBed.configureTestingModule({ + declarations: [ + GeoMapComponent, + ], + }); + fixture = TestBed.createComponent(GeoMapComponent); + component = fixture.componentInstance; + geoMapD3 = component.geoMapD3; + }); + + it('should instantiate.', () => { + expect(component).toBeInstanceOf(GeoMapComponent); + }); + + it('should render d3 on init.', () => { + spyOn(geoMapD3, 'render'); + component.ngOnInit(); + expect(geoMapD3.render).toHaveBeenCalled(); + }); + + it('should clear d3 on destroy.', () => { + spyOn(geoMapD3, 'clear'); + component.ngOnDestroy(); + expect(geoMapD3.clear).toHaveBeenCalled(); + }); +});
fbe4e89077f57b73f76641132098832835f64879
app/test/unit/onboarding-tutorial-test.ts
app/test/unit/onboarding-tutorial-test.ts
import { setupOnboardingTutorialRepo } from '../helpers/repositories' describe('OnboardingTutorial', () => { describe('isEditorInstalled()', () => { it('returns true if step has been skipped', async () => { const repo = await setupOnboardingTutorialRepo() }) it('returns true if resolved editor exists', () => {}) }) })
Add some basic structure for OnboardingTutorial test
Add some basic structure for OnboardingTutorial test
TypeScript
mit
artivilla/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,say25/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,say25/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,say25/desktop,j-f1/forked-desktop
--- +++ @@ -0,0 +1,11 @@ +import { setupOnboardingTutorialRepo } from '../helpers/repositories' + +describe('OnboardingTutorial', () => { + describe('isEditorInstalled()', () => { + it('returns true if step has been skipped', async () => { + const repo = await setupOnboardingTutorialRepo() + }) + + it('returns true if resolved editor exists', () => {}) + }) +})
69663a63140981655d282871c76c515aa5a6d938
server/routes/passport.ts
server/routes/passport.ts
///<reference path="../../typings/globals/passport/index.d.ts"/> ///<reference path="../../typings/globals/passport-local/index.d.ts"/> ///<reference path="../../typings/globals/bcryptjs/index.d.ts"/> ///<reference path="../../typings/globals/mysql/index.d.ts"/> ///<reference path="../../typings/globals/connect-flash/index.d.ts"/> import { Router, Request, Response } from "express"; import * as passport from "passport"; import * as session from 'express-session'; import * as localStrategy from "passport-local"; import * as bcrypt from "bcryptjs" import * as mysql from 'mysql'; var flash = require('connect-flash') import { User } from '../../client/sharedClasses/user'; import { dbConfig } from '../config'; let LocalStrategy = localStrategy.Strategy; let connection = mysql.createConnection(dbConfig); const authRouter: Router = Router(); /** * Serialize the user details to persistent login session */ passport.serializeUser((user: User, done) => { done(null, { id: user.id, fisrtName: user.first_name, lastName: user.last_name, email: user.email, district: user.district, userType: user.type }); }); /** * Deserialize user details from login session */ passport.deserializeUser((user, done) => { done(null, user); }); /** * Login with LocalStrategy */ passport.use('local-login', new LocalStrategy({ usernameField: 'email', passwordField: 'password', }, (email, password, done) => { connection.query('SELECT * FROM users WHERE email = ?', [email], (err, rows) => { if (err) { return done(err); } if (!rows.length) { console.log('no user found') return done(null, false, { message: 'User not found' }); } if (!bcrypt.compareSync(password, rows[0].password)) { console.log('incorrect password'); return done(null, false, { message: 'Oops! Wrong password' }); } console.log('password correct'); return done(null, rows[0]); }); })); authRouter.use(passport.initialize()); authRouter.use(passport.session()); authRouter.post('/login', passport.authenticate('local-login', { failureRedirect: '/#/initquiz', // redirect back to the signup page if there is an error }), (req, res) => { console.log("hello"); // if (req.body.remember) { // req.session.cookie.maxAge = 1000 * 60 * 3; // } else { // req.session.cookie.expires = false; // } console.log(req.body); console.log(res); res.redirect('/#/home'); }); authRouter.use(flash()); export { authRouter, passport }
Add login functionality with Passport JS
Add login functionality with Passport JS
TypeScript
mit
shavindraSN/examen,shavindraSN/examen,shavindraSN/examen
--- +++ @@ -0,0 +1,88 @@ +///<reference path="../../typings/globals/passport/index.d.ts"/> +///<reference path="../../typings/globals/passport-local/index.d.ts"/> +///<reference path="../../typings/globals/bcryptjs/index.d.ts"/> +///<reference path="../../typings/globals/mysql/index.d.ts"/> +///<reference path="../../typings/globals/connect-flash/index.d.ts"/> + +import { Router, Request, Response } from "express"; +import * as passport from "passport"; +import * as session from 'express-session'; +import * as localStrategy from "passport-local"; +import * as bcrypt from "bcryptjs" +import * as mysql from 'mysql'; +var flash = require('connect-flash') + +import { User } from '../../client/sharedClasses/user'; +import { dbConfig } from '../config'; + +let LocalStrategy = localStrategy.Strategy; +let connection = mysql.createConnection(dbConfig); +const authRouter: Router = Router(); + +/** + * Serialize the user details to persistent login session + */ +passport.serializeUser((user: User, done) => { + done(null, { + id: user.id, + fisrtName: user.first_name, + lastName: user.last_name, + email: user.email, + district: user.district, + userType: user.type + }); +}); + +/** + * Deserialize user details from login session + */ +passport.deserializeUser((user, done) => { + done(null, user); +}); + +/** + * Login with LocalStrategy + */ +passport.use('local-login', new LocalStrategy({ + usernameField: 'email', + passwordField: 'password', +}, (email, password, done) => { + connection.query('SELECT * FROM users WHERE email = ?', [email], (err, rows) => { + if (err) { + return done(err); + } + if (!rows.length) { + console.log('no user found') + return done(null, false, { message: 'User not found' }); + } + if (!bcrypt.compareSync(password, rows[0].password)) { + console.log('incorrect password'); + return done(null, false, { message: 'Oops! Wrong password' }); + } + console.log('password correct'); + return done(null, rows[0]); + }); +})); +authRouter.use(passport.initialize()); +authRouter.use(passport.session()); + + +authRouter.post('/login', passport.authenticate('local-login', { + failureRedirect: '/#/initquiz', // redirect back to the signup page if there is an error +}), + (req, res) => { + console.log("hello"); + + // if (req.body.remember) { + // req.session.cookie.maxAge = 1000 * 60 * 3; + // } else { + // req.session.cookie.expires = false; + // } + console.log(req.body); + console.log(res); + res.redirect('/#/home'); + }); + +authRouter.use(flash()); + +export { authRouter, passport }
f87a85522495a367fda7021172a5c03b211284bb
src/test/components/ng-http-loader.component.on-push.spec.ts
src/test/components/ng-http-loader.component.on-push.spec.ts
/* * 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 { HttpClient } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ChangeDetectionStrategy, Component } from '@angular/core'; import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NgHttpLoaderModule } from '../../lib/ng-http-loader.module'; @Component({ template: '<ng-http-loader></ng-http-loader>', changeDetection: ChangeDetectionStrategy.OnPush }) export class HostComponent { } describe('NgHttpLoaderComponent OnPush', () => { let component: HostComponent; let fixture: ComponentFixture<HostComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [HostComponent], imports: [HttpClientTestingModule, NgHttpLoaderModule.forRoot()] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HostComponent); component = fixture.componentInstance; }); it('should work as expected when the host component has ChangeDetectionStrategy.OnPush', fakeAsync(inject( [HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => { http.get('/fake').subscribe(); tick(); fixture.detectChanges(); let spinner = fixture .debugElement .query(By.css('#spinner')) .nativeElement; expect(spinner).toBeTruthy(); httpMock.expectOne('/fake').flush({}); tick(); fixture.detectChanges(); spinner = fixture .debugElement .query(By.css('#spinner')); expect(spinner).toBeNull(); } ))); });
Add test with ChangeDetectionStrategy.OnPush on an host component
Add test with ChangeDetectionStrategy.OnPush on an host component
TypeScript
mit
mpalourdio/ng-http-loader,mpalourdio/ng-http-loader,mpalourdio/ng-http-loader
--- +++ @@ -0,0 +1,62 @@ +/* + * 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 { HttpClient } from '@angular/common/http'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { NgHttpLoaderModule } from '../../lib/ng-http-loader.module'; + +@Component({ + template: '<ng-http-loader></ng-http-loader>', + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class HostComponent { +} + +describe('NgHttpLoaderComponent OnPush', () => { + let component: HostComponent; + let fixture: ComponentFixture<HostComponent>; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [HostComponent], + imports: [HttpClientTestingModule, NgHttpLoaderModule.forRoot()] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(HostComponent); + component = fixture.componentInstance; + }); + + it('should work as expected when the host component has ChangeDetectionStrategy.OnPush', fakeAsync(inject( + [HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => { + http.get('/fake').subscribe(); + tick(); + fixture.detectChanges(); + let spinner = fixture + .debugElement + .query(By.css('#spinner')) + .nativeElement; + expect(spinner).toBeTruthy(); + + httpMock.expectOne('/fake').flush({}); + tick(); + fixture.detectChanges(); + + spinner = fixture + .debugElement + .query(By.css('#spinner')); + expect(spinner).toBeNull(); + } + ))); +});
7c39eaae7e7bd3410a02dd0dec3336429fa36bea
src/Test/Ast/Dash.ts
src/Test/Ast/Dash.ts
import { expect } from 'chai' import Up from '../../index' import { insideDocumentAndParagraph } from './Helpers' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' context('2 consecutive dashes normally produce an en dash.', () => { specify('This applies in regular text', () => { expect(Up.toAst("Okay--I'll eat the tarantula.")).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode("Okay–I'll eat the tarantula.") ])) }) }) describe('When either of the dashes are escaped, no en dash is produced:', () => { specify('First dash:', () => { expect(Up.toAst("Okay\\--I'll eat the tarantula.")).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode("Okay--I'll eat the tarantula.") ])) }) specify('Second dash:', () => { expect(Up.toAst("Okay-\\-I'll eat the tarantula.")).to.be.eql( insideDocumentAndParagraph([ new PlainTextNode("Okay--I'll eat the tarantula.") ])) }) })
Add 2 passing and 1 failing en dash test
Add 2 passing and 1 failing en dash test
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,31 @@ +import { expect } from 'chai' +import Up from '../../index' +import { insideDocumentAndParagraph } from './Helpers' +import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' + + +context('2 consecutive dashes normally produce an en dash.', () => { + specify('This applies in regular text', () => { + expect(Up.toAst("Okay--I'll eat the tarantula.")).to.be.eql( + insideDocumentAndParagraph([ + new PlainTextNode("Okay–I'll eat the tarantula.") + ])) + }) +}) + + +describe('When either of the dashes are escaped, no en dash is produced:', () => { + specify('First dash:', () => { + expect(Up.toAst("Okay\\--I'll eat the tarantula.")).to.be.eql( + insideDocumentAndParagraph([ + new PlainTextNode("Okay--I'll eat the tarantula.") + ])) + }) + + specify('Second dash:', () => { + expect(Up.toAst("Okay-\\-I'll eat the tarantula.")).to.be.eql( + insideDocumentAndParagraph([ + new PlainTextNode("Okay--I'll eat the tarantula.") + ])) + }) +})
9297ece17633e28fa2bb97dc1f44d2df3958cd8d
src/test/javascript/e2e/entities/oauth-client.spec.ts
src/test/javascript/e2e/entities/oauth-client.spec.ts
import { browser, element, by, $ } from 'protractor'; describe('Project e2e test', () => { const username = element(by.id('username')); const password = element(by.id('password')); const adminMenu = element(by.id('admin-menu')); const accountMenu = element(by.id('account-menu')); const login = element(by.id('login')); const logout = element(by.id('logout')); beforeAll(() => { browser.get('/'); accountMenu.click(); login.click(); username.sendKeys('admin'); password.sendKeys('admin'); element(by.css('button[type=submit]')).click(); browser.waitForAngular(); }); it('should load OAuth clients', () => { adminMenu.click(); element.all(by.css('[routerLink="oauth-client"]')).first().click().then(() => { const expectVal = /managementPortalApp.oauthClient.home.title/; element.all(by.css('h4 span')).first().getAttribute('jhiTranslate').then((value) => { expect(value).toMatch(expectVal); }); }); }); it('should load create OAuth Client dialog', () => { element(by.css('jhi-oauth-client h4 button.btn-primary')).click().then(() => { const expectVal = /managementPortalApp.oauthClient.home.createOrEditLabel/; element.all(by.css('h4.modal-title')).first().getAttribute('jhiTranslate').then((value) => { expect(value).toMatch(expectVal); }); element(by.css('button.close')).click(); }); }); it('should disable edit and delete buttons for protected clients', () => { // find the table row that contains the protected badge, and assert it contains zero enabled buttons element(by.cssContainingText('span.badge-info', 'protected: true')).element(by.xpath('ancestor::tr')) .all(by.css('button')).filter((button) => button.isEnabled()).count().then((count) => expect(count).toEqual(0)); }); afterAll(function () { accountMenu.click(); logout.click(); }); });
Add e2e test for oauth-client component
Add e2e test for oauth-client component
TypeScript
apache-2.0
RADAR-CNS/ManagementPortal,RADAR-CNS/ManagementPortal,RADAR-CNS/ManagementPortal,RADAR-CNS/ManagementPortal,RADAR-CNS/ManagementPortal
--- +++ @@ -0,0 +1,56 @@ +import { browser, element, by, $ } from 'protractor'; + +describe('Project e2e test', () => { + + const username = element(by.id('username')); + const password = element(by.id('password')); + const adminMenu = element(by.id('admin-menu')); + const accountMenu = element(by.id('account-menu')); + const login = element(by.id('login')); + const logout = element(by.id('logout')); + + beforeAll(() => { + browser.get('/'); + + accountMenu.click(); + login.click(); + + username.sendKeys('admin'); + password.sendKeys('admin'); + element(by.css('button[type=submit]')).click(); + browser.waitForAngular(); + }); + + it('should load OAuth clients', () => { + adminMenu.click(); + element.all(by.css('[routerLink="oauth-client"]')).first().click().then(() => { + const expectVal = /managementPortalApp.oauthClient.home.title/; + element.all(by.css('h4 span')).first().getAttribute('jhiTranslate').then((value) => { + expect(value).toMatch(expectVal); + }); + }); + }); + + it('should load create OAuth Client dialog', () => { + element(by.css('jhi-oauth-client h4 button.btn-primary')).click().then(() => { + const expectVal = /managementPortalApp.oauthClient.home.createOrEditLabel/; + element.all(by.css('h4.modal-title')).first().getAttribute('jhiTranslate').then((value) => { + expect(value).toMatch(expectVal); + }); + + element(by.css('button.close')).click(); + }); + }); + + it('should disable edit and delete buttons for protected clients', () => { + // find the table row that contains the protected badge, and assert it contains zero enabled buttons + element(by.cssContainingText('span.badge-info', 'protected: true')).element(by.xpath('ancestor::tr')) + .all(by.css('button')).filter((button) => button.isEnabled()).count().then((count) => + expect(count).toEqual(0)); + }); + + afterAll(function () { + accountMenu.click(); + logout.click(); + }); +});
c8fe5a5b94139f9998d1da856e791cb80fa1b6e6
tests/pos/misc/func-arg.ts
tests/pos/misc/func-arg.ts
// "Fatal error: exception Parsing.Parse_error" /*@ foo :: (func:number) => number */ function foo(func:number) { return func } // SAFE /*@ bar :: (xunc:number) => number */ function bar(xunc:number) { return xunc }
Add test for argument named 'func'
Add test for argument named 'func'
TypeScript
bsd-3-clause
UCSD-PL/RefScript,UCSD-PL/RefScript,UCSD-PL/RefScript
--- +++ @@ -0,0 +1,11 @@ +// "Fatal error: exception Parsing.Parse_error" +/*@ foo :: (func:number) => number */ +function foo(func:number) { + return func +} + +// SAFE +/*@ bar :: (xunc:number) => number */ +function bar(xunc:number) { + return xunc +}
63211a477b67d9ffbcf62613dc2ab7a41e14130a
types/react-radio-group/react-radio-group-tests.tsx
types/react-radio-group/react-radio-group-tests.tsx
import * as React from 'react'; import { Radio, RadioGroup } from "react-radio-group"; class ReactRadioGroup extends React.Component<RadioGroup.RadioGroupProps> { handleChange: RadioGroup.RadioGroupProps['onChange'] = value => { console.log(value); } render() { return ( <div> <RadioGroup name="radioGroup" onChange={this.handleChange} selectedValue={2}> <Radio id="Option A" value="a" /> <Radio id="Option B" value={2} /> <Radio id="Option C" value={["hello"]} disabled /> </RadioGroup> </div> ); } }
import * as React from 'react'; import { Radio, RadioGroup } from "react-radio-group"; class ReactRadioGroup extends React.Component<RadioGroup.RadioGroupProps, { selectedValue: React.InputHTMLAttributes<HTMLInputElement>['value'] }> { state = { selectedValue: 2, }; handleChange: RadioGroup.RadioGroupProps['onChange'] = selectedValue => { console.log(selectedValue); this.setState({ selectedValue }); } render() { return ( <div> <RadioGroup name="radioGroup" onChange={this.handleChange} selectedValue={this.state.selectedValue}> <Radio id="Option A" value="a" /> <Radio id="Option B" value={2} /> <Radio id="Option C" value={["hello"]} disabled /> </RadioGroup> </div> ); } }
Update test to set state on change
Update test to set state on change
TypeScript
mit
dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,magny/DefinitelyTyped,rolandzwaga/DefinitelyTyped,mcliment/DefinitelyTyped,one-pieces/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped
--- +++ @@ -1,15 +1,20 @@ import * as React from 'react'; import { Radio, RadioGroup } from "react-radio-group"; -class ReactRadioGroup extends React.Component<RadioGroup.RadioGroupProps> { - handleChange: RadioGroup.RadioGroupProps['onChange'] = value => { - console.log(value); +class ReactRadioGroup extends React.Component<RadioGroup.RadioGroupProps, { selectedValue: React.InputHTMLAttributes<HTMLInputElement>['value'] }> { + state = { + selectedValue: 2, + }; + + handleChange: RadioGroup.RadioGroupProps['onChange'] = selectedValue => { + console.log(selectedValue); + this.setState({ selectedValue }); } render() { return ( <div> - <RadioGroup name="radioGroup" onChange={this.handleChange} selectedValue={2}> + <RadioGroup name="radioGroup" onChange={this.handleChange} selectedValue={this.state.selectedValue}> <Radio id="Option A" value="a" /> <Radio id="Option B" value={2} /> <Radio id="Option C" value={["hello"]} disabled />
aa247ba4458c734a77209630e303a140f5cf1594
src/app/home/home.spec.ts
src/app/home/home.spec.ts
import { beforeEachProviders, describe, expect, it, inject, } from '@angular/core/testing'; import { Inject, Injector } from '@angular/core/index'; import { Component, Injectable } from '@angular/core'; import { TestComponentBuilder } from '@angular/compiler/testing'; import { HomeComponent } from './home.component'; // let optimizationInfo = new ControlGroup({ // symbols: new Control(['GOOG', 'FB', 'HP']), // startDate: new Control('01-01-12'), // endDate: new Control('03-20-16'), // initialInvestment: new Control(1000) // }); // Test DOM interactions describe('The HomeComponent together with the DOM', () => { beforeEachProviders(() => [ TestComponentBuilder, HomeComponent ]); it('should have three child components', inject([TestComponentBuilder], (tcb) => { var html = `<user-input></user-input><barchart></barchart><results-table></results-table>`; tcb.overrideTemplate(html); return tcb.createAsync(HomeComponent).then(fixture => { let home = fixture.componentInstance; let element = fixture.nativeElement; fixture.detectChanges(); //trigger change detection expect(element.querySelector('user-input')).not.toBeNull(); }) .catch(e => console.log(e)); })); // beforeEachProviders(() => [ // ROUTER_PROVIDERS, // provide(ROUTER_PRIMARY_COMPONENT, { useValue: HomeComponent }), // provide(ApplicationRef, { useClass: MockApplicationRef }), // provide(APP_BASE_HREF, { useValue: '/' }), // ]); // it('should contain the user input, barchart, and results table components.', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { // return tcb.createAsync(TestComponent).then((fixture) => { // fixture.detectChanges(); // let compiled = fixture.debugElement.nativeElement; // expect(compiled).toBeDefined(); // console.log(compiled); // expect(compiled.querySelector('user-inpt')) // .not.toBeNull(); // expect(compiled.querySelector('barchart')) // .not.toBeNull(); // expect(compiled.querySelector('results-table')) // .not.toBeNull(); // }); // })); });
Reduce scope of home component unit tests.
Reduce scope of home component unit tests.
TypeScript
mit
coshx/portfolio_optimizer,coshx/portfolio_optimizer,coshx/portfolio_optimizer,coshx/portfolio_optimizer
--- +++ @@ -0,0 +1,62 @@ +import { + beforeEachProviders, + describe, + expect, + it, + inject, +} from '@angular/core/testing'; +import { Inject, Injector } from '@angular/core/index'; +import { Component, Injectable } from '@angular/core'; +import { TestComponentBuilder } from '@angular/compiler/testing'; +import { HomeComponent } from './home.component'; + +// let optimizationInfo = new ControlGroup({ +// symbols: new Control(['GOOG', 'FB', 'HP']), +// startDate: new Control('01-01-12'), +// endDate: new Control('03-20-16'), +// initialInvestment: new Control(1000) +// }); + +// Test DOM interactions +describe('The HomeComponent together with the DOM', () => { + beforeEachProviders(() => [ + TestComponentBuilder, + HomeComponent + ]); + + it('should have three child components', inject([TestComponentBuilder], (tcb) => { + var html = `<user-input></user-input><barchart></barchart><results-table></results-table>`; + tcb.overrideTemplate(html); + return tcb.createAsync(HomeComponent).then(fixture => { + let home = fixture.componentInstance; + let element = fixture.nativeElement; + fixture.detectChanges(); //trigger change detection + expect(element.querySelector('user-input')).not.toBeNull(); + }) + .catch(e => console.log(e)); + })); + + + + // beforeEachProviders(() => [ + // ROUTER_PROVIDERS, + // provide(ROUTER_PRIMARY_COMPONENT, { useValue: HomeComponent }), + // provide(ApplicationRef, { useClass: MockApplicationRef }), + // provide(APP_BASE_HREF, { useValue: '/' }), + // ]); + + // it('should contain the user input, barchart, and results table components.', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { + // return tcb.createAsync(TestComponent).then((fixture) => { + // fixture.detectChanges(); + // let compiled = fixture.debugElement.nativeElement; + // expect(compiled).toBeDefined(); + // console.log(compiled); + // expect(compiled.querySelector('user-inpt')) + // .not.toBeNull(); + // expect(compiled.querySelector('barchart')) + // .not.toBeNull(); + // expect(compiled.querySelector('results-table')) + // .not.toBeNull(); + // }); + // })); +});
c9167df45d9563d817e9d8d5be580e0ab0c682a7
spec/mobilev3playerapi.spec.ts
spec/mobilev3playerapi.spec.ts
import { PlayerAPI } from 'bitmovin-player'; import { isMobileV3PlayerAPI, MobileV3PlayerAPI, MobileV3PlayerEvent } from '../src/ts/mobilev3playerapi'; import { PlayerWrapper } from '../src/ts/uimanager'; describe('isMobileV3PlayerAPI', () => { const playerApi = { exports: { PlayerEvent: { } } } as PlayerAPI; const mobileV3PlayerApi = { exports: { PlayerEvent: MobileV3PlayerEvent } } as unknown as MobileV3PlayerAPI; const wrappedPlayerApi = new PlayerWrapper(playerApi); const wrappedMobileV3PlayerApi = new PlayerWrapper(mobileV3PlayerApi); it('should return false for a regular PlayerAPI instance', () => { expect(isMobileV3PlayerAPI(playerApi)).toBeFalsy(); }); it('should return false for a regular wrapped PlayerAPI instance', () => { expect(isMobileV3PlayerAPI(wrappedPlayerApi.getPlayer())).toBeFalsy(); }); it('should return true for a mobile v3 PlayerAPI instance', () => { expect(isMobileV3PlayerAPI(mobileV3PlayerApi)).toBeTruthy(); }); it('should return false for a mobile v3 wrapped PlayerAPI instance', () => { expect(isMobileV3PlayerAPI(wrappedMobileV3PlayerApi.getPlayer())).toBeTruthy(); }); });
Add unit tests for isMobileV3PlayerAPI
Add unit tests for isMobileV3PlayerAPI
TypeScript
mit
bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui
--- +++ @@ -0,0 +1,26 @@ +import { PlayerAPI } from 'bitmovin-player'; +import { isMobileV3PlayerAPI, MobileV3PlayerAPI, MobileV3PlayerEvent } from '../src/ts/mobilev3playerapi'; +import { PlayerWrapper } from '../src/ts/uimanager'; + +describe('isMobileV3PlayerAPI', () => { + const playerApi = { exports: { PlayerEvent: { } } } as PlayerAPI; + const mobileV3PlayerApi = { exports: { PlayerEvent: MobileV3PlayerEvent } } as unknown as MobileV3PlayerAPI; + const wrappedPlayerApi = new PlayerWrapper(playerApi); + const wrappedMobileV3PlayerApi = new PlayerWrapper(mobileV3PlayerApi); + + it('should return false for a regular PlayerAPI instance', () => { + expect(isMobileV3PlayerAPI(playerApi)).toBeFalsy(); + }); + + it('should return false for a regular wrapped PlayerAPI instance', () => { + expect(isMobileV3PlayerAPI(wrappedPlayerApi.getPlayer())).toBeFalsy(); + }); + + it('should return true for a mobile v3 PlayerAPI instance', () => { + expect(isMobileV3PlayerAPI(mobileV3PlayerApi)).toBeTruthy(); + }); + + it('should return false for a mobile v3 wrapped PlayerAPI instance', () => { + expect(isMobileV3PlayerAPI(wrappedMobileV3PlayerApi.getPlayer())).toBeTruthy(); + }); +});
c77498da9ee7bcfbbc2129a3bec6d3311cfdd6ed
test/unit/core/images/row/image-row.spec.ts
test/unit/core/images/row/image-row.spec.ts
import {ImageDocument} from 'idai-components-2'; import {ImageRow} from '../../../../../app/core/images/row/image-row'; describe('ImageRow', () => { it('first page', () => { const imageDocuments = [ { resource: { type: 'Drawing', id: 'i1', identifier: 'I1', width: 100, height: 100, relations: { depicts: []}, shortDescription: 'S1', originalFilename: 'blub' } } ] as unknown as Array<ImageDocument>; const imageRow = new ImageRow(1000, 100, 100, imageDocuments); const nextPageResult = imageRow.nextPage(); expect(nextPageResult.newImageIds).toEqual(['i1']); expect(nextPageResult.scrollWidth).toBe(0); }); });
Add unit test for image-row
Add unit test for image-row
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -0,0 +1,25 @@ +import {ImageDocument} from 'idai-components-2'; +import {ImageRow} from '../../../../../app/core/images/row/image-row'; + + +describe('ImageRow', () => { + + it('first page', () => { + + const imageDocuments = [ + { + resource: { + type: 'Drawing', id: 'i1', identifier: 'I1', width: 100, + height: 100, relations: { depicts: []}, + shortDescription: 'S1', originalFilename: 'blub' + } + } + ] as unknown as Array<ImageDocument>; + + const imageRow = new ImageRow(1000, 100, 100, imageDocuments); + + const nextPageResult = imageRow.nextPage(); + expect(nextPageResult.newImageIds).toEqual(['i1']); + expect(nextPageResult.scrollWidth).toBe(0); + }); +});
41a121deab7230ebcfef1ab2fc45af16eaf6dd36
app/src/ui/ui-view.tsx
app/src/ui/ui-view.tsx
import * as React from 'react' interface IUiViewProps extends React.Props<UiView> { id?: string } export class UiView extends React.Component<IUiViewProps, void> { public render() { return <div id={this.props.id} className='ui-view'> {this.props.children} </div> } }
Add a high-order view component
Add a high-order view component
TypeScript
mit
BugTesterTest/desktops,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,say25/desktop,BugTesterTest/desktops,gengjiawen/desktop,desktop/desktop,hjobrien/desktop,artivilla/desktop,hjobrien/desktop,shiftkey/desktop,shiftkey/desktop,say25/desktop,say25/desktop,hjobrien/desktop,j-f1/forked-desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,kactus-io/kactus,BugTesterTest/desktops,shiftkey/desktop,kactus-io/kactus,hjobrien/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,desktop/desktop,artivilla/desktop,gengjiawen/desktop,gengjiawen/desktop,BugTesterTest/desktops
--- +++ @@ -0,0 +1,13 @@ +import * as React from 'react' + +interface IUiViewProps extends React.Props<UiView> { + id?: string +} + +export class UiView extends React.Component<IUiViewProps, void> { + public render() { + return <div id={this.props.id} className='ui-view'> + {this.props.children} + </div> + } +}
958f8cdaa054f333b604020d272c0fd4822955aa
src/actions/databaseFilterSettings.ts
src/actions/databaseFilterSettings.ts
import { updateValue } from './updateValue'; import { UPDATE_DB_SEARCH_TERM } from '../constants'; export interface UpdateDatabaseSearchTerm { readonly type: UPDATE_DB_SEARCH_TERM; readonly data: string; } export const changeSearchTerm = updateValue<string>(UPDATE_DB_SEARCH_TERM);
Add action to update database search term.
Add action to update database search term.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -0,0 +1,9 @@ +import { updateValue } from './updateValue'; +import { UPDATE_DB_SEARCH_TERM } from '../constants'; + +export interface UpdateDatabaseSearchTerm { + readonly type: UPDATE_DB_SEARCH_TERM; + readonly data: string; +} + +export const changeSearchTerm = updateValue<string>(UPDATE_DB_SEARCH_TERM);
8696943a9c3fc4e235b0a25370ae61984fa40792
src/delir-core/src/renderer/pipeline/ExpressionContext.ts
src/delir-core/src/renderer/pipeline/ExpressionContext.ts
import RenderingRequest from './render-request' import {Clip} from '../../project' import {ParameterValueTypes} from '../../plugin-support/type-descriptor' export interface Exposes { req: RenderingRequest clipProperties: {[propName: string]: ParameterValueTypes} currentValue: any } export const makeContext = (exposes: Exposes) => { const clipPropertyProxy = new Proxy(exposes.clipProperties, { set: () => { throw new Error(`Illegal property setting in expression`) } }) return { console, get time() { return exposes.req.time }, get frame() { return exposes.req.frame }, get timeOnComposition() { return exposes.req.timeOnComposition }, get frameOnComposition() { return exposes.req.frameOnComposition }, get width() { return exposes.req.width }, get height() { return exposes.req.height }, get audioBuffer() { return exposes.req.destAudioBuffer }, get duration() { return exposes.req.durationFrames / exposes.req.framerate }, get durationFrames() { return exposes.req.durationFrames }, get clipProp() { return clipPropertyProxy }, get currentValue() { return exposes.currentValue }, } } export const expressionContextTypeDefinition = ` interface Clip {} declare const time: number; declare const time: number; declare const frame: number; declare const timeOnComposition: number; declare const frameOnComposition: number; declare const width: number; declare const height: number; declare const audioBuffer: Float32Array[]; declare const duration: number; declare const durationFrames: number; declare const clipProp: {[propertyName: string]: any}; declare const currentValue: any; `
Implement expression support (without UI)
Implement expression support (without UI)
TypeScript
mit
Ragg-/Delir,Ragg-/Delir,Ragg-/Delir,Ragg-/Delir
--- +++ @@ -0,0 +1,47 @@ +import RenderingRequest from './render-request' +import {Clip} from '../../project' +import {ParameterValueTypes} from '../../plugin-support/type-descriptor' + +export interface Exposes { + req: RenderingRequest + clipProperties: {[propName: string]: ParameterValueTypes} + currentValue: any +} + +export const makeContext = (exposes: Exposes) => { + const clipPropertyProxy = new Proxy(exposes.clipProperties, { + set: () => { throw new Error(`Illegal property setting in expression`) } + }) + + return { + console, + get time() { return exposes.req.time }, + get frame() { return exposes.req.frame }, + get timeOnComposition() { return exposes.req.timeOnComposition }, + get frameOnComposition() { return exposes.req.frameOnComposition }, + get width() { return exposes.req.width }, + get height() { return exposes.req.height }, + get audioBuffer() { return exposes.req.destAudioBuffer }, + get duration() { return exposes.req.durationFrames / exposes.req.framerate }, + get durationFrames() { return exposes.req.durationFrames }, + get clipProp() { return clipPropertyProxy }, + get currentValue() { return exposes.currentValue }, + } +} + +export const expressionContextTypeDefinition = ` +interface Clip {} + +declare const time: number; +declare const time: number; +declare const frame: number; +declare const timeOnComposition: number; +declare const frameOnComposition: number; +declare const width: number; +declare const height: number; +declare const audioBuffer: Float32Array[]; +declare const duration: number; +declare const durationFrames: number; +declare const clipProp: {[propertyName: string]: any}; +declare const currentValue: any; +`
f0b7dfd49389f0ecba9ee6ccab0825a5fa5fddef
tests/cases/fourslash/quickInfoForIndexerResultWithConstraint.ts
tests/cases/fourslash/quickInfoForIndexerResultWithConstraint.ts
/// <reference path='fourslash.ts'/> ////function foo<T>(x: T) { //// return x; ////} ////function other2<T extends Date>(arg: T) { //// var b: { [x: string]: T }; //// var r2/*1*/ = foo(b); // just shows T ////} goTo.marker('1'); verify.quickInfoIs('{ [x: string]: T; }');
Test update for resolved bug
Test update for resolved bug
TypeScript
apache-2.0
hippich/typescript,mbebenita/shumway.ts,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,hippich/typescript,popravich/typescript,mbebenita/shumway.ts,hippich/typescript,popravich/typescript,popravich/typescript,fdecampredon/jsx-typescript-old-version
--- +++ @@ -0,0 +1,13 @@ +/// <reference path='fourslash.ts'/> + +////function foo<T>(x: T) { +//// return x; +////} + +////function other2<T extends Date>(arg: T) { +//// var b: { [x: string]: T }; +//// var r2/*1*/ = foo(b); // just shows T +////} + +goTo.marker('1'); +verify.quickInfoIs('{ [x: string]: T; }');
2e44bccb36566596a15a7c1b9763ddb1b88afc7b
tests/cases/fourslash/renameDestructuringNestedBindingElement.ts
tests/cases/fourslash/renameDestructuringNestedBindingElement.ts
/// <reference path='fourslash.ts' /> ////interface MultiRobot { //// name: string; //// skills: { //// [|primary|]: string; //// secondary: string; //// }; ////} ////let multiRobots: MultiRobot[]; ////for (let { skills: {[|primary|]: primaryA, secondary: secondaryA } } of multiRobots) { //// console.log(primaryA); ////} ////for (let { skills: {[|primary|], secondary } } of multiRobots) { //// console.log([|primary|]); ////} let ranges = test.ranges() for (let range of ranges) { goTo.position(range.start); verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false); }
Test case for nested binding element's rename
Test case for nested binding element's rename
TypeScript
apache-2.0
synaptek/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,thr0w/Thr0wScript,ziacik/TypeScript,erikmcc/TypeScript,kitsonk/TypeScript,synaptek/TypeScript,microsoft/TypeScript,ziacik/TypeScript,TukekeSoft/TypeScript,TukekeSoft/TypeScript,erikmcc/TypeScript,alexeagle/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,jwbay/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,donaldpipowitch/TypeScript,plantain-00/TypeScript,thr0w/Thr0wScript,mihailik/TypeScript,basarat/TypeScript,kitsonk/TypeScript,minestarks/TypeScript,mihailik/TypeScript,kitsonk/TypeScript,jeremyepling/TypeScript,DLehenbauer/TypeScript,mihailik/TypeScript,plantain-00/TypeScript,mihailik/TypeScript,microsoft/TypeScript,TukekeSoft/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,synaptek/TypeScript,Eyas/TypeScript,DLehenbauer/TypeScript,kpreisser/TypeScript,vilic/TypeScript,vilic/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,Eyas/TypeScript,plantain-00/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,RyanCavanaugh/TypeScript,Eyas/TypeScript,jwbay/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,plantain-00/TypeScript,jeremyepling/TypeScript,chuckjaz/TypeScript,jwbay/TypeScript,ziacik/TypeScript,chuckjaz/TypeScript,erikmcc/TypeScript,erikmcc/TypeScript,chuckjaz/TypeScript,vilic/TypeScript,nojvek/TypeScript,thr0w/Thr0wScript,Microsoft/TypeScript,Microsoft/TypeScript,basarat/TypeScript,jwbay/TypeScript,basarat/TypeScript,basarat/TypeScript,Eyas/TypeScript,minestarks/TypeScript,vilic/TypeScript,synaptek/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,DLehenbauer/TypeScript,DLehenbauer/TypeScript,weswigham/TypeScript,jeremyepling/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,chuckjaz/TypeScript,ziacik/TypeScript,kpreisser/TypeScript,microsoft/TypeScript,thr0w/Thr0wScript
--- +++ @@ -0,0 +1,22 @@ +/// <reference path='fourslash.ts' /> + +////interface MultiRobot { +//// name: string; +//// skills: { +//// [|primary|]: string; +//// secondary: string; +//// }; +////} +////let multiRobots: MultiRobot[]; +////for (let { skills: {[|primary|]: primaryA, secondary: secondaryA } } of multiRobots) { +//// console.log(primaryA); +////} +////for (let { skills: {[|primary|], secondary } } of multiRobots) { +//// console.log([|primary|]); +////} + +let ranges = test.ranges() +for (let range of ranges) { + goTo.position(range.start); + verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false); +}
e2a71ee2882c2c66c7b2dba4507364e792d6c300
src/components/AccordionItem.spec.tsx
src/components/AccordionItem.spec.tsx
import * as React from 'react'; import { cleanup, render } from 'react-testing-library'; import { default as Accordion } from './Accordion'; import AccordionItem from './AccordionItem'; enum UUIDS { FOO = 'FOO', BAR = 'Bar', } describe('AccordionItem', () => { afterEach(() => { cleanup(); }); it('renders without erroring', () => { expect(() => { render(<Accordion />); }).not.toThrow(); }); describe('className + expandedClassName', () => { it('are “BEM” by default', () => { const { getByTestId } = render( <Accordion> <AccordionItem data-testid={UUIDS.FOO} /> </Accordion>, ); expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ 'accordion__item', ]); }); it('can be overridden', () => { const { getByTestId } = render( <Accordion preExpanded={[UUIDS.FOO]}> <AccordionItem uuid={UUIDS.FOO} data-testid={UUIDS.FOO} className="foo" expandedClassName="foo--expanded" /> </Accordion>, ); expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ 'foo', 'foo--expanded', ]); }); }); });
Add unit tests for AccordionItem's className and expandedClassName props
Add unit tests for AccordionItem's className and expandedClassName props
TypeScript
mit
springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion
--- +++ @@ -0,0 +1,52 @@ +import * as React from 'react'; +import { cleanup, render } from 'react-testing-library'; +import { default as Accordion } from './Accordion'; +import AccordionItem from './AccordionItem'; + +enum UUIDS { + FOO = 'FOO', + BAR = 'Bar', +} + +describe('AccordionItem', () => { + afterEach(() => { + cleanup(); + }); + + it('renders without erroring', () => { + expect(() => { + render(<Accordion />); + }).not.toThrow(); + }); + + describe('className + expandedClassName', () => { + it('are “BEM” by default', () => { + const { getByTestId } = render( + <Accordion> + <AccordionItem data-testid={UUIDS.FOO} /> + </Accordion>, + ); + expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ + 'accordion__item', + ]); + }); + + it('can be overridden', () => { + const { getByTestId } = render( + <Accordion preExpanded={[UUIDS.FOO]}> + <AccordionItem + uuid={UUIDS.FOO} + data-testid={UUIDS.FOO} + className="foo" + expandedClassName="foo--expanded" + /> + </Accordion>, + ); + + expect(Array.from(getByTestId(UUIDS.FOO).classList)).toEqual([ + 'foo', + 'foo--expanded', + ]); + }); + }); +});
70bb3c2f921a767b43e5792a13709ca2d83c6d63
source/behaviors/stopEventPropagation/stopEventPropagation.ts
source/behaviors/stopEventPropagation/stopEventPropagation.ts
// uses typings/angular module rl.utilities.behaviors.stopEventPropogation { 'use strict'; export var moduleName: string = 'rl.utilities.behaviors.stopEventPropogation'; export var directiveName: string = 'rlStopEventPropagation'; export interface IStopEventPropagationAttrs extends ng.IAttributes { rlStopEventPropagation: string; } function stopEventPropagation(): ng.IDirective { 'use strict'; return { restrict: 'A', link(scope: ng.IScope , element: ng.IAugmentedJQuery , attrs: IStopEventPropagationAttrs): void { element.on(attrs.rlStopEventPropagation, (event: JQueryEventObject): void => { event.preventDefault(); event.stopPropagation(); }); } }; } angular.module(moduleName, []) .directive(directiveName, stopEventPropagation); }
Add stop event propagation behavior.
Add stop event propagation behavior.
TypeScript
mit
SamGraber/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,csengineer13/TypeScript-Angular-Utilities,csengineer13/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities
--- +++ @@ -0,0 +1,30 @@ +// uses typings/angular + +module rl.utilities.behaviors.stopEventPropogation { + 'use strict'; + + export var moduleName: string = 'rl.utilities.behaviors.stopEventPropogation'; + export var directiveName: string = 'rlStopEventPropagation'; + + export interface IStopEventPropagationAttrs extends ng.IAttributes { + rlStopEventPropagation: string; + } + + function stopEventPropagation(): ng.IDirective { + 'use strict'; + return { + restrict: 'A', + link(scope: ng.IScope + , element: ng.IAugmentedJQuery + , attrs: IStopEventPropagationAttrs): void { + element.on(attrs.rlStopEventPropagation, (event: JQueryEventObject): void => { + event.preventDefault(); + event.stopPropagation(); + }); + } + }; + } + + angular.module(moduleName, []) + .directive(directiveName, stopEventPropagation); +}
93564c7d2efe895aeebd38a9cac578957e9c89c6
src/vg-controls/vg-playback-button/vg-playback-button.spec.ts
src/vg-controls/vg-playback-button/vg-playback-button.spec.ts
import {it, describe, expect, beforeEach, inject} from 'angular2/testing'; import {VgPlaybackButton} from "./vg-playback-button"; import {VgAPI} from "../../services/vg-api"; import {ElementRef} from "angular2/core"; describe('Play/Pause Button', () => { let playbackButton:VgPlaybackButton; let ref:ElementRef; let api:VgAPI; beforeEach(() => { ref = { nativeElement: { getAttribute: (name) => { return name; } } }; api = new VgAPI(); api.medias = { main: { state: 'play' }, secondary: { state: 'pause' } }; playbackButton = new VgPlaybackButton(ref, api); }); it('Should set playbackIndex default value to 1', () => { expect(playbackButton.playbackIndex).toEqual(1); }); it('Should get media by id on init', () => { spyOn(playbackButton.elem, 'getAttribute').and.callThrough(); spyOn(api, 'getMediaById').and.callFake(() => { return { volume: 1 }; }); playbackButton.ngOnInit(); expect(playbackButton.elem.getAttribute).toHaveBeenCalledWith('vg-for'); expect(api.getMediaById).toHaveBeenCalledWith('vg-for'); }); describe('onClick (single and multiple media)', () => { it('should increase playbackIndex', () => { api.medias = { main: { state: 'play' } }; playbackButton.target = api; playbackButton.onClick(); expect(playbackButton.playbackIndex).toEqual(2); }); it('should set playbackRate to target media', () => { api.medias = { main: { state: 'play' } }; playbackButton.target = api; playbackButton.onClick(); expect(playbackButton.target.playbackRate).toEqual('1.5'); }); it('should set playbackRate to target media', () => { let media = { playbackRate: { test: '1' } }; playbackButton.target = media; playbackButton.vgFor = 'test'; playbackButton.onClick(); expect(playbackButton.target.playbackRate.test).toEqual('1.5'); }); }); });
Raise coverage. Initial unit tests
test(vgPlaybackButton): Raise coverage. Initial unit tests #1 Raise coverage to 100%
TypeScript
mit
videogular/videogular2,videogular/videogular2,amitkumarmahajan/videogular2,kwarismian/videogular2,videogular/videogular2,kwarismian/videogular2,kwarismian/videogular2,amitkumarmahajan/videogular2,amitkumarmahajan/videogular2
--- +++ @@ -0,0 +1,96 @@ +import {it, describe, expect, beforeEach, inject} from 'angular2/testing'; +import {VgPlaybackButton} from "./vg-playback-button"; +import {VgAPI} from "../../services/vg-api"; +import {ElementRef} from "angular2/core"; + +describe('Play/Pause Button', () => { + let playbackButton:VgPlaybackButton; + let ref:ElementRef; + let api:VgAPI; + + beforeEach(() => { + ref = { + nativeElement: { + getAttribute: (name) => { + return name; + } + } + }; + + api = new VgAPI(); + api.medias = { + main: { + state: 'play' + }, + secondary: { + state: 'pause' + } + }; + + + playbackButton = new VgPlaybackButton(ref, api); + }); + + it('Should set playbackIndex default value to 1', () => { + expect(playbackButton.playbackIndex).toEqual(1); + }); + + it('Should get media by id on init', () => { + spyOn(playbackButton.elem, 'getAttribute').and.callThrough(); + spyOn(api, 'getMediaById').and.callFake(() => { + return { + volume: 1 + }; + }); + + playbackButton.ngOnInit(); + + expect(playbackButton.elem.getAttribute).toHaveBeenCalledWith('vg-for'); + expect(api.getMediaById).toHaveBeenCalledWith('vg-for'); + }); + + describe('onClick (single and multiple media)', () => { + it('should increase playbackIndex', () => { + api.medias = { + main: { + state: 'play' + } + }; + + playbackButton.target = api; + + playbackButton.onClick(); + + expect(playbackButton.playbackIndex).toEqual(2); + }); + + it('should set playbackRate to target media', () => { + api.medias = { + main: { + state: 'play' + } + }; + + playbackButton.target = api; + + playbackButton.onClick(); + + expect(playbackButton.target.playbackRate).toEqual('1.5'); + }); + + it('should set playbackRate to target media', () => { + let media = { + playbackRate: { + test: '1' + } + }; + + playbackButton.target = media; + playbackButton.vgFor = 'test'; + + playbackButton.onClick(); + + expect(playbackButton.target.playbackRate.test).toEqual('1.5'); + }); + }); +});
3339ab5f4a64da28abb44c3cd3f4c6031fe9b597
src/reducers/account.ts
src/reducers/account.ts
import { MaybeAccount } from '../types'; import { ConnectAccountAction } from '../actions/connectAccount'; import { CONNECT_ACCOUNT_SUCCESS } from '../constants'; export default ( state: MaybeAccount = null, action: ConnectAccountAction ): MaybeAccount => { switch (action.type) { case CONNECT_ACCOUNT_SUCCESS: return { ...state, ...action.data }; default: return state; } };
Add reducer for responding to CONNECT_ACCOUNT_SUCCESS
Add reducer for responding to CONNECT_ACCOUNT_SUCCESS
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -0,0 +1,17 @@ +import { MaybeAccount } from '../types'; +import { ConnectAccountAction } from '../actions/connectAccount'; +import { CONNECT_ACCOUNT_SUCCESS } from '../constants'; + + + +export default ( + state: MaybeAccount = null, + action: ConnectAccountAction +): MaybeAccount => { + switch (action.type) { + case CONNECT_ACCOUNT_SUCCESS: + return { ...state, ...action.data }; + default: + return state; + } +};
db17262ea4f7d1736acd842a3afa9f1a19ee39a4
public/app/core/utils/CancelablePromise.ts
public/app/core/utils/CancelablePromise.ts
// https://github.com/facebook/react/issues/5465 export interface CancelablePromise<T> { promise: Promise<T>; cancel: () => void; } export const makePromiseCancelable = <T>(promise: Promise<T>): CancelablePromise<T> => { let hasCanceled_ = false; const wrappedPromise = new Promise<T>((resolve, reject) => { promise.then(val => (hasCanceled_ ? reject({ isCanceled: true }) : resolve(val))); promise.catch(error => (hasCanceled_ ? reject({ isCanceled: true }) : reject(error))); }); return { promise: wrappedPromise, cancel() { hasCanceled_ = true; }, }; };
Add util for handling promise cancelation to avoid setting state on unmounted components
Add util for handling promise cancelation to avoid setting state on unmounted components https://github.com/facebook/react/issues/5465
TypeScript
agpl-3.0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
--- +++ @@ -0,0 +1,22 @@ +// https://github.com/facebook/react/issues/5465 + +export interface CancelablePromise<T> { + promise: Promise<T>; + cancel: () => void; +} + +export const makePromiseCancelable = <T>(promise: Promise<T>): CancelablePromise<T> => { + let hasCanceled_ = false; + + const wrappedPromise = new Promise<T>((resolve, reject) => { + promise.then(val => (hasCanceled_ ? reject({ isCanceled: true }) : resolve(val))); + promise.catch(error => (hasCanceled_ ? reject({ isCanceled: true }) : reject(error))); + }); + + return { + promise: wrappedPromise, + cancel() { + hasCanceled_ = true; + }, + }; +};
ba11c26e9383c2f3f3f6589def1dddee01e590d0
test/test-wavpack.ts
test/test-wavpack.ts
import {} from "mocha"; import {assert} from "chai"; import * as mm from "../src"; import * as fs from "fs-extra"; import * as path from "path"; import {SourceStream} from "./util"; const t = assert; describe("WavPack decoding", () => { const samplePath = path.join(__dirname, 'samples'); const wv1 = path.join(samplePath, "MusicBrainz - Beth Hart - Sinner's Prayer.wv"); function checkFormat(format) { t.strictEqual(format.dataformat, 'WavPack', 'format.dataformat'); t.deepEqual(format.tagTypes, ['APEv2'], 'format.tagTypes'); t.approximately(format.duration, 2.123, 1 / 1000, "format.duration"); } function checkCommon(common) { t.strictEqual(common.title, "Sinner's Prayer", "common.title"); t.deepEqual(common.artists, ['Beth Hart', 'Joe Bonamassa'], "common.artist"); } it("should decode a WavPack audio file (.wv)", () => { return mm.parseFile(wv1, {native: true}).then(metadata => { checkFormat(metadata.format); checkCommon(metadata.common); }); }); it("should decode a WavPack audio stream (audio/x-wavpack)", () => { const stream = fs.createReadStream(wv1); return mm.parseStream(stream, 'audio/x-wavpack', {native: true}).then(metadata => { checkFormat(metadata.format); checkCommon(metadata.common); }).then(() => { stream.close(); }); }); });
Add unit dedicated tests for WavPack, ensure MIME-tpe is used once.
Add unit dedicated tests for WavPack, ensure MIME-tpe is used once.
TypeScript
mit
Borewit/music-metadata,Borewit/music-metadata
--- +++ @@ -0,0 +1,48 @@ +import {} from "mocha"; +import {assert} from "chai"; +import * as mm from "../src"; +import * as fs from "fs-extra"; +import * as path from "path"; +import {SourceStream} from "./util"; + +const t = assert; + +describe("WavPack decoding", () => { + + const samplePath = path.join(__dirname, 'samples'); + const wv1 = path.join(samplePath, "MusicBrainz - Beth Hart - Sinner's Prayer.wv"); + + function checkFormat(format) { + t.strictEqual(format.dataformat, 'WavPack', 'format.dataformat'); + t.deepEqual(format.tagTypes, ['APEv2'], 'format.tagTypes'); + t.approximately(format.duration, 2.123, 1 / 1000, "format.duration"); + } + + function checkCommon(common) { + t.strictEqual(common.title, "Sinner's Prayer", "common.title"); + t.deepEqual(common.artists, ['Beth Hart', 'Joe Bonamassa'], "common.artist"); + } + + it("should decode a WavPack audio file (.wv)", () => { + + return mm.parseFile(wv1, {native: true}).then(metadata => { + checkFormat(metadata.format); + checkCommon(metadata.common); + }); + + }); + + it("should decode a WavPack audio stream (audio/x-wavpack)", () => { + + const stream = fs.createReadStream(wv1); + + return mm.parseStream(stream, 'audio/x-wavpack', {native: true}).then(metadata => { + checkFormat(metadata.format); + checkCommon(metadata.common); + }).then(() => { + stream.close(); + }); + + }); + +});
55fa13d1b34191edbddf02606d9ed8fb5ba583e6
src/app/add-assignment/add-assignment.component.spec.ts
src/app/add-assignment/add-assignment.component.spec.ts
import { beforeEachProviders, describe, inject, it } from '@angular/core/testing'; import { AddAssignmentComponent } from './add-assignment.component'; describe('AddAssignmentComponent', () => { beforeEachProviders(() => [ AddAssignmentComponent ]); let component: AddAssignmentComponent; beforeEach(inject([AddAssignmentComponent], (comp: AddAssignmentComponent) => { component = comp; })); it('should initialize array of number of possible answer on construction', () => { expect(component.numOfPossibleAnswers).toEqual([1, 2, 3, 4, 5]); }); it('should emit closeModal event', () => { component.close.subscribe(event => { expect(event.value).toBe('closeModal'); }); component.closeModal(); }); });
Add tests for add-assignment component
Add tests for add-assignment component
TypeScript
mit
bryant-pham/brograder,bryant-pham/brograder,bryant-pham/brograder,bryant-pham/brograder
--- +++ @@ -0,0 +1,32 @@ +import { + beforeEachProviders, + describe, + inject, + it +} from '@angular/core/testing'; + +import { AddAssignmentComponent } from './add-assignment.component'; + +describe('AddAssignmentComponent', () => { + beforeEachProviders(() => [ + AddAssignmentComponent + ]); + + let component: AddAssignmentComponent; + + beforeEach(inject([AddAssignmentComponent], (comp: AddAssignmentComponent) => { + component = comp; + })); + + it('should initialize array of number of possible answer on construction', () => { + expect(component.numOfPossibleAnswers).toEqual([1, 2, 3, 4, 5]); + }); + + it('should emit closeModal event', () => { + component.close.subscribe(event => { + expect(event.value).toBe('closeModal'); + }); + + component.closeModal(); + }); +});
40c03e5c12223b199f69f5dcccce8d3cf92d7d28
src/SyntaxNodes/OutlineSyntaxNode.ts
src/SyntaxNodes/OutlineSyntaxNode.ts
import { SyntaxNode } from '../SyntaxNodes/SyntaxNode' import { PlainTextNode } from '../SyntaxNodes/PlainTextNode' import { RichSyntaxNode } from '../SyntaxNodes/RichSyntaxNode' export abstract class OutlineSyntaxNode extends SyntaxNode { private OUTLINE_SYNTAX_NODE: any = null }
Add outline syntax node class
Add outline syntax node class
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,7 @@ +import { SyntaxNode } from '../SyntaxNodes/SyntaxNode' +import { PlainTextNode } from '../SyntaxNodes/PlainTextNode' +import { RichSyntaxNode } from '../SyntaxNodes/RichSyntaxNode' + +export abstract class OutlineSyntaxNode extends SyntaxNode { + private OUTLINE_SYNTAX_NODE: any = null +}
a312fb4075ac3d2029172f6894aa4dd1bac2f074
src/config/editorsImgMap.ts
src/config/editorsImgMap.ts
import { ANDROIDSTUDIO, ATOM, CHROME, ECLIPSE, SUBLIMETEXT2, SUBLIMETEXT3, VIM, VSCODE } from "../constants/editors"; import { androidStudio128Path, atom128Path, chrome128Path, eclipse128Path, sublimeText128Path, vim128Path, vsCode128Path } from "../constants/imgPaths"; interface EditorImageMap { [s: string]: string; } const imgMap: EditorImageMap = { [ANDROIDSTUDIO]: androidStudio128Path, [ATOM]: atom128Path, [CHROME]: chrome128Path, [ECLIPSE]: eclipse128Path, [SUBLIMETEXT2]: sublimeText128Path, [SUBLIMETEXT3]: sublimeText128Path, // Should this be a different image? [VIM]: vim128Path, [VSCODE]: vsCode128Path }; export default imgMap;
Create an image map to make it more configurable which Editor to which image
Create an image map to make it more configurable which Editor to which image
TypeScript
bsd-3-clause
wakatime/desktop,wakatime/wakatime-desktop,wakatime/desktop,wakatime/wakatime-desktop,wakatime/desktop
--- +++ @@ -0,0 +1,36 @@ +import { + ANDROIDSTUDIO, + ATOM, + CHROME, + ECLIPSE, + SUBLIMETEXT2, + SUBLIMETEXT3, + VIM, + VSCODE +} from "../constants/editors"; +import { + androidStudio128Path, + atom128Path, + chrome128Path, + eclipse128Path, + sublimeText128Path, + vim128Path, + vsCode128Path +} from "../constants/imgPaths"; + +interface EditorImageMap { + [s: string]: string; +} + +const imgMap: EditorImageMap = { + [ANDROIDSTUDIO]: androidStudio128Path, + [ATOM]: atom128Path, + [CHROME]: chrome128Path, + [ECLIPSE]: eclipse128Path, + [SUBLIMETEXT2]: sublimeText128Path, + [SUBLIMETEXT3]: sublimeText128Path, // Should this be a different image? + [VIM]: vim128Path, + [VSCODE]: vsCode128Path +}; + +export default imgMap;
7fdeebf2e92c6860a04680cbeefd7a369a22a464
src/Test/Ast/EdgeCases/UnorderedList.ts
src/Test/Ast/EdgeCases/UnorderedList.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 { UnorderedListNode } from '../../../SyntaxNodes/UnorderedListNode' import { UnorderedListItemNode } from '../../../SyntaxNodes/UnorderedListItemNode' import { OrderedListNode } from '../../../SyntaxNodes/OrderedListNode' import { OrderedListItemNode } from '../../../SyntaxNodes/OrderedListItemNode' import { SectionSeparatorNode } from '../../../SyntaxNodes/SectionSeparatorNode' import { HeadingNode } from '../../../SyntaxNodes/HeadingNode' describe('An unordered list with a single item', () => { it('can be sandwched by section separator streaks', () => { const text = ` ----------- * Gloves -----------` expect(Up.ast(text)).to.be.eql( new DocumentNode([ new SectionSeparatorNode(), new UnorderedListNode([ new UnorderedListItemNode([ new ParagraphNode([ new PlainTextNode('Mittens') ]) ]) ]), new SectionSeparatorNode() ])) }) })
Add failing unordered list test
Add failing unordered list test
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,45 @@ +/// <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 { UnorderedListNode } from '../../../SyntaxNodes/UnorderedListNode' +import { UnorderedListItemNode } from '../../../SyntaxNodes/UnorderedListItemNode' +import { OrderedListNode } from '../../../SyntaxNodes/OrderedListNode' +import { OrderedListItemNode } from '../../../SyntaxNodes/OrderedListItemNode' +import { SectionSeparatorNode } from '../../../SyntaxNodes/SectionSeparatorNode' +import { HeadingNode } from '../../../SyntaxNodes/HeadingNode' + + +describe('An unordered list with a single item', () => { + it('can be sandwched by section separator streaks', () => { + const text = ` +----------- +* Gloves +-----------` + expect(Up.ast(text)).to.be.eql( + new DocumentNode([ + new SectionSeparatorNode(), + new UnorderedListNode([ + new UnorderedListItemNode([ + new ParagraphNode([ + new PlainTextNode('Mittens') + ]) + ]) + ]), + new SectionSeparatorNode() + ])) + }) +})
761bdd75c8ddad48bb66fcbc9a81eddff120ced6
app/src/main-process/menu/get-all-menu-items.ts
app/src/main-process/menu/get-all-menu-items.ts
import { Menu, MenuItem } from 'electron' /** * Returns an iterator that traverses the menu and all * submenus and yields each menu item therein. */ export function* getAllMenuItems(menu: Menu): IterableIterator<MenuItem> { for (const menuItem of menu.items) { yield menuItem if (menuItem.type === 'submenu' && menuItem.submenu !== undefined) { yield* getAllMenuItems(menuItem.submenu) } } }
Add a helper method for recursing through all menu items in a menu
Add a helper method for recursing through all menu items in a menu
TypeScript
mit
kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,desktop/desktop,kactus-io/kactus,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,artivilla/desktop,artivilla/desktop,say25/desktop,say25/desktop,desktop/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop
--- +++ @@ -0,0 +1,15 @@ +import { Menu, MenuItem } from 'electron' + +/** + * Returns an iterator that traverses the menu and all + * submenus and yields each menu item therein. + */ +export function* getAllMenuItems(menu: Menu): IterableIterator<MenuItem> { + for (const menuItem of menu.items) { + yield menuItem + + if (menuItem.type === 'submenu' && menuItem.submenu !== undefined) { + yield* getAllMenuItems(menuItem.submenu) + } + } +}
046da41166cfc5248c6e1bd711f5c946dc62af65
src/angular-cesium/components/ac-static-circle-desc/ac-static-circle-desc.component.spec.ts
src/angular-cesium/components/ac-static-circle-desc/ac-static-circle-desc.component.spec.ts
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AcEllipseStaticDescComponent } from './ac-ellipse-static-desc.component'; describe('AcEllipseStaticDescComponent', () => { let component: AcEllipseStaticDescComponent; let fixture: ComponentFixture<AcEllipseStaticDescComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [AcEllipseStaticDescComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AcEllipseStaticDescComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
Undo remove static desc tests
Undo remove static desc tests
TypeScript
mit
TGFTech/angular-cesium,TGFTech/angular-cesium,TGFTech/angular-cesium
--- +++ @@ -0,0 +1,26 @@ +/* tslint:disable:no-unused-variable */ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { AcEllipseStaticDescComponent } from './ac-ellipse-static-desc.component'; + +describe('AcEllipseStaticDescComponent', () => { + let component: AcEllipseStaticDescComponent; + let fixture: ComponentFixture<AcEllipseStaticDescComponent>; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [AcEllipseStaticDescComponent] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(AcEllipseStaticDescComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +});
b0dff0fbfd89912aa84c82d8c3348c72f0974743
app/src/ui/history/compare-branch-list-item.tsx
app/src/ui/history/compare-branch-list-item.tsx
import * as React from 'react' import { Octicon, OcticonSymbol } from '../octicons' import { HighlightText } from '../lib/highlight-text' import { Branch } from '../../models/branch' import { ICompareResult } from '../../lib/git' import { Dispatcher } from '../../lib/dispatcher' import { Repository } from '../../models/repository' interface ICompareBranchListItemProps { readonly dispatcher: Dispatcher readonly repository: Repository readonly branch: Branch readonly isCurrentBranch: boolean /** The characters in the branch name to highlight */ readonly matches: ReadonlyArray<number> } interface ICompareBranchListItemState { readonly compareState: ICompareResult | null } export class CompareBranchListItem extends React.Component< ICompareBranchListItemProps, ICompareBranchListItemState > { public constructor(props: ICompareBranchListItemProps) { super(props) this.state = { compareState: null, } } public async componentWillMount() { const compareState = await this.props.dispatcher.GetCompareResult( this.props.repository, this.props.branch ) this.setState({ compareState }) } public render() { const isCurrentBranch = this.props.isCurrentBranch const branch = this.props.branch const icon = isCurrentBranch ? OcticonSymbol.check : OcticonSymbol.gitBranch const compareState = this.state.compareState if (compareState === null) { return null } return ( <div className="branches-list-item"> <Octicon className="icon" symbol={icon} /> <div className="name" title={branch.name}> <HighlightText text={branch.name} highlight={this.props.matches} /> </div> <div className="branch-commit-counter"> {compareState.ahead} <Octicon className="icon" symbol={OcticonSymbol.arrowUp} /> {compareState.behind} <Octicon className="icon" symbol={OcticonSymbol.arrowDown} /> </div> </div> ) } }
Add new component for rendering branches with ahead/behind info
Add new component for rendering branches with ahead/behind info
TypeScript
mit
desktop/desktop,say25/desktop,say25/desktop,desktop/desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,artivilla/desktop,artivilla/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,kactus-io/kactus,kactus-io/kactus,j-f1/forked-desktop
--- +++ @@ -0,0 +1,70 @@ +import * as React from 'react' + +import { Octicon, OcticonSymbol } from '../octicons' +import { HighlightText } from '../lib/highlight-text' +import { Branch } from '../../models/branch' +import { ICompareResult } from '../../lib/git' +import { Dispatcher } from '../../lib/dispatcher' +import { Repository } from '../../models/repository' + +interface ICompareBranchListItemProps { + readonly dispatcher: Dispatcher + readonly repository: Repository + readonly branch: Branch + readonly isCurrentBranch: boolean + + /** The characters in the branch name to highlight */ + readonly matches: ReadonlyArray<number> +} + +interface ICompareBranchListItemState { + readonly compareState: ICompareResult | null +} + +export class CompareBranchListItem extends React.Component< + ICompareBranchListItemProps, + ICompareBranchListItemState +> { + public constructor(props: ICompareBranchListItemProps) { + super(props) + + this.state = { + compareState: null, + } + } + + public async componentWillMount() { + const compareState = await this.props.dispatcher.GetCompareResult( + this.props.repository, + this.props.branch + ) + + this.setState({ compareState }) + } + + public render() { + const isCurrentBranch = this.props.isCurrentBranch + const branch = this.props.branch + const icon = isCurrentBranch ? OcticonSymbol.check : OcticonSymbol.gitBranch + const compareState = this.state.compareState + + if (compareState === null) { + return null + } + + return ( + <div className="branches-list-item"> + <Octicon className="icon" symbol={icon} /> + <div className="name" title={branch.name}> + <HighlightText text={branch.name} highlight={this.props.matches} /> + </div> + <div className="branch-commit-counter"> + {compareState.ahead} + <Octicon className="icon" symbol={OcticonSymbol.arrowUp} /> + {compareState.behind} + <Octicon className="icon" symbol={OcticonSymbol.arrowDown} /> + </div> + </div> + ) + } +}
f7ba7188f3d9b54126605e4ae88105db702cbdd2
tests/cases/fourslash/completionListInObjectBindingPattern13.ts
tests/cases/fourslash/completionListInObjectBindingPattern13.ts
/// <reference path='fourslash.ts'/> ////interface I { //// x: number; //// y: string; //// z: boolean; ////} //// ////interface J { //// x: string; //// y: string; ////} //// ////let { /**/ }: I | J = { x: 10 }; goTo.marker(); verify.completionListContains("x"); verify.completionListContains("y"); verify.not.completionListContains("z");
Add test case for completion when destructuring from a union type.
Add test case for completion when destructuring from a union type.
TypeScript
apache-2.0
billti/TypeScript,jwbay/TypeScript,MartyIX/TypeScript,jbondc/TypeScript,enginekit/TypeScript,nojvek/TypeScript,HereSinceres/TypeScript,jwbay/TypeScript,moander/TypeScript,chuckjaz/TypeScript,ziacik/TypeScript,weswigham/TypeScript,JohnZ622/TypeScript,mmoskal/TypeScript,erikmcc/TypeScript,AbubakerB/TypeScript,jeremyepling/TypeScript,mmoskal/TypeScript,rgbkrk/TypeScript,jamesrmccallum/TypeScript,SmallAiTT/TypeScript,RyanCavanaugh/TypeScript,TukekeSoft/TypeScript,webhost/TypeScript,ionux/TypeScript,samuelhorwitz/typescript,erikmcc/TypeScript,AbubakerB/TypeScript,mmoskal/TypeScript,nojvek/TypeScript,HereSinceres/TypeScript,keir-rex/TypeScript,thr0w/Thr0wScript,ZLJASON/TypeScript,Microsoft/TypeScript,tempbottle/TypeScript,jeremyepling/TypeScript,DLehenbauer/TypeScript,billti/TypeScript,jamesrmccallum/TypeScript,vilic/TypeScript,erikmcc/TypeScript,moander/TypeScript,moander/TypeScript,jeremyepling/TypeScript,fabioparra/TypeScript,moander/TypeScript,synaptek/TypeScript,MartyIX/TypeScript,plantain-00/TypeScript,weswigham/TypeScript,kimamula/TypeScript,shanexu/TypeScript,matthewjh/TypeScript,OlegDokuka/TypeScript,evgrud/TypeScript,hoanhtien/TypeScript,plantain-00/TypeScript,donaldpipowitch/TypeScript,SaschaNaz/TypeScript,SaschaNaz/TypeScript,impinball/TypeScript,bpowers/TypeScript,tinganho/TypeScript,nagyistoce/TypeScript,JohnZ622/TypeScript,chuckjaz/TypeScript,RyanCavanaugh/TypeScript,mihailik/TypeScript,abbasmhd/TypeScript,yazeng/TypeScript,fabioparra/TypeScript,jteplitz602/TypeScript,Viromo/TypeScript,kitsonk/TypeScript,hitesh97/TypeScript,kumikumi/TypeScript,msynk/TypeScript,shiftkey/TypeScript,rgbkrk/TypeScript,kimamula/TypeScript,shanexu/TypeScript,weswigham/TypeScript,impinball/TypeScript,kingland/TypeScript,kimamula/TypeScript,msynk/TypeScript,zhengbli/TypeScript,billti/TypeScript,ionux/TypeScript,Eyas/TypeScript,matthewjh/TypeScript,shovon/TypeScript,DLehenbauer/TypeScript,vilic/TypeScript,chocolatechipui/TypeScript,ionux/TypeScript,basarat/TypeScript,tempbottle/TypeScript,ionux/TypeScript,hitesh97/TypeScript,tinganho/TypeScript,vilic/TypeScript,shanexu/TypeScript,blakeembrey/TypeScript,ziacik/TypeScript,tinganho/TypeScript,OlegDokuka/TypeScript,msynk/TypeScript,keir-rex/TypeScript,Microsoft/TypeScript,SimoneGianni/TypeScript,TukekeSoft/TypeScript,alexeagle/TypeScript,SimoneGianni/TypeScript,bpowers/TypeScript,RReverser/TypeScript,bpowers/TypeScript,basarat/TypeScript,microsoft/TypeScript,progre/TypeScript,mihailik/TypeScript,evgrud/TypeScript,synaptek/TypeScript,sassson/TypeScript,kingland/TypeScript,fearthecowboy/TypeScript,nycdotnet/TypeScript,samuelhorwitz/typescript,mszczepaniak/TypeScript,hitesh97/TypeScript,zmaruo/TypeScript,fearthecowboy/TypeScript,erikmcc/TypeScript,synaptek/TypeScript,Viromo/TypeScript,mszczepaniak/TypeScript,gonifade/TypeScript,samuelhorwitz/typescript,thr0w/Thr0wScript,SimoneGianni/TypeScript,blakeembrey/TypeScript,jdavidberger/TypeScript,enginekit/TypeScript,fabioparra/TypeScript,mcanthony/TypeScript,germ13/TypeScript,Eyas/TypeScript,Eyas/TypeScript,kpreisser/TypeScript,sassson/TypeScript,Mqgh2013/TypeScript,pcan/TypeScript,minestarks/TypeScript,RReverser/TypeScript,donaldpipowitch/TypeScript,Mqgh2013/TypeScript,ziacik/TypeScript,zhengbli/TypeScript,mcanthony/TypeScript,plantain-00/TypeScript,jdavidberger/TypeScript,chuckjaz/TypeScript,samuelhorwitz/typescript,Mqgh2013/TypeScript,nycdotnet/TypeScript,DanielRosenwasser/TypeScript,microsoft/TypeScript,jdavidberger/TypeScript,SmallAiTT/TypeScript,mszczepaniak/TypeScript,shovon/TypeScript,kingland/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,kitsonk/TypeScript,mcanthony/TypeScript,DanielRosenwasser/TypeScript,AbubakerB/TypeScript,DLehenbauer/TypeScript,matthewjh/TypeScript,OlegDokuka/TypeScript,tempbottle/TypeScript,zmaruo/TypeScript,abbasmhd/TypeScript,nycdotnet/TypeScript,SaschaNaz/TypeScript,DanielRosenwasser/TypeScript,suto/TypeScript,JohnZ622/TypeScript,nycdotnet/TypeScript,shiftkey/TypeScript,vilic/TypeScript,zmaruo/TypeScript,progre/TypeScript,yortus/TypeScript,shanexu/TypeScript,zhengbli/TypeScript,jwbay/TypeScript,pcan/TypeScript,germ13/TypeScript,evgrud/TypeScript,alexeagle/TypeScript,mihailik/TypeScript,nagyistoce/TypeScript,yazeng/TypeScript,kitsonk/TypeScript,jbondc/TypeScript,hoanhtien/TypeScript,alexeagle/TypeScript,jamesrmccallum/TypeScript,ZLJASON/TypeScript,thr0w/Thr0wScript,jwbay/TypeScript,basarat/TypeScript,donaldpipowitch/TypeScript,MartyIX/TypeScript,webhost/TypeScript,SaschaNaz/TypeScript,synaptek/TypeScript,chocolatechipui/TypeScript,progre/TypeScript,suto/TypeScript,fabioparra/TypeScript,rodrigues-daniel/TypeScript,rodrigues-daniel/TypeScript,mihailik/TypeScript,yortus/TypeScript,Eyas/TypeScript,nojvek/TypeScript,jteplitz602/TypeScript,nagyistoce/TypeScript,kumikumi/TypeScript,thr0w/Thr0wScript,HereSinceres/TypeScript,impinball/TypeScript,sassson/TypeScript,basarat/TypeScript,hoanhtien/TypeScript,keir-rex/TypeScript,rodrigues-daniel/TypeScript,fearthecowboy/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,pcan/TypeScript,DLehenbauer/TypeScript,TukekeSoft/TypeScript,plantain-00/TypeScript,mcanthony/TypeScript,shovon/TypeScript,RyanCavanaugh/TypeScript,germ13/TypeScript,nojvek/TypeScript,Viromo/TypeScript,kimamula/TypeScript,rodrigues-daniel/TypeScript,suto/TypeScript,AbubakerB/TypeScript,enginekit/TypeScript,jteplitz602/TypeScript,gonifade/TypeScript,SmallAiTT/TypeScript,kpreisser/TypeScript,evgrud/TypeScript,mmoskal/TypeScript,blakeembrey/TypeScript,ZLJASON/TypeScript,jbondc/TypeScript,kumikumi/TypeScript,rgbkrk/TypeScript,JohnZ622/TypeScript,yortus/TypeScript,chocolatechipui/TypeScript,blakeembrey/TypeScript,DanielRosenwasser/TypeScript,shiftkey/TypeScript,Viromo/TypeScript,abbasmhd/TypeScript,kpreisser/TypeScript,gonifade/TypeScript,yazeng/TypeScript,chuckjaz/TypeScript,minestarks/TypeScript,RReverser/TypeScript,webhost/TypeScript,MartyIX/TypeScript,yortus/TypeScript,ziacik/TypeScript
--- +++ @@ -0,0 +1,19 @@ +/// <reference path='fourslash.ts'/> + +////interface I { +//// x: number; +//// y: string; +//// z: boolean; +////} +//// +////interface J { +//// x: string; +//// y: string; +////} +//// +////let { /**/ }: I | J = { x: 10 }; + +goTo.marker(); +verify.completionListContains("x"); +verify.completionListContains("y"); +verify.not.completionListContains("z");
4c6b639e0ceda039ef2b9545eabb75d96a61f7ae
src/search/alphaBeta.ts
src/search/alphaBeta.ts
export function alphaBeta<TNode>(node: TNode, depth: number, alpha: number, beta: number, isMaximizingPlayer: boolean, evaluate: (node: TNode) => number, isTerminalNode: (node: TNode) => boolean, getChildren: (node: TNode) => TNode[]) { if (depth == 0 || isTerminalNode(node)) return evaluate(node); if (isMaximizingPlayer) { let score = -Infinity; const children = getChildren(node); for (let i = 0; i < children.length; i++) { let child = children[i]; score = Math.max(score, alphaBeta(child, depth - 1, alpha, beta, false, evaluate, isTerminalNode, getChildren)); alpha = Math.max(alpha, score); if (beta <= alpha) break; } return score; } let score = Infinity; const children = getChildren(node); for (let i = 0; i < children.length; i++) { let child = children[i]; score = Math.min(score, alphaBeta(child, depth - 1, alpha, beta, false, evaluate, isTerminalNode, getChildren)); beta = Math.min(beta, score); if (beta <= alpha) break; } return score; }
Add a basic alpha-beta evaluation function
Add a basic alpha-beta evaluation function
TypeScript
mit
artfuldev/tictactoe-ai,artfuldev/tictactoe-ai
--- +++ @@ -0,0 +1,29 @@ +export function alphaBeta<TNode>(node: TNode, depth: number, alpha: number, + beta: number, isMaximizingPlayer: boolean, evaluate: (node: TNode) => number, + isTerminalNode: (node: TNode) => boolean, getChildren: (node: TNode) => TNode[]) { + if (depth == 0 || isTerminalNode(node)) return evaluate(node); + if (isMaximizingPlayer) { + let score = -Infinity; + const children = getChildren(node); + for (let i = 0; i < children.length; i++) { + let child = children[i]; + score = Math.max(score, + alphaBeta(child, depth - 1, alpha, beta, false, evaluate, isTerminalNode, + getChildren)); + alpha = Math.max(alpha, score); + if (beta <= alpha) break; + } + return score; + } + let score = Infinity; + const children = getChildren(node); + for (let i = 0; i < children.length; i++) { + let child = children[i]; + score = Math.min(score, + alphaBeta(child, depth - 1, alpha, beta, false, evaluate, isTerminalNode, + getChildren)); + beta = Math.min(beta, score); + if (beta <= alpha) break; + } + return score; +}
83b1c102694d394e1212343438b07ec57fd265a3
src/constants.ts
src/constants.ts
import * as path from 'path'; export const DEFAULT_APP_NAME = 'APP'; // Update both together, and update app / package.json / devDeps / electron export const DEFAULT_ELECTRON_VERSION = '12.0.2'; export const DEFAULT_CHROME_VERSION = '89.0.4389.90'; export const ELECTRON_MAJOR_VERSION = parseInt( DEFAULT_ELECTRON_VERSION.split('.')[0], 10, ); export const PLACEHOLDER_APP_DIR = path.join(__dirname, './../', 'app');
import * as path from 'path'; export const DEFAULT_APP_NAME = 'APP'; // Update both together, and update app / package.json / devDeps / electron export const DEFAULT_ELECTRON_VERSION = '12.0.4'; export const DEFAULT_CHROME_VERSION = '89.0.4389.114'; export const ELECTRON_MAJOR_VERSION = parseInt( DEFAULT_ELECTRON_VERSION.split('.')[0], 10, ); export const PLACEHOLDER_APP_DIR = path.join(__dirname, './../', 'app');
Bump to Electron 12.0.4 with Chrome 89.0.4389.114
Bump to Electron 12.0.4 with Chrome 89.0.4389.114 With recent security fixes. See https://github.com/electron/electron/releases/tag/v12.0.4 and https://github.com/electron/electron/releases/tag/v12.0.3
TypeScript
bsd-2-clause
jiahaog/Nativefier,jiahaog/Nativefier,jiahaog/Nativefier
--- +++ @@ -3,8 +3,8 @@ export const DEFAULT_APP_NAME = 'APP'; // Update both together, and update app / package.json / devDeps / electron -export const DEFAULT_ELECTRON_VERSION = '12.0.2'; -export const DEFAULT_CHROME_VERSION = '89.0.4389.90'; +export const DEFAULT_ELECTRON_VERSION = '12.0.4'; +export const DEFAULT_CHROME_VERSION = '89.0.4389.114'; export const ELECTRON_MAJOR_VERSION = parseInt( DEFAULT_ELECTRON_VERSION.split('.')[0],
a8db9a3b642e5bc2d50496f2352d2529e7a69b32
client/constants/components.ts
client/constants/components.ts
// Imported from https://github.com/twbs/bootstrap/blob/v4.3.1/scss/_variables.scss import { gray } from './colors' export const border = { width: '1px', color: gray[300], radius: '.25rem', radiusLg: '.3rem', radiusSm: '.2rem', }
Add border constans of Bootstrap
Add border constans of Bootstrap
TypeScript
mit
crowi/crowi,crowi/crowi,crowi/crowi
--- +++ @@ -0,0 +1,11 @@ +// Imported from https://github.com/twbs/bootstrap/blob/v4.3.1/scss/_variables.scss + +import { gray } from './colors' + +export const border = { + width: '1px', + color: gray[300], + radius: '.25rem', + radiusLg: '.3rem', + radiusSm: '.2rem', +}
d8bf0eb019bcefa6d7cb5e637df81f58cf6ae623
__tests__/api/index.ts
__tests__/api/index.ts
import { Api } from '../../src/api' describe('Api class', () => { let api = new Api(); beforeEach(() => { api = new Api(); }); test('setAccessToken set Authorization HTTP header', () => { const token = 'abc'; const expected = `Bearer ${token}`; api.setAccessToken(token); expect(api['baseConfig']['headers']['Authorization']).toBe(expected); }); });
Add Api setAccessToken method test
Add Api setAccessToken method test
TypeScript
mit
y0za/trumpet,y0za/trumpet,y0za/trumpet,y0za/trumpet
--- +++ @@ -0,0 +1,16 @@ +import { Api } from '../../src/api' + +describe('Api class', () => { + let api = new Api(); + + beforeEach(() => { + api = new Api(); + }); + + test('setAccessToken set Authorization HTTP header', () => { + const token = 'abc'; + const expected = `Bearer ${token}`; + api.setAccessToken(token); + expect(api['baseConfig']['headers']['Authorization']).toBe(expected); + }); +});
ab0e2d66e0779f07eeaac1b25322ac4e5190e97a
types/react-router-dom/react-router-dom-tests.tsx
types/react-router-dom/react-router-dom-tests.tsx
import * as React from 'react'; import { NavLink, NavLinkProps, match, Link, RouteComponentProps } from 'react-router-dom'; import * as H from 'history'; const getIsActive = (extraProp: string) => (match: match, location: H.Location) => !!extraProp; interface Props extends NavLinkProps { extraProp: string; } export default function(props: Props) { const {extraProp, ...rest} = props; const isActive = getIsActive(extraProp); return ( <NavLink {...rest} isActive={isActive}/> ); } type OtherProps = RouteComponentProps<{ id: string; }>; const Component: React.SFC<OtherProps> = props => { if (!props.match) { return null; } const { id } = props.match.params; return ( <div>{id}</div> ); }; <Link to="/url" />; const acceptRef = (node: HTMLAnchorElement | null) => {}; <Link to="/url" replace={true} innerRef={acceptRef} />;
import * as React from 'react'; import { NavLink, NavLinkProps, match, Link, RouteComponentProps } from 'react-router-dom'; import * as H from 'history'; const getIsActive = (extraProp: string) => (match: match, location: H.Location) => !!extraProp; interface Props extends NavLinkProps { extraProp: string; } export default function(props: Props) { const {extraProp, ...rest} = props; const isActive = getIsActive(extraProp); return ( <NavLink {...rest} isActive={isActive}/> ); } type OtherProps = RouteComponentProps<{ id: string; }>; const Component: React.SFC<OtherProps> = props => { if (!props.match) { return null; } const { id } = props.match.params; return ( <div>{id}</div> ); }; <Link to="/url" />; const refCallback: React.Ref<HTMLAnchorElement> = node => {}; <Link to="/url" replace={true} innerRef={refCallback} />; const ref = React.createRef<HTMLAnchorElement>(); <Link to="/url" replace={true} innerRef={ref} />;
Add failing test for ref objects
[react-router-dom] Add failing test for ref objects
TypeScript
mit
georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped
--- +++ @@ -39,5 +39,7 @@ <Link to="/url" />; -const acceptRef = (node: HTMLAnchorElement | null) => {}; -<Link to="/url" replace={true} innerRef={acceptRef} />; +const refCallback: React.Ref<HTMLAnchorElement> = node => {}; +<Link to="/url" replace={true} innerRef={refCallback} />; +const ref = React.createRef<HTMLAnchorElement>(); +<Link to="/url" replace={true} innerRef={ref} />;
703defba62b675793e886e930df2d5552d443c5b
tests/ts/query-builder-api/join-methods.ts
tests/ts/query-builder-api/join-methods.ts
import { Person } from '../fixtures/person'; import { raw } from '../../..'; (async () => { await Person.query() .joinRelation('pets') .where('pets.species', 'dog'); await Person.query() .joinRelation('pets', { alias: 'p' }) .where('p.species', 'dog'); await Person.query() .joinRelation('[pets, parent]') .where('pets.species', 'dog') .where('parent.name', 'Arnold'); await Person.query() .joinRelation({ pets: true, parent: true }) .where('pets.species', 'dog') .where('parent.name', 'Arnold'); await Person.query() .select('persons.id', 'parent:parent.name as grandParentName') .joinRelation('[pets, parent.[pets, parent]]') .where('parent:pets.species', 'dog'); await Person.query() .select('persons.id', 'pr:pr.name as grandParentName') .joinRelation('[pets, parent.[pets, parent]]', { aliases: { parent: 'pr', pets: 'pt' } }) .where('pr:pt.species', 'dog'); await Person.query() .select('persons.id', 'pr:pr.name as grandParentName') .joinRelation('[pets as pt, parent as pr.[pets as pt, parent as pr]]') .where('pr:pt.species', 'dog'); await Person.query().innerJoinRelation('pets'); await Person.query().outerJoinRelation('pets'); await Person.query().leftJoinRelation('pets'); await Person.query().leftOuterJoinRelation('pets'); await Person.query().rightJoinRelation('pets'); await Person.query().rightOuterJoinRelation('pets'); await Person.query().fullOuterJoinRelation('pets'); await Person.query().join(raw('pets')); await Person.query().joinRaw('pets'); await Person.query().innerJoin(raw('pets')); await Person.query().leftJoin(raw('pets')); await Person.query().leftOuterJoin(raw('pets')); await Person.query().rightJoin(raw('pets')); await Person.query().rightOuterJoin(raw('pets')); await Person.query().outerJoin(raw('pets')); await Person.query().fullOuterJoin(raw('pets')); await Person.query().crossJoin(raw('pets')); })();
Add tests for join methods
Add tests for join methods Signed-off-by: Will Soto <[email protected]> #1431
TypeScript
mit
Vincit/objection.js,Vincit/objection.js,Vincit/objection.js
--- +++ @@ -0,0 +1,63 @@ +import { Person } from '../fixtures/person'; +import { raw } from '../../..'; + +(async () => { + await Person.query() + .joinRelation('pets') + .where('pets.species', 'dog'); + + await Person.query() + .joinRelation('pets', { alias: 'p' }) + .where('p.species', 'dog'); + + await Person.query() + .joinRelation('[pets, parent]') + .where('pets.species', 'dog') + .where('parent.name', 'Arnold'); + + await Person.query() + .joinRelation({ + pets: true, + parent: true + }) + .where('pets.species', 'dog') + .where('parent.name', 'Arnold'); + + await Person.query() + .select('persons.id', 'parent:parent.name as grandParentName') + .joinRelation('[pets, parent.[pets, parent]]') + .where('parent:pets.species', 'dog'); + + await Person.query() + .select('persons.id', 'pr:pr.name as grandParentName') + .joinRelation('[pets, parent.[pets, parent]]', { + aliases: { + parent: 'pr', + pets: 'pt' + } + }) + .where('pr:pt.species', 'dog'); + + await Person.query() + .select('persons.id', 'pr:pr.name as grandParentName') + .joinRelation('[pets as pt, parent as pr.[pets as pt, parent as pr]]') + .where('pr:pt.species', 'dog'); + + await Person.query().innerJoinRelation('pets'); + await Person.query().outerJoinRelation('pets'); + await Person.query().leftJoinRelation('pets'); + await Person.query().leftOuterJoinRelation('pets'); + await Person.query().rightJoinRelation('pets'); + await Person.query().rightOuterJoinRelation('pets'); + await Person.query().fullOuterJoinRelation('pets'); + await Person.query().join(raw('pets')); + await Person.query().joinRaw('pets'); + await Person.query().innerJoin(raw('pets')); + await Person.query().leftJoin(raw('pets')); + await Person.query().leftOuterJoin(raw('pets')); + await Person.query().rightJoin(raw('pets')); + await Person.query().rightOuterJoin(raw('pets')); + await Person.query().outerJoin(raw('pets')); + await Person.query().fullOuterJoin(raw('pets')); + await Person.query().crossJoin(raw('pets')); +})();
8accf9e0fcfa3142f4c01495b5dcb2f8d8c0df0b
spec/errors.spec.ts
spec/errors.spec.ts
import {jsonMember, jsonObject, TypedJSON} from '../src'; describe('errors', () => { class CustomType { } it('should be thrown when types could not be determined', () => { @jsonObject class TestNonDeterminableTypes { @jsonMember bar: CustomType; } const typedJson = new TypedJSON(TestNonDeterminableTypes); typedJson.config({ errorHandler: e => { throw e; }, }); expect(() => typedJson.parse({bar: 'bar'})).toThrow(); }); });
Test whether undeterminable types throw errors
Test whether undeterminable types throw errors
TypeScript
mit
JohnWhiteTB/TypedJSON,JohnWhiteTB/TypedJSON,JohnWeisz/TypedJSON,JohnWeisz/TypedJSON,JohnWhiteTB/TypedJSON
--- +++ @@ -0,0 +1,24 @@ +import {jsonMember, jsonObject, TypedJSON} from '../src'; + +describe('errors', () => { + class CustomType { + } + + it('should be thrown when types could not be determined', () => { + @jsonObject + class TestNonDeterminableTypes { + + @jsonMember + bar: CustomType; + } + + const typedJson = new TypedJSON(TestNonDeterminableTypes); + typedJson.config({ + errorHandler: e => { + throw e; + }, + }); + + expect(() => typedJson.parse({bar: 'bar'})).toThrow(); + }); +});
ef24732d51a19f174b8025836dc23ad47b7a0f51
desktop/core/src/desktop/js/components/directives/overflowOnHoverDirective.ts
desktop/core/src/desktop/js/components/directives/overflowOnHoverDirective.ts
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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 { DirectiveOptions } from 'vue'; interface OverflowOnHoverHTMLElement extends HTMLElement { disposeOverflowOnHover?: () => void; } interface OverflowOnHoverValue { direction?: 'y' | 'x' | 'both'; } const getOverflowStyle = ( value: OverflowOnHoverValue ): keyof Pick<CSSStyleDeclaration, 'overflow' | 'overflowX' | 'overflowY'> => { if (value && value.direction === 'x') { return 'overflowX'; } if (value && value.direction === 'y') { return 'overflowY'; } return 'overflow'; }; export const overflowOnHover: DirectiveOptions = { bind: (el: OverflowOnHoverHTMLElement, binding) => { const value = <OverflowOnHoverValue>binding.value; const overflowStyle = getOverflowStyle(value); const initialOverflowValue = el.style[overflowStyle]; el.style[overflowStyle] = 'hidden'; let isTouch = false; const onTouchStart = () => { isTouch = true; }; let showDelay = -1; const onMouseEnter = () => { showDelay = window.setTimeout(() => { el.style[overflowStyle] = 'auto'; }, 30); }; const onMouseLeave = () => { window.clearTimeout(showDelay); if (!isTouch) { el.style[overflowStyle] = 'hidden'; } }; el.addEventListener('touchstart', onTouchStart); el.addEventListener('mouseenter', onMouseEnter); el.addEventListener('mouseleave', onMouseLeave); el.disposeOverflowOnHover = () => { window.clearTimeout(showDelay); el.removeEventListener('touchstart', onTouchStart); el.removeEventListener('mouseenter', onMouseEnter); el.removeEventListener('mouseleave', onMouseLeave); el.style[overflowStyle] = initialOverflowValue; }; }, unbind: (el: OverflowOnHoverHTMLElement) => { if (el.disposeOverflowOnHover) { el.disposeOverflowOnHover(); } } };
Add an overflow on hover Vue directive
[frontend] Add an overflow on hover Vue directive Similar to the ko binding we have to only show scrollbars when mouse is hovering over an element
TypeScript
apache-2.0
cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue
--- +++ @@ -0,0 +1,82 @@ +// Licensed to Cloudera, Inc. under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. Cloudera, Inc. licenses this file +// to you 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 { DirectiveOptions } from 'vue'; + +interface OverflowOnHoverHTMLElement extends HTMLElement { + disposeOverflowOnHover?: () => void; +} + +interface OverflowOnHoverValue { + direction?: 'y' | 'x' | 'both'; +} + +const getOverflowStyle = ( + value: OverflowOnHoverValue +): keyof Pick<CSSStyleDeclaration, 'overflow' | 'overflowX' | 'overflowY'> => { + if (value && value.direction === 'x') { + return 'overflowX'; + } + if (value && value.direction === 'y') { + return 'overflowY'; + } + return 'overflow'; +}; + +export const overflowOnHover: DirectiveOptions = { + bind: (el: OverflowOnHoverHTMLElement, binding) => { + const value = <OverflowOnHoverValue>binding.value; + const overflowStyle = getOverflowStyle(value); + const initialOverflowValue = el.style[overflowStyle]; + el.style[overflowStyle] = 'hidden'; + + let isTouch = false; + const onTouchStart = () => { + isTouch = true; + }; + + let showDelay = -1; + const onMouseEnter = () => { + showDelay = window.setTimeout(() => { + el.style[overflowStyle] = 'auto'; + }, 30); + }; + + const onMouseLeave = () => { + window.clearTimeout(showDelay); + if (!isTouch) { + el.style[overflowStyle] = 'hidden'; + } + }; + + el.addEventListener('touchstart', onTouchStart); + el.addEventListener('mouseenter', onMouseEnter); + el.addEventListener('mouseleave', onMouseLeave); + + el.disposeOverflowOnHover = () => { + window.clearTimeout(showDelay); + el.removeEventListener('touchstart', onTouchStart); + el.removeEventListener('mouseenter', onMouseEnter); + el.removeEventListener('mouseleave', onMouseLeave); + el.style[overflowStyle] = initialOverflowValue; + }; + }, + unbind: (el: OverflowOnHoverHTMLElement) => { + if (el.disposeOverflowOnHover) { + el.disposeOverflowOnHover(); + } + } +};
452327be41440ebd0c74a4040a1b4ef7660c206d
packages/material/src/complex/NoBorderTableCell.tsx
packages/material/src/complex/NoBorderTableCell.tsx
import { withStyles } from '@material-ui/core/styles'; import { TableCell } from '@material-ui/core'; import * as React from 'react'; const styles = { noBottomBorder: { borderBottom: 'none' } }; const NoBorderTableCell = ({ classes, children, ...otherProps }: any) => ( <TableCell className={classes.noBottomBorder} {...otherProps}> {children} </TableCell> ); export default withStyles(styles)(NoBorderTableCell);
Add table cell with disabled bottom border
[material] Add table cell with disabled bottom border
TypeScript
mit
qb-project/jsonforms,qb-project/jsonforms,qb-project/jsonforms
--- +++ @@ -0,0 +1,17 @@ +import { withStyles } from '@material-ui/core/styles'; +import { TableCell } from '@material-ui/core'; +import * as React from 'react'; + +const styles = { + noBottomBorder: { + borderBottom: 'none' + } +}; + +const NoBorderTableCell = ({ classes, children, ...otherProps }: any) => ( + <TableCell className={classes.noBottomBorder} {...otherProps}> + {children} + </TableCell> +); + +export default withStyles(styles)(NoBorderTableCell);
9dc66f26d0620ee84442ba1fd13381d854472a02
src/app/+customer/customer.routes.ts
src/app/+customer/customer.routes.ts
import { RouterConfig } from '@angular/router'; import { CustomerComponent } from './customer.component'; import { CustomerOrdersComponent } from './customerOrders.component'; import { CustomerDetailsComponent } from './customerDetails.component'; import { CustomerEditComponent } from './customerEdit.component'; export const CustomerRoutes: RouterConfig = [ { path: 'customers/:id', component: CustomerComponent, children: [ { path:'orders', component: CustomerOrdersComponent }, { path:'details', component: CustomerDetailsComponent }, { path:'edit', component: CustomerEditComponent } ] } ];
import { RouterConfig } from '@angular/router'; import { CustomerComponent } from './customer.component'; import { CustomerOrdersComponent } from './customerOrders.component'; import { CustomerDetailsComponent } from './customerDetails.component'; import { CustomerEditComponent } from './customerEdit.component'; export const CustomerRoutes: RouterConfig = [ { path: 'customers/:id', terminal: true, redirectTo: '/customers/:id/details' }, //route path with only a customer id to the details route. { path: 'customers/:id', component: CustomerComponent, children: [ { path:'orders', component: CustomerOrdersComponent }, { path:'details', component: CustomerDetailsComponent }, { path:'edit', component: CustomerEditComponent } ] } ];
Add redirect from path to .../id to .../id/details
Add redirect from path to .../id to .../id/details Routes to customer id only will now redirect to customer details page.
TypeScript
mit
DanWahlin/Angular-JumpStart,m-williams/Angular2-JumpStart,DanWahlin/Angular-JumpStart,DanWahlin/Angular2-JumpStart,m-williams/Angular2-JumpStart,DanWahlin/Angular2-JumpStart,m-williams/Angular2-JumpStart,DanWahlin/Angular2-JumpStart,DanWahlin/Angular-JumpStart
--- +++ @@ -6,6 +6,7 @@ import { CustomerEditComponent } from './customerEdit.component'; export const CustomerRoutes: RouterConfig = [ + { path: 'customers/:id', terminal: true, redirectTo: '/customers/:id/details' }, //route path with only a customer id to the details route. { path: 'customers/:id', component: CustomerComponent,
17772e1b4462b90f76d271bf09dba348797aea64
src/uri-quickpick.ts
src/uri-quickpick.ts
import * as vscode from 'vscode'; class UriQuickPickItem implements vscode.QuickPickItem { description = ""; detail = ""; constructor(public label: string, public uri: vscode.Uri) { } } export async function uriQuickPick(uris: vscode.Uri[], placeHolder?: string): Promise<vscode.Uri> { if (uris.length === 0) return undefined; if (uris.length === 1) return uris[0]; let picks = uris.map((u) => new UriQuickPickItem(vscode.workspace.asRelativePath(u), u)); let pick = await vscode.window.showQuickPick(picks, { placeHolder: placeHolder }); if (!pick) return undefined; return pick.uri; }
Add a uri quick pick helper
Add a uri quick pick helper
TypeScript
mpl-2.0
hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform
--- +++ @@ -0,0 +1,27 @@ +import * as vscode from 'vscode'; + +class UriQuickPickItem implements vscode.QuickPickItem { + description = ""; + detail = ""; + + constructor(public label: string, public uri: vscode.Uri) { + + } +} + +export async function uriQuickPick(uris: vscode.Uri[], placeHolder?: string): Promise<vscode.Uri> { + if (uris.length === 0) + return undefined; + + if (uris.length === 1) + return uris[0]; + + let picks = uris.map((u) => new UriQuickPickItem(vscode.workspace.asRelativePath(u), u)); + let pick = await vscode.window.showQuickPick(picks, { + placeHolder: placeHolder + }); + if (!pick) + return undefined; + + return pick.uri; +}
aa52f58bcf69c356ca28524168741d855557464e
src/utils/extend.ts
src/utils/extend.ts
export function shallowCopy(target: Object, source: Object) { for (var key in source) if (source.hasOwnProperty(key)) target[key] = source[key]; } export function shallowExtend(target: Object, ...sources: Object[]) { sources.forEach(source => shallowCopy(target, source)); } export function shallowExtendNew(target: Object, ...sources: Object[]) { return shallowExtend({}, target, sources); }
Add utility methods for extensions and copying
Add utility methods for extensions and copying
TypeScript
mit
cyclic-ui/cyclic-ui,cyclic-ui/cyclic-ui
--- +++ @@ -0,0 +1,13 @@ +export function shallowCopy(target: Object, source: Object) { + for (var key in source) + if (source.hasOwnProperty(key)) + target[key] = source[key]; +} + +export function shallowExtend(target: Object, ...sources: Object[]) { + sources.forEach(source => shallowCopy(target, source)); +} + +export function shallowExtendNew(target: Object, ...sources: Object[]) { + return shallowExtend({}, target, sources); +}
eb1fc336fa819437c319e0b11aab1807329c0f2c
tools/packager.ts
tools/packager.ts
import { writeFileSync, readFileSync } from 'fs'; const packageJson = JSON.parse(readFileSync('./package.json').toString()); delete packageJson.devDependencies; delete packageJson.scripts; writeFileSync('./dist/package.json', JSON.stringify(packageJson, null, 2));
Prepare package for npm distribution
Prepare package for npm distribution
TypeScript
mit
czeckd/angular2-dual-listbox,czeckd/angular-dual-listbox,czeckd/angular2-dual-listbox,czeckd/angular-dual-listbox,czeckd/angular-dual-listbox,czeckd/angular2-dual-listbox
--- +++ @@ -0,0 +1,6 @@ +import { writeFileSync, readFileSync } from 'fs'; + +const packageJson = JSON.parse(readFileSync('./package.json').toString()); +delete packageJson.devDependencies; +delete packageJson.scripts; +writeFileSync('./dist/package.json', JSON.stringify(packageJson, null, 2));
408c7d5cbee4492361e9122f68301e4e00ee7f1b
src/autocomplete/autocomplete-container-directive.ts
src/autocomplete/autocomplete-container-directive.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 { Directive, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[containerDirective]' }) export class AutocompleteContainerDirective { constructor(public viewList: ViewContainerRef) {} }
Create container directive for items
feat(autocomplete): Create container directive for items
TypeScript
mit
TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui
--- +++ @@ -0,0 +1,32 @@ +/* + 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 { Directive, ViewContainerRef } from '@angular/core'; + +@Directive({ + selector: '[containerDirective]' +}) +export class AutocompleteContainerDirective { + + constructor(public viewList: ViewContainerRef) {} + +}
2fa1d649378af0317583582276f3e33903f73c9d
src/modules/list-toolbar/list-toolbar.component.spec.ts
src/modules/list-toolbar/list-toolbar.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ListState, ListStateDispatcher, ListStateModel } from '../list/state'; import { SkyListToolbarModule } from './'; import { ListToolbarTestComponent } from './fixtures/list-toolbar.component.fixture'; import { BehaviorSubject, Subject } from 'rxjs'; describe('List Toolbar Component', () => { let state: ListState, dispatcher: ListStateDispatcher, fixture: any, element: any; beforeEach((done) => { dispatcher = new ListStateDispatcher(); state = new ListState(new ListStateModel(), dispatcher); TestBed .configureTestingModule({ declarations: [ ListToolbarTestComponent ], imports: [ SkyListToolbarModule ], providers: [ { provide: ListState, useValue: state }, { provide: ListStateDispatcher, useValue: dispatcher } ] }) .compileComponents().then(() => { fixture = TestBed.createComponent(ListToolbarTestComponent); element = fixture.nativeElement as HTMLElement; fixture.detectChanges(); // always skip the first update to ListState, when state is ready // run detectChanges once more then begin tests state.skip(1).take(1).subscribe((s: any) => { fixture.detectChanges(); done(); }); }); }); it('should add search by default', () => { expect(element.querySelector("[cmp-id='search']")).not.toBeNull(); }); });
import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { ListState, ListStateDispatcher, ListStateModel } from '../list/state'; import { SkyListToolbarModule } from './'; import { ListToolbarTestComponent } from './fixtures/list-toolbar.component.fixture'; import { BehaviorSubject, Subject } from 'rxjs'; describe('List Toolbar Component', () => { let state: ListState, dispatcher: ListStateDispatcher, fixture: any, element: any; beforeEach(async(() => { dispatcher = new ListStateDispatcher(); state = new ListState(new ListStateModel(), dispatcher); TestBed.configureTestingModule({ declarations: [ ListToolbarTestComponent ], imports: [ SkyListToolbarModule ], providers: [ { provide: ListState, useValue: state }, { provide: ListStateDispatcher, useValue: dispatcher } ] }); fixture = TestBed.createComponent(ListToolbarTestComponent); element = fixture.nativeElement as HTMLElement; fixture.detectChanges(); // always skip the first update to ListState, when state is ready // run detectChanges once more then begin tests state.skip(1).take(1).subscribe(() => fixture.detectChanges()); })); it('should add search by default', () => { expect(element.querySelector("[cmp-id='search']")).not.toBeNull(); }); });
Use async() helper instead of jasmine async
Use async() helper instead of jasmine async
TypeScript
mit
Blackbaud-LuisBello/microedge-skyux2-contrib,Blackbaud-ChrisFranz/microedge-skyux2-contrib,Blackbaud-ChrisFranz/microedge-skyux2-contrib,blackbaud-joshgerdes/microedge-skyux2-contrib,Blackbaud-KristinaDurivage/microedge-skyux2-contrib,Blackbaud-LuisBello/microedge-skyux2-contrib,blackbaud-joshgerdes/microedge-skyux2-contrib,Blackbaud-KristinaDurivage/microedge-skyux2-contrib
--- +++ @@ -1,6 +1,7 @@ import { ComponentFixture, - TestBed + TestBed, + async } from '@angular/core/testing'; import { ListState, @@ -19,36 +20,31 @@ fixture: any, element: any; - beforeEach((done) => { + beforeEach(async(() => { dispatcher = new ListStateDispatcher(); state = new ListState(new ListStateModel(), dispatcher); - TestBed - .configureTestingModule({ - declarations: [ - ListToolbarTestComponent - ], - imports: [ - SkyListToolbarModule - ], - providers: [ - { provide: ListState, useValue: state }, - { provide: ListStateDispatcher, useValue: dispatcher } - ] - }) - .compileComponents().then(() => { - fixture = TestBed.createComponent(ListToolbarTestComponent); - element = fixture.nativeElement as HTMLElement; - fixture.detectChanges(); + TestBed.configureTestingModule({ + declarations: [ + ListToolbarTestComponent + ], + imports: [ + SkyListToolbarModule + ], + providers: [ + { provide: ListState, useValue: state }, + { provide: ListStateDispatcher, useValue: dispatcher } + ] + }); - // always skip the first update to ListState, when state is ready - // run detectChanges once more then begin tests - state.skip(1).take(1).subscribe((s: any) => { - fixture.detectChanges(); - done(); - }); - }); - }); + fixture = TestBed.createComponent(ListToolbarTestComponent); + element = fixture.nativeElement as HTMLElement; + fixture.detectChanges(); + + // always skip the first update to ListState, when state is ready + // run detectChanges once more then begin tests + state.skip(1).take(1).subscribe(() => fixture.detectChanges()); + })); it('should add search by default', () => { expect(element.querySelector("[cmp-id='search']")).not.toBeNull();
8277dea295d72a5063c2c672f4852286fa29ac9f
lib/ts/toZipSlicer.ts
lib/ts/toZipSlicer.ts
module microtome.slicer { export class ToZipSlicer { constructor(slicer:AdvancedSlicer){ } do(cfg: microtome.printer.PrinterConfig):JSZip{ let zip = new JSZip(); return zip; } } }
Bring in skeleton of new to zipfile slicer
Bring in skeleton of new to zipfile slicer
TypeScript
apache-2.0
DanielJoyce/microtome,DanielJoyce/microtome,Microtome/microtome,Microtome/microtome,DanielJoyce/microtome,DanielJoyce/microtome,Microtome/microtome
--- +++ @@ -0,0 +1,12 @@ +module microtome.slicer { + export class ToZipSlicer { + + constructor(slicer:AdvancedSlicer){ + } + + do(cfg: microtome.printer.PrinterConfig):JSZip{ + let zip = new JSZip(); + return zip; + } + } +}
d14858d32d187797cfbeff7f0963a48a8451da2a
src/SlackResponses.ts
src/SlackResponses.ts
import { WebAPICallResult } from "@slack/web-api"; /** * Taken from https://api.slack.com/methods/team.info */ export interface TeamInfoResponse extends WebAPICallResult { team: { id: string; name: string; domain: string; }; } /** * Taken from https://api.slack.com/methods/conversations.info */ export interface ConversationsInfoResponse extends WebAPICallResult { channel: { id: string; name: string; }; }
Add file to store response formats to slack API calls
Add file to store response formats to slack API calls
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,22 @@ +import { WebAPICallResult } from "@slack/web-api"; + +/** + * Taken from https://api.slack.com/methods/team.info + */ +export interface TeamInfoResponse extends WebAPICallResult { + team: { + id: string; + name: string; + domain: string; + }; +} + +/** + * Taken from https://api.slack.com/methods/conversations.info + */ +export interface ConversationsInfoResponse extends WebAPICallResult { + channel: { + id: string; + name: string; + }; +}
b56c7d64d2a95e49dd0db81d92da3d0188567243
tests/cases/fourslash/completionListInvalidMemberNames2.ts
tests/cases/fourslash/completionListInvalidMemberNames2.ts
/// <reference path='fourslash.ts' /> ////enum Foo { //// X, Y, '☆' ////} ////var x = Foo./**/ goTo.marker(); verify.memberListContains("X"); verify.memberListContains("Y"); verify.memberListCount(2);
Add test for enums with members with unicode names
Add test for enums with members with unicode names
TypeScript
apache-2.0
fdecampredon/jsx-typescript-old-version,hippich/typescript,mbebenita/shumway.ts,popravich/typescript,hippich/typescript,hippich/typescript,fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts,popravich/typescript,mbebenita/shumway.ts,popravich/typescript
--- +++ @@ -0,0 +1,11 @@ +/// <reference path='fourslash.ts' /> + +////enum Foo { +//// X, Y, '☆' +////} +////var x = Foo./**/ + +goTo.marker(); +verify.memberListContains("X"); +verify.memberListContains("Y"); +verify.memberListCount(2);
1c53eb937eac55d4c084d24e155ad2ead75eccd8
app/set/set.service.ts
app/set/set.service.ts
import {Injectable} from 'angular2/core'; import {Http, Response} from 'angular2/http'; import {Observable} from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import {Set} from './set'; @Injectable() export class SetService { private setsObservable: Observable<Set[]>; constructor( private http: Http) { } public getSets(): Observable<Set[]> { if(!this.setsObservable) { this.setsObservable = this.http.get('http://mtgjson.com/json/AllSetsArray-x.json') .map((res: Response) => { //return _.values(res.json()); return res.json(); }); } return this.setsObservable; } }
Add SetService and method to get all Sets
Add SetService and method to get all Sets
TypeScript
mit
christianhg/magicalc,christianhg/magicalc,christianhg/magicalc
--- +++ @@ -0,0 +1,26 @@ +import {Injectable} from 'angular2/core'; +import {Http, Response} from 'angular2/http'; +import {Observable} from 'rxjs/Rx'; +import 'rxjs/add/operator/map'; + +import {Set} from './set'; + +@Injectable() + +export class SetService { + private setsObservable: Observable<Set[]>; + + constructor( + private http: Http) { } + + public getSets(): Observable<Set[]> { + if(!this.setsObservable) { + this.setsObservable = this.http.get('http://mtgjson.com/json/AllSetsArray-x.json') + .map((res: Response) => { + //return _.values(res.json()); + return res.json(); + }); + } + return this.setsObservable; + } +}
5db64ce545a4a291fa1944b03de974eae11d94f8
test/reducers/slides/actions/moveSlideDown-spec.ts
test/reducers/slides/actions/moveSlideDown-spec.ts
import { expect } from 'chai'; import { MOVE_SLIDE_DOWN } 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('MOVE_SLIDE_DOWN', () => { it('should not move the slide when current selected slide is 0', () => { expect( reducer(initialState, { type: MOVE_SLIDE_DOWN, slideNumber: 0 }) ).to.deep.equal(initialState); }); it('should swap slide 1 and slide 0 when slide 1 is active', () => { const _initialState = [slide, dummySlide1]; expect( reducer(_initialState, { type: MOVE_SLIDE_DOWN, slideNumber: 1 }) ).to.deep.equal([dummySlide1, slide]); }); }); }
Add MOVE_SLIDE_DOWN test for slide reducer
test: Add MOVE_SLIDE_DOWN test for slide reducer
TypeScript
mit
Team-CHAD/DevDecks,Team-CHAD/DevDecks,DevDecks/devdecks,chengsieuly/devdecks,DevDecks/devdecks,Team-CHAD/DevDecks,DevDecks/devdecks,chengsieuly/devdecks,chengsieuly/devdecks
--- +++ @@ -0,0 +1,36 @@ +import { expect } from 'chai'; +import { MOVE_SLIDE_DOWN } 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('MOVE_SLIDE_DOWN', () => { + it('should not move the slide when current selected slide is 0', () => { + expect( + reducer(initialState, { + type: MOVE_SLIDE_DOWN, + slideNumber: 0 + }) + ).to.deep.equal(initialState); + }); + + it('should swap slide 1 and slide 0 when slide 1 is active', () => { + const _initialState = [slide, dummySlide1]; + expect( + reducer(_initialState, { + type: MOVE_SLIDE_DOWN, + slideNumber: 1 + }) + ).to.deep.equal([dummySlide1, slide]); + }); + }); +}
b140e9b8f238b277469930d82353b6c5316b09fd
countdown/countdown-tests.ts
countdown/countdown-tests.ts
// Type definitions for countdown.js // Project: http://countdownjs.org/ // Definitions by: Gabriel Juchault https://github.com/gjuchault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="countdown.d.ts" /> import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; let ts: Timespan; let interval: number; ts = <Timespan>countdown(new Date()); ts = <Timespan>countdown(150); interval = <number>countdown(new Date(), function (ts: Timespan) { document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); }, countdown.HOURS | countdown.MINUTES | countdown.SECONDS, 2, 2 ); clearInterval(interval); ts.toString('foo'); ts.toHTML('em', 'foo'); countdown.resetFormat(); countdown.setLabels('a', 'b', 'c', 'd', 'e'); countdown.setLabels('a', 'b', 'c', 'd', 'e', function (value: number): string { return 'ok'; }, function (value: number, unit: number): string { return 'ok'; }); countdown.setLabels(null, null, null, null, 'Now.'); countdown.setLabels( ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium', ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia', ' and ', ', ', '', n => n.toString());
/// <reference path="countdown.d.ts" /> import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; let ts: Timespan; let interval: number; ts = <Timespan>countdown(new Date()); ts = <Timespan>countdown(150); interval = <number>countdown(new Date(), function (ts: Timespan) { document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); }, countdown.HOURS | countdown.MINUTES | countdown.SECONDS, 2, 2 ); clearInterval(interval); ts.toString('foo'); ts.toHTML('em', 'foo'); countdown.resetFormat(); countdown.setLabels('a', 'b', 'c', 'd', 'e'); countdown.setLabels('a', 'b', 'c', 'd', 'e', function (value: number): string { return 'ok'; }, function (value: number, unit: number): string { return 'ok'; }); countdown.setLabels(null, null, null, null, 'Now.'); countdown.setLabels( ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium', ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia', ' and ', ', ', '', n => n.toString());
Remove header tags from tests
Remove header tags from tests
TypeScript
mit
jimthedev/DefinitelyTyped,rcchen/DefinitelyTyped,subash-a/DefinitelyTyped,dsebastien/DefinitelyTyped,nainslie/DefinitelyTyped,scriby/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,aciccarello/DefinitelyTyped,arusakov/DefinitelyTyped,micurs/DefinitelyTyped,mcrawshaw/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,pocesar/DefinitelyTyped,benliddicott/DefinitelyTyped,AgentME/DefinitelyTyped,psnider/DefinitelyTyped,ashwinr/DefinitelyTyped,yuit/DefinitelyTyped,xStrom/DefinitelyTyped,jimthedev/DefinitelyTyped,Penryn/DefinitelyTyped,hellopao/DefinitelyTyped,arma-gast/DefinitelyTyped,shlomiassaf/DefinitelyTyped,schmuli/DefinitelyTyped,chrootsu/DefinitelyTyped,psnider/DefinitelyTyped,isman-usoh/DefinitelyTyped,progre/DefinitelyTyped,georgemarshall/DefinitelyTyped,arma-gast/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrismbarr/DefinitelyTyped,abbasmhd/DefinitelyTyped,schmuli/DefinitelyTyped,subash-a/DefinitelyTyped,jimthedev/DefinitelyTyped,progre/DefinitelyTyped,smrq/DefinitelyTyped,borisyankov/DefinitelyTyped,YousefED/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped,damianog/DefinitelyTyped,gandjustas/DefinitelyTyped,arusakov/DefinitelyTyped,aciccarello/DefinitelyTyped,gandjustas/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,florentpoujol/DefinitelyTyped,danfma/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,YousefED/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,rolandzwaga/DefinitelyTyped,florentpoujol/DefinitelyTyped,magny/DefinitelyTyped,nycdotnet/DefinitelyTyped,borisyankov/DefinitelyTyped,shlomiassaf/DefinitelyTyped,dsebastien/DefinitelyTyped,abner/DefinitelyTyped,johan-gorter/DefinitelyTyped,alexdresko/DefinitelyTyped,scriby/DefinitelyTyped,minodisk/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,rcchen/DefinitelyTyped,sledorze/DefinitelyTyped,use-strict/DefinitelyTyped,chrootsu/DefinitelyTyped,use-strict/DefinitelyTyped,abner/DefinitelyTyped,hellopao/DefinitelyTyped,daptiv/DefinitelyTyped,psnider/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,martinduparc/DefinitelyTyped,mcrawshaw/DefinitelyTyped,alvarorahul/DefinitelyTyped,mcliment/DefinitelyTyped,hellopao/DefinitelyTyped,minodisk/DefinitelyTyped,martinduparc/DefinitelyTyped,syuilo/DefinitelyTyped,arusakov/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,chrismbarr/DefinitelyTyped,rolandzwaga/DefinitelyTyped,magny/DefinitelyTyped,syuilo/DefinitelyTyped,QuatroCode/DefinitelyTyped,damianog/DefinitelyTyped,benishouga/DefinitelyTyped,AgentME/DefinitelyTyped,Penryn/DefinitelyTyped,yuit/DefinitelyTyped,danfma/DefinitelyTyped,schmuli/DefinitelyTyped,abbasmhd/DefinitelyTyped,AgentME/DefinitelyTyped,sledorze/DefinitelyTyped,paulmorphy/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,johan-gorter/DefinitelyTyped,nycdotnet/DefinitelyTyped,AgentME/DefinitelyTyped,alexdresko/DefinitelyTyped,georgemarshall/DefinitelyTyped,amir-arad/DefinitelyTyped,martinduparc/DefinitelyTyped,paulmorphy/DefinitelyTyped,zuzusik/DefinitelyTyped,ashwinr/DefinitelyTyped,markogresak/DefinitelyTyped,xStrom/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,aciccarello/DefinitelyTyped,HPFOD/DefinitelyTyped,smrq/DefinitelyTyped,isman-usoh/DefinitelyTyped,pocesar/DefinitelyTyped,zuzusik/DefinitelyTyped,pocesar/DefinitelyTyped,HPFOD/DefinitelyTyped,zuzusik/DefinitelyTyped,QuatroCode/DefinitelyTyped,one-pieces/DefinitelyTyped,benishouga/DefinitelyTyped,alvarorahul/DefinitelyTyped,nainslie/DefinitelyTyped
--- +++ @@ -1,8 +1,3 @@ -// Type definitions for countdown.js -// Project: http://countdownjs.org/ -// Definitions by: Gabriel Juchault https://github.com/gjuchault -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - /// <reference path="countdown.d.ts" /> import { countdown, Timespan, CountdownStatic, Format } from 'countdown';
bb916e3c770ee967b3187f3a1863876777ee61f8
src/examples/union-values.ts
src/examples/union-values.ts
import { Union, Literal } from '../index' const Day = Union( Literal('Sunday'), Literal('Monday'), Literal('Tuesday'), Literal('Wednesday'), Literal('Thursday'), Literal('Friday'), Literal('Saturday'), ) for (const day of Day.Alternatives.map(lit => lit.value)) { console.log(`Good morning, it's ${day}!`) }
Add an example of iterating over the values of a union of literals
Add an example of iterating over the values of a union of literals
TypeScript
mit
pelotom/runtypes,typeetfunc/runtypes,pelotom/runtypes
--- +++ @@ -0,0 +1,15 @@ +import { Union, Literal } from '../index' + +const Day = Union( + Literal('Sunday'), + Literal('Monday'), + Literal('Tuesday'), + Literal('Wednesday'), + Literal('Thursday'), + Literal('Friday'), + Literal('Saturday'), +) + +for (const day of Day.Alternatives.map(lit => lit.value)) { + console.log(`Good morning, it's ${day}!`) +}
a8d03e63b6cb6e5b21e90d754a3f158f4ea1bef5
src/marketplace/offerings/store/utils.spec.ts
src/marketplace/offerings/store/utils.spec.ts
import { OfferingComponent } from '@waldur/marketplace/types'; import { formatOfferingRequest } from './utils'; const OFFERING_FORM_DATA = { name: 'Offering', category: { title: 'VMs', url: 'URL', icon: 'URL', offering_count: 1, sections: [], }, type: { value: 'VMware.VirtualMachine', label: 'VMware Virtual machine', }, attributes: {}, options: [], plans: [ { name: 'Basic', unit: { label: 'Per month', value: 'month', }, prices: { disk: 700, ram: 800, cpu: 900, }, quotas: { disk: 10, ram: 10, cpu: 10, }, archived: false, unit_price: 0, }, ], }; const USAGE_COMPONENTS: OfferingComponent[] = [ { billing_type: 'usage', type: 'disk', name: 'Disk', description: '', measured_unit: 'MB', limit_period: null, limit_amount: null, }, { billing_type: 'usage', type: 'ram', name: 'RAM', description: '', measured_unit: 'MB', limit_period: null, limit_amount: null, }, { billing_type: 'usage', type: 'cpu', name: 'CPU', description: '', measured_unit: 'hours', limit_period: null, limit_amount: null, }, ]; const FIXED_COMPONENTS: OfferingComponent[] = [ { billing_type: 'fixed', type: 'disk', name: 'Disk', description: '', measured_unit: 'MB', limit_period: null, limit_amount: null, }, { billing_type: 'fixed', type: 'ram', name: 'RAM', description: '', measured_unit: 'MB', limit_period: null, limit_amount: null, }, { billing_type: 'fixed', type: 'cpu', name: 'CPU', description: '', measured_unit: 'hours', limit_period: null, limit_amount: null, }, ]; describe('Marketplace offering serializer', () => { it('should skip quotas for built-in usage components', () => { expect(formatOfferingRequest(OFFERING_FORM_DATA, USAGE_COMPONENTS).plans[0].quotas).toEqual({}); }); it('should not skip quotas for built-in fixed components', () => { expect(formatOfferingRequest(OFFERING_FORM_DATA, FIXED_COMPONENTS).plans[0].quotas).toEqual({ disk: 10, ram: 10, cpu: 10, }); }); });
Add unit tests for quota serialization
Add unit tests for quota serialization [WAL-2551]
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -0,0 +1,116 @@ +import { OfferingComponent } from '@waldur/marketplace/types'; + +import { formatOfferingRequest } from './utils'; + +const OFFERING_FORM_DATA = { + name: 'Offering', + category: { + title: 'VMs', + url: 'URL', + icon: 'URL', + offering_count: 1, + sections: [], + }, + type: { + value: 'VMware.VirtualMachine', + label: 'VMware Virtual machine', + }, + attributes: {}, + options: [], + plans: [ + { + name: 'Basic', + unit: { + label: 'Per month', + value: 'month', + }, + prices: { + disk: 700, + ram: 800, + cpu: 900, + }, + quotas: { + disk: 10, + ram: 10, + cpu: 10, + }, + archived: false, + unit_price: 0, + }, + ], +}; + +const USAGE_COMPONENTS: OfferingComponent[] = [ + { + billing_type: 'usage', + type: 'disk', + name: 'Disk', + description: '', + measured_unit: 'MB', + limit_period: null, + limit_amount: null, + }, + { + billing_type: 'usage', + type: 'ram', + name: 'RAM', + description: '', + measured_unit: 'MB', + limit_period: null, + limit_amount: null, + }, + { + billing_type: 'usage', + type: 'cpu', + name: 'CPU', + description: '', + measured_unit: 'hours', + limit_period: null, + limit_amount: null, + }, +]; + +const FIXED_COMPONENTS: OfferingComponent[] = [ + { + billing_type: 'fixed', + type: 'disk', + name: 'Disk', + description: '', + measured_unit: 'MB', + limit_period: null, + limit_amount: null, + }, + { + billing_type: 'fixed', + type: 'ram', + name: 'RAM', + description: '', + measured_unit: 'MB', + limit_period: null, + limit_amount: null, + }, + { + billing_type: 'fixed', + type: 'cpu', + name: 'CPU', + description: '', + measured_unit: 'hours', + limit_period: null, + limit_amount: null, + }, +]; + +describe('Marketplace offering serializer', () => { + it('should skip quotas for built-in usage components', () => { + expect(formatOfferingRequest(OFFERING_FORM_DATA, USAGE_COMPONENTS).plans[0].quotas).toEqual({}); + }); + + it('should not skip quotas for built-in fixed components', () => { + expect(formatOfferingRequest(OFFERING_FORM_DATA, FIXED_COMPONENTS).plans[0].quotas).toEqual({ + disk: 10, + ram: 10, + cpu: 10, + }); + }); + +});
e3a764f6b83628089b294beb85535103ce4f4f75
abstract-factory/ts-version.ts
abstract-factory/ts-version.ts
abstract class Item { protected caption: string; constructor(caption: string) { this.caption = caption; } abstract makeHtml(): string; } abstract class Link extends Item { protected url: string; constructor(caption: string, url: string) { super(caption); this.url = url; } abstract makeHtml(): string; } abstract class Tray extends Item { protected trayList: Array<Item>; add(item: Item): void { this.trayList.push(item); } abstract makeHtml(): string; } abstract class Page { protected title: string; protected author: string; constructor(title: string, author: string) { this.title = title; this.author = author; } add(): void {} output(): void {} abstract makeHtml(): string; } abstract class Factory { static getFactory(className: any) { return new className(); } abstract createLink(): void; abstract createTray(): void; abstract createPage(): void; }
Add ts version of Abstract Factory
Add ts version of Abstract Factory
TypeScript
mit
Erichain/design-patterns-in-typescript,Erichain/design-patterns-in-typescript
--- +++ @@ -0,0 +1,57 @@ +abstract class Item { + protected caption: string; + + constructor(caption: string) { + this.caption = caption; + } + + abstract makeHtml(): string; +} + +abstract class Link extends Item { + protected url: string; + + constructor(caption: string, url: string) { + super(caption); + + this.url = url; + } + + abstract makeHtml(): string; +} + +abstract class Tray extends Item { + protected trayList: Array<Item>; + + add(item: Item): void { + this.trayList.push(item); + } + + abstract makeHtml(): string; +} + +abstract class Page { + protected title: string; + protected author: string; + + constructor(title: string, author: string) { + this.title = title; + this.author = author; + } + + add(): void {} + + output(): void {} + + abstract makeHtml(): string; +} + +abstract class Factory { + static getFactory(className: any) { + return new className(); + } + + abstract createLink(): void; + abstract createTray(): void; + abstract createPage(): void; +}
2e9073b507b8209b4ce49d7e0f164f6b6c63f054
app/test/unit/stats-store-test.ts
app/test/unit/stats-store-test.ts
import { expect } from 'chai' import { TestStatsDatabase } from '../helpers/databases' import { StatsStore } from '../../src/lib/stats' import { UiActivityKind, IUiActivityMonitor, } from '../../src/ui/lib/ui-activity-monitor' import { Emitter, Disposable } from 'event-kit' class FakeActivityMonitor implements IUiActivityMonitor { private readonly emitter = new Emitter() public subscriptionCount = 0 public onActivity(handler: (kind: UiActivityKind) => void) { this.subscriptionCount++ const disp = this.emitter.on('activity', handler) return new Disposable(() => { disp.dispose() this.subscriptionCount-- }) } private emit(kind: UiActivityKind) { this.emitter.emit('activity', kind) } public fakeMouseActivity() { this.emit('pointer') } public fakeKeyboardActivity() { this.emit('keyboard') } public fakeMenuActivity() { this.emit('menu') } } describe('StatsStore', () => { async function createStatsDb() { const statsDb = new TestStatsDatabase() await statsDb.reset() return statsDb } it("unsubscribes from the activity monitor when it's no longer needed", async () => { const statsDb = await createStatsDb() const activityMonitor = new FakeActivityMonitor() new StatsStore(statsDb, activityMonitor) expect(activityMonitor.subscriptionCount).to.equal(1) activityMonitor.fakeMouseActivity() expect(activityMonitor.subscriptionCount).to.equal(0) // Use a read-write transaction to ensure that the write operation // from the StatsStore has completed before we try reading the table. await statsDb.transaction('rw!', statsDb.dailyMeasures, async () => { const statsEntry = await statsDb.dailyMeasures.limit(1).first() expect(statsEntry).to.not.be.undefined expect(statsEntry!.active).to.be.true }) }) })
Add a test to ensure that statsstore unsubscribes
Add a test to ensure that statsstore unsubscribes
TypeScript
mit
kactus-io/kactus,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,desktop/desktop,say25/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus
--- +++ @@ -0,0 +1,72 @@ +import { expect } from 'chai' + +import { TestStatsDatabase } from '../helpers/databases' + +import { StatsStore } from '../../src/lib/stats' +import { + UiActivityKind, + IUiActivityMonitor, +} from '../../src/ui/lib/ui-activity-monitor' +import { Emitter, Disposable } from 'event-kit' + +class FakeActivityMonitor implements IUiActivityMonitor { + private readonly emitter = new Emitter() + public subscriptionCount = 0 + + public onActivity(handler: (kind: UiActivityKind) => void) { + this.subscriptionCount++ + + const disp = this.emitter.on('activity', handler) + + return new Disposable(() => { + disp.dispose() + this.subscriptionCount-- + }) + } + + private emit(kind: UiActivityKind) { + this.emitter.emit('activity', kind) + } + + public fakeMouseActivity() { + this.emit('pointer') + } + + public fakeKeyboardActivity() { + this.emit('keyboard') + } + + public fakeMenuActivity() { + this.emit('menu') + } +} + +describe('StatsStore', () => { + async function createStatsDb() { + const statsDb = new TestStatsDatabase() + await statsDb.reset() + return statsDb + } + + it("unsubscribes from the activity monitor when it's no longer needed", async () => { + const statsDb = await createStatsDb() + const activityMonitor = new FakeActivityMonitor() + + new StatsStore(statsDb, activityMonitor) + + expect(activityMonitor.subscriptionCount).to.equal(1) + + activityMonitor.fakeMouseActivity() + + expect(activityMonitor.subscriptionCount).to.equal(0) + + // Use a read-write transaction to ensure that the write operation + // from the StatsStore has completed before we try reading the table. + await statsDb.transaction('rw!', statsDb.dailyMeasures, async () => { + const statsEntry = await statsDb.dailyMeasures.limit(1).first() + + expect(statsEntry).to.not.be.undefined + expect(statsEntry!.active).to.be.true + }) + }) +})
0e64070d18f0d3ca7984cdc613bf17ccf4a85568
app/providers/pax-calculator/pax-calculator.ts
app/providers/pax-calculator/pax-calculator.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { SoloClass } from '../classes/solo-class'; /* Generated class for the PaxCalculator provider. See https://angular.io/docs/ts/latest/guide/dependency-injection.html for more info on providers and Angular 2 DI. */ @Injectable() export class PaxCalculator { constructor(private http: Http) {} calculatePaxTime(rawTime: number, soloClass: SoloClass) { return rawTime * soloClass.paxModifier; } convertRawTime(rawTime: number, fromClass: SoloClass, toClass: SoloClass) { return this.calculatePaxTime(rawTime, fromClass) / toClass.paxModifier; } convertPaxTime(paxTime: number, fromClass: SoloClass, toClass: SoloClass) { return this.calculatePaxTime(paxTime / fromClass.paxModifier, toClass); } }
Add a provider to calculate pax times and convert between classes
Add a provider to calculate pax times and convert between classes
TypeScript
mit
blatzblaster/ionic-solo,blatzblaster/ionic-solo,blatzblaster/ionic-solo
--- +++ @@ -0,0 +1,28 @@ +import { Injectable } from '@angular/core'; +import { Http } from '@angular/http'; +import 'rxjs/add/operator/map'; +import { SoloClass } from '../classes/solo-class'; + +/* + Generated class for the PaxCalculator provider. + + See https://angular.io/docs/ts/latest/guide/dependency-injection.html + for more info on providers and Angular 2 DI. +*/ +@Injectable() +export class PaxCalculator { + + constructor(private http: Http) {} + + calculatePaxTime(rawTime: number, soloClass: SoloClass) { + return rawTime * soloClass.paxModifier; + } + + convertRawTime(rawTime: number, fromClass: SoloClass, toClass: SoloClass) { + return this.calculatePaxTime(rawTime, fromClass) / toClass.paxModifier; + } + + convertPaxTime(paxTime: number, fromClass: SoloClass, toClass: SoloClass) { + return this.calculatePaxTime(paxTime / fromClass.paxModifier, toClass); + } +}
cbcea9b119abd120d8287e7dc5d11dcd2371ae34
test/unit/Document.spec.ts
test/unit/Document.spec.ts
import { ready } from '../../lib/Document'; describe('ready', () => { it('should execute the callback immediately if the document is ready', () => { let document: any = { readyState: 'complete', addEventListener: jasmine.createSpy('EventListener') }; let callback: jasmine.Spy = jasmine.createSpy('Function'); ready(document, callback); expect(callback).toHaveBeenCalled(); expect(document.addEventListener).toHaveBeenCalledTimes(0); }); it('should add an event listener for the DOMContentLoaded event if the document is not ready', () => { let document: any = { readyState: 'loading', addEventListener: jasmine.createSpy('EventListener') }; let callback: jasmine.Spy = jasmine.createSpy('Function'); ready(document, callback); expect(callback).toHaveBeenCalledTimes(0); expect(document.addEventListener).toHaveBeenCalledWith('DOMContentLoaded', jasmine.any(Function)); }); });
Add unit tests for Document.ready
Add unit tests for Document.ready
TypeScript
unknown
michaelbull/zoom.ts,MikeBull94/zoom.ts,MikeBull94/zoom.ts,michaelbull/zoom.ts,MikeBull94/zoom.ts
--- +++ @@ -0,0 +1,29 @@ +import { ready } from '../../lib/Document'; + +describe('ready', () => { + it('should execute the callback immediately if the document is ready', () => { + let document: any = { + readyState: 'complete', + addEventListener: jasmine.createSpy('EventListener') + }; + + let callback: jasmine.Spy = jasmine.createSpy('Function'); + ready(document, callback); + + expect(callback).toHaveBeenCalled(); + expect(document.addEventListener).toHaveBeenCalledTimes(0); + }); + + it('should add an event listener for the DOMContentLoaded event if the document is not ready', () => { + let document: any = { + readyState: 'loading', + addEventListener: jasmine.createSpy('EventListener') + }; + + let callback: jasmine.Spy = jasmine.createSpy('Function'); + ready(document, callback); + + expect(callback).toHaveBeenCalledTimes(0); + expect(document.addEventListener).toHaveBeenCalledWith('DOMContentLoaded', jasmine.any(Function)); + }); +});
4e5ac7cf9e0b0e45d3ae0fd4e8760721959b5979
src/migration/1546730871436-CoreEconRemoveLogos.ts
src/migration/1546730871436-CoreEconRemoveLogos.ts
import {MigrationInterface, QueryRunner} from "typeorm"; import {Chart} from '../model/Chart' export class CoreEconRemoveLogos1546730871436 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { const charts = await Chart.find() for (let chart of charts) { if (chart.config.internalNotes === "core-econ.org") { chart.config.hideLogo = true await chart.save() } } } public async down(queryRunner: QueryRunner): Promise<any> { } }
Remove logos from core econ charts
Remove logos from core econ charts
TypeScript
mit
OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher
--- +++ @@ -0,0 +1,19 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; +import {Chart} from '../model/Chart' + +export class CoreEconRemoveLogos1546730871436 implements MigrationInterface { + + public async up(queryRunner: QueryRunner): Promise<any> { + const charts = await Chart.find() + for (let chart of charts) { + if (chart.config.internalNotes === "core-econ.org") { + chart.config.hideLogo = true + await chart.save() + } + } + } + + public async down(queryRunner: QueryRunner): Promise<any> { + } + +}
ef12ada5d7dd4e45f0956ef7070d677c17966662
demo/57-add-parent-numbered-lists.ts
demo/57-add-parent-numbered-lists.ts
// Numbered lists - Add parent number in sub number // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; import { AlignmentType, Document, HeadingLevel, Packer, Paragraph } from "../build"; const doc = new Document({ numbering: { config: [ { levels: [ { level: 0, format: "decimal", text: "%1", alignment: AlignmentType.START, style: { paragraph: { indent: { left: 720, hanging: 260 }, }, }, }, { level: 1, format: "decimal", text: "%1.%2", alignment: AlignmentType.START, style: { paragraph: { indent: { left: 1.25 * 720, hanging: 1.25 * 260 }, }, run: { bold: true, size: 18, font: "Times New Roman", }, }, }, ], reference: "my-number-numbering-reference", }, ], }, }); doc.addSection({ children: [ new Paragraph({ text: "How to make cake", heading: HeadingLevel.HEADING_1, }), new Paragraph({ text: "Step 1 - Add sugar", numbering: { reference: "my-number-numbering-reference", level: 0, }, }), new Paragraph({ text: "Step 2 - Add wheat", numbering: { reference: "my-number-numbering-reference", level: 0, }, }), new Paragraph({ text: "Step 2a - Stir the wheat in a circle", numbering: { reference: "my-number-numbering-reference", level: 1, }, }), new Paragraph({ text: "Step 3 - Put in oven", numbering: { reference: "my-number-numbering-reference", level: 0, }, }), new Paragraph({ text: "How to make cake", heading: HeadingLevel.HEADING_1, }), ], }); Packer.toBuffer(doc).then((buffer) => { fs.writeFileSync("My Document.docx", buffer); });
Add parent to numbered list
Add parent to numbered list
TypeScript
mit
dolanmiu/docx,dolanmiu/docx,dolanmiu/docx
--- +++ @@ -0,0 +1,88 @@ +// Numbered lists - Add parent number in sub number +// Import from 'docx' rather than '../build' if you install from npm +import * as fs from "fs"; +import { AlignmentType, Document, HeadingLevel, Packer, Paragraph } from "../build"; + +const doc = new Document({ + numbering: { + config: [ + { + levels: [ + { + level: 0, + format: "decimal", + text: "%1", + alignment: AlignmentType.START, + style: { + paragraph: { + indent: { left: 720, hanging: 260 }, + }, + }, + }, + { + level: 1, + format: "decimal", + text: "%1.%2", + alignment: AlignmentType.START, + style: { + paragraph: { + indent: { left: 1.25 * 720, hanging: 1.25 * 260 }, + }, + run: { + bold: true, + size: 18, + font: "Times New Roman", + }, + }, + }, + ], + reference: "my-number-numbering-reference", + }, + ], + }, +}); + +doc.addSection({ + children: [ + new Paragraph({ + text: "How to make cake", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph({ + text: "Step 1 - Add sugar", + numbering: { + reference: "my-number-numbering-reference", + level: 0, + }, + }), + new Paragraph({ + text: "Step 2 - Add wheat", + numbering: { + reference: "my-number-numbering-reference", + level: 0, + }, + }), + new Paragraph({ + text: "Step 2a - Stir the wheat in a circle", + numbering: { + reference: "my-number-numbering-reference", + level: 1, + }, + }), + new Paragraph({ + text: "Step 3 - Put in oven", + numbering: { + reference: "my-number-numbering-reference", + level: 0, + }, + }), + new Paragraph({ + text: "How to make cake", + heading: HeadingLevel.HEADING_1, + }), + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +});
ee2e97fc6f68ee30c7c4d9e4fc0dabbe94f039ec
tests/pos/operators/short-circuit.ts
tests/pos/operators/short-circuit.ts
/*@ foo :: (arr: Array<Immutable, string>) => { boolean | true } */ function foo(arr) { if (arr.length > 0) { if (arr[0] === "blah") { return true; } } return false; } /*@ bar :: (arr: Array<Immutable, string>) => { boolean | true } */ function bar(arr) { if ((arr.length > 0) && (arr[0] === "blah")) { return true; } return false; }
Add test for short circuiting of &&
Add test for short circuiting of &&
TypeScript
bsd-3-clause
UCSD-PL/RefScript,UCSD-PL/RefScript,UCSD-PL/RefScript
--- +++ @@ -0,0 +1,17 @@ +/*@ foo :: (arr: Array<Immutable, string>) => { boolean | true } */ +function foo(arr) { + if (arr.length > 0) { + if (arr[0] === "blah") { + return true; + } + } + return false; +} + +/*@ bar :: (arr: Array<Immutable, string>) => { boolean | true } */ +function bar(arr) { + if ((arr.length > 0) && (arr[0] === "blah")) { + return true; + } + return false; +}
7f9a43951468f4f0046e6073be178b12e2187a51
app/services/crumpet-service.ts
app/services/crumpet-service.ts
/** * Created by lthompson on 18/06/2016. */ import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import {Observable} from "rxjs/Rx"; import {Crumpet} from "../data/Crumpet"; @Injectable() export class CrumpetService { constructor(private http:Http) {} listCrumpets():Observable<Crumpet[]> { var url = 'http://wondercrumpet.com/services/crumpet/list.json'; return this .http .get(url) .map(result => this.cleanData(result.json())) .catch(this.handleErrors); } cleanData(json):Crumpet[] { return json.crumpets as Crumpet[]; } handleErrors(error: Response) { console.log('Error calling crumpet service: ', JSON.stringify(error)); return Observable.throw(error); } }
Add crumpet HTTP service which returns an Observable of Crumpet[] or throws an observable error.
Add crumpet HTTP service which returns an Observable of Crumpet[] or throws an observable error.
TypeScript
unlicense
luketn/WonderCrumpet
--- +++ @@ -0,0 +1,31 @@ +/** + * Created by lthompson on 18/06/2016. + */ +import {Injectable} from "@angular/core"; +import {Http} from "@angular/http"; +import {Observable} from "rxjs/Rx"; +import {Crumpet} from "../data/Crumpet"; + +@Injectable() +export class CrumpetService { + + constructor(private http:Http) {} + + listCrumpets():Observable<Crumpet[]> { + var url = 'http://wondercrumpet.com/services/crumpet/list.json'; + return this + .http + .get(url) + .map(result => this.cleanData(result.json())) + .catch(this.handleErrors); + } + + cleanData(json):Crumpet[] { + return json.crumpets as Crumpet[]; + } + + handleErrors(error: Response) { + console.log('Error calling crumpet service: ', JSON.stringify(error)); + return Observable.throw(error); + } +}
e0398b206ec2e4f4edff0809474bad0951a673b3
src/adhocracy/adhocracy/frontend/static/js/ResourcesBaseSpec.ts
src/adhocracy/adhocracy/frontend/static/js/ResourcesBaseSpec.ts
/// <reference path="../lib/DefinitelyTyped/jasmine/jasmine.d.ts"/> /// <reference path="_all.d.ts"/> import JasmineHelpers = require("./JasmineHelpers"); import ResourcesBase = require("./ResourcesBase"); class Sheet1 extends ResourcesBase.Sheet { public static _meta : ResourcesBase.ISheetMetaApi = { readable: ["comments"], editable: [], creatable: [], create_mandatory: [], references: ["ref1", "ref2"] }; } class Sheet2 extends ResourcesBase.Sheet { public static _meta : ResourcesBase.ISheetMetaApi = { readable: ["comments"], editable: [], creatable: [], create_mandatory: [], references: ["ref1", "ref4"] }; } export var register = () => { describe("ResourcesBase", () => { describe("Resource.getReferences", () => { var resource : ResourcesBase.Resource; beforeEach(() => { jasmine.addMatchers(JasmineHelpers.customMatchers); resource = new ResourcesBase.Resource("sometype"); resource.data = { sheet1: new Sheet1(), sheet2: new Sheet2() }; }); it("returns the union of all references in all sheets", () => { (<any>expect(resource.getReferences())).toSetEqual(["ref1", "ref2", "ref4"]); }); }); }); };
Add unit test for ResourcesBase
Add unit test for ResourcesBase
TypeScript
agpl-3.0
liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator
--- +++ @@ -0,0 +1,48 @@ +/// <reference path="../lib/DefinitelyTyped/jasmine/jasmine.d.ts"/> +/// <reference path="_all.d.ts"/> + +import JasmineHelpers = require("./JasmineHelpers"); +import ResourcesBase = require("./ResourcesBase"); + +class Sheet1 extends ResourcesBase.Sheet { + public static _meta : ResourcesBase.ISheetMetaApi = { + readable: ["comments"], + editable: [], + creatable: [], + create_mandatory: [], + references: ["ref1", "ref2"] + }; +} + +class Sheet2 extends ResourcesBase.Sheet { + public static _meta : ResourcesBase.ISheetMetaApi = { + readable: ["comments"], + editable: [], + creatable: [], + create_mandatory: [], + references: ["ref1", "ref4"] + }; +} + +export var register = () => { + describe("ResourcesBase", () => { + describe("Resource.getReferences", () => { + var resource : ResourcesBase.Resource; + + beforeEach(() => { + jasmine.addMatchers(JasmineHelpers.customMatchers); + + resource = new ResourcesBase.Resource("sometype"); + + resource.data = { + sheet1: new Sheet1(), + sheet2: new Sheet2() + }; + }); + + it("returns the union of all references in all sheets", () => { + (<any>expect(resource.getReferences())).toSetEqual(["ref1", "ref2", "ref4"]); + }); + }); + }); +};
12ac8b7383e607ae228ff838c73ebbdcd56d64a5
types/custom-functions-runtime/custom-functions-runtime-tests.ts
types/custom-functions-runtime/custom-functions-runtime-tests.ts
/* Note that this is a sample function for the purpose of running the below CustomFunctionsMappings test */ function ADD10(n: number) { return n + 10; } CustomFunctionMappings = { addTen: ADD10 }; async function getStockValues(ticker: string, handler: CustomFunctions.StreamingHandler<number>) { const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); handler.setResult(dollars); } async function getStockValuesOneTime(ticker: string, handler: CustomFunctions.CancelableHandler) { let shouldStop = false; handler.onCanceled = () => shouldStop = true; await pause(1000); if (shouldStop) { return null; } const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); return dollars; } async function getStockValuesNowWithNoCancelling(ticker: string) { const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); return dollars; } declare function pause(ms: number): Promise<void>;
/* Note that this is a sample function for the purpose of running the below CustomFunctionsMappings test */ function ADD10(n: number) { return n + 10; } CustomFunctionMappings = { addTen: ADD10 }; async function getStockValues(ticker: string): Promise<number> { const response = await fetch(`myService.com/prices/${ticker}`); return (await response.json())['price']; } async function getStockValuesCancellable( ticker: string, handler: CustomFunctions.CancelableHandler ): Promise<number> { let shouldStop = false; handler.onCanceled = () => (shouldStop = true); await pause(1000); if (shouldStop) { return null; } const response = await fetch(`myService.com/prices/${ticker}`); return (await response.json())['price']; } async function stockPriceStream( ticker: string, handler: CustomFunctions.StreamingHandler<number> ) { var updateFrequency = 10 /* milliseconds*/; var isPending = false; var timer = setInterval(function() { // If there is already a pending request, skip this iteration: if (isPending) { return; } var url = `myService.com/prices/${ticker}`; isPending = true; fetch(url) .then(function(response) { return response.json(); }) .then(function(data) { handler.setResult(data.price); }) .catch(function(error) { handler.setResult(new Error(error)); }) .then(function() { isPending = false; }); }, updateFrequency); handler.onCanceled = () => { clearInterval(timer); }; } declare function pause(ms: number): Promise<void>;
Update tests to allow a streaming error, and general test cleanup
Update tests to allow a streaming error, and general test cleanup
TypeScript
mit
dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped
--- +++ @@ -7,27 +7,61 @@ addTen: ADD10 }; -async function getStockValues(ticker: string, handler: CustomFunctions.StreamingHandler<number>) { - const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); - handler.setResult(dollars); +async function getStockValues(ticker: string): Promise<number> { + const response = await fetch(`myService.com/prices/${ticker}`); + return (await response.json())['price']; } -async function getStockValuesOneTime(ticker: string, handler: CustomFunctions.CancelableHandler) { +async function getStockValuesCancellable( + ticker: string, + handler: CustomFunctions.CancelableHandler +): Promise<number> { let shouldStop = false; - handler.onCanceled = () => shouldStop = true; + handler.onCanceled = () => (shouldStop = true); await pause(1000); if (shouldStop) { return null; } - const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); - return dollars; + const response = await fetch(`myService.com/prices/${ticker}`); + return (await response.json())['price']; } -async function getStockValuesNowWithNoCancelling(ticker: string) { - const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); - return dollars; +async function stockPriceStream( + ticker: string, + handler: CustomFunctions.StreamingHandler<number> +) { + var updateFrequency = 10 /* milliseconds*/; + var isPending = false; + + var timer = setInterval(function() { + // If there is already a pending request, skip this iteration: + if (isPending) { + return; + } + + var url = `myService.com/prices/${ticker}`; + isPending = true; + + fetch(url) + .then(function(response) { + return response.json(); + }) + .then(function(data) { + handler.setResult(data.price); + }) + .catch(function(error) { + handler.setResult(new Error(error)); + }) + .then(function() { + isPending = false; + }); + }, updateFrequency); + + handler.onCanceled = () => { + clearInterval(timer); + }; } declare function pause(ms: number): Promise<void>;
7d6117cc6936466a104ada267f2e4ed7979357fa
src/common-ui/components/NotifBanner.tsx
src/common-ui/components/NotifBanner.tsx
import React from 'react' import styled, { ThemeProvider } from 'styled-components' interface Theme { wide?: boolean } export interface Props extends Theme { mainText?: string mainBtnText?: string onClose: React.MouseEventHandler onMainBtnClick: React.MouseEventHandler } export class NotifBanner extends React.PureComponent<Props> { static defaultProps: Partial<Props> = { mainBtnText: `What's new?`, mainText: 'Memex Updated!', } private get theme(): Theme { return { wide: this.props.wide, } } render() { return ( <ThemeProvider theme={this.theme}> <Banner> <MainContent> <MainText>{this.props.mainText}</MainText> <MainBtn onClick={this.props.onMainBtnClick}> {this.props.mainText} </MainBtn> </MainContent> <CloseBtn onClick={this.props.onMainBtnClick}>X</CloseBtn> </Banner> </ThemeProvider> ) } } const Banner = styled.div` background: #5cd9a6; height: 31px; width: 100%; ${({ theme }) => (theme.wide ? `margin: 0 300px;` : '')} ` const MainContent = styled.div`` const MainText = styled.span`` const MainBtn = styled.button`` const CloseBtn = styled.button``
Write basic view for update notif banner
Write basic view for update notif banner
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -0,0 +1,54 @@ +import React from 'react' +import styled, { ThemeProvider } from 'styled-components' + +interface Theme { + wide?: boolean +} + +export interface Props extends Theme { + mainText?: string + mainBtnText?: string + onClose: React.MouseEventHandler + onMainBtnClick: React.MouseEventHandler +} + +export class NotifBanner extends React.PureComponent<Props> { + static defaultProps: Partial<Props> = { + mainBtnText: `What's new?`, + mainText: 'Memex Updated!', + } + + private get theme(): Theme { + return { + wide: this.props.wide, + } + } + + render() { + return ( + <ThemeProvider theme={this.theme}> + <Banner> + <MainContent> + <MainText>{this.props.mainText}</MainText> + <MainBtn onClick={this.props.onMainBtnClick}> + {this.props.mainText} + </MainBtn> + </MainContent> + <CloseBtn onClick={this.props.onMainBtnClick}>X</CloseBtn> + </Banner> + </ThemeProvider> + ) + } +} + +const Banner = styled.div` + background: #5cd9a6; + height: 31px; + width: 100%; + ${({ theme }) => (theme.wide ? `margin: 0 300px;` : '')} +` + +const MainContent = styled.div`` +const MainText = styled.span`` +const MainBtn = styled.button`` +const CloseBtn = styled.button``
e078a5ddad24bfc295e868191b60a46b6a80118e
app/src/lib/git/environment.ts
app/src/lib/git/environment.ts
import { envForAuthentication } from './authentication' import { IGitAccount } from '../../models/git-account' /** * Create a set of environment variables to use when invoking a Git * subcommand that needs to communicate with a remote (i.e. fetch, clone, * push, pull, ls-remote, etc etc). * * The environment variables deal with setting up sane defaults, configuring * authentication, and resolving proxy urls if necessary. * * @param account The authentication information (if available) to provide * to Git for use when connectingt to the remote * @param remoteUrl The primary remote URL for this operation. Note that Git * might connect to other remotes in order to fulfill the * operation. As an example, a clone of * https://github.com/desktop/desktop could containt a submodule * pointing to another host entirely. Used to resolve which * proxy (if any) should be used for the operation. */ export function envForRemoteOperation(account: IGitAccount, remoteUrl: string) { return { ...envForAuthentication(account), } }
Create stub replacement for envForAuthentication
Create stub replacement for envForAuthentication
TypeScript
mit
j-f1/forked-desktop,say25/desktop,say25/desktop,artivilla/desktop,say25/desktop,desktop/desktop,kactus-io/kactus,desktop/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus
--- +++ @@ -0,0 +1,25 @@ +import { envForAuthentication } from './authentication' +import { IGitAccount } from '../../models/git-account' + +/** + * Create a set of environment variables to use when invoking a Git + * subcommand that needs to communicate with a remote (i.e. fetch, clone, + * push, pull, ls-remote, etc etc). + * + * The environment variables deal with setting up sane defaults, configuring + * authentication, and resolving proxy urls if necessary. + * + * @param account The authentication information (if available) to provide + * to Git for use when connectingt to the remote + * @param remoteUrl The primary remote URL for this operation. Note that Git + * might connect to other remotes in order to fulfill the + * operation. As an example, a clone of + * https://github.com/desktop/desktop could containt a submodule + * pointing to another host entirely. Used to resolve which + * proxy (if any) should be used for the operation. + */ +export function envForRemoteOperation(account: IGitAccount, remoteUrl: string) { + return { + ...envForAuthentication(account), + } +}
63b50531d6cf9bafa62e4df783cd17d068b2264b
examples/angular-cli/src/stories/metadata-individual.stories.ts
examples/angular-cli/src/stories/metadata-individual.stories.ts
import { storiesOf } from '@storybook/angular'; import { TokenComponent, ITEMS, DEFAULT_NAME } from './moduleMetadata/token.component'; storiesOf('Metadata|Individual', module) .add('Individual 1', () => ({ template: `<storybook-simple-token-component [name]="name"></storybook-simple-token-component>`, props: { name: 'Prop Name', }, moduleMetadata: { imports: [], declarations: [], providers: [ { provide: ITEMS, useValue: ['Joe', 'Jane'], }, ], }, })) .add('Individual 2', () => ({ template: `<storybook-simple-token-component></storybook-simple-token-component>`, moduleMetadata: { imports: [], declarations: [TokenComponent], providers: [ { provide: ITEMS, useValue: ['Jim', 'Jill'], }, { provide: DEFAULT_NAME, useValue: 'Provider Name', }, ], }, }));
import { storiesOf } from '@storybook/angular'; import { TokenComponent, ITEMS, DEFAULT_NAME } from './moduleMetadata/token.component'; storiesOf('Metadata|Individual', module) .add('Individual 1', () => ({ template: `<storybook-simple-token-component [name]="name"></storybook-simple-token-component>`, props: { name: 'Prop Name', }, moduleMetadata: { imports: [], declarations: [TokenComponent], providers: [ { provide: ITEMS, useValue: ['Joe', 'Jane'], }, ], }, })) .add('Individual 2', () => ({ template: `<storybook-simple-token-component></storybook-simple-token-component>`, moduleMetadata: { imports: [], declarations: [TokenComponent], providers: [ { provide: ITEMS, useValue: ['Jim', 'Jill'], }, { provide: DEFAULT_NAME, useValue: 'Provider Name', }, ], }, }));
Fix "Metadata|Individual@Individual 1" story - missing declaration
Fix "Metadata|Individual@Individual 1" story - missing declaration
TypeScript
mit
storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,rhalff/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook
--- +++ @@ -9,7 +9,7 @@ }, moduleMetadata: { imports: [], - declarations: [], + declarations: [TokenComponent], providers: [ { provide: ITEMS,
558e188c60a81dfdfc147edfd708f37cfd268efc
typescript/graphs/algorithms/prims-mst.ts
typescript/graphs/algorithms/prims-mst.ts
import { Vertex, Edge } from '../graph'; import { Tree, Node } from '../../trees/tree'; type MstEdge<T> = [Vertex<T, number>, number, Vertex<T, number>]; // Prim's Algorithm function minimalSpanningTree<T>(v: Vertex<T, number>, totalVerticesNum: number): Tree<T> { const visited: Set<Vertex<T,number>> = new Set([v]); const nodes = [new Node<T>(v.value)]; while (visited.size < totalVerticesNum) { const closestVertices: MstEdge<T>[] = []; visited.forEach((vt: Vertex<T, number>) => { const closest = vt.edges .filter(e => !visited.has(e.vertex)) .sort((a, b) => b.weight - a.weight) .pop(); if (closest) { closestVertices.push([vt, closest.weight, closest.vertex]); } }); const grouped = closestVertices.reduce((obj, e: MstEdge<T>) => { const dest = e[2] as any as string; if (obj[dest]) { obj[dest].push(e); } else { obj[dest] = [e]; } return obj; }, {}); Object.keys(grouped).forEach(key => { const [ src, _, dest ]: MstEdge<T> = grouped[key] .sort((a: MstEdge<T>, b: MstEdge<T>) => b[1] - a[1]) .pop(); const node = nodes.find(n => n.value === src.value); const newNode = new Node(dest.value); node.children.push(newNode); nodes.push(newNode); visited.add(dest); }); } return new Tree(nodes[0]); } // Demo: const vertexA = new Vertex<string, number>('A'); const vertexB = new Vertex<string, number>('B'); const vertexC = new Vertex<string, number>('C'); const vertexD = new Vertex<string, number>('D'); const vertexE = new Vertex<string, number>('E'); const vertexF = new Vertex<string, number>('F'); vertexA .addAdjacentVertex(vertexB, false, 2) .addAdjacentVertex(vertexD, false, 5) .addAdjacentVertex(vertexE, false, 1); vertexB .addAdjacentVertex(vertexD, false, 14) .addAdjacentVertex(vertexC, false, 8); vertexD .addAdjacentVertex(vertexF, false, 1) .addAdjacentVertex(vertexE, false, 2) .addAdjacentVertex(vertexC, false, 10); vertexE.addAdjacentVertex(vertexF, false, 7); vertexC.addAdjacentVertex(vertexF, false, 3); const tree = minimalSpanningTree<string>(vertexA, 6); console.log(tree.toString());
Add TS Prim's MST algorithm
Add TS Prim's MST algorithm
TypeScript
mit
hAWKdv/DataStructures,hAWKdv/DataStructures
--- +++ @@ -0,0 +1,81 @@ +import { Vertex, Edge } from '../graph'; +import { Tree, Node } from '../../trees/tree'; + +type MstEdge<T> = [Vertex<T, number>, number, Vertex<T, number>]; + +// Prim's Algorithm +function minimalSpanningTree<T>(v: Vertex<T, number>, totalVerticesNum: number): Tree<T> { + const visited: Set<Vertex<T,number>> = new Set([v]); + const nodes = [new Node<T>(v.value)]; + + while (visited.size < totalVerticesNum) { + const closestVertices: MstEdge<T>[] = []; + + visited.forEach((vt: Vertex<T, number>) => { + const closest = vt.edges + .filter(e => !visited.has(e.vertex)) + .sort((a, b) => b.weight - a.weight) + .pop(); + + if (closest) { + closestVertices.push([vt, closest.weight, closest.vertex]); + } + }); + + const grouped = closestVertices.reduce((obj, e: MstEdge<T>) => { + const dest = e[2] as any as string; + if (obj[dest]) { + obj[dest].push(e); + } else { + obj[dest] = [e]; + } + return obj; + }, {}); + + + Object.keys(grouped).forEach(key => { + const [ src, _, dest ]: MstEdge<T> = grouped[key] + .sort((a: MstEdge<T>, b: MstEdge<T>) => b[1] - a[1]) + .pop(); + + const node = nodes.find(n => n.value === src.value); + const newNode = new Node(dest.value); + + node.children.push(newNode); + nodes.push(newNode); + visited.add(dest); + }); + } + + return new Tree(nodes[0]); +} + +// Demo: + +const vertexA = new Vertex<string, number>('A'); +const vertexB = new Vertex<string, number>('B'); +const vertexC = new Vertex<string, number>('C'); +const vertexD = new Vertex<string, number>('D'); +const vertexE = new Vertex<string, number>('E'); +const vertexF = new Vertex<string, number>('F'); + +vertexA + .addAdjacentVertex(vertexB, false, 2) + .addAdjacentVertex(vertexD, false, 5) + .addAdjacentVertex(vertexE, false, 1); + +vertexB + .addAdjacentVertex(vertexD, false, 14) + .addAdjacentVertex(vertexC, false, 8); + +vertexD + .addAdjacentVertex(vertexF, false, 1) + .addAdjacentVertex(vertexE, false, 2) + .addAdjacentVertex(vertexC, false, 10); + +vertexE.addAdjacentVertex(vertexF, false, 7); + +vertexC.addAdjacentVertex(vertexF, false, 3); + +const tree = minimalSpanningTree<string>(vertexA, 6); +console.log(tree.toString());
5b20b8bf4160812cd94c7282c9320606ef18eb88
src/Parsing/Inline/RaisedVoiceContext.ts
src/Parsing/Inline/RaisedVoiceContext.ts
import { TokenizableConvention } from './TokenizableConvention' import { TokenizerSnapshot } from './TokenizerSnapshot' import { TokenizerContext } from './TokenizerContext' export class RaisedVoiceContext extends TokenizerContext { initialTokenIndex: number countRemainingDelimiterChars: number constructor( public convention: TokenizableConvention, public snapshot: TokenizerSnapshot, private delimiterLength: number ) { super(convention, snapshot) this.reset() } reset(): void { super.reset() this.countRemainingDelimiterChars = this.delimiterLength } }
Add barebones raised voice context
Add barebones raised voice context
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,22 @@ +import { TokenizableConvention } from './TokenizableConvention' +import { TokenizerSnapshot } from './TokenizerSnapshot' +import { TokenizerContext } from './TokenizerContext' + +export class RaisedVoiceContext extends TokenizerContext { + initialTokenIndex: number + countRemainingDelimiterChars: number + + constructor( + public convention: TokenizableConvention, + public snapshot: TokenizerSnapshot, + private delimiterLength: number + ) { + super(convention, snapshot) + this.reset() + } + + reset(): void { + super.reset() + this.countRemainingDelimiterChars = this.delimiterLength + } +}
f9a1ce531ebf5bf4ce1079df3313ebb5d12d3f14
src/Misc/KTX2/transcoderManager.ts
src/Misc/KTX2/transcoderManager.ts
import { transcodeTarget, sourceTextureFormat, Transcoder } from './transcoder'; import { Nullable } from '../../types'; import { WASMMemoryManager } from './wasmMemoryManager'; /** * @hidden */ export class TranscoderManager { public static _Transcoders: Array<typeof Transcoder> = []; public static registerTranscoder(transcoder: typeof Transcoder) { TranscoderManager._Transcoders.push(transcoder); } private static _transcoderInstances: { [key: string]: Transcoder } = {}; private _wasmMemoryManager: WASMMemoryManager; public findTranscoder(src: sourceTextureFormat, dst: transcodeTarget): Nullable<Transcoder> { let transcoder: Nullable<Transcoder> = null; for (let i = 0; i < TranscoderManager._Transcoders.length; ++i) { if (TranscoderManager._Transcoders[i].CanTranscode(src, dst)) { const key = sourceTextureFormat[src] + "_" + transcodeTarget[dst]; transcoder = TranscoderManager._transcoderInstances[key]; if (!transcoder) { transcoder = new TranscoderManager._Transcoders[i](); transcoder!.initialize(); if (transcoder!.needMemoryManager()) { if (!this._wasmMemoryManager) { this._wasmMemoryManager = new WASMMemoryManager(); } transcoder!.setMemoryManager(this._wasmMemoryManager); } TranscoderManager._transcoderInstances[key] = transcoder; } break; } } return transcoder; } }
Add a transcoder manager class
Add a transcoder manager class
TypeScript
apache-2.0
RaananW/Babylon.js,sebavan/Babylon.js,sebavan/Babylon.js,sebavan/Babylon.js,RaananW/Babylon.js,NicolasBuecher/Babylon.js,BabylonJS/Babylon.js,Kesshi/Babylon.js,NicolasBuecher/Babylon.js,Kesshi/Babylon.js,BabylonJS/Babylon.js,BabylonJS/Babylon.js,Kesshi/Babylon.js,NicolasBuecher/Babylon.js,RaananW/Babylon.js
--- +++ @@ -0,0 +1,44 @@ +import { transcodeTarget, sourceTextureFormat, Transcoder } from './transcoder'; +import { Nullable } from '../../types'; +import { WASMMemoryManager } from './wasmMemoryManager'; + +/** + * @hidden + */ +export class TranscoderManager { + + public static _Transcoders: Array<typeof Transcoder> = []; + + public static registerTranscoder(transcoder: typeof Transcoder) { + TranscoderManager._Transcoders.push(transcoder); + } + + private static _transcoderInstances: { [key: string]: Transcoder } = {}; + + private _wasmMemoryManager: WASMMemoryManager; + + public findTranscoder(src: sourceTextureFormat, dst: transcodeTarget): Nullable<Transcoder> { + let transcoder: Nullable<Transcoder> = null; + + for (let i = 0; i < TranscoderManager._Transcoders.length; ++i) { + if (TranscoderManager._Transcoders[i].CanTranscode(src, dst)) { + const key = sourceTextureFormat[src] + "_" + transcodeTarget[dst]; + transcoder = TranscoderManager._transcoderInstances[key]; + if (!transcoder) { + transcoder = new TranscoderManager._Transcoders[i](); + transcoder!.initialize(); + if (transcoder!.needMemoryManager()) { + if (!this._wasmMemoryManager) { + this._wasmMemoryManager = new WASMMemoryManager(); + } + transcoder!.setMemoryManager(this._wasmMemoryManager); + } + TranscoderManager._transcoderInstances[key] = transcoder; + } + break; + } + } + + return transcoder; + } +}
621321e5439cb9f03387c5b86c4276c2c93c5a02
src/reducers/watcherTree.ts
src/reducers/watcherTree.ts
import { SelectWatcherTreeNodeAction } from '../actions/watcherTree'; import { SELECT_WATCHER_FILE, SELECT_WATCHER_FOLDER } from '../constants'; import { WatcherTreeSettings } from '../types'; const initial: WatcherTreeSettings = { selectionKind: null, selectionId: null, } export default ( state = initial, action: SelectWatcherTreeNodeAction ): WatcherTreeSettings => { switch (action.type) { case SELECT_WATCHER_FILE: return { ...state, selectionId: action.watcherId, selectionKind: action.watcherKind }; case SELECT_WATCHER_FOLDER: return { ...state, selectionId: null, selectionKind: 'folder' } default: return state; } };
Add reducer to respond to watcher selection actions.
Add reducer to respond to watcher selection actions.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -0,0 +1,30 @@ +import { SelectWatcherTreeNodeAction } from '../actions/watcherTree'; +import { SELECT_WATCHER_FILE, SELECT_WATCHER_FOLDER } from '../constants'; +import { WatcherTreeSettings } from '../types'; + +const initial: WatcherTreeSettings = { + selectionKind: null, + selectionId: null, +} + +export default ( + state = initial, + action: SelectWatcherTreeNodeAction +): WatcherTreeSettings => { + switch (action.type) { + case SELECT_WATCHER_FILE: + return { + ...state, + selectionId: action.watcherId, + selectionKind: action.watcherKind + }; + case SELECT_WATCHER_FOLDER: + return { + ...state, + selectionId: null, + selectionKind: 'folder' + } + default: + return state; + } +};
091f9dede75d89be1b3f37551893c29fdddd0ec8
packages/epics/src/types/actions.ts
packages/epics/src/types/actions.ts
export const LAUNCH_KERNEL_SUCCESSFUL = "LAUNCH_KERNEL_SUCCESSFUL"; export type NewKernelAction = { type: "LAUNCH_KERNEL_SUCCESSFUL", payload: { kernel: LocalKernelProps | RemoteKernelProps, kernelRef: KernelRef, contentRef: ContentRef, selectNextKernel: boolean } };
Add types subdirectory for @nteract/epics
Add types subdirectory for @nteract/epics
TypeScript
bsd-3-clause
rgbkrk/nteract,nteract/composition,nteract/nteract,nteract/composition,nteract/composition,rgbkrk/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,rgbkrk/nteract,rgbkrk/nteract,rgbkrk/nteract
--- +++ @@ -0,0 +1,10 @@ +export const LAUNCH_KERNEL_SUCCESSFUL = "LAUNCH_KERNEL_SUCCESSFUL"; +export type NewKernelAction = { + type: "LAUNCH_KERNEL_SUCCESSFUL", + payload: { + kernel: LocalKernelProps | RemoteKernelProps, + kernelRef: KernelRef, + contentRef: ContentRef, + selectNextKernel: boolean + } +};
1f6a9b62cb2c526662546faeeda6e04e14990a3c
src/injectors/forwardContext.spec.ts
src/injectors/forwardContext.spec.ts
import * as React from 'react'; import {expect} from 'chai'; import {forwardContext} from './forwardContext'; describe('forwardContext', () => { it('should forward value from context to props', () => { const injector = forwardContext('myProp'); const passedDownProps = {}; injector.propInjector({}, { myProp: 1 }, (name, value) => passedDownProps[name] = value); expect(passedDownProps['myProp']).to.be.equals(1); }); it('should not forward value from context if context does not have the prop', () => { const injector = forwardContext('myProp'); const passedDownProps = {}; injector.propInjector({}, null, (name, value) => passedDownProps[name] = value); injector.propInjector({}, {}, (name, value) => passedDownProps[name] = value); expect(passedDownProps).not.haveOwnPropertyDescriptor('myProp'); }); it('should forward value from context to props as aliased', () => { const injector = forwardContext('myProp', { alias: 'yourProp' }); const passedDownProps = {}; injector.propInjector({}, { myProp: 1 }, (name, value) => passedDownProps[name] = value); expect(passedDownProps['yourProp']).to.be.equals(1); }); it('should properly set validator on contextType even if none is provided', () => { const injector = forwardContext('myProp'); const contextTypes = {}; injector.contextTypeInjector((name, value) => contextTypes[name] = value); expect(contextTypes['myProp']).to.be.equals(React.PropTypes.any); }); it('should properly override the provided validator on contextType', () => { const injector = forwardContext('myProp', {validator: React.PropTypes.number}); const contextTypes = {}; injector.contextTypeInjector((name, value) => contextTypes[name] = value); expect(contextTypes['myProp']).to.be.equals(React.PropTypes.number); }); });
Add some tests for forwardContext
Add some tests for forwardContext
TypeScript
mit
alitaheri/react-mixout
--- +++ @@ -0,0 +1,44 @@ +import * as React from 'react'; +import {expect} from 'chai'; + +import {forwardContext} from './forwardContext'; + +describe('forwardContext', () => { + + it('should forward value from context to props', () => { + const injector = forwardContext('myProp'); + const passedDownProps = {}; + injector.propInjector({}, { myProp: 1 }, (name, value) => passedDownProps[name] = value); + expect(passedDownProps['myProp']).to.be.equals(1); + }); + + it('should not forward value from context if context does not have the prop', () => { + const injector = forwardContext('myProp'); + const passedDownProps = {}; + injector.propInjector({}, null, (name, value) => passedDownProps[name] = value); + injector.propInjector({}, {}, (name, value) => passedDownProps[name] = value); + expect(passedDownProps).not.haveOwnPropertyDescriptor('myProp'); + }); + + it('should forward value from context to props as aliased', () => { + const injector = forwardContext('myProp', { alias: 'yourProp' }); + const passedDownProps = {}; + injector.propInjector({}, { myProp: 1 }, (name, value) => passedDownProps[name] = value); + expect(passedDownProps['yourProp']).to.be.equals(1); + }); + + it('should properly set validator on contextType even if none is provided', () => { + const injector = forwardContext('myProp'); + const contextTypes = {}; + injector.contextTypeInjector((name, value) => contextTypes[name] = value); + expect(contextTypes['myProp']).to.be.equals(React.PropTypes.any); + }); + + it('should properly override the provided validator on contextType', () => { + const injector = forwardContext('myProp', {validator: React.PropTypes.number}); + const contextTypes = {}; + injector.contextTypeInjector((name, value) => contextTypes[name] = value); + expect(contextTypes['myProp']).to.be.equals(React.PropTypes.number); + }); + +});
4c07c087e22c556f0b2369cbb090e6b5ce1550bf
src/app/transcription/transcription.ts
src/app/transcription/transcription.ts
import { Annotation } from 'alveo-transcriber'; const STORAGE_VERSION = "att_1.0"; export class Transcription { remote_id: string; storage_spec: string; annotations: Array<Annotation>; constructor(remote_id: string= "", annotations: Array<Annotation>, ) { this.remote_id = remote_id this.annotations = annotations; this.storage_spec = "att_1.0"; } }
Implement to provide seamless metadata and upgrade route
Implement to provide seamless metadata and upgrade route
TypeScript
bsd-3-clause
Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber
--- +++ @@ -0,0 +1,18 @@ +import { Annotation } from 'alveo-transcriber'; + +const STORAGE_VERSION = "att_1.0"; + +export class Transcription { + remote_id: string; + storage_spec: string; + annotations: Array<Annotation>; + + constructor(remote_id: string= "", + annotations: Array<Annotation>, + ) { + this.remote_id = remote_id + this.annotations = annotations; + this.storage_spec = "att_1.0"; + } +} +
a009c227726d0bb7e0a9219c7a1636e8b6265c83
src/Test/Ast/Config/Audio.ts
src/Test/Ast/Config/Audio.ts
import { expect } from 'chai' import { Up } from '../../../index' import { insideDocumentAndParagraph } from '../Helpers' import { AudioNode } from '../../../SyntaxNodes/AudioNode' import { DocumentNode } from '../../../SyntaxNodes/DocumentNode' describe('The term that represents video conventions', () => { const up = new Up({ i18n: { terms: { audio: 'listen' } } }) it('comes from the "audio" config term', () => { const text = '[listen: chanting at Nevada caucus -> https://example.com/audio.ogg]' expect(up.toAst(text)).to.be.eql( new DocumentNode([ new AudioNode('chanting at Nevada caucus', 'https://example.com/audio.ogg') ]) ) }) it('is always case insensitive', () => { const text = '[LISTEN: chanting at Nevada caucus -> https://example.com/audio.ogg]' expect(up.toAst(text)).to.be.eql( new DocumentNode([ new AudioNode('chanting at Nevada caucus', 'https://example.com/audio.ogg') ]) ) }) })
Add 2 passing config tests
Add 2 passing config tests
TypeScript
mit
start/up,start/up
--- +++ @@ -0,0 +1,34 @@ +import { expect } from 'chai' +import { Up } from '../../../index' +import { insideDocumentAndParagraph } from '../Helpers' +import { AudioNode } from '../../../SyntaxNodes/AudioNode' +import { DocumentNode } from '../../../SyntaxNodes/DocumentNode' + + +describe('The term that represents video conventions', () => { + const up = new Up({ + i18n: { + terms: { audio: 'listen' } + } + }) + + it('comes from the "audio" config term', () => { + const text = '[listen: chanting at Nevada caucus -> https://example.com/audio.ogg]' + + expect(up.toAst(text)).to.be.eql( + new DocumentNode([ + new AudioNode('chanting at Nevada caucus', 'https://example.com/audio.ogg') + ]) + ) + }) + + it('is always case insensitive', () => { + const text = '[LISTEN: chanting at Nevada caucus -> https://example.com/audio.ogg]' + + expect(up.toAst(text)).to.be.eql( + new DocumentNode([ + new AudioNode('chanting at Nevada caucus', 'https://example.com/audio.ogg') + ]) + ) + }) +})
6123a88f187b8b725cf7770d30b0a5de920fa774
ngLabels/App_Script/LabelDataService.ts
ngLabels/App_Script/LabelDataService.ts
/// <reference path="label.d.ts" /> /// <reference path="../scripts/typings/angularjs/angular.d.ts" /> /// <reference path="../scripts/typings/angularjs/angular-resource.d.ts" /> module LabelApplication { import Rest = LabelApplication.Rest; import ngr = ng.resource; // create an interface for the resource type because I like to use // create instead of save for new objects: interface ILabelResourceClass<T> extends ngr.IResourceClass<T> { create(label: Rest.Label, success: Function); } LabelEditor.editorModule.factory('labelDataService', ["$resource", (r) => { return new LabelDataService(r); }]); export class LabelDataService { private resource: ILabelResourceClass<ngr.IResource<Rest.Label>>; constructor($resource: ngr.IResourceService) { this.resource = <ILabelResourceClass<ngr.IResource<Rest.Label>>> $resource( "api/Labels/:id", { id: "@id" }, { get: { method: "GET" }, save: { method: "PUT" }, query: { method: "GET", isArray: true }, create: { method: "POST" }, delete: { method: "DELETE" } }); } public retrieveAllLabels() { return this.resource.query(); } public updateLabel(label: Rest.Label) { this.resource.save({ id: label.Id }, label); } } };
Add the label Data Service
Add the label Data Service This could be a lengthy chat.
TypeScript
apache-2.0
BillWagner/TypeScriptAngular,BillWagner/TypeScriptAngular,BillWagner/TypeScriptAngular,BillWagner/TypeScriptAngular
--- +++ @@ -0,0 +1,44 @@ +/// <reference path="label.d.ts" /> +/// <reference path="../scripts/typings/angularjs/angular.d.ts" /> +/// <reference path="../scripts/typings/angularjs/angular-resource.d.ts" /> + +module LabelApplication { + import Rest = LabelApplication.Rest; + import ngr = ng.resource; + + // create an interface for the resource type because I like to use + // create instead of save for new objects: + interface ILabelResourceClass<T> extends ngr.IResourceClass<T> { + create(label: Rest.Label, success: Function); + } + + LabelEditor.editorModule.factory('labelDataService', ["$resource", + (r) => { + return new LabelDataService(r); + }]); + + export class LabelDataService { + private resource: ILabelResourceClass<ngr.IResource<Rest.Label>>; + + constructor($resource: ngr.IResourceService) { + this.resource = <ILabelResourceClass<ngr.IResource<Rest.Label>>> $resource( + "api/Labels/:id", + { id: "@id" }, + { + get: { method: "GET" }, + save: { method: "PUT" }, + query: { method: "GET", isArray: true }, + create: { method: "POST" }, + delete: { method: "DELETE" } + }); + } + + public retrieveAllLabels() { + return this.resource.query(); + } + + public updateLabel(label: Rest.Label) { + this.resource.save({ id: label.Id }, label); + } + } +};
33cfcd47dc9b3c41f640cd258e1d4f905f6f085f
platforms/platform-alexa/src/output/templates/SendDialogDelegateRequest.ts
platforms/platform-alexa/src/output/templates/SendDialogDelegateRequest.ts
import { BaseOutput, Output, OutputOptions, OutputTemplate } from '@jovotech/framework'; export interface SendDialogDelegateRequestOptions extends OutputOptions { target: 'AMAZON.Conversations' | 'skill'; } @Output() export class SendDialogDelegateRequest extends BaseOutput<SendDialogDelegateRequestOptions> { build(): OutputTemplate | OutputTemplate[] { return { platforms: { alexa: { nativeResponse: { version: '1.0', sessionAttributes: {}, response: { directives: [ { type: 'Dialog.DelegateRequest', target: this.options.target, period: { until: 'EXPLICIT_RETURN', }, }, ], }, }, }, }, }; } }
Add output template to send a DialogDelegateRequest
:sparkles: Add output template to send a DialogDelegateRequest
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -0,0 +1,32 @@ +import { BaseOutput, Output, OutputOptions, OutputTemplate } from '@jovotech/framework'; + +export interface SendDialogDelegateRequestOptions extends OutputOptions { + target: 'AMAZON.Conversations' | 'skill'; +} + +@Output() +export class SendDialogDelegateRequest extends BaseOutput<SendDialogDelegateRequestOptions> { + build(): OutputTemplate | OutputTemplate[] { + return { + platforms: { + alexa: { + nativeResponse: { + version: '1.0', + sessionAttributes: {}, + response: { + directives: [ + { + type: 'Dialog.DelegateRequest', + target: this.options.target, + period: { + until: 'EXPLICIT_RETURN', + }, + }, + ], + }, + }, + }, + }, + }; + } +}
ba189ce84b1c279544f9e94fc2318a6bc6ba477e
src/util/matchStringCasing.ts
src/util/matchStringCasing.ts
export default function matchStringCasing(original: string, template: string) { return original .split('') .map( (letter, i) => template[i] ? template[i] === template[i].toUpperCase() ? letter.toUpperCase() : letter.toLowerCase() : letter, ) .join(''); }
Create util function for matching string casing
Create util function for matching string casing
TypeScript
mit
martinhartt/messagelint,martinhartt/messagelint,martinhartt/messagelint
--- +++ @@ -0,0 +1,11 @@ +export default function matchStringCasing(original: string, template: string) { + return original + .split('') + .map( + (letter, i) => + template[i] + ? template[i] === template[i].toUpperCase() ? letter.toUpperCase() : letter.toLowerCase() + : letter, + ) + .join(''); +}
24bd8ab233f01c838f0869b9841b2cf7d30af38f
src/helpers/observable.service.ts
src/helpers/observable.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable() export class ObservableHelper { toPromise(observable: Observable<T>): Promise<T> { let value; let promise = new Promise((resolve, reject) => { observable.subscribe( v => value = v, reject, () => resolve(value) ); }); return promise; } }
Add helper method to convert an observable to a promise.
Add helper method to convert an observable to a promise.
TypeScript
bsd-2-clause
ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile
--- +++ @@ -0,0 +1,19 @@ +import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs'; + +@Injectable() + +export class ObservableHelper { + toPromise(observable: Observable<T>): Promise<T> { + let value; + let promise = new Promise((resolve, reject) => { + observable.subscribe( + v => value = v, + reject, + () => resolve(value) + ); + }); + + return promise; + } +}
52539db5f0369c29f6caa98e19b46e56dc86245f
app/sorcery/sorcery.service.ts
app/sorcery/sorcery.service.ts
import {Injectable} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; import {Card} from '../card/card'; import {CardService} from '../card/card.service'; import {Sorcery} from './sorcery'; @Injectable() export class SorceryService { constructor(private cardService: CardService) { } private getSorceries(): Observable<Sorcery[]> { return this.cardService.getCards() .map((cards: Card[]) => { return _.filter(cards, (card: Card) => { return _.includes(card.types, 'Sorcery'); }); }); } }
Create SorceryService and method to get all Sorceries
Create SorceryService and method to get all Sorceries
TypeScript
mit
christianhg/magicalc,christianhg/magicalc,christianhg/magicalc
--- +++ @@ -0,0 +1,21 @@ +import {Injectable} from 'angular2/core'; +import {Observable} from 'rxjs/Rx'; + +import {Card} from '../card/card'; +import {CardService} from '../card/card.service'; +import {Sorcery} from './sorcery'; + +@Injectable() + +export class SorceryService { + constructor(private cardService: CardService) { } + + private getSorceries(): Observable<Sorcery[]> { + return this.cardService.getCards() + .map((cards: Card[]) => { + return _.filter(cards, (card: Card) => { + return _.includes(card.types, 'Sorcery'); + }); + }); + } +}
36f8b6b65efba6d520e6d7d34f4994a43a5d6713
client/service/auth.service.ts
client/service/auth.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions } from '@angular/http'; import { Router } from '@angular/router'; import 'rxjs/add/operator/toPromise'; @Injectable() export class AuthService { constructor(private _http: Http, private _router: Router) { } /** * Check for a session in the local Storage * * @return {Boolean} session - If there is a session return true else * return false */ private validateSession():boolean { if(localStorage.getItem('session')) { let session = localStorage.getItem('session'); return true; } else { return false; } } /** * Check Credentials that is stored inside localStorage * if valid session is there returns true otherwise * users are navigate login page */ checkCredentials() { if(localStorage.getItem('auth') && this.validateSession()) { return true; } else { this._router.navigate(['/login']); } } checkLoginCredentials() { if(localStorage.getItem('auth') && this.validateSession()) { return true; } else { return false; } } /** * Get session from the server and store in the Browser local storage * * @param {callback} done - Actions to be done after getting credentials */ getCredentials(done) { let url = '/api/session'; this._http.get(url) .toPromise() .then(response => { localStorage.setItem('auth', response.json().token); localStorage.setItem('session', new Date().getTime().toString()); done(); }) .catch(() => { this._router.navigateByUrl('/login'); }) } /** * Get user details for the current user that is saved in `Passport` session */ getUserDetails() { let url = '/api/session'; return this._http.get(url) .toPromise() .then(response => { return response.json(); }) } /** * Handle error caught in Http requests */ private handleError(error: any): Promise<any> { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } logout() { let url = '/api/logout'; this._http.delete(url) .toPromise() .then(response => { console.log(response); }) .catch(() => { console.log('logout error'); }) localStorage.removeItem('auth'); localStorage.removeItem('session'); this._router.navigate(['/login']); } }
Add following features - Validate user sessions from local storage - Check for credentials - Get credentials. This get session from server and save in the broswer local storage - Get user details. This returns user details of server session - logout - remove session from the browser
Add following features - Validate user sessions from local storage - Check for credentials - Get credentials. This get session from server and save in the broswer local storage - Get user details. This returns user details of server session - logout - remove session from the browser
TypeScript
mit
shavindraSN/examen,shavindraSN/examen,shavindraSN/examen
--- +++ @@ -0,0 +1,104 @@ +import { Injectable } from '@angular/core'; +import { Http, Headers, RequestOptions } from '@angular/http'; +import { Router } from '@angular/router'; +import 'rxjs/add/operator/toPromise'; + +@Injectable() +export class AuthService { + constructor(private _http: Http, private _router: Router) { } + + /** + * Check for a session in the local Storage + * + * @return {Boolean} session - If there is a session return true else + * return false + */ + private validateSession():boolean { + if(localStorage.getItem('session')) { + let session = localStorage.getItem('session'); + return true; + } + else { + return false; + } + } + + /** + * Check Credentials that is stored inside localStorage + * if valid session is there returns true otherwise + * users are navigate login page + */ + checkCredentials() { + if(localStorage.getItem('auth') && this.validateSession()) { + return true; + } + else { + this._router.navigate(['/login']); + } + } + + checkLoginCredentials() { + if(localStorage.getItem('auth') && this.validateSession()) { + return true; + } + else { + return false; + } + } + /** + * Get session from the server and store in the Browser local storage + * + * @param {callback} done - Actions to be done after getting credentials + */ + getCredentials(done) { + let url = '/api/session'; + + this._http.get(url) + .toPromise() + .then(response => { + localStorage.setItem('auth', response.json().token); + localStorage.setItem('session', new Date().getTime().toString()); + done(); + }) + .catch(() => { + this._router.navigateByUrl('/login'); + }) + } + + /** + * Get user details for the current user that is saved in `Passport` session + */ + getUserDetails() { + let url = '/api/session'; + + return this._http.get(url) + .toPromise() + .then(response => { + return response.json(); + }) + } + + /** + * Handle error caught in Http requests + */ + private handleError(error: any): Promise<any> { + + console.error('An error occurred', error); // for demo purposes only + return Promise.reject(error.message || error); + } + + logout() { + let url = '/api/logout'; + this._http.delete(url) + .toPromise() + .then(response => { + console.log(response); + }) + .catch(() => { + console.log('logout error'); + }) + localStorage.removeItem('auth'); + localStorage.removeItem('session'); + this._router.navigate(['/login']); + } +}
2d6e91a2e8396e5702d29d12f30928c9557d7fda
src/remote/countMoves.ts
src/remote/countMoves.ts
import { FileMoveService as fms, datastore } from '../models'; import _ = require("underscore"); import moment = require('moment'); async function countDay(day: number) { let now = moment().utc(); let start = now.clone().subtract(day, 'days'); let end = start.clone().add(1, 'days'); let query = datastore .createQuery(fms.kind) .select('__key__') .filter('when', '>=', start.toDate()) .filter('when', '<', end.toDate()) .limit(100); let [results]: any = await datastore.runQuery(query); return { total: results.length, users: _.uniq(results.map((result: any) => result[datastore.KEY].parent.id)).length, }; } async function main() { for (let i = 1; i <= 30; i++) { console.log(i, await countDay(i)); } } main().catch(console.error);
Create file move counter script
Create file move counter script
TypeScript
bsd-2-clause
mustpax/sortmybox,mustpax/sortmybox,mustpax/sortmybox
--- +++ @@ -0,0 +1,28 @@ +import { FileMoveService as fms, datastore } from '../models'; +import _ = require("underscore"); +import moment = require('moment'); + +async function countDay(day: number) { + let now = moment().utc(); + let start = now.clone().subtract(day, 'days'); + let end = start.clone().add(1, 'days'); + let query = datastore + .createQuery(fms.kind) + .select('__key__') + .filter('when', '>=', start.toDate()) + .filter('when', '<', end.toDate()) + .limit(100); + let [results]: any = await datastore.runQuery(query); + return { + total: results.length, + users: _.uniq(results.map((result: any) => result[datastore.KEY].parent.id)).length, + }; +} + +async function main() { + for (let i = 1; i <= 30; i++) { + console.log(i, await countDay(i)); + } +} + +main().catch(console.error);
b56f1d18ba9576d92a93cdd536ab8a81a465d6ab
client/Library/Components/PersistentCharacterLibraryViewModel.tsx
client/Library/Components/PersistentCharacterLibraryViewModel.tsx
import * as React from "react"; import { PersistentCharacter } from "../../../common/PersistentCharacter"; import { LibrariesCommander } from "../../Commands/LibrariesCommander"; import { Button } from "../../Components/Button"; import { TextEnricher } from "../../TextEnricher/TextEnricher"; import { FilterCache } from "../FilterCache"; import { Listing } from "../Listing"; import { PersistentCharacterLibrary } from "../PersistentCharacterLibrary"; import { BuildListingTree } from "./BuildListingTree"; import { LibraryFilter } from "./LibraryFilter"; import { ListingViewModel } from "./Listing"; export type PersistentCharacterLibraryViewModelProps = { librariesCommander: LibrariesCommander; library: PersistentCharacterLibrary; statBlockTextEnricher: TextEnricher; }; interface State { filter: string; } export class PersistentCharacterLibraryViewModel extends React.Component<PersistentCharacterLibraryViewModelProps, State> { constructor(props: PersistentCharacterLibraryViewModelProps) { super(props); this.state = { filter: "", }; this.filterCache = new FilterCache(this.props.library.GetListings()); } public componentDidMount() { //TODO: Update component when adding and removing listings from library } public componentWillUnmount() { //this.librarySubscription.dispose(); } private filterCache: FilterCache<Listing<PersistentCharacter>>; private librarySubscription: KnockoutSubscription; private loadSavedStatBlock = (listing: Listing<PersistentCharacter>, hideOnAdd: boolean) => { this.props.librariesCommander.AddPersistentCharacterFromListing(listing, hideOnAdd); } private editStatBlock = (l: Listing<PersistentCharacter>) => { l.CurrentName.subscribe(_ => this.forceUpdate()); this.props.librariesCommander.EditPersistentCharacterStatBlock(l.Id); } private buildListingComponent = (l: Listing<PersistentCharacter>) => <ListingViewModel key={l.Id} name={l.CurrentName()} onAdd={this.loadSavedStatBlock} onEdit={this.editStatBlock} listing={l} /> public render() { const filteredListings = this.filterCache.GetFilteredEntries(this.state.filter); const listingAndFolderComponents = BuildListingTree(this.buildListingComponent, filteredListings); return (<div className="library"> <LibraryFilter applyFilterFn={filter => this.setState({ filter })} /> <ul className="listings"> {listingAndFolderComponents} </ul> <div className="buttons"> <Button additionalClassNames="hide" fontAwesomeIcon="chevron-up" onClick={() => this.props.librariesCommander.HideLibraries()} /> <Button additionalClassNames="new" fontAwesomeIcon="plus" onClick={() => alert("TODO")} /> </div> </div>); } }
Add component for Persistent Character Library
Add component for Persistent Character Library
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -0,0 +1,75 @@ +import * as React from "react"; +import { PersistentCharacter } from "../../../common/PersistentCharacter"; +import { LibrariesCommander } from "../../Commands/LibrariesCommander"; +import { Button } from "../../Components/Button"; +import { TextEnricher } from "../../TextEnricher/TextEnricher"; +import { FilterCache } from "../FilterCache"; +import { Listing } from "../Listing"; +import { PersistentCharacterLibrary } from "../PersistentCharacterLibrary"; +import { BuildListingTree } from "./BuildListingTree"; +import { LibraryFilter } from "./LibraryFilter"; +import { ListingViewModel } from "./Listing"; + +export type PersistentCharacterLibraryViewModelProps = { + librariesCommander: LibrariesCommander; + library: PersistentCharacterLibrary; + statBlockTextEnricher: TextEnricher; +}; + +interface State { + filter: string; +} + +export class PersistentCharacterLibraryViewModel extends React.Component<PersistentCharacterLibraryViewModelProps, State> { + constructor(props: PersistentCharacterLibraryViewModelProps) { + super(props); + this.state = { + filter: "", + }; + + this.filterCache = new FilterCache(this.props.library.GetListings()); + } + + public componentDidMount() { + //TODO: Update component when adding and removing listings from library + } + + public componentWillUnmount() { + //this.librarySubscription.dispose(); + } + + private filterCache: FilterCache<Listing<PersistentCharacter>>; + private librarySubscription: KnockoutSubscription; + + private loadSavedStatBlock = (listing: Listing<PersistentCharacter>, hideOnAdd: boolean) => { + this.props.librariesCommander.AddPersistentCharacterFromListing(listing, hideOnAdd); + } + + private editStatBlock = (l: Listing<PersistentCharacter>) => { + l.CurrentName.subscribe(_ => this.forceUpdate()); + this.props.librariesCommander.EditPersistentCharacterStatBlock(l.Id); + } + + private buildListingComponent = (l: Listing<PersistentCharacter>) => <ListingViewModel + key={l.Id} + name={l.CurrentName()} + onAdd={this.loadSavedStatBlock} + onEdit={this.editStatBlock} + listing={l} /> + + public render() { + const filteredListings = this.filterCache.GetFilteredEntries(this.state.filter); + const listingAndFolderComponents = BuildListingTree(this.buildListingComponent, filteredListings); + + return (<div className="library"> + <LibraryFilter applyFilterFn={filter => this.setState({ filter })} /> + <ul className="listings"> + {listingAndFolderComponents} + </ul> + <div className="buttons"> + <Button additionalClassNames="hide" fontAwesomeIcon="chevron-up" onClick={() => this.props.librariesCommander.HideLibraries()} /> + <Button additionalClassNames="new" fontAwesomeIcon="plus" onClick={() => alert("TODO")} /> + </div> + </div>); + } +}
36089487f99c926e4aaddf9904da46f053558c4b
src/YamlSetting.ts
src/YamlSetting.ts
/// <reference types="node" /> import * as fs from 'fs'; import Setting from './Setting'; import yaml from 'yaml'; class YamlSetting extends Setting { _filePath: string = 'settings.yml'; private readonly _ext: string = 'yml'; constructor( filePath?: string ){ super(); if(filePath){ this._filePath = filePath; } this.init(); } init(): void { try{ let fd = fs.openSync(this._filePath, 'a+'); let yamlStr = fs.readFileSync(this._filePath, { encoding: 'utf8' }); this._config = yamlStr ? yaml.safeLoad(yamlStr) : {}; }catch(err){ throw err; } } flush(callback: Function = (() => {})): void { fs.writeFile(this._filePath, yaml.safeDump(this._config), callback); } /* * Write current settings to file */ flushSync(): void { try{ fs.writeFileSync(this._filePath, yaml.safeDump(this._config)); }catch(err){ throw err; } } }
Add yaml setting file support
Add yaml setting file support
TypeScript
mit
woodstage/node-app-settings,woodstage/node-app-settings
--- +++ @@ -0,0 +1,42 @@ +/// <reference types="node" /> +import * as fs from 'fs'; +import Setting from './Setting'; +import yaml from 'yaml'; + +class YamlSetting extends Setting { + _filePath: string = 'settings.yml'; + private readonly _ext: string = 'yml'; + + constructor( filePath?: string ){ + super(); + if(filePath){ + this._filePath = filePath; + } + this.init(); + } + + init(): void { + try{ + let fd = fs.openSync(this._filePath, 'a+'); + let yamlStr = fs.readFileSync(this._filePath, { encoding: 'utf8' }); + this._config = yamlStr ? yaml.safeLoad(yamlStr) : {}; + }catch(err){ + throw err; + } + } + + flush(callback: Function = (() => {})): void { + fs.writeFile(this._filePath, yaml.safeDump(this._config), callback); + } + + /* + * Write current settings to file + */ + flushSync(): void { + try{ + fs.writeFileSync(this._filePath, yaml.safeDump(this._config)); + }catch(err){ + throw err; + } + } +}
76c48d03a25df69f54e5f31bbec162d81d03d20a
test/types/map.test-d.ts
test/types/map.test-d.ts
import {expectType} from 'tsd'; import * as fl from '../../index.js'; const resolved = fl.resolve (42); const rejected = fl.reject ('uh-oh'); const resolvedPar = fl.Par (resolved); const rejectedPar = fl.Par (rejected); // Standard usage on Future instances. expectType<fl.FutureInstance<never, string>> (fl.map (String) (resolved)); expectType<fl.FutureInstance<string, string>> (fl.map (String) (rejected)); // Standard usage on ConcurrentFuture instances. expectType<fl.ConcurrentFutureInstance<never, string>> (fl.map (String) (resolvedPar)); expectType<fl.ConcurrentFutureInstance<string, string>> (fl.map (String) (rejectedPar)); // Usage with pipe on Future instances (https://git.io/JLx3F). expectType<fl.FutureInstance<never, string>> (resolved .pipe (fl.map (String))); expectType<fl.FutureInstance<string, string>> (rejected .pipe (fl.map (String)));
Add typescript type tests for map
Add typescript type tests for map
TypeScript
mit
fluture-js/Fluture,fluture-js/Fluture,fluture-js/Fluture
--- +++ @@ -0,0 +1,21 @@ +import {expectType} from 'tsd'; + +import * as fl from '../../index.js'; + +const resolved = fl.resolve (42); +const rejected = fl.reject ('uh-oh'); + +const resolvedPar = fl.Par (resolved); +const rejectedPar = fl.Par (rejected); + +// Standard usage on Future instances. +expectType<fl.FutureInstance<never, string>> (fl.map (String) (resolved)); +expectType<fl.FutureInstance<string, string>> (fl.map (String) (rejected)); + +// Standard usage on ConcurrentFuture instances. +expectType<fl.ConcurrentFutureInstance<never, string>> (fl.map (String) (resolvedPar)); +expectType<fl.ConcurrentFutureInstance<string, string>> (fl.map (String) (rejectedPar)); + +// Usage with pipe on Future instances (https://git.io/JLx3F). +expectType<fl.FutureInstance<never, string>> (resolved .pipe (fl.map (String))); +expectType<fl.FutureInstance<string, string>> (rejected .pipe (fl.map (String)));
1bc1c5ae173f5ec397cd8db7660df8c2ffb92aca
src/state/StateService2.ts
src/state/StateService2.ts
/// <reference path="../../typings/rx-dom/rx.dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as rxdom from "rx.dom"; import {Node} from "../Graph"; export class StateContext2 { private nodes: Node[] = []; private alpha: number = 0; public update(): void { this.alpha = 0; } public appendNodes(nodes: Node[]): void { for (let i: number; i < nodes.length; i++) { this.nodes.push(nodes[i]); } } } export class StateService2 { private context: StateContext2; private frameSubscription: rx.IDisposable; constructor () { this.context = new StateContext2(); let frameScheduler: rxdom.IRequestAnimationFrameScheduler = rx.Scheduler.requestAnimationFrame; let frame: () => void = this.frame.bind(this); this.frameSubscription = rx.Observable.generate( 0, function (x: number): boolean { return true; }, function (x: number): number { return x + 1; }, function (x: number): number { return x; }, frameScheduler ).subscribe(frame); } public dispose(): void { this.frameSubscription.dispose(); } public frame(): void { this.context.update(); } }
Add empty state service using request animation frame.
Add empty state service using request animation frame.
TypeScript
mit
mapillary/mapillary-js,mapillary/mapillary-js
--- +++ @@ -0,0 +1,50 @@ +/// <reference path="../../typings/rx-dom/rx.dom.d.ts" /> +/// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> + +import * as rx from "rx"; +import * as rxdom from "rx.dom"; + +import {Node} from "../Graph"; + +export class StateContext2 { + private nodes: Node[] = []; + private alpha: number = 0; + + public update(): void { + this.alpha = 0; + } + + public appendNodes(nodes: Node[]): void { + for (let i: number; i < nodes.length; i++) { + this.nodes.push(nodes[i]); + } + } +} + +export class StateService2 { + private context: StateContext2; + private frameSubscription: rx.IDisposable; + + constructor () { + this.context = new StateContext2(); + + let frameScheduler: rxdom.IRequestAnimationFrameScheduler = rx.Scheduler.requestAnimationFrame; + let frame: () => void = this.frame.bind(this); + + this.frameSubscription = rx.Observable.generate( + 0, + function (x: number): boolean { return true; }, + function (x: number): number { return x + 1; }, + function (x: number): number { return x; }, + frameScheduler + ).subscribe(frame); + } + + public dispose(): void { + this.frameSubscription.dispose(); + } + + public frame(): void { + this.context.update(); + } +}
f61101f3f57c135dc551fb1557f35b418b08789d
src/datasets/utils.spec.ts
src/datasets/utils.spec.ts
import { xBetweenDates } from './utils'; describe('DatasetUtils', () => { describe('xBetweenDates', () => { it('should create function', () => { expect(xBetweenDates(new Date(), new Date())).toBeInstanceOf(Function); }); it('should return whether input date in range or not', () => { const time = new Date(); const f = xBetweenDates(new Date(time.getTime() - 10), new Date(time.getTime() + 10)); expect(f({ x: new Date(time.getTime() - 20), y: 0 })).toBeFalse(); expect(f({ x: new Date(time.getTime() - 10), y: 0 })).toBeFalse(); expect(f({ x: new Date(time.getTime()), y: 0 })).toBeTrue(); expect(f({ x: new Date(time.getTime() + 10), y: 0 })).toBeTrue(); expect(f({ x: new Date(time.getTime() + 20), y: 0 })).toBeFalse(); }); }); });
Add tests for dataset utils
Add tests for dataset utils
TypeScript
apache-2.0
googleinterns/guide-doge,googleinterns/guide-doge,googleinterns/guide-doge
--- +++ @@ -0,0 +1,19 @@ +import { xBetweenDates } from './utils'; + +describe('DatasetUtils', () => { + describe('xBetweenDates', () => { + it('should create function', () => { + expect(xBetweenDates(new Date(), new Date())).toBeInstanceOf(Function); + }); + + it('should return whether input date in range or not', () => { + const time = new Date(); + const f = xBetweenDates(new Date(time.getTime() - 10), new Date(time.getTime() + 10)); + expect(f({ x: new Date(time.getTime() - 20), y: 0 })).toBeFalse(); + expect(f({ x: new Date(time.getTime() - 10), y: 0 })).toBeFalse(); + expect(f({ x: new Date(time.getTime()), y: 0 })).toBeTrue(); + expect(f({ x: new Date(time.getTime() + 10), y: 0 })).toBeTrue(); + expect(f({ x: new Date(time.getTime() + 20), y: 0 })).toBeFalse(); + }); + }); +});
32e4d0bf8dedc6ad9a0b413498bcc1988f6bcca7
ui/src/tempVars/components/TemplatePreviewList.tsx
ui/src/tempVars/components/TemplatePreviewList.tsx
import React, {PureComponent} from 'react' import uuid from 'uuid' import {ErrorHandling} from 'src/shared/decorators/errors' import FancyScrollbar from 'src/shared/components/FancyScrollbar' import TemplatePreviewListItem from 'src/tempVars/components/TemplatePreviewListItem' import {TEMPLATE_PREVIEW_LIST_DIMENSIONS as DIMENSIONS} from 'src/tempVars/constants' import {TemplateValue} from 'src/types' const {RESULTS_TO_DISPLAY, LI_HEIGHT, LI_MARGIN_BOTTOM, OFFSET} = DIMENSIONS interface Props { items: TemplateValue[] onUpdateDefaultTemplateValue: (item: TemplateValue) => void } @ErrorHandling class TemplatePreviewList extends PureComponent<Props> { public render() { const {items, onUpdateDefaultTemplateValue} = this.props return ( <div className="temp-builder--results-list"> <FancyScrollbar autoHide={false} autoHeight={true} maxHeight={this.resultsListHeight} > {items.map(item => ( <TemplatePreviewListItem key={uuid.v4()} onClick={onUpdateDefaultTemplateValue} item={item} /> ))} </FancyScrollbar> </div> ) } private get resultsListHeight() { const {items} = this.props const count = Math.min(items.length, RESULTS_TO_DISPLAY) return count * (LI_HEIGHT + LI_MARGIN_BOTTOM) - OFFSET } } export default TemplatePreviewList
import React, {PureComponent} from 'react' import uuid from 'uuid' import {ErrorHandling} from 'src/shared/decorators/errors' import FancyScrollbar from 'src/shared/components/FancyScrollbar' import TemplatePreviewListItem from 'src/tempVars/components/TemplatePreviewListItem' import {TEMPLATE_PREVIEW_LIST_DIMENSIONS as DIMENSIONS} from 'src/tempVars/constants' import {TemplateValue} from 'src/types' const {RESULTS_TO_DISPLAY, LI_HEIGHT, LI_MARGIN_BOTTOM, OFFSET} = DIMENSIONS interface Props { items: TemplateValue[] onUpdateDefaultTemplateValue: (item: TemplateValue) => void } @ErrorHandling class TemplatePreviewList extends PureComponent<Props> { public render() { const {items, onUpdateDefaultTemplateValue} = this.props return ( <div className="temp-builder--results-list"> <FancyScrollbar autoHide={false} autoHeight={true} maxHeight={this.resultsListHeight} > {items.map(item => ( <TemplatePreviewListItem key={uuid.v4()} onClick={onUpdateDefaultTemplateValue} item={item} /> ))} </FancyScrollbar> </div> ) } private get resultsListHeight() { const {items} = this.props const count = Math.min(items.length, RESULTS_TO_DISPLAY) const scrollOffset = count > RESULTS_TO_DISPLAY ? OFFSET : 0 return count * (LI_HEIGHT + LI_MARGIN_BOTTOM) - scrollOffset } } export default TemplatePreviewList
Remove offset if displaying an unscrollable number of items in templates previews
Remove offset if displaying an unscrollable number of items in templates previews
TypeScript
mit
influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,nooproblem/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb
--- +++ @@ -42,8 +42,8 @@ private get resultsListHeight() { const {items} = this.props const count = Math.min(items.length, RESULTS_TO_DISPLAY) - - return count * (LI_HEIGHT + LI_MARGIN_BOTTOM) - OFFSET + const scrollOffset = count > RESULTS_TO_DISPLAY ? OFFSET : 0 + return count * (LI_HEIGHT + LI_MARGIN_BOTTOM) - scrollOffset } }