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
c252ce2f08d99c2698b0d67a8fd95da199efe436
src/internal.ts
src/internal.ts
/** * @since 2.10.0 */ import { Either, Left } from './Either' import { NonEmptyArray } from './NonEmptyArray' import { Option, Some } from './Option' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' // ------------------------------------------------------------------------------------- // Option // ------------------------------------------------------------------------------------- /** @internal */ export const isSome = <A>(fa: Option<A>): fa is Some<A> => fa._tag === 'Some' // ------------------------------------------------------------------------------------- // Either // ------------------------------------------------------------------------------------- /** @internal */ export const isLeft = <E, A>(ma: Either<E, A>): ma is Left<E> => ma._tag === 'Left' // ------------------------------------------------------------------------------------- // Record // ------------------------------------------------------------------------------------- const _hasOwnProperty = Object.prototype.hasOwnProperty /** * This wrapper is needed to workaround https://github.com/gcanti/fp-ts/issues/1249. * * @internal */ export function hasOwnProperty(this: any, k: string, r?: object) { /* istanbul ignore next */ return _hasOwnProperty.call(r === undefined ? this : r, k) } // ------------------------------------------------------------------------------------- // NonEmptyArray // ------------------------------------------------------------------------------------- /** @internal */ export const fromReadonlyNonEmptyArray = <A>(as: ReadonlyNonEmptyArray<A>): NonEmptyArray<A> => [as[0], ...as.slice(1)]
/** * @since 2.10.0 */ import { Either, Left } from './Either' import { NonEmptyArray } from './NonEmptyArray' import { Option, Some } from './Option' import { ReadonlyNonEmptyArray } from './ReadonlyNonEmptyArray' // ------------------------------------------------------------------------------------- // Option // ------------------------------------------------------------------------------------- /** @internal */ export const isSome = <A>(fa: Option<A>): fa is Some<A> => fa._tag === 'Some' // ------------------------------------------------------------------------------------- // Either // ------------------------------------------------------------------------------------- /** @internal */ export const isLeft = <E, A>(ma: Either<E, A>): ma is Left<E> => ma._tag === 'Left' // ------------------------------------------------------------------------------------- // Record // ------------------------------------------------------------------------------------- /** @internal */ export const hasOwnProperty = Object.prototype.hasOwnProperty // ------------------------------------------------------------------------------------- // NonEmptyArray // ------------------------------------------------------------------------------------- /** @internal */ export const fromReadonlyNonEmptyArray = <A>(as: ReadonlyNonEmptyArray<A>): NonEmptyArray<A> => [as[0], ...as.slice(1)]
Revert "Workaround issue with `hasOwnProperty`"
Revert "Workaround issue with `hasOwnProperty`" This reverts commit 8718afef60daebf27bd372014561fff2607c9c96.
TypeScript
mit
gcanti/fp-ts,gcanti/fp-ts
--- +++ @@ -24,17 +24,8 @@ // Record // ------------------------------------------------------------------------------------- -const _hasOwnProperty = Object.prototype.hasOwnProperty - -/** - * This wrapper is needed to workaround https://github.com/gcanti/fp-ts/issues/1249. - * - * @internal - */ -export function hasOwnProperty(this: any, k: string, r?: object) { - /* istanbul ignore next */ - return _hasOwnProperty.call(r === undefined ? this : r, k) -} +/** @internal */ +export const hasOwnProperty = Object.prototype.hasOwnProperty // ------------------------------------------------------------------------------------- // NonEmptyArray
21b7c0e71afd14484adfb100d6da432ec49bb6d7
app/src/ui/lib/bytes.ts
app/src/ui/lib/bytes.ts
import { round } from './round' /** * Number sign display mode */ export const enum Sign { Normal, Forced, } /** * Display bytes in human readable format like: * 23GB * -43B * It's also possible to force sign in order to get the * plus sign in case of positive numbers like: * +23GB * -43B */ export const formatBytes = ( bytes: number, signType: Sign = Sign.Normal, decimals = 0 ) => { if (!Number.isFinite(bytes)) { return 'Unknown' } const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] const sizeIndex = Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024)) const sign = signType === Sign.Forced && bytes > 0 ? '+' : '' return `${sign}${value}${sizes[sizeIndex]}` const value = round(bytes / Math.pow(1024, sizeIndex), decimals) }
import { round } from './round' /** * Number sign display mode */ export const enum Sign { Normal, Forced, } /** * Display bytes in human readable format like: * 23GB * -43B * It's also possible to force sign in order to get the * plus sign in case of positive numbers like: * +23GB * -43B */ export const formatBytes = ( bytes: number, signType: Sign = Sign.Normal, decimals = 0 ) => { if (!Number.isFinite(bytes)) { return 'Unknown' } const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] const sizeIndex = Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024)) const sign = signType === Sign.Forced && bytes > 0 ? '+' : '' const value = round(bytes / Math.pow(1024, sizeIndex), decimals) return `${sign}${value} ${sizes[sizeIndex]}` }
Add a space between unit and number
Add a space between unit and number
TypeScript
mit
artivilla/desktop,artivilla/desktop,artivilla/desktop,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,desktop/desktop,say25/desktop
--- +++ @@ -28,6 +28,6 @@ const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] const sizeIndex = Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024)) const sign = signType === Sign.Forced && bytes > 0 ? '+' : '' - return `${sign}${value}${sizes[sizeIndex]}` const value = round(bytes / Math.pow(1024, sizeIndex), decimals) + return `${sign}${value} ${sizes[sizeIndex]}` }
6da978071e9202926372dc1033883f3b7f173879
client/src/app/app.component.ts
client/src/app/app.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthenticationService } from './core/authentication.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Tour of Heroes'; constructor(private authenticationService: AuthenticationService, private router: Router) { } logout() { this.authenticationService.logout(); this.router.navigate(['/']); } isAuthenticated(): Boolean { return this.authenticationService.token !== null; } }
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthenticationService } from './core/authentication.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Tour of Heroes'; constructor(private authenticationService: AuthenticationService, private router: Router) { } logout() { this.authenticationService.logout(); this.router.navigate(['/']); } isAuthenticated(): Boolean { return (typeof this.authenticationService.token != 'undefined' && this.authenticationService.token !== null); } }
Fix bug in isAuthenticated not checking for undefined value
Fix bug in isAuthenticated not checking for undefined value
TypeScript
mit
thinhpham/mean-docker,thinhpham/mean-docker,thinhpham/mean-docker,thinhpham/mean-docker
--- +++ @@ -18,6 +18,6 @@ } isAuthenticated(): Boolean { - return this.authenticationService.token !== null; + return (typeof this.authenticationService.token != 'undefined' && this.authenticationService.token !== null); } }
ccc0f8515b550f8ec8224fdc24accad3a8986822
test/helpers.ts
test/helpers.ts
import { GitProcess, IGitResult } from '../lib' // NOTE: bump these versions to the latest stable releases export const gitVersion = '2.19.2' export const gitLfsVersion = '2.6.0' const temp = require('temp').track() export async function initialize(repositoryName: string): Promise<string> { const testRepoPath = temp.mkdirSync(`desktop-git-test-${repositoryName}`) await GitProcess.exec(['init'], testRepoPath) await GitProcess.exec(['config', 'user.email', '"[email protected]"'], testRepoPath) await GitProcess.exec(['config', 'user.name', '"Some User"'], testRepoPath) return testRepoPath } export function verify(result: IGitResult, callback: (result: IGitResult) => void) { try { callback(result) } catch (e) { console.log('error encountered while verifying; poking at response from Git:') console.log(` - exitCode: ${result.exitCode}`) console.log(` - stdout: ${result.stdout.trim()}`) console.log(` - stderr: ${result.stderr.trim()}`) console.log() throw e } }
import { GitProcess, IGitResult } from '../lib' // NOTE: bump these versions to the latest stable releases export const gitVersion = '2.19.3' export const gitLfsVersion = '2.6.0' const temp = require('temp').track() export async function initialize(repositoryName: string): Promise<string> { const testRepoPath = temp.mkdirSync(`desktop-git-test-${repositoryName}`) await GitProcess.exec(['init'], testRepoPath) await GitProcess.exec(['config', 'user.email', '"[email protected]"'], testRepoPath) await GitProcess.exec(['config', 'user.name', '"Some User"'], testRepoPath) return testRepoPath } export function verify(result: IGitResult, callback: (result: IGitResult) => void) { try { callback(result) } catch (e) { console.log('error encountered while verifying; poking at response from Git:') console.log(` - exitCode: ${result.exitCode}`) console.log(` - stdout: ${result.stdout.trim()}`) console.log(` - stderr: ${result.stderr.trim()}`) console.log() throw e } }
Update test to use Git 2.19.3
Update test to use Git 2.19.3
TypeScript
mit
desktop/dugite,desktop/dugite,desktop/dugite
--- +++ @@ -1,7 +1,7 @@ import { GitProcess, IGitResult } from '../lib' // NOTE: bump these versions to the latest stable releases -export const gitVersion = '2.19.2' +export const gitVersion = '2.19.3' export const gitLfsVersion = '2.6.0' const temp = require('temp').track()
0d73f5e867ca76e158dde834fda1502fe2f99f91
index.d.ts
index.d.ts
declare module 'connected-react-router' { import * as React from 'react' import { Middleware, Reducer } from 'redux' import { History, Path, Location, LocationState, LocationDescriptorObject } from 'history' interface ConnectedRouterProps { history: History } export enum RouterActionType { POP = 'POP', PUSH = 'PUSH' } export interface RouterState { location: Location action: RouterActionType.POP | RouterActionType.PUSH } export const LOCATION_CHANGE: string export const CALL_HISTORY_METHOD: string export function push(path: Path, state?: LocationState): RouterAction; export function push(location: LocationDescriptorObject): RouterAction; export function replace(path: Path, state?: LocationState): RouterAction; export function replace(location: LocationDescriptorObject): RouterAction; export function go(n: number): RouterAction export function goBack(): RouterAction export function goForward(): RouterAction export const routerActions: { push: typeof push, replace: typeof replace, go: typeof go, goBack: typeof goBack, goForward: typeof goForward, } export interface LocationActionPayload { method: string; args?: any[]; } export interface RouterAction { type: typeof CALL_HISTORY_METHOD; payload: LocationActionPayload; } export class ConnectedRouter extends React.Component<ConnectedRouterProps, {}> { } export function connectRouter(history: History) : <S>(reducer: Reducer<S>) => Reducer<S> export function routerMiddleware(history: History): Middleware }
declare module 'connected-react-router' { import * as React from 'react' import { Middleware, Reducer } from 'redux' import { History, Path, Location, LocationState, LocationDescriptorObject } from 'history' interface ConnectedRouterProps { history: History } export enum RouterActionType { POP = 'POP', PUSH = 'PUSH' } export interface RouterState { location: Location action: RouterActionType.POP | RouterActionType.PUSH } export const LOCATION_CHANGE: '@@router/LOCATION_CHANGE' export const CALL_HISTORY_METHOD: string export function push(path: Path, state?: LocationState): RouterAction; export function push(location: LocationDescriptorObject): RouterAction; export function replace(path: Path, state?: LocationState): RouterAction; export function replace(location: LocationDescriptorObject): RouterAction; export function go(n: number): RouterAction export function goBack(): RouterAction export function goForward(): RouterAction export const routerActions: { push: typeof push, replace: typeof replace, go: typeof go, goBack: typeof goBack, goForward: typeof goForward, } export interface LocationActionPayload { method: string; args?: any[]; } export interface RouterAction { type: typeof CALL_HISTORY_METHOD; payload: LocationActionPayload; } export class ConnectedRouter extends React.Component<ConnectedRouterProps, {}> { } export function connectRouter(history: History) : <S>(reducer: Reducer<S>) => Reducer<S> export function routerMiddleware(history: History): Middleware }
Use string literal type for action type
Use string literal type for action type
TypeScript
mit
supasate/connected-react-router
--- +++ @@ -17,7 +17,7 @@ action: RouterActionType.POP | RouterActionType.PUSH } - export const LOCATION_CHANGE: string + export const LOCATION_CHANGE: '@@router/LOCATION_CHANGE' export const CALL_HISTORY_METHOD: string export function push(path: Path, state?: LocationState): RouterAction;
be145e248c968ac633a5e465177976417062c895
src/components/SearchTable/SearchCard.tsx
src/components/SearchTable/SearchCard.tsx
import * as React from 'react'; // import { DisableableAction } from '@shopify/polaris/types/'; import { SearchItem, Requester } from '../../types'; import { ResourceList } from '@shopify/polaris'; import InfoContainer from './InfoContainer'; // import { actions } from '../../utils/hitItem'; import { truncate } from '../../utils/formatting'; import { generateBadges } from '../../utils/badges'; export interface Props { readonly hit: SearchItem; readonly requester?: Requester; readonly onClick: (hit: SearchItem) => void; } const SearchCard = ({ hit, requester, onClick }: Props) => { const { requesterName, title } = hit; const handleClick = () => onClick(hit); const actions = [ { content: 'Accept', accessibilityLabel: 'Accept', icon: 'add', onClick: handleClick } ]; return ( <ResourceList.Item actions={actions} badges={generateBadges(requester)} attributeOne={truncate(requesterName, 40)} attributeTwo={truncate(title, 80)} attributeThree={ <InfoContainer reward={hit.reward} batchSize={hit.batchSize} />} /> ); }; export default SearchCard;
import * as React from 'react'; // import { DisableableAction } from '@shopify/polaris/types/'; import { SearchItem, Requester } from '../../types'; import { ResourceList } from '@shopify/polaris'; import InfoContainer from './InfoContainer'; import { truncate } from '../../utils/formatting'; import { generateBadges } from '../../utils/badges'; export interface Props { readonly hit: SearchItem; readonly requester?: Requester; readonly onClick: (hit: SearchItem) => void; } const SearchCard = ({ hit, requester, onClick }: Props) => { const { requesterName, groupId, title } = hit; const handleClick = () => onClick(hit); const actions = [ { content: 'Preview', accessibilityLabel: 'Preview', icon: 'external', external: true, url: `https://www.mturk.com/mturk/preview?groupId=${groupId}` }, { content: 'Accept', accessibilityLabel: 'Accept', icon: 'external', external: true, url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}` }, { content: 'Add', accessibilityLabel: 'Add', icon: 'add', primary: true, onClick: handleClick } ]; return ( <ResourceList.Item actions={actions} badges={generateBadges(requester)} attributeOne={truncate(requesterName, 40)} attributeTwo={truncate(title, 80)} attributeThree={ <InfoContainer reward={hit.reward} batchSize={hit.batchSize} />} /> ); }; export default SearchCard;
Add additional actions to ResourceList.Items to go directly to a HIT's page.
Add additional actions to ResourceList.Items to go directly to a HIT's page.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -3,7 +3,6 @@ import { SearchItem, Requester } from '../../types'; import { ResourceList } from '@shopify/polaris'; import InfoContainer from './InfoContainer'; -// import { actions } from '../../utils/hitItem'; import { truncate } from '../../utils/formatting'; import { generateBadges } from '../../utils/badges'; @@ -14,14 +13,29 @@ } const SearchCard = ({ hit, requester, onClick }: Props) => { - const { requesterName, title } = hit; + const { requesterName, groupId, title } = hit; const handleClick = () => onClick(hit); const actions = [ { + content: 'Preview', + accessibilityLabel: 'Preview', + icon: 'external', + external: true, + url: `https://www.mturk.com/mturk/preview?groupId=${groupId}` + }, + { content: 'Accept', accessibilityLabel: 'Accept', + icon: 'external', + external: true, + url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}` + }, + { + content: 'Add', + accessibilityLabel: 'Add', icon: 'add', + primary: true, onClick: handleClick } ];
fb00f95c2d5469874e87e8d3ec31c0a8acfa4ba9
src/router.ts
src/router.ts
import Vue from 'vue'; import VueRouter from 'vue-router'; import DatasetsPage from './components/DatasetsPage.vue'; Vue.use(VueRouter); const router = new VueRouter({ routes: [ { path: '/', redirect: '/about' }, { path: '/annotations', component: async () => await import(/* webpackChunkName: "AnnotationsPage" */ './components/AnnotationsPage.vue') }, { path: '/datasets', component: DatasetsPage, children: [ {path: '', component: async () => await import(/* webpackChunkName: "DatasetTable" */ './components/DatasetTable.vue')}, {path: 'edit/:dataset_id', component: async () => await import(/* webpackChunkName: "MetadataEditPage" */ './components/MetadataEditPage.vue'), name: 'edit-metadata'}, { path: ':dataset_id/add-optical-image', name: 'add-optical-image', component: async () => await import(/* webpackChunkName: "ImageAlignmentPage" */ './components/ImageAlignmentPage.vue') } ] }, { path: '/upload', component: async () => await import(/* webpackChunkName: "UploadPage" */ './components/UploadPage.vue') }, { path: '/about', component: async () => await import(/* webpackChunkName: "AboutPage" */ './components/AboutPage.vue') }, { path: '/help', component: async () => await import(/* webpackChunkName: "HelpPage" */ './components/HelpPage.vue') } ] }) export default router;
import Vue from 'vue'; import VueRouter from 'vue-router'; import AboutPage from './components/AboutPage.vue'; import DatasetsPage from './components/DatasetsPage.vue'; Vue.use(VueRouter); const router = new VueRouter({ routes: [ { path: '/', redirect: '/about' }, { path: '/annotations', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "AnnotationsPage" */ './components/AnnotationsPage.vue') }, { path: '/datasets', component: DatasetsPage, children: [ {path: '', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "DatasetTable" */ './components/DatasetTable.vue')}, {path: 'edit/:dataset_id', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "MetadataEditPage" */ './components/MetadataEditPage.vue'), name: 'edit-metadata'}, { path: ':dataset_id/add-optical-image', name: 'add-optical-image', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "ImageAlignmentPage" */ './components/ImageAlignmentPage.vue') } ] }, { path: '/upload', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "UploadPage" */ './components/UploadPage.vue') }, { path: '/about', component: AboutPage }, { path: '/help', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "HelpPage" */ './components/HelpPage.vue') } ] }) export default router;
Include AboutPage in initial bundle Prefetch other chunks
Include AboutPage in initial bundle Prefetch other chunks
TypeScript
apache-2.0
METASPACE2020/sm-webapp,METASPACE2020/sm-webapp,METASPACE2020/sm-webapp,METASPACE2020/sm-webapp
--- +++ @@ -1,31 +1,32 @@ import Vue from 'vue'; import VueRouter from 'vue-router'; +import AboutPage from './components/AboutPage.vue'; import DatasetsPage from './components/DatasetsPage.vue'; Vue.use(VueRouter); const router = new VueRouter({ routes: [ { path: '/', redirect: '/about' }, - { path: '/annotations', component: async () => await import(/* webpackChunkName: "AnnotationsPage" */ './components/AnnotationsPage.vue') }, + { path: '/annotations', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "AnnotationsPage" */ './components/AnnotationsPage.vue') }, { path: '/datasets', component: DatasetsPage, children: [ - {path: '', component: async () => await import(/* webpackChunkName: "DatasetTable" */ './components/DatasetTable.vue')}, - {path: 'edit/:dataset_id', component: async () => await import(/* webpackChunkName: "MetadataEditPage" */ './components/MetadataEditPage.vue'), name: 'edit-metadata'}, + {path: '', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "DatasetTable" */ './components/DatasetTable.vue')}, + {path: 'edit/:dataset_id', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "MetadataEditPage" */ './components/MetadataEditPage.vue'), name: 'edit-metadata'}, { path: ':dataset_id/add-optical-image', name: 'add-optical-image', - component: async () => await import(/* webpackChunkName: "ImageAlignmentPage" */ './components/ImageAlignmentPage.vue') + component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "ImageAlignmentPage" */ './components/ImageAlignmentPage.vue') } ] }, { path: '/upload', - component: async () => await import(/* webpackChunkName: "UploadPage" */ './components/UploadPage.vue') + component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "UploadPage" */ './components/UploadPage.vue') }, - { path: '/about', component: async () => await import(/* webpackChunkName: "AboutPage" */ './components/AboutPage.vue') }, - { path: '/help', component: async () => await import(/* webpackChunkName: "HelpPage" */ './components/HelpPage.vue') } + { path: '/about', component: AboutPage }, + { path: '/help', component: async () => await import(/* webpackPrefetch: true, webpackChunkName: "HelpPage" */ './components/HelpPage.vue') } ] })
536bca01e371e6584585845e6de0075acdebfe8e
after/frame/frame.web.ts
after/frame/frame.web.ts
namespace $ { export class $mol_after_frame extends $mol_object2 { static queue = new Set< ()=> void >() static scheduled = 0 static schedule( task : ()=> void ) { this.queue.add( task ) if( this.scheduled ) return this.scheduled = requestAnimationFrame( ()=> this.run() ) } static run() { this.scheduled = 0 const promise = Promise.resolve() for( const task of this.queue ) { promise.then( task ) } this.queue = new Set } constructor( public task : ()=> void , ) { super() const Frame = this.constructor as typeof $mol_after_frame Frame.schedule( task ) } destructor() { const Frame = this.constructor as typeof $mol_after_frame Frame.queue.delete( this.task ) } } }
namespace $ { export class $mol_after_frame extends $mol_object2 { id : any constructor( public task : ()=> void , ) { super() this.id = requestAnimationFrame( task ) } destructor() { cancelAnimationFrame( this.id ) } } }
Revert "$mol_after_frame: reduce native api usage to improve performance."
Revert "$mol_after_frame: reduce native api usage to improve performance." This reverts commit 7d1a135a1f05300944f2e5c4722f0636f0b39300.
TypeScript
mit
eigenmethod/mol,eigenmethod/mol,eigenmethod/mol
--- +++ @@ -2,46 +2,17 @@ export class $mol_after_frame extends $mol_object2 { - static queue = new Set< ()=> void >() - static scheduled = 0 - - static schedule( task : ()=> void ) { - - this.queue.add( task ) - - if( this.scheduled ) return - this.scheduled = requestAnimationFrame( ()=> this.run() ) - - } - - static run() { - - this.scheduled = 0 - - const promise = Promise.resolve() - - for( const task of this.queue ) { - promise.then( task ) - } - - this.queue = new Set - - } + id : any constructor( public task : ()=> void , ) { - super() - - const Frame = this.constructor as typeof $mol_after_frame - Frame.schedule( task ) - + this.id = requestAnimationFrame( task ) } destructor() { - const Frame = this.constructor as typeof $mol_after_frame - Frame.queue.delete( this.task ) + cancelAnimationFrame( this.id ) } }
e768807e8d457bfa57ea2bef4b13c29fd62dbdca
src/app/pages/reset-password/reset.component.ts
src/app/pages/reset-password/reset.component.ts
import { Component } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Http } from '@angular/http'; import { MdSnackBar } from '@angular/material'; @Component({ selector: 'reset-password', styleUrls: ['./reset-components.css'], templateUrl: './reset.components.html' }) export class ResetPasswordComponent { public currentToken: any; public reset: any = {}; constructor( public route: ActivatedRoute, public http: Http, public snackBar: MdSnackBar, private router: Router ) { this.currentToken = this.route.snapshot.params['token']; } public resetPassword() { this.http.post('/reset/' + this.currentToken, this.reset) .subscribe((data) => { console.log(data); }, (error) => { let response = JSON.parse(error._body); this.openSnackBar(response.message.msg, 'OK'); }); } public openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); } }
import { Component } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ApiHttp } from '../../api-http.service'; import { MdSnackBar } from '@angular/material'; @Component({ selector: 'reset-password', styleUrls: ['./reset-components.css'], templateUrl: './reset.components.html' }) export class ResetPasswordComponent { public currentToken: any; public reset: any = {}; constructor( public route: ActivatedRoute, public http: ApiHttp, public snackBar: MdSnackBar, private router: Router ) { this.currentToken = this.route.snapshot.params['token']; } public resetPassword() { this.http.post('/reset/' + this.currentToken, this.reset) .subscribe((data) => { console.log(data); }, (error) => { let response = JSON.parse(error._body); this.openSnackBar(response.message.msg, 'OK'); }); } public openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); } }
Update reset page to use ApiHttp
Update reset page to use ApiHttp
TypeScript
mit
gcriva/gcriva-frontend,gcriva/gcriva-frontend,gcriva/gcriva-frontend,gcriva/gcriva-frontend
--- +++ @@ -1,6 +1,6 @@ import { Component } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; -import { Http } from '@angular/http'; +import { ApiHttp } from '../../api-http.service'; import { MdSnackBar } from '@angular/material'; @Component({ @@ -14,7 +14,7 @@ public reset: any = {}; constructor( public route: ActivatedRoute, - public http: Http, + public http: ApiHttp, public snackBar: MdSnackBar, private router: Router ) {
ccc479215df693a58585daa9d82e05085c2139df
ui/switch/switch.android.ts
ui/switch/switch.android.ts
import observable = require("ui/core/observable"); import view = require("ui/core/view"); import application = require("application"); export class Switch extends view.View { private static checkedProperty = "checked"; private _android: android.widget.Switch; constructor() { super(); this._android = new android.widget.Switch(application.android.currentContext); } get android(): android.widget.Switch { return this._android; } get checked(): boolean { return this.android.isChecked(); } set checked(value: boolean) { this.setProperty(Switch.checkedProperty, value); } public setNativeProperty(data: observable.PropertyChangeData) { if (data.propertyName === Switch.checkedProperty) { this.android.setChecked(data.value); } else if (true) { // } } }
import observable = require("ui/core/observable"); import view = require("ui/core/view"); import application = require("application"); export class Switch extends view.View { private static checkedProperty = "checked"; private _android: android.widget.Switch; constructor() { super(); this._android = new android.widget.Switch(application.android.currentContext); var that = this; this._android.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener({ onCheckedChanged: function (sender, isChecked) { that.updateTwoWayBinding(Switch.checkedProperty, sender.isChecked()); that.setProperty(Switch.checkedProperty, sender.isChecked()); } })); } get android(): android.widget.Switch { return this._android; } get checked(): boolean { return this.android.isChecked(); } set checked(value: boolean) { this.setProperty(Switch.checkedProperty, value); } public setNativeProperty(data: observable.PropertyChangeData) { if (data.propertyName === Switch.checkedProperty) { this.android.setChecked(data.value); } else if (true) { // } } }
Switch for Android listener added
Switch for Android listener added
TypeScript
mit
NativeScript/NativeScript,hdeshev/NativeScript,genexliu/NativeScript,NativeScript/NativeScript,NativeScript/NativeScript,genexliu/NativeScript,NativeScript/NativeScript,NativeScript/NativeScript,hdeshev/NativeScript,hdeshev/NativeScript,genexliu/NativeScript
--- +++ @@ -9,6 +9,14 @@ constructor() { super(); this._android = new android.widget.Switch(application.android.currentContext); + + var that = this; + this._android.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener({ + onCheckedChanged: function (sender, isChecked) { + that.updateTwoWayBinding(Switch.checkedProperty, sender.isChecked()); + that.setProperty(Switch.checkedProperty, sender.isChecked()); + } + })); } get android(): android.widget.Switch {
ebc761f0d4c0e6262b2960a0d53aae75ceac9665
src/app/app.ts
src/app/app.ts
import {Component, View, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {RouteConfig, ROUTER_PROVIDERS, ROUTER_DIRECTIVES, LocationStrategy, HashLocationStrategy} from 'angular2/router'; import {PersonsView} from './views/persons/personsViewComponent'; import {AboutView} from './views/about/aboutViewComponent'; import {SomethingView} from './views/something/somethingViewComponent'; @Component({ selector: 'my-app' }) @View({ templateUrl: 'app/app.html', directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ {path: '/about', name: 'About', component: AboutView}, {path: '/something', name: 'Something', component: SomethingView}, {path: '/persons', name: 'Persons', component: PersonsView, useAsDefault: true} ]) class AppComponent { } bootstrap( AppComponent, [ ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy}) ]);
import {Component, View, provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {RouteConfig, ROUTER_PROVIDERS, ROUTER_DIRECTIVES, LocationStrategy, HashLocationStrategy} from 'angular2/router'; import {PersonsView} from './views/persons/personsViewComponent'; import {AboutView} from './views/about/aboutViewComponent'; import {SomethingView} from './views/something/somethingViewComponent'; @Component({ selector: 'my-app' }) @View({ templateUrl: 'app/app.html', directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ {path: '/about', name: 'About', component: AboutView}, {path: '/something', name: 'Something', component: SomethingView}, {path: '/persons', name: 'Persons', component: PersonsView, useAsDefault: true} ]) class AppComponent { } // Use this for hash based location strategy (old style when running in live-server mode) bootstrap(AppComponent, [ ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy}) ]); // Use this for HTML5 Push location strategy //bootstrap(AppComponent, [ROUTER_PROVIDERS]);
Duplicate boostrap to be able to toggle easy between HTML5 push and hash based location strategy
Duplicate boostrap to be able to toggle easy between HTML5 push and hash based location strategy
TypeScript
mit
lokanx/courses-angular2-persons,lokanx/courses-angular2-persons,lokanx/courses-angular2-persons
--- +++ @@ -24,9 +24,11 @@ class AppComponent { } -bootstrap( - AppComponent, - [ +// Use this for hash based location strategy (old style when running in live-server mode) +bootstrap(AppComponent, [ ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy}) - ]); +]); + +// Use this for HTML5 Push location strategy +//bootstrap(AppComponent, [ROUTER_PROVIDERS]);
166a449e879bc7d0278ed68f3bf78c58b69f696b
src/System/Tasks/Task.ts
src/System/Tasks/Task.ts
import { CancellationToken, Progress } from "vscode"; import { Extension } from "../Extensibility/Extension"; import { IProgressState } from "./IProgressState"; /** * Represents a task. * * @template TExtension * The type of the extension. */ export abstract class Task<TExtension extends Extension = Extension> { /** * The extension this task belongs to. */ private extension: TExtension; /** * Initializes a new instance of the `Task` class. * * @param extension * The extension this task belongs to. */ public constructor(extension: TExtension) { this.extension = extension; } /** * Gets or sets the extension this task belongs to. */ public get Extension(): TExtension { return this.extension; } /** * Gets the title of the task. */ public abstract get Title(): string; /** * Gets a value indicating whether this task can be canceled. */ public get Cancellable(): boolean { return false; } /** * Executes the task. * * @param progressReporter * A component for reporting progress. * * @param cancellationToken * A component for handling cancellation-requests. */ public abstract async Execute(progressReporter?: Progress<IProgressState>, cancellationToken?: CancellationToken): Promise<void>; }
import { CancellationToken, Progress } from "vscode"; import { Extension } from "../Extensibility/Extension"; import { IProgressState } from "./IProgressState"; /** * Represents a task. * * @template TExtension * The type of the extension. */ export abstract class Task<TExtension extends Extension = Extension> { /** * The extension this task belongs to. */ private extension: TExtension; /** * Initializes a new instance of the `Task` class. * * @param extension * The extension this task belongs to. */ public constructor(extension: TExtension) { this.extension = extension; } /** * Gets or sets the extension this task belongs to. */ public get Extension(): TExtension { return this.extension; } /** * Gets the title of the task. */ public abstract get Title(): string; /** * Gets a value indicating whether this task can be canceled. */ public get Cancellable(): boolean { return true; } /** * Executes the task. * * @param progressReporter * A component for reporting progress. * * @param cancellationToken * A component for handling cancellation-requests. */ public abstract async Execute(progressReporter?: Progress<IProgressState>, cancellationToken?: CancellationToken): Promise<void>; }
Make tasks cancellable by default
Make tasks cancellable by default
TypeScript
mit
manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter
--- +++ @@ -44,7 +44,7 @@ */ public get Cancellable(): boolean { - return false; + return true; } /**
606e3c657d7af50eeb5674f604ee6659ddec9e85
src/renderer/index.ts
src/renderer/index.ts
// This is the entry point for the renderer process. // // Here we disable a few electron settings and mount the root component. import { renderRoot } from "./root-component" import { webFrame } from "electron" /** * CSS reset */ /** * Electron-focused CSS resets */ /** * Zooming resets */ webFrame.setVisualZoomLevelLimits(1, 1) webFrame.setLayoutZoomLevelLimits(0, 0) /** * Drag and drop resets */ document.addEventListener("dragover", (event): void => event.preventDefault()) document.addEventListener("drop", (event): void => event.preventDefault()) // mount the root component renderRoot()
// This is the entry point for the renderer process. // // Here we disable a few electron settings and mount the root component. import { renderRoot } from "./components/root-component" import { webFrame } from "electron" /** * CSS reset */ /** * Electron-focused CSS resets */ /** * Zooming resets */ webFrame.setVisualZoomLevelLimits(1, 1) webFrame.setLayoutZoomLevelLimits(0, 0) /** * Drag and drop resets */ document.addEventListener("dragover", (event): void => event.preventDefault()) document.addEventListener("drop", (event): void => event.preventDefault()) // mount the root component renderRoot()
Fix root component import path
Fix root component import path
TypeScript
agpl-3.0
briandk/transcriptase,briandk/transcriptase
--- +++ @@ -2,7 +2,7 @@ // // Here we disable a few electron settings and mount the root component. -import { renderRoot } from "./root-component" +import { renderRoot } from "./components/root-component" import { webFrame } from "electron" /**
51fa4f736208b01a5d507390aa6cf4080ec2f45d
query-string/query-string.d.ts
query-string/query-string.d.ts
// Type definitions for query-string v3.0.0 // Project: https://github.com/sindresorhus/query-string // Definitions by: Sam Verschueren <https://github.com/SamVerschueren> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "query-string" { type value = string | boolean | number; interface StringifyOptions { strict?: boolean; encode?: boolean; } /** * Parse a query string into an object. * Leading ? or # are ignored, so you can pass location.search or location.hash directly. * @param str */ export function parse(str: string): { [key: string]: string | string[] }; /** * Stringify an object into a query string, sorting the keys. * * @param obj */ export function stringify(obj: { [key: string]: value | value[] }, options?: StringifyOptions): string; /** * Extract a query string from a URL that can be passed into .parse(). * * @param str */ export function extract(str: string): string; }
// Type definitions for query-string v3.0.0 // Project: https://github.com/sindresorhus/query-string // Definitions by: Sam Verschueren <https://github.com/SamVerschueren> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "query-string" { interface StringifyOptions { strict?: boolean; encode?: boolean; } /** * Parse a query string into an object. * Leading ? or # are ignored, so you can pass location.search or location.hash directly. * @param str */ export function parse(str: string): { [key: string]: string | string[] }; /** * Stringify an object into a query string, sorting the keys. * * @param obj */ export function stringify(obj: any, options?: StringifyOptions): string; /** * Extract a query string from a URL that can be passed into .parse(). * * @param str */ export function extract(str: string): string; }
Allow stringifying any type of object
Allow stringifying any type of object Previously was limited only to plain objects
TypeScript
mit
QuatroCode/DefinitelyTyped,benishouga/DefinitelyTyped,isman-usoh/DefinitelyTyped,scriby/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AgentME/DefinitelyTyped,shlomiassaf/DefinitelyTyped,chrootsu/DefinitelyTyped,hellopao/DefinitelyTyped,johan-gorter/DefinitelyTyped,nycdotnet/DefinitelyTyped,magny/DefinitelyTyped,subash-a/DefinitelyTyped,smrq/DefinitelyTyped,martinduparc/DefinitelyTyped,dsebastien/DefinitelyTyped,subash-a/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,aciccarello/DefinitelyTyped,jimthedev/DefinitelyTyped,shlomiassaf/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,amir-arad/DefinitelyTyped,jimthedev/DefinitelyTyped,syuilo/DefinitelyTyped,smrq/DefinitelyTyped,alvarorahul/DefinitelyTyped,mcrawshaw/DefinitelyTyped,HPFOD/DefinitelyTyped,alvarorahul/DefinitelyTyped,mcliment/DefinitelyTyped,benishouga/DefinitelyTyped,markogresak/DefinitelyTyped,mcrawshaw/DefinitelyTyped,jimthedev/DefinitelyTyped,use-strict/DefinitelyTyped,schmuli/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,schmuli/DefinitelyTyped,sledorze/DefinitelyTyped,pocesar/DefinitelyTyped,danfma/DefinitelyTyped,zuzusik/DefinitelyTyped,arusakov/DefinitelyTyped,aciccarello/DefinitelyTyped,hellopao/DefinitelyTyped,nycdotnet/DefinitelyTyped,danfma/DefinitelyTyped,QuatroCode/DefinitelyTyped,georgemarshall/DefinitelyTyped,HPFOD/DefinitelyTyped,pocesar/DefinitelyTyped,progre/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,pocesar/DefinitelyTyped,YousefED/DefinitelyTyped,yuit/DefinitelyTyped,isman-usoh/DefinitelyTyped,arusakov/DefinitelyTyped,alexdresko/DefinitelyTyped,benliddicott/DefinitelyTyped,arusakov/DefinitelyTyped,psnider/DefinitelyTyped,borisyankov/DefinitelyTyped,hellopao/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,sledorze/DefinitelyTyped,minodisk/DefinitelyTyped,use-strict/DefinitelyTyped,dsebastien/DefinitelyTyped,benishouga/DefinitelyTyped,YousefED/DefinitelyTyped,rolandzwaga/DefinitelyTyped,zuzusik/DefinitelyTyped,abbasmhd/DefinitelyTyped,martinduparc/DefinitelyTyped,chrismbarr/DefinitelyTyped,abbasmhd/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,syuilo/DefinitelyTyped,alexdresko/DefinitelyTyped,johan-gorter/DefinitelyTyped,scriby/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,martinduparc/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,micurs/DefinitelyTyped,yuit/DefinitelyTyped,progre/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,chrismbarr/DefinitelyTyped,rolandzwaga/DefinitelyTyped,psnider/DefinitelyTyped,ashwinr/DefinitelyTyped,ashwinr/DefinitelyTyped,schmuli/DefinitelyTyped,psnider/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,chrootsu/DefinitelyTyped,georgemarshall/DefinitelyTyped,minodisk/DefinitelyTyped,one-pieces/DefinitelyTyped
--- +++ @@ -4,8 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "query-string" { - type value = string | boolean | number; - + interface StringifyOptions { strict?: boolean; encode?: boolean; } /** @@ -20,7 +19,7 @@ * * @param obj */ - export function stringify(obj: { [key: string]: value | value[] }, options?: StringifyOptions): string; + export function stringify(obj: any, options?: StringifyOptions): string; /** * Extract a query string from a URL that can be passed into .parse().
cac616fe60d9e7f5f60df75ccfca88e37f1a5d86
src/app/search/search.component.ts
src/app/search/search.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Person, SearchService } from '../shared/index'; import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit, OnDestroy { query: string; searchResults: Array<Person>; sub: Subscription; constructor(private searchService: SearchService, private router: Router, private route: ActivatedRoute) { this.sub = this.route.params.subscribe(params => { if (params['term']) { this.query = decodeURIComponent(params['term']); this.search(); } }); } search(): void { this.searchService.search(this.query).subscribe( data => { this.searchResults = data; }, error => console.log(error) ); } onSelect(person: Person) { this.router.navigate(['/edit', person.id]); } ngOnInit() { } ngOnDestroy() { this.sub.unsubscribe(); } }
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Person, SearchService } from '../shared'; import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit, OnDestroy { query: string; searchResults: Array<Person>; sub: Subscription; constructor(private searchService: SearchService, private router: Router, private route: ActivatedRoute) { this.sub = this.route.params.subscribe(params => { if (params['term']) { this.query = decodeURIComponent(params['term']); this.search(); } }); } search(): void { this.searchService.search(this.query).subscribe( data => { this.searchResults = data; }, error => console.log(error) ); } onSelect(person: Person) { this.router.navigate(['/edit', person.id]); } ngOnInit() { } ngOnDestroy() { this.sub.unsubscribe(); } }
Remove index from shared import
Remove index from shared import
TypeScript
apache-2.0
oktadeveloper/okta-angular-openid-connect-example,oktadeveloper/okta-angular-openid-connect-example,oktadeveloper/okta-angular-openid-connect-example
--- +++ @@ -1,5 +1,5 @@ import { Component, OnInit, OnDestroy } from '@angular/core'; -import { Person, SearchService } from '../shared/index'; +import { Person, SearchService } from '../shared'; import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs';
877e2805d9a40055b9546c652b22bd50d64df66d
src/app/plugins/platform/Docker/plugins/cms/Drupal8/createDrupalDockerfile.ts
src/app/plugins/platform/Docker/plugins/cms/Drupal8/createDrupalDockerfile.ts
import { Dockerfile } from 'dockerfilejs'; export interface CreateDrupalDockerfileOptions { /** * Which PHP tag to use (e.g., `7.4`) */ tag: string; /** * Whether or not to include the Memcached PECL extension. */ memcached: boolean; } function createDrupalDockerfile({ tag, memcached, }: CreateDrupalDockerfileOptions) { const dockerfile = new Dockerfile(); dockerfile.from({ image: 'forumone/drupal8', tag: `${tag}-xdebug`, stage: 'dev', }); if (memcached) { dockerfile.run('f1-ext-install pecl:memcached'); } dockerfile.from({ image: 'forumone/drupal8', tag, }); if (memcached) { dockerfile.run('f1-ext-install pecl:memcached'); } return dockerfile; } export default createDrupalDockerfile;
import { Dockerfile } from 'dockerfilejs'; export interface CreateDrupalDockerfileOptions { /** * Which PHP tag to use (e.g., `7.4`) */ tag: string; /** * Whether or not to include the Memcached PECL extension. */ memcached: boolean; } function createDrupalDockerfile({ tag, memcached, }: CreateDrupalDockerfileOptions) { const dockerfile = new Dockerfile(); dockerfile.from({ image: 'forumone/drupal8', tag: `${tag}-xdebug`, stage: 'dev', }); if (memcached) { dockerfile.run('f1-ext-install pecl:memcached'); } dockerfile.stage().from({ image: 'forumone/drupal8', tag, }); if (memcached) { dockerfile.run('f1-ext-install pecl:memcached'); } return dockerfile; } export default createDrupalDockerfile;
Fix missing .stage() in D8 dockerfiles
Fix missing .stage() in D8 dockerfiles
TypeScript
mit
forumone/generator-web-starter,forumone/generator-web-starter,forumone/generator-web-starter,forumone/generator-web-starter,forumone/generator-web-starter
--- +++ @@ -28,7 +28,7 @@ dockerfile.run('f1-ext-install pecl:memcached'); } - dockerfile.from({ + dockerfile.stage().from({ image: 'forumone/drupal8', tag, });
6c364a9efe036e59f17112aaf2c259e0e42a3fa2
ui/src/shared/reducers/overlayTechnology.ts
ui/src/shared/reducers/overlayTechnology.ts
const initialState = { options: { dismissOnClickOutside: false, dismissOnEscape: false, transitionTime: 300, }, overlayNode: null, } export default function overlayTechnology(state = initialState, action) { switch (action.type) { case 'SHOW_OVERLAY': { const {overlayNode, options} = action.payload return {...state, overlayNode, options} } case 'DISMISS_OVERLAY': { return { ...state, overlayNode: null, options: null, } } } return state }
const initialState = { options: { dismissOnClickOutside: false, dismissOnEscape: false, transitionTime: 300, }, overlayNode: null, } export default function overlayTechnology(state = initialState, action) { switch (action.type) { case 'SHOW_OVERLAY': { const {overlayNode, options} = action.payload return {...state, overlayNode, options} } case 'DISMISS_OVERLAY': { const {options} = initialState return { ...state, overlayNode: null, options, } } } return state }
Set overlay back to initial state when dismissed
Set overlay back to initial state when dismissed
TypeScript
mit
nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,nooproblem/influxdb
--- +++ @@ -16,10 +16,11 @@ } case 'DISMISS_OVERLAY': { + const {options} = initialState return { ...state, overlayNode: null, - options: null, + options, } } }
ec4a5fefe815efeac548b6b466239ab8f82309c3
docs/_shared/Ad.tsx
docs/_shared/Ad.tsx
import * as React from 'react'; import { loadScript } from 'utils/helpers'; import { Grid, createStyles, Theme, withStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ '@global': { '#codefund': { '& .cf-wrapper': { backgroundColor: theme.palette.type === 'dark' ? theme.palette.background.paper + '! important' : 'auto', }, '& .cf-text': { color: theme.palette.text.primary + '! important', }, }, }, }); const Ad: React.FunctionComponent = () => { React.useEffect(() => { const codefundScriptPosition = document.querySelector('#codefund-script-position'); if (codefundScriptPosition) { loadScript('https://codefund.io/properties/137/funder.js', codefundScriptPosition); } }, []); return ( <Grid container> <span id="codefund-script-position" /> <div id="codefund" /> </Grid> ); }; export default withStyles(styles)(Ad);
import * as React from 'react'; import { loadScript } from 'utils/helpers'; import { Grid, createStyles, Theme, withStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ '@global': { '#codefund': { '& .cf-wrapper': { backgroundColor: theme.palette.type === 'dark' ? theme.palette.background.paper + '! important' : 'auto', }, '& .cf-text': { color: theme.palette.text.primary + '! important', }, }, }, }); const Ad: React.FunctionComponent = () => { React.useEffect(() => { const codefundScriptPosition = document.querySelector('#codefund-script-position'); if (codefundScriptPosition) { loadScript('https://codefund.io/properties/197/funder.js', codefundScriptPosition); } }, []); return ( <Grid container> <span id="codefund-script-position" /> <div id="codefund" /> </Grid> ); }; export default withStyles(styles)(Ad);
Fix incorrect id in codefund script
Fix incorrect id in codefund script
TypeScript
mit
mbrookes/material-ui,rscnt/material-ui,mbrookes/material-ui,callemall/material-ui,callemall/material-ui,oliviertassinari/material-ui,mui-org/material-ui,rscnt/material-ui,callemall/material-ui,oliviertassinari/material-ui,oliviertassinari/material-ui,dmtrKovalenko/material-ui-pickers,mbrookes/material-ui,callemall/material-ui,rscnt/material-ui,mui-org/material-ui,dmtrKovalenko/material-ui-pickers,mui-org/material-ui
--- +++ @@ -22,7 +22,7 @@ const codefundScriptPosition = document.querySelector('#codefund-script-position'); if (codefundScriptPosition) { - loadScript('https://codefund.io/properties/137/funder.js', codefundScriptPosition); + loadScript('https://codefund.io/properties/197/funder.js', codefundScriptPosition); } }, []);
ec7a15613f2ccdb7e63d0ffc1d154bfa93395355
types/configstore/configstore-tests.ts
types/configstore/configstore-tests.ts
import Configstore = require('configstore'); const cs = new Configstore('foo'); let value: any; let key: string; let num: number; let object: any; cs.set(key, value); value = cs.get(key); cs.delete(key); object = cs.all; cs.all = object; num = cs.size; key = cs.path;
import Configstore = require('configstore'); const cs = new Configstore('foo'); let value: any; let key: string; let num: number; let object: any; let path: string; cs.set(key, value); value = cs.get(key); cs.delete(key); object = cs.all; cs.all = object; num = cs.size; path = cs.path; const csWithPathOption = new Configstore('foo', null, { configPath: path }); csWithPathOption.set(key, value); value = csWithPathOption.get(key); csWithPathOption.delete(key); key = csWithPathOption.path;
Add test for ConfigStoreOptions.configPath in @types/configstore
Add test for ConfigStoreOptions.configPath in @types/configstore
TypeScript
mit
borisyankov/DefinitelyTyped,magny/DefinitelyTyped,mcliment/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped
--- +++ @@ -5,6 +5,7 @@ let key: string; let num: number; let object: any; +let path: string; cs.set(key, value); value = cs.get(key); @@ -13,4 +14,12 @@ object = cs.all; cs.all = object; num = cs.size; -key = cs.path; +path = cs.path; + +const csWithPathOption = new Configstore('foo', null, { configPath: path }); + +csWithPathOption.set(key, value); +value = csWithPathOption.get(key); +csWithPathOption.delete(key); + +key = csWithPathOption.path;
7a709fde3b852208481c1f4b6b6f0ea22c0856f3
types/koa-session/koa-session-tests.ts
types/koa-session/koa-session-tests.ts
import * as Koa from 'koa'; import * as session from 'koa-session'; const app = new Koa(); app.use(session(app)); app.listen(3000);
import * as Koa from 'koa'; import session = require('koa-session'); const app = new Koa(); app.use(session(app)); app.listen(3000);
Modify the module style of koa-session
Modify the module style of koa-session
TypeScript
mit
amir-arad/DefinitelyTyped,one-pieces/DefinitelyTyped,isman-usoh/DefinitelyTyped,chrootsu/DefinitelyTyped,abbasmhd/DefinitelyTyped,AgentME/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,borisyankov/DefinitelyTyped,chrootsu/DefinitelyTyped,benishouga/DefinitelyTyped,magny/DefinitelyTyped,QuatroCode/DefinitelyTyped,zuzusik/DefinitelyTyped,alexdresko/DefinitelyTyped,dsebastien/DefinitelyTyped,dsebastien/DefinitelyTyped,arusakov/DefinitelyTyped,minodisk/DefinitelyTyped,georgemarshall/DefinitelyTyped,jimthedev/DefinitelyTyped,nycdotnet/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,benishouga/DefinitelyTyped,zuzusik/DefinitelyTyped,jimthedev/DefinitelyTyped,isman-usoh/DefinitelyTyped,borisyankov/DefinitelyTyped,ashwinr/DefinitelyTyped,AgentME/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,nycdotnet/DefinitelyTyped,aciccarello/DefinitelyTyped,benliddicott/DefinitelyTyped,minodisk/DefinitelyTyped,jimthedev/DefinitelyTyped,markogresak/DefinitelyTyped,mcliment/DefinitelyTyped,ashwinr/DefinitelyTyped,abbasmhd/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,QuatroCode/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,arusakov/DefinitelyTyped,aciccarello/DefinitelyTyped,alexdresko/DefinitelyTyped,aciccarello/DefinitelyTyped,rolandzwaga/DefinitelyTyped,rolandzwaga/DefinitelyTyped,benishouga/DefinitelyTyped
--- +++ @@ -1,5 +1,5 @@ import * as Koa from 'koa'; -import * as session from 'koa-session'; +import session = require('koa-session'); const app = new Koa();
84a110f95a45f9ca98f292194f0c631d5006db7e
src/components/composites/Menu/Menu.tsx
src/components/composites/Menu/Menu.tsx
import React from 'react'; import type { IMenuProps } from './props'; import View from '../../primitives/View'; import { usePropsConfig } from '../../../hooks'; import { usePopover } from '../../../core'; export const Menu = ({ trigger, closeOnSelect = true, children, onOpen, onClose, ...props }: IMenuProps) => { let triggerRef = React.useRef(); const newProps = usePropsConfig('Menu', props); let [isOpen, toggle] = React.useState<boolean>(false); const { setPopover, closePopover } = usePopover(); const closeMenu = () => { closePopover(); toggle(false); onClose && onClose(); }; const openMenu = () => { setPopover(<View {...newProps}>{children}</View>, { triggerRef, animationDuration: 200, onClose: closeMenu, parentComponentConfig: { open: isOpen, closeMenu, closeOnSelect }, }); toggle(true); onOpen && onOpen(); }; return trigger( { onPress: openMenu, ref: triggerRef, }, { open: isOpen } ); };
import React from 'react'; import type { IMenuProps } from './props'; import View from '../../primitives/View'; import { usePropsConfig } from '../../../hooks'; import { usePopover } from '../../../core'; export const Menu = ({ trigger, closeOnSelect = true, children, onOpen, onClose, ...props }: IMenuProps) => { let triggerRef = React.useRef(); const newProps = usePropsConfig('Menu', props); let [isOpen, toggle] = React.useState<boolean>(false); const { setPopover, closePopover } = usePopover(); const closeMenu = () => { closePopover(); toggle(false); onClose && onClose(); }; const openMenu = () => { setPopover(<View {...newProps}>{children}</View>, { triggerRef, animationDuration: 200, onClose: closeMenu, parentComponentConfig: { open: isOpen, closeMenu, closeOnSelect }, }); toggle(true); onOpen && onOpen(); }; return ( <View flex={1} ref={triggerRef}> {trigger( { onPress: openMenu, }, { open: isOpen } )} </View> ); };
Revert "Fixes for Modal position"
Revert "Fixes for Modal position" This reverts commit 1546dd84bdba8524c3cac5c8befc92614b5f97f8.
TypeScript
mit
GeekyAnts/NativeBase,GeekyAnts/NativeBase,GeekyAnts/NativeBase,GeekyAnts/NativeBase,GeekyAnts/NativeBase
--- +++ @@ -32,11 +32,15 @@ toggle(true); onOpen && onOpen(); }; - return trigger( - { - onPress: openMenu, - ref: triggerRef, - }, - { open: isOpen } + + return ( + <View flex={1} ref={triggerRef}> + {trigger( + { + onPress: openMenu, + }, + { open: isOpen } + )} + </View> ); };
1585c2a12cc63ba7d2aca3e150857c07fb6d77d5
static/js/alert_popup.ts
static/js/alert_popup.ts
import $ from "jquery"; export function initialize(): void { // this will hide the alerts that you click "x" on. $("body").on("click", ".alert-box > div .exit", function () { const $alert = $(this).closest(".alert-box > div"); $alert.addClass("fade-out"); setTimeout(() => { $alert.removeClass("fade-out show"); }, 300); }); $(".alert-box").on("click", ".stackframe .expand", function () { $(this).parent().siblings(".code-context").toggle("fast"); }); }
import $ from "jquery"; export function initialize(): void { // this will hide the alerts that you click "x" on. $("body").on("click", ".alert-box > div .exit", function () { const $alert = $(this).closest(".alert-box > div"); $alert.addClass("fade-out"); setTimeout(() => { $alert.removeClass("fade-out show"); }, 300); }); $(".alert-box").on("click", ".stackframe", function () { $(this).siblings(".code-context").toggle("fast"); }); }
Enlarge click target for expanding rows.
blueslip_stacktrace: Enlarge click target for expanding rows. Signed-off-by: Anders Kaseorg <[email protected]>
TypeScript
apache-2.0
rht/zulip,hackerkid/zulip,zulip/zulip,andersk/zulip,kou/zulip,hackerkid/zulip,punchagan/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,andersk/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,kou/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,zulip/zulip,zulip/zulip,punchagan/zulip,eeshangarg/zulip,eeshangarg/zulip,punchagan/zulip,hackerkid/zulip,andersk/zulip,punchagan/zulip,eeshangarg/zulip,andersk/zulip,rht/zulip,rht/zulip,eeshangarg/zulip,hackerkid/zulip,rht/zulip,punchagan/zulip,hackerkid/zulip,zulip/zulip,zulip/zulip,punchagan/zulip,andersk/zulip,hackerkid/zulip,rht/zulip,kou/zulip,hackerkid/zulip,rht/zulip,punchagan/zulip,kou/zulip,zulip/zulip,kou/zulip
--- +++ @@ -10,7 +10,7 @@ }, 300); }); - $(".alert-box").on("click", ".stackframe .expand", function () { - $(this).parent().siblings(".code-context").toggle("fast"); + $(".alert-box").on("click", ".stackframe", function () { + $(this).siblings(".code-context").toggle("fast"); }); }
85f362b376cd26551c69e2097b81f70df362efef
api-server/src/controller/BrandController.ts
api-server/src/controller/BrandController.ts
import { JsonController, Get, Post, Patch, Put, Delete, Authorized, Param, QueryParam } from "routing-controllers" import { getConnectionManager, Repository, FindManyOptions, Connection } from 'typeorm'; import { EntityFromParam, EntityFromBody, EntityFromBodyParam } from "typeorm-routing-controllers-extensions" interface Dictionary<T> { [key: string]: T; } @JsonController('/api/brands') export class ShopController { private connection: Connection constructor() { this.connection = getConnectionManager().get() } @Get("/") getAll( @QueryParam("type") type: string) { if (type === 'simpleList') return this.connection .query('SELECT DISTINCT p.brand FROM product p WHERE p.brand IS NOT NULL ORDER BY p.brand ASC') .then(data => data.map((row:any) => row.brand)) } }
import { JsonController, Get, Post, Patch, Put, Delete, Authorized, Param, QueryParam } from "routing-controllers" import { getConnectionManager, Repository, FindManyOptions, Connection } from 'typeorm'; import { EntityFromParam, EntityFromBody, EntityFromBodyParam } from "typeorm-routing-controllers-extensions" interface Dictionary<T> { [key: string]: T; } @JsonController('/api/brands') export class BrandController { private connection: Connection constructor() { this.connection = getConnectionManager().get() } @Get("/") getAll( @QueryParam("type") type: string) { if (type === 'simpleList') return this.connection .query('SELECT DISTINCT p.brand FROM product p WHERE p.brand IS NOT NULL ORDER BY p.brand ASC') .then(data => data.map((row:any) => row.brand)) } }
Fix api brand controller copy-paste error
Fix api brand controller copy-paste error
TypeScript
mit
davidglezz/tfg,davidglezz/tfg,davidglezz/tfg,davidglezz/tfg
--- +++ @@ -5,7 +5,7 @@ interface Dictionary<T> { [key: string]: T; } @JsonController('/api/brands') -export class ShopController { +export class BrandController { private connection: Connection constructor() {
6dce9aff3ad210f17504b2a8afce2bb462365b48
components/menu/SubMenu.tsx
components/menu/SubMenu.tsx
import * as React from 'react'; import * as PropTypes from 'prop-types'; import { SubMenu as RcSubMenu } from 'rc-menu'; import classNames from 'classnames'; interface TitleClickEntity { key: string; domEvent: Event; } export interface SubMenuProps { rootPrefixCls?: string; className?: string; disabled?: boolean; title?: React.ReactNode; style?: React.CSSProperties; onTitleClick?: (clickEntity: TitleClickEntity) => void; } class SubMenu extends React.Component<SubMenuProps, any> { static contextTypes = { antdMenuTheme: PropTypes.string, }; // fix issue:https://github.com/ant-design/ant-design/issues/8666 static isSubMenu = 1; context: any; private subMenu: any; onKeyDown = (e: React.MouseEvent<HTMLElement>) => { this.subMenu.onKeyDown(e); }; saveSubMenu = (subMenu: any) => { this.subMenu = subMenu; }; render() { const { rootPrefixCls, className } = this.props; const theme = this.context.antdMenuTheme; return ( <RcSubMenu {...this.props} ref={this.saveSubMenu} popupClassName={classNames(`${rootPrefixCls}-${theme}`, className)} /> ); } } export default SubMenu;
import * as React from 'react'; import * as PropTypes from 'prop-types'; import { SubMenu as RcSubMenu } from 'rc-menu'; import classNames from 'classnames'; interface TitleEventEntity { key: string; domEvent: Event; } export interface SubMenuProps { rootPrefixCls?: string; className?: string; disabled?: boolean; title?: React.ReactNode; style?: React.CSSProperties; onTitleClick?: (e: TitleEventEntity) => void; onTitleMouseEnter?: (e: TitleEventEntity) => void; onTitleMouseLeave?: (e: TitleEventEntity) => void; } class SubMenu extends React.Component<SubMenuProps, any> { static contextTypes = { antdMenuTheme: PropTypes.string, }; // fix issue:https://github.com/ant-design/ant-design/issues/8666 static isSubMenu = 1; context: any; private subMenu: any; onKeyDown = (e: React.MouseEvent<HTMLElement>) => { this.subMenu.onKeyDown(e); }; saveSubMenu = (subMenu: any) => { this.subMenu = subMenu; }; render() { const { rootPrefixCls, className } = this.props; const theme = this.context.antdMenuTheme; return ( <RcSubMenu {...this.props} ref={this.saveSubMenu} popupClassName={classNames(`${rootPrefixCls}-${theme}`, className)} /> ); } } export default SubMenu;
Add onTitleMouseEnter and onTitleMouseLeave to public interface
Add onTitleMouseEnter and onTitleMouseLeave to public interface
TypeScript
mit
elevensky/ant-design,elevensky/ant-design,icaife/ant-design,ant-design/ant-design,zheeeng/ant-design,ant-design/ant-design,icaife/ant-design,ant-design/ant-design,elevensky/ant-design,icaife/ant-design,elevensky/ant-design,zheeeng/ant-design,ant-design/ant-design,zheeeng/ant-design,zheeeng/ant-design,icaife/ant-design
--- +++ @@ -3,7 +3,7 @@ import { SubMenu as RcSubMenu } from 'rc-menu'; import classNames from 'classnames'; -interface TitleClickEntity { +interface TitleEventEntity { key: string; domEvent: Event; } @@ -14,7 +14,9 @@ disabled?: boolean; title?: React.ReactNode; style?: React.CSSProperties; - onTitleClick?: (clickEntity: TitleClickEntity) => void; + onTitleClick?: (e: TitleEventEntity) => void; + onTitleMouseEnter?: (e: TitleEventEntity) => void; + onTitleMouseLeave?: (e: TitleEventEntity) => void; } class SubMenu extends React.Component<SubMenuProps, any> {
894bac11748775091ba848e772a1a6e6ed1e2a33
src/server/src/healthcheck/healthcheck.controller.ts
src/server/src/healthcheck/healthcheck.controller.ts
import { Controller, Get } from "@nestjs/common"; import { HealthCheck, HealthCheckResult, HealthCheckService, TypeOrmHealthIndicator } from "@nestjs/terminus"; import TopologyLoadedIndicator from "./topology-loaded.indicator"; @Controller("healthcheck") export class HealthcheckController { constructor( private health: HealthCheckService, private readonly db: TypeOrmHealthIndicator, private topoLoaded: TopologyLoadedIndicator ) {} @Get() @HealthCheck() healthCheck(): Promise<HealthCheckResult> { return this.health.check([ async () => this.db.pingCheck("database"), () => this.topoLoaded.isHealthy("topology") ]); } }
import { Controller, Get } from "@nestjs/common"; import { HealthCheck, HealthCheckResult, HealthCheckService, TypeOrmHealthIndicator } from "@nestjs/terminus"; import TopologyLoadedIndicator from "./topology-loaded.indicator"; @Controller("healthcheck") export class HealthcheckController { constructor( private health: HealthCheckService, private readonly db: TypeOrmHealthIndicator, private topoLoaded: TopologyLoadedIndicator ) {} @Get() @HealthCheck() healthCheck(): Promise<HealthCheckResult> { return this.health.check([ async () => this.db.pingCheck("database", { timeout: 3000 }), () => this.topoLoaded.isHealthy("topology") ]); } }
Increase healthcheck DB timeout to 3 seconds
Increase healthcheck DB timeout to 3 seconds This matches the timeout on the load balancer target group
TypeScript
apache-2.0
PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder
--- +++ @@ -20,7 +20,7 @@ @HealthCheck() healthCheck(): Promise<HealthCheckResult> { return this.health.check([ - async () => this.db.pingCheck("database"), + async () => this.db.pingCheck("database", { timeout: 3000 }), () => this.topoLoaded.isHealthy("topology") ]); }
de358f3e7abe8de06e0801469bd824626c125164
src/components/ConfigForm.tsx
src/components/ConfigForm.tsx
import React from "react"; import { inject, observer } from "mobx-react" import { ConfigStore, CONFIG_STORE } from "../stores/ConfigStore" import { JDKProject, Task } from "../stores/model" import JDKProjectForm from "./JDKProjectForm"; import TaskForm from "./TaskForm"; import "../styles/Forms.css"; interface Props { configStore?: ConfigStore } class ConfigForm extends React.PureComponent<Props> { renderForm = () => { const { selectedConfig, selectedGroupId } = this.props.configStore!; switch (selectedGroupId) { case "jdkProjects": return ( <JDKProjectForm project={selectedConfig as JDKProject} /> ); case "tasks": return ( <TaskForm task={selectedConfig as Task} /> ); default: return null; } } render() { return ( <div className="form-container"> <form> {this.renderForm()} </form> </div> ) } } export default inject(CONFIG_STORE)(observer(ConfigForm));
import React from "react"; import { inject, observer } from "mobx-react" import { ConfigStore, CONFIG_STORE } from "../stores/ConfigStore" import { JDKProject, Task } from "../stores/model" import JDKProjectForm from "./JDKProjectForm"; import TaskForm from "./TaskForm"; import "../styles/Forms.css"; interface Props { configStore?: ConfigStore } class ConfigForm extends React.PureComponent<Props> { renderForm = () => { const { selectedConfig, selectedGroupId } = this.props.configStore!; if (!selectedConfig) { return } switch (selectedGroupId) { case "jdkProjects": return ( <JDKProjectForm project={selectedConfig as JDKProject} /> ); case "tasks": return ( <TaskForm task={selectedConfig as Task} /> ); default: return null; } } render() { return ( <div className="form-container"> <form> {this.renderForm()} </form> </div> ) } } export default inject(CONFIG_STORE)(observer(ConfigForm));
Return null if no config is selected
Return null if no config is selected
TypeScript
mit
TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin
--- +++ @@ -16,6 +16,9 @@ renderForm = () => { const { selectedConfig, selectedGroupId } = this.props.configStore!; + if (!selectedConfig) { + return + } switch (selectedGroupId) { case "jdkProjects": return (
688dc438d9674ede6ab737b1d106a4de08bb74d6
app/react/src/server/framework-preset-react-docgen.ts
app/react/src/server/framework-preset-react-docgen.ts
import { TransformOptions } from '@babel/core'; import { Configuration } from 'webpack'; type Docgen = 'react-docgen' | 'react-docgen-typescript'; interface TypescriptOptions { typescriptOptions?: { docgen?: Docgen }; } const DEFAULT_DOCGEN = 'react-docgen-typescript'; export function babel( config: TransformOptions, { typescriptOptions }: TypescriptOptions = { typescriptOptions: {} } ) { const docgen = typescriptOptions?.docgen || DEFAULT_DOCGEN; return { ...config, overrides: [ { test: docgen === 'react-docgen' ? /\.(mjs|tsx?|jsx?)$/ : /\.(mjs|jsx?)$/, plugins: [ [ require.resolve('babel-plugin-react-docgen'), { DOC_GEN_COLLECTION_NAME: 'STORYBOOK_REACT_CLASSES', }, ], ], }, ], }; } export function webpackFinal( config: Configuration, { typescriptOptions }: TypescriptOptions = { typescriptOptions: {} } ) { const docgen = typescriptOptions?.docgen || DEFAULT_DOCGEN; if (docgen !== 'react-docgen-typescript') return config; return { ...config, module: { ...config.module, rules: [ ...config.module.rules, { loader: require.resolve('react-docgen-typescript-loader'), }, ], }, }; }
import { TransformOptions } from '@babel/core'; import { Configuration } from 'webpack'; type Docgen = 'react-docgen' | 'react-docgen-typescript'; interface TypescriptOptions { typescriptOptions?: { docgen?: Docgen }; } const DEFAULT_DOCGEN = 'react-docgen'; export function babel( config: TransformOptions, { typescriptOptions }: TypescriptOptions = { typescriptOptions: {} } ) { const docgen = typescriptOptions?.docgen || DEFAULT_DOCGEN; return { ...config, overrides: [ { test: docgen === 'react-docgen' ? /\.(mjs|tsx?|jsx?)$/ : /\.(mjs|jsx?)$/, plugins: [ [ require.resolve('babel-plugin-react-docgen'), { DOC_GEN_COLLECTION_NAME: 'STORYBOOK_REACT_CLASSES', }, ], ], }, ], }; } export function webpackFinal( config: Configuration, { typescriptOptions }: TypescriptOptions = { typescriptOptions: {} } ) { const docgen = typescriptOptions?.docgen || DEFAULT_DOCGEN; if (docgen !== 'react-docgen-typescript') return config; return { ...config, module: { ...config.module, rules: [ ...config.module.rules, { loader: require.resolve('react-docgen-typescript-loader'), }, ], }, }; }
Switch to react-docgen as the default config
React: Switch to react-docgen as the default config
TypeScript
mit
storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook
--- +++ @@ -5,7 +5,7 @@ interface TypescriptOptions { typescriptOptions?: { docgen?: Docgen }; } -const DEFAULT_DOCGEN = 'react-docgen-typescript'; +const DEFAULT_DOCGEN = 'react-docgen'; export function babel( config: TransformOptions,
f38a254092364b0a9dd7d9455cb05db1b181011c
app/src/lib/git/diff-index.ts
app/src/lib/git/diff-index.ts
import { git } from './core' import { Repository } from '../../models/repository' export async function getChangedPathsInIndex(repository: Repository): Promise<string[]> { const result = await git([ 'diff-index', '--cached', '--name-only', '-z', 'HEAD' ], repository.path, 'getChangedPathsInIndex') return result.stdout.length ? result.stdout.split('\0') : [] }
import { git } from './core' import { Repository } from '../../models/repository' export async function getChangedPathsInIndex(repository: Repository): Promise<string[]> { const args = [ 'diff-index', '--cached', '--name-only', '-z' ] let result = await git([ ...args, 'HEAD' ], repository.path, 'getChangedPathsInIndex', { successExitCodes: new Set([ 0, 128 ]), }) // 128 from diff-index either means that the path isn't a repository or (more // likely) that the repository HEAD is unborn. If HEAD is unborn we'll diff // the index against the null tree instead. if (result.exitCode === 128) { result = await git([ ...args, '4b825dc642cb6eb9a060e54bf8d69288fbee4904' ], repository.path, 'getChangedPathsInIndex') } return result.stdout.length ? result.stdout.split('\0') : [] }
Deal with unborn heads in getChangedPathsInIndex
Deal with unborn heads in getChangedPathsInIndex
TypeScript
mit
say25/desktop,desktop/desktop,shiftkey/desktop,gengjiawen/desktop,shiftkey/desktop,artivilla/desktop,hjobrien/desktop,hjobrien/desktop,kactus-io/kactus,j-f1/forked-desktop,say25/desktop,say25/desktop,gengjiawen/desktop,kactus-io/kactus,gengjiawen/desktop,gengjiawen/desktop,hjobrien/desktop,kactus-io/kactus,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,hjobrien/desktop
--- +++ @@ -2,7 +2,19 @@ import { Repository } from '../../models/repository' export async function getChangedPathsInIndex(repository: Repository): Promise<string[]> { - const result = await git([ 'diff-index', '--cached', '--name-only', '-z', 'HEAD' ], repository.path, 'getChangedPathsInIndex') + + const args = [ 'diff-index', '--cached', '--name-only', '-z' ] + + let result = await git([ ...args, 'HEAD' ], repository.path, 'getChangedPathsInIndex', { + successExitCodes: new Set([ 0, 128 ]), + }) + + // 128 from diff-index either means that the path isn't a repository or (more + // likely) that the repository HEAD is unborn. If HEAD is unborn we'll diff + // the index against the null tree instead. + if (result.exitCode === 128) { + result = await git([ ...args, '4b825dc642cb6eb9a060e54bf8d69288fbee4904' ], repository.path, 'getChangedPathsInIndex') + } return result.stdout.length ? result.stdout.split('\0')
8fa165917d76d839e0cffd537eea70cd239a71f7
gulp.config.ts
gulp.config.ts
/// <reference path="./node_modules/ng1-template-gulp/typings/gulp.config.d.ts"/> 'use strict'; let utils: IUtils = require('ng1-template-gulp').utils; module.exports = function(config: IConfig) { /** * Create all application modules and add them to the config.modules array in increasing order * of their dependencies to one another. * The common module is added by default, so you do not need to add it if it's needed. If it is * not needed, you'll need to remove it first. */ config.modules.push(utils.createModule('security')); config.modules.push(utils.createModule('demo')); // Add your project-specific configurations by adding to or modifying the config object. config.styles.usesLess = true; config.styles.injections.unshift(`${config.folders.bower}bootstrap/dist/css/bootstrap.css`); };
/// <reference path="./node_modules/ng1-template-gulp/typings/gulp.config.d.ts"/> 'use strict'; let utils: IUtils = require('ng1-template-gulp').utils; module.exports = function(config: IConfig) { /** * The following variables represent aspects of the default configuration. * If you are changing any existing values in the default config, update or delete the variables accordingly. */ let commonModule: IModule = config.modules[0]; /** * Create all application modules and add them to the config.modules array in increasing order * of their dependencies to one another. * The common module is added by default, so you do not need to add it if it's needed. If it is * not needed, you'll need to remove it first. */ config.modules.push(utils.createModule('security')); config.modules.push(utils.createModule('demo')); // Add your project-specific configurations by adding to or modifying the config object. };
Add variable for common module.
Add variable for common module.
TypeScript
apache-2.0
angular-template/ng1-template,angular-template/ng1-template,angular-template/ng1-template,angular-template/ng1-template
--- +++ @@ -5,6 +5,12 @@ let utils: IUtils = require('ng1-template-gulp').utils; module.exports = function(config: IConfig) { + /** + * The following variables represent aspects of the default configuration. + * If you are changing any existing values in the default config, update or delete the variables accordingly. + */ + let commonModule: IModule = config.modules[0]; + /** * Create all application modules and add them to the config.modules array in increasing order * of their dependencies to one another. @@ -15,7 +21,4 @@ config.modules.push(utils.createModule('demo')); // Add your project-specific configurations by adding to or modifying the config object. - config.styles.usesLess = true; - - config.styles.injections.unshift(`${config.folders.bower}bootstrap/dist/css/bootstrap.css`); };
741f08acf5bbff04ed9aa5bae5baffa9d967cc7e
src/marketplace/resources/list/ResourceStateField.tsx
src/marketplace/resources/list/ResourceStateField.tsx
import * as React from 'react'; import { StateIndicator } from '@waldur/core/StateIndicator'; import { Resource } from '../types'; export const ResourceStateField = ({ row }: {row: Resource}) => ( <StateIndicator label={row.state} variant={ row.state === 'Erred' ? 'danger' : row.state === 'Terminated' ? 'warning' : 'primary' } active={['Creating', 'Updating', 'Terminating'].includes(row.state)} /> );
import * as React from 'react'; import { StateIndicator } from '@waldur/core/StateIndicator'; import { pick } from '@waldur/core/utils'; import { ResourceState } from '@waldur/resource/state/ResourceState'; import { Resource as ResourceType } from '@waldur/resource/types'; import { Resource } from '../types'; const pickResource = pick(['action', 'action_details', 'runtime_state']); const OPENSTACK_OFFERINGS = ['Packages.Template', 'OpenStackTenant.Instance', 'OpenStackTenant.Volume']; export const ResourceStateField = ({ row }: {row: Resource}) => { if (OPENSTACK_OFFERINGS.includes(row.offering_type)) { const resource = { resource_type: row.offering_type, service_settings_state: 'OK', state: row.backend_metadata.state || 'Erred', ...pickResource(row.backend_metadata), } as ResourceType; return <ResourceState resource={resource}/>; } else { return ( <StateIndicator label={row.state} variant={ row.state === 'Erred' ? 'danger' : row.state === 'Terminated' ? 'warning' : 'primary' } active={['Creating', 'Updating', 'Terminating'].includes(row.state)} /> ); } };
Revert change to state display in marketplace resource list
Revert change to state display in marketplace resource list
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -1,17 +1,36 @@ import * as React from 'react'; import { StateIndicator } from '@waldur/core/StateIndicator'; +import { pick } from '@waldur/core/utils'; +import { ResourceState } from '@waldur/resource/state/ResourceState'; +import { Resource as ResourceType } from '@waldur/resource/types'; import { Resource } from '../types'; -export const ResourceStateField = ({ row }: {row: Resource}) => ( - <StateIndicator - label={row.state} - variant={ - row.state === 'Erred' ? 'danger' : - row.state === 'Terminated' ? 'warning' : - 'primary' - } - active={['Creating', 'Updating', 'Terminating'].includes(row.state)} - /> -); +const pickResource = pick(['action', 'action_details', 'runtime_state']); + +const OPENSTACK_OFFERINGS = ['Packages.Template', 'OpenStackTenant.Instance', 'OpenStackTenant.Volume']; + +export const ResourceStateField = ({ row }: {row: Resource}) => { + if (OPENSTACK_OFFERINGS.includes(row.offering_type)) { + const resource = { + resource_type: row.offering_type, + service_settings_state: 'OK', + state: row.backend_metadata.state || 'Erred', + ...pickResource(row.backend_metadata), + } as ResourceType; + return <ResourceState resource={resource}/>; + } else { + return ( + <StateIndicator + label={row.state} + variant={ + row.state === 'Erred' ? 'danger' : + row.state === 'Terminated' ? 'warning' : + 'primary' + } + active={['Creating', 'Updating', 'Terminating'].includes(row.state)} + /> + ); + } +};
299f66cad0ae62ac6b9ed5fc4f08b5c120704508
pages/_app.tsx
pages/_app.tsx
import { Fragment } from "react" import App, { Container } from "next/app" import Head from "next/head" import "normalize.css/normalize.css" // A custom app to support importing CSS files globally class MyApp extends App { public render(): JSX.Element { const { Component, pageProps } = this.props return ( <Fragment> <Head> <meta name="viewport" content="width=device-width, initial-scale=1" /> </Head> <div> <Component {...pageProps} /> </div> <style jsx>{` div { width: 70vw; } `}</style> <style jsx global>{` body { display: flex; justify-content: center; align-items: center; background: black; color: white; } a { color: #ffcc00; } @media (prefers-color-scheme: light) { body { background: white; color: black; } a { color: #ff9500; } } `}</style> </Fragment> ) } } export default MyApp
import { Fragment } from "react" import App, { Container } from "next/app" import Head from "next/head" import "normalize.css/normalize.css" // A custom app to support importing CSS files globally class MyApp extends App { public render(): JSX.Element { const { Component, pageProps } = this.props return ( <Fragment> <Head> <meta name="viewport" content="width=device-width, initial-scale=1" /> </Head> <div> <Component {...pageProps} /> </div> <style jsx>{` div { width: 70vw; } `}</style> <style jsx global>{` body { display: flex; justify-content: center; align-items: center; background: black; color: white; } a { color: #ffcc00; } @media (prefers-color-scheme: light) { body { background: white; color: black; } a { color: #007aff; } } `}</style> </Fragment> ) } } export default MyApp
Change link coloraturas to blue for light scheme
Change link coloraturas to blue for light scheme
TypeScript
mit
JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk
--- +++ @@ -44,7 +44,7 @@ } a { - color: #ff9500; + color: #007aff; } } `}</style>
41899cb7fdfc9e87fa4d2773f106f84c2c3dceb2
src/lib/angry-log.service.ts
src/lib/angry-log.service.ts
import { isDevMode, Injectable } from "@angular/core"; import { Http, Response } from "@angular/http"; import { Observable } from "rxjs/Observable"; import "rxjs/add/operator/catch"; import "rxjs/add/operator/map"; import { ErrorObservable } from "rxjs/observable/ErrorObservable"; @Injectable() export class AngryLogService { public assert: Function; public clear: Function; public condition: boolean; public count: Function; public debug: Function; public dir: Function; public dirxml: Function; public error: Function; public exception: Function; public group: Function; public groupCollapsed: Function; public groupEnd: Function; public info: Function; public log: Function; public msIsIndependentlyComposed: Function; public profile: Function; public profileEnd: Function; public select: Function; public table: Function; public time: Function; public timeEnd: Function; public trace: Function; public warn: Function; public URL: string; private http: Http; constructor(http: Http) { this.condition = isDevMode(); this.http = http; this.wrapConsole(); } private wrapConsole(): void { for (let key of Object.keys(window.console)) { this[key] = this.resolveFunc(key); } } private resolveFunc(attrName: string): Function { let attr: Function = window.console[attrName]; let isFunction: boolean = typeof attr === "function"; if (attr && this.condition) { if (isFunction) { return attr.bind(window.console); } return attr; } if (this.URL && attrName === "error") { return this.remoteLog; } return (): void => {}; } private remoteLog(message: string): Observable<Response> { return this.http.post(this.URL, { message }) .map((response: Response): Response => response.json()) .catch((response: Response): ErrorObservable<Response> => Observable.throw(response.json())); } }
import { Injectable } from "@angular/core"; import { Http } from "@angular/http"; import { LoggerOptions } from "./angry-log.types"; import { AngryLogger } from "./angry-log.logger"; @Injectable() export class AngryLogService extends AngryLogger { constructor(http: Http) { super(http); } public instantiateLogger(options?: LoggerOptions): AngryLogger { let logger: AngryLogger = new AngryLogger(this.http); if (!options) { return logger; } for (let key of Object.keys(options)) { logger[key] = options[key]; } return logger; } }
Extend Logger and add instantiation of loggers
Extend Logger and add instantiation of loggers
TypeScript
mit
gbrlsnchs/angry-log
--- +++ @@ -1,72 +1,25 @@ -import { isDevMode, Injectable } from "@angular/core"; -import { Http, Response } from "@angular/http"; -import { Observable } from "rxjs/Observable"; -import "rxjs/add/operator/catch"; -import "rxjs/add/operator/map"; -import { ErrorObservable } from "rxjs/observable/ErrorObservable"; +import { Injectable } from "@angular/core"; +import { Http } from "@angular/http"; +import { LoggerOptions } from "./angry-log.types"; +import { AngryLogger } from "./angry-log.logger"; @Injectable() -export class AngryLogService { - public assert: Function; - public clear: Function; - public condition: boolean; - public count: Function; - public debug: Function; - public dir: Function; - public dirxml: Function; - public error: Function; - public exception: Function; - public group: Function; - public groupCollapsed: Function; - public groupEnd: Function; - public info: Function; - public log: Function; - public msIsIndependentlyComposed: Function; - public profile: Function; - public profileEnd: Function; - public select: Function; - public table: Function; - public time: Function; - public timeEnd: Function; - public trace: Function; - public warn: Function; - public URL: string; - private http: Http; - +export class AngryLogService extends AngryLogger { constructor(http: Http) { - this.condition = isDevMode(); - this.http = http; - this.wrapConsole(); + super(http); } - private wrapConsole(): void { - for (let key of Object.keys(window.console)) { - this[key] = this.resolveFunc(key); - } - } + public instantiateLogger(options?: LoggerOptions): AngryLogger { + let logger: AngryLogger = new AngryLogger(this.http); - private resolveFunc(attrName: string): Function { - let attr: Function = window.console[attrName]; - let isFunction: boolean = typeof attr === "function"; - - if (attr && this.condition) { - if (isFunction) { - return attr.bind(window.console); - } - - return attr; + if (!options) { + return logger; } - if (this.URL && attrName === "error") { - return this.remoteLog; + for (let key of Object.keys(options)) { + logger[key] = options[key]; } - return (): void => {}; - } - - private remoteLog(message: string): Observable<Response> { - return this.http.post(this.URL, { message }) - .map((response: Response): Response => response.json()) - .catch((response: Response): ErrorObservable<Response> => Observable.throw(response.json())); + return logger; } }
5fc4845d74682fe70de39c31f758f4f827bfc34b
src/service/infra/Scraper.ts
src/service/infra/Scraper.ts
import { BookmarkAttrs } from '../../store' const FORM = '.bookmark-detail-unit form:not(.remove-bookmark-form)' export class Scraper { scrapeBookmarkPage(doc: Document): BookmarkAttrs { const res = {} as any const arr = jQuery(FORM, doc).serializeArray() for (const { name, value } of arr) { if (name === 'comment') { res.comment = value } else if (name === 'tag') { res.tags = value } else if (name === 'restrict') { res.restrict = Number(value) } } return res } }
import { BookmarkAttrs } from '../../store' const FORM = '.bookmark-detail-unit form:not(.remove-bookmark-form) input' export class Scraper { scrapeBookmarkPage(doc: Document): BookmarkAttrs { const res = {} as any const elements: NodeListOf<HTMLInputElement> = doc.querySelectorAll(FORM); const arr = Array.from(elements); for (const { name, value } of arr) { if (name === 'comment') { res.comment = value } else if (name === 'tag') { res.tags = value } else if (name === 'restrict') { res.restrict = Number(value) } } return res } }
Fix bookmark page load error
Fix bookmark page load error
TypeScript
mit
8th713/cockpit-for-pixiv,8th713/cockpit-for-pixiv
--- +++ @@ -1,11 +1,12 @@ import { BookmarkAttrs } from '../../store' -const FORM = '.bookmark-detail-unit form:not(.remove-bookmark-form)' +const FORM = '.bookmark-detail-unit form:not(.remove-bookmark-form) input' export class Scraper { scrapeBookmarkPage(doc: Document): BookmarkAttrs { const res = {} as any - const arr = jQuery(FORM, doc).serializeArray() + const elements: NodeListOf<HTMLInputElement> = doc.querySelectorAll(FORM); + const arr = Array.from(elements); for (const { name, value } of arr) { if (name === 'comment') {
becf5cd6594df53ee89aa2ba10475b8e1d5aa20c
src/shared/utils/promises.ts
src/shared/utils/promises.ts
export const resolvedPromise = Promise.resolve(true); export async function waitFor<T>(action: () => T | Promise<T>, checkEveryMilliseconds: number = 500, tryForMilliseconds: number = 10000, token?: { isCancellationRequested: boolean }): Promise<T | undefined> { let timeRemaining = tryForMilliseconds; while (timeRemaining > 0 && !(token && token.isCancellationRequested)) { const res = await action(); if (res) return res; await new Promise((resolve) => setTimeout(resolve, checkEveryMilliseconds)); timeRemaining -= checkEveryMilliseconds; } }
export const resolvedPromise = Promise.resolve(true); export async function waitFor<T>(action: () => T | Promise<T>, checkEveryMilliseconds: number = 100, tryForMilliseconds: number = 10000, token?: { isCancellationRequested: boolean }): Promise<T | undefined> { let timeRemaining = tryForMilliseconds; while (timeRemaining > 0 && !(token && token.isCancellationRequested)) { const res = await action(); if (res) return res; await new Promise((resolve) => setTimeout(resolve, checkEveryMilliseconds)); timeRemaining -= checkEveryMilliseconds; } }
Reduce default checkEveryMilliseconds to speed up tests a little
Reduce default checkEveryMilliseconds to speed up tests a little
TypeScript
mit
Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code
--- +++ @@ -1,6 +1,6 @@ export const resolvedPromise = Promise.resolve(true); -export async function waitFor<T>(action: () => T | Promise<T>, checkEveryMilliseconds: number = 500, tryForMilliseconds: number = 10000, token?: { isCancellationRequested: boolean }): Promise<T | undefined> { +export async function waitFor<T>(action: () => T | Promise<T>, checkEveryMilliseconds: number = 100, tryForMilliseconds: number = 10000, token?: { isCancellationRequested: boolean }): Promise<T | undefined> { let timeRemaining = tryForMilliseconds; while (timeRemaining > 0 && !(token && token.isCancellationRequested)) { const res = await action();
c2b64708ddbdde889b38dc29ad8f599117d64dec
src/states/boot.state.ts
src/states/boot.state.ts
import { LoadState } from './load.state' export class BootState extends Phaser.State { static KEY: string = 'boot_state' create(): void { this.game.stage.backgroundColor = 'd6f3f6' this.game.scale.pageAlignHorizontally = true this.game.scale.pageAlignVertically = true this.game.physics.startSystem(Phaser.Physics.ARCADE) this.game.state.start(LoadState.KEY) } }
import { LoadState } from './load.state' export class BootState extends Phaser.State { static KEY: string = 'boot_state' create(): void { this.game.stage.backgroundColor = 'd6f3f6' this.game.scale.pageAlignHorizontally = true this.game.scale.pageAlignVertically = true this.game.renderer.renderSession.roundPixels = true this.game.physics.startSystem(Phaser.Physics.ARCADE) this.game.state.start(LoadState.KEY) } }
Set round pixels to true.
Set round pixels to true.
TypeScript
mit
dmk2014/phaser-template,dmk2014/phaser-template,dmk2014/phaser-template
--- +++ @@ -7,8 +7,11 @@ create(): void { this.game.stage.backgroundColor = 'd6f3f6' + this.game.scale.pageAlignHorizontally = true this.game.scale.pageAlignVertically = true + + this.game.renderer.renderSession.roundPixels = true this.game.physics.startSystem(Phaser.Physics.ARCADE)
ff113ba3c010b831ef791628ec8b2c0544e3cb9b
src/utils/hitDatabase.ts
src/utils/hitDatabase.ts
import { HitDatabaseEntry } from '../types'; export const conflictsPreserveBonus = ( oldEntry: HitDatabaseEntry, newEntry: HitDatabaseEntry ): HitDatabaseEntry => { return { ...newEntry, bonus: oldEntry.bonus }; }; export const keepPaidOrApproved = (el: HitDatabaseEntry) => el.status === 'Paid' || el.status === 'Pending Payment'; export const keepPending = (el: HitDatabaseEntry) => el.status === 'Pending';
import { HitDatabaseEntry } from '../types'; export const conflictsPreserveBonus = ( oldEntry: HitDatabaseEntry, newEntry: HitDatabaseEntry ): HitDatabaseEntry => { return { ...newEntry, bonus: oldEntry.bonus }; }; export const keepPaidOrApproved = (el: HitDatabaseEntry) => el.status === 'Paid' || el.status === 'Pending Payment'; export const keepPending = (el: HitDatabaseEntry) => el.status === 'Pending'; export const calculateAcceptanceRate = ( total: number, rejected: number ): number => { return (total - rejected) / total * 100; };
Add utility function to calculate acceptance rate.
Add utility function to calculate acceptance rate.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -14,3 +14,10 @@ el.status === 'Paid' || el.status === 'Pending Payment'; export const keepPending = (el: HitDatabaseEntry) => el.status === 'Pending'; + +export const calculateAcceptanceRate = ( + total: number, + rejected: number +): number => { + return (total - rejected) / total * 100; +};
dd7b0e5357640756ee39b2acbc356e3cec2063e5
packages/components/containers/payments/AmountButton.tsx
packages/components/containers/payments/AmountButton.tsx
import { Currency } from '@proton/shared/lib/interfaces'; import { Button, ButtonProps, Price } from '../../components'; import { classnames } from '../../helpers'; interface Props extends Omit<ButtonProps, 'onSelect' | 'onClick'> { value?: number; amount?: number; currency?: Currency; onSelect: (value: number) => void; } const AmountButton = ({ value = 0, amount = 0, currency, onSelect, className = '', ...rest }: Props) => { return ( <Button aria-pressed={value === amount} className={classnames([className, value === amount && 'is-active'])} onClick={() => onSelect(value)} {...rest} > <Price currency={currency}>{value}</Price> </Button> ); }; export default AmountButton;
import { Currency } from '@proton/shared/lib/interfaces'; import { Button, ButtonProps, Price } from '../../components'; import { classnames } from '../../helpers'; interface Props extends Omit<ButtonProps, 'onSelect' | 'onClick'> { value?: number; amount?: number; currency?: Currency; onSelect: (value: number) => void; } const AmountButton = ({ value = 0, amount = 0, currency, onSelect, className = '', ...rest }: Props) => { return ( <Button aria-pressed={value === amount} className={classnames(['field', className, value === amount && 'is-active'])} onClick={() => onSelect(value)} {...rest} > <Price currency={currency}>{value}</Price> </Button> ); }; export default AmountButton;
Fix add credit focus style
Fix add credit focus style Some people did not understand these were buttons and not fields, especially because of missing focus styles - just added `field` class on them :) UXE-126
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -14,7 +14,7 @@ return ( <Button aria-pressed={value === amount} - className={classnames([className, value === amount && 'is-active'])} + className={classnames(['field', className, value === amount && 'is-active'])} onClick={() => onSelect(value)} {...rest} >
499b333a32473863a6d54b6427254e13e4a344b6
src/vl.ts
src/vl.ts
import {Encoding} from './Encoding'; import * as util from './util'; import * as consts from './consts'; import * as data from './data'; import * as enc from './enc'; import * as encDef from './encDef'; import * as compiler from './compiler/compiler'; import * as schema from './schema/schema'; import {format} from 'd3-format'; var vl:any = {}; util.extend(vl, consts, util); vl.Encoding = Encoding; vl.compiler = compiler; vl.compile = vl.compiler.compile; vl.data = data; vl.enc = enc; vl.encDef = encDef; vl.schema = schema; vl.toShorthand = vl.Encoding.shorthand; vl.format = format; vl.version = '__VERSION__'; declare var module; module.exports = vl;
import {Encoding} from './Encoding'; import * as util from './util'; import * as consts from './consts'; import * as data from './data'; import * as enc from './enc'; import * as encDef from './encdef'; import * as compiler from './compiler/compiler'; import * as schema from './schema/schema'; import {format} from 'd3-format'; var vl:any = {}; util.extend(vl, consts, util); vl.Encoding = Encoding; vl.compiler = compiler; vl.compile = vl.compiler.compile; vl.data = data; vl.enc = enc; vl.encDef = encDef; vl.schema = schema; vl.toShorthand = vl.Encoding.shorthand; vl.format = format; vl.version = '__VERSION__'; declare var module; module.exports = vl;
Fix spelling in module name
Fix spelling in module name
TypeScript
bsd-3-clause
uwdata/vega-lite,uwdata/vega-lite,vega/vega-lite,uwdata/vega-lite,vega/vega-lite,uwdata/vega-lite,vega/vega-lite,vega/vega-lite,vega/vega-lite,uwdata/vega-lite
--- +++ @@ -4,7 +4,7 @@ import * as consts from './consts'; import * as data from './data'; import * as enc from './enc'; -import * as encDef from './encDef'; +import * as encDef from './encdef'; import * as compiler from './compiler/compiler'; import * as schema from './schema/schema';
ce6b328932073433713ec142511f7c1967623805
src/utils/validation.ts
src/utils/validation.ts
export const validateInbounds = (value: string) => { const num = parseFloat(value); return num >= 0 && num <= 100; }; export const validateInteger = (value: string): boolean => /^\d+$/.test(value); export const validateNumber = (value: string): boolean => !Number.isNaN(parseFloat(value)) && isFinite(parseFloat(value)); export const validatePositiveNumber = (value: string): boolean => validateNumber(value) && parseFloat(value) >= 0; export const validateRejectionThreshold = (value: string) => (validateInbounds(value) && validateInteger(value)) || value === ''; export const validatePersistedStateKey = (key: string) => key.startsWith('reduxPersist:') && !!/reduxPersist:(.*)/g.exec(key); export const selectReduxPersistStateKey = (key: string) => (/reduxPersist:(.*)/g.exec(key) as RegExpExecArray)[1];
export const validateInbounds = (value: string) => { const num = parseFloat(value); return num >= 0 && num <= 100; }; export const validateInteger = (value: string): boolean => /^\d+$/.test(value); export const validateNumber = (value: string): boolean => !Number.isNaN(parseFloat(value)) && Number.isFinite(parseFloat(value)); export const validatePositiveNumber = (value: string): boolean => validateNumber(value) && parseFloat(value) >= 0; export const validateRejectionThreshold = (value: string) => (validateInbounds(value) && validateInteger(value)) || value === ''; export const validatePersistedStateKey = (key: string) => key.startsWith('reduxPersist:') && !!/reduxPersist:(.*)/g.exec(key); export const selectReduxPersistStateKey = (key: string) => (/reduxPersist:(.*)/g.exec(key) as RegExpExecArray)[1];
Use Number.isFinite rather than window.isFinite.
Use Number.isFinite rather than window.isFinite.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -6,7 +6,7 @@ export const validateInteger = (value: string): boolean => /^\d+$/.test(value); export const validateNumber = (value: string): boolean => - !Number.isNaN(parseFloat(value)) && isFinite(parseFloat(value)); + !Number.isNaN(parseFloat(value)) && Number.isFinite(parseFloat(value)); export const validatePositiveNumber = (value: string): boolean => validateNumber(value) && parseFloat(value) >= 0;
a4d7ade79104c7d8b0c476955f8ac99058453c25
server/src/lib/notifiers/SmtpNotifier.ts
server/src/lib/notifiers/SmtpNotifier.ts
import * as BluebirdPromise from "bluebird"; import Nodemailer = require("nodemailer"); import { AbstractEmailNotifier } from "../notifiers/AbstractEmailNotifier"; import { SmtpNotifierConfiguration } from "../configuration/Configuration"; export class SmtpNotifier extends AbstractEmailNotifier { private transporter: any; constructor(options: SmtpNotifierConfiguration, nodemailer: typeof Nodemailer) { super(); const smtpOptions = { host: options.host, port: options.port, secure: options.secure, // upgrade later with STARTTLS auth: { user: options.username, pass: options.password } }; console.log(smtpOptions); const transporter = nodemailer.createTransport(smtpOptions); this.transporter = BluebirdPromise.promisifyAll(transporter); // verify connection configuration console.log("Checking SMTP server connection."); transporter.verify(function (error, success) { if (error) { throw new Error("Unable to connect to SMTP server. \ Please check the service is running and your credentials are correct."); } else { console.log("SMTP Server is ready to take our messages"); } }); } sendEmail(email: string, subject: string, content: string) { const mailOptions = { from: "[email protected]", to: email, subject: subject, html: content }; return this.transporter.sendMail(mailOptions, (error: Error, data: string) => { if (error) { return console.log(error); } console.log("Message sent: %s", JSON.stringify(data)); }); } }
import * as BluebirdPromise from "bluebird"; import Nodemailer = require("nodemailer"); import { AbstractEmailNotifier } from "../notifiers/AbstractEmailNotifier"; import { SmtpNotifierConfiguration } from "../configuration/Configuration"; export class SmtpNotifier extends AbstractEmailNotifier { private transporter: any; constructor(options: SmtpNotifierConfiguration, nodemailer: typeof Nodemailer) { super(); const smtpOptions = { host: options.host, port: options.port, secure: options.secure, // upgrade later with STARTTLS auth: { user: options.username, pass: options.password } }; const transporter = nodemailer.createTransport(smtpOptions); this.transporter = BluebirdPromise.promisifyAll(transporter); // verify connection configuration transporter.verify(function (error, success) { if (error) { throw new Error("Unable to connect to SMTP server. \ Please check the service is running and your credentials are correct."); } else { console.log("SMTP Server is ready to take our messages"); } }); } sendEmail(email: string, subject: string, content: string) { const mailOptions = { from: "[email protected]", to: email, subject: subject, html: content }; return this.transporter.sendMail(mailOptions, (error: Error, data: string) => { if (error) { return console.log(error); } console.log("Message sent: %s", JSON.stringify(data)); }); } }
Remove useless logs displaying smtp credentials
Remove useless logs displaying smtp credentials
TypeScript
mit
clems4ever/two-factor-auth-server,clems4ever/authelia,clems4ever/two-factor-auth-server,clems4ever/authelia,clems4ever/authelia,clems4ever/authelia,clems4ever/authelia
--- +++ @@ -20,12 +20,10 @@ pass: options.password } }; - console.log(smtpOptions); const transporter = nodemailer.createTransport(smtpOptions); this.transporter = BluebirdPromise.promisifyAll(transporter); // verify connection configuration - console.log("Checking SMTP server connection."); transporter.verify(function (error, success) { if (error) { throw new Error("Unable to connect to SMTP server. \
45c680b7772de61e7a735b2f8dcba202ca94824c
www/src/app/components/index.ts
www/src/app/components/index.ts
export * from './null/null.component'; export * from './home/home.component'; export * from './login/login.component'; export * from './logout/logout.component'; export * from './setup/setup.component'; export * from './topbar/topbar.component'; export * from './category-bar/category-bar.component';
export * from './null/null.component'; export * from './topbar/topbar.component'; export * from './category-bar/category-bar.component'; export * from './home/home.component'; export * from './login/login.component'; export * from './logout/logout.component'; export * from './setup/setup.component';
Move topbar and category bar up
Move topbar and category bar up
TypeScript
mit
petrstehlik/pyngShop,petrstehlik/pyngShop,petrstehlik/pyngShop,petrstehlik/pyngShop
--- +++ @@ -1,7 +1,7 @@ export * from './null/null.component'; +export * from './topbar/topbar.component'; +export * from './category-bar/category-bar.component'; export * from './home/home.component'; export * from './login/login.component'; export * from './logout/logout.component'; export * from './setup/setup.component'; -export * from './topbar/topbar.component'; -export * from './category-bar/category-bar.component';
f829e40e5b166862b7b028da54fd01a0e6f63148
src/lru-cache/lru-cache.ts
src/lru-cache/lru-cache.ts
import { DoublyLinkedList, DoublyLinkedNode, Pair } from '..'; export class LruCache<T, U> { private cache: Map<T, Pair<U, DoublyLinkedNode<T>>> = new Map<T, Pair<U, DoublyLinkedNode<T>>>(); private lru: DoublyLinkedList<T> = new DoublyLinkedList<T>(); constructor( public capacity: number ) { ; } public get(key: T): U { const cached = this.cache.get(key); if (cached) { this.use(cached); return cached.first; } } public set(key: T, value: U): void { const cached = this.cache.get(key); if (cached) { cached.first = value; this.use(cached); } else { if (this.cache.size === this.capacity) { const evictKey = this.lru.popBack(); this.cache.delete(evictKey); } this.lru.pushFront(key); this.cache.set(key, new Pair<U, DoublyLinkedNode<T>>(value, this.lru.front)); } } public isEmpty(): boolean { return this.cache.size === 0; } private use(cached: Pair<U, DoublyLinkedNode<T>>): void { const key = cached.second.data; this.lru.deleteNode(cached.second); this.lru.pushFront(key); cached.second = this.lru.front; } }
import { DoublyLinkedList, DoublyLinkedNode, Pair } from '..'; export class LruCache<T, U> { private cache: Map<T, Pair<U, DoublyLinkedNode<T>>> = new Map<T, Pair<U, DoublyLinkedNode<T>>>(); private lru: DoublyLinkedList<T> = new DoublyLinkedList<T>(); constructor( public capacity: number ) { ; } public get(key: T): U { const cached = this.cache.get(key); if (cached) { this.use(cached); return cached.first; } } public set(key: T, value: U): void { const cached = this.cache.get(key); if (cached) { cached.first = value; this.use(cached); } else { if (this.cache.size === this.capacity) { const evictKey = this.lru.popBack(); this.cache.delete(evictKey); } this.lru.pushFront(key); this.cache.set(key, new Pair<U, DoublyLinkedNode<T>>(value, this.lru.front)); } } public get size(): number { return this.cache.size; } public isEmpty(): boolean { return this.size === 0; } private use(cached: Pair<U, DoublyLinkedNode<T>>): void { const key = cached.second.data; this.lru.deleteNode(cached.second); this.lru.pushFront(key); cached.second = this.lru.front; } }
Implement LruCache size property as a getter
Implement LruCache size property as a getter
TypeScript
mit
worsnupd/ts-data-structures
--- +++ @@ -34,8 +34,12 @@ } } + public get size(): number { + return this.cache.size; + } + public isEmpty(): boolean { - return this.cache.size === 0; + return this.size === 0; } private use(cached: Pair<U, DoublyLinkedNode<T>>): void {
b9bd4f933f3820f4fe954b34fc9cc9a5712b7cd6
frontend/src/main/js/config.tsx
frontend/src/main/js/config.tsx
import axios from 'axios'; export namespace Config { interface BackendConfig { scoreToWinSet: number; setsToWinMatch: number; } export let pointsPerMatch: number; export let pointsPerSet: number; export const teamMode = false; // const BACKEND_URL = 'http://localhost:8080'; export const timedMatchMode = true; export const timePerSet = 5; export function initConfig(): Promise<void> { return axios.get('/view/configuration') .then(res => res.data) .then((config: BackendConfig) => { pointsPerSet = config.scoreToWinSet; pointsPerMatch = config.setsToWinMatch; return; }); } }
import axios from 'axios'; export namespace Config { interface BackendConfig { scoreToWinSet: number; setsToWinMatch: number; } export let pointsPerMatch: number; export let pointsPerSet: number; export const teamMode = false; // const BACKEND_URL = 'http://localhost:8080'; export const timedMatchMode = false; export const timePerSet = 5; export function initConfig(): Promise<void> { return axios.get('/view/configuration') .then(res => res.data) .then((config: BackendConfig) => { pointsPerSet = config.scoreToWinSet; pointsPerMatch = config.setsToWinMatch; return; }); } }
Disable timed match mode for merge
Disable timed match mode for merge
TypeScript
bsd-3-clause
holisticon/ranked,holisticon/ranked,holisticon/ranked,holisticon/ranked,holisticon/ranked
--- +++ @@ -11,7 +11,7 @@ export const teamMode = false; // const BACKEND_URL = 'http://localhost:8080'; - export const timedMatchMode = true; + export const timedMatchMode = false; export const timePerSet = 5; export function initConfig(): Promise<void> {
77223cb9cc13961c2762bec24a348c72e63a6217
source/init/constants.ts
source/init/constants.ts
import {setVersionInfo, setAppName, setTimezone} from '@frogpond/constants' export const SENTRY_DSN = 'https://[email protected]/2' import {version, name} from '../../package.json' setVersionInfo(version) setAppName(name) setTimezone('America/Chicago')
import {setVersionInfo, setAppName, setTimezone} from '@frogpond/constants' export const SENTRY_DSN = 'https://[email protected]/5637838' import {version, name} from '../../package.json' setVersionInfo(version) setAppName(name) setTimezone('America/Chicago')
Switch DSN over to hosted sentry url
sentry: Switch DSN over to hosted sentry url Signed-off-by: Kristofer Rye <[email protected]>
TypeScript
agpl-3.0
StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native
--- +++ @@ -1,7 +1,7 @@ import {setVersionInfo, setAppName, setTimezone} from '@frogpond/constants' export const SENTRY_DSN = - 'https://[email protected]/2' + 'https://[email protected]/5637838' import {version, name} from '../../package.json'
3f4ed7631686f2a3805be41b6fd9a3878164dd21
source/material/wmsmaterial.ts
source/material/wmsmaterial.ts
export class WmsMaterial extends THREE.MeshPhongMaterial { constructor(public options: any) { super({ map: getLoader(), transparent: true, opacity: options.opacity ? options.opacity : 1, side: THREE.DoubleSide }); function getLoader() { let loader = new THREE.TextureLoader(); loader.crossOrigin = ""; let url = options.template .replace("${width}", options.width ? options.width : 512) .replace("${height}", options.height ? options.height : 512) .replace("${bbox}", options.bbox.join(",")); return loader.load(url); } } }
export class WmsMaterial extends THREE.MeshPhongMaterial { constructor(public options: {width: number, height: number, template: string, bbox: number[], opacity: number}) { super({ map: getLoader(), transparent: true, opacity: options.opacity ? options.opacity : 1, side: THREE.DoubleSide }); function getLoader() { let loader = new THREE.TextureLoader(); loader.crossOrigin = ""; let url = options.template .replace("${width}", options.width ? options.width : 512) .replace("${height}", options.height ? options.height : 512) .replace("${bbox}", options.bbox.join(",")); return loader.load(url); } } }
Add some types to material
Add some types to material
TypeScript
apache-2.0
Tomella/explorer-3d,Tomella/explorer-3d,Tomella/explorer-3d
--- +++ @@ -1,6 +1,6 @@ export class WmsMaterial extends THREE.MeshPhongMaterial { - constructor(public options: any) { + constructor(public options: {width: number, height: number, template: string, bbox: number[], opacity: number}) { super({ map: getLoader(), transparent: true,
cbb5884de5d1ba198e0d68d9ddd62c76f7d59bab
Frontend/app/user/signin/signin.component.ts
Frontend/app/user/signin/signin.component.ts
import { AuthHttp } from '../../utils/AuthHttp.service'; import { Component } from '@angular/core'; import { MentiiConfig } from '../../mentii.config'; import { Router } from '@angular/router'; import { SigninModel } from './signin.model'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import { UserService } from '../user.service'; @Component({ moduleId: module.id, selector: 'signin-form', templateUrl: 'signin.html' }) export class SigninComponent { model = new SigninModel('', ''); mentiiConfig = new MentiiConfig(); isLoading = false; constructor(public userService: UserService, public authHttpService: AuthHttp , public router: Router, public toastr: ToastsManager){ } handleSuccess(data) { this.isLoading = false; if (data.payload.token) { this.authHttpService.login(data.payload.token); this.authHttpService.saveRole(data.user.userRole); this.router.navigateByUrl('/dashboard'); } else { alert("Success but no token. False authentication."); } } handleError(err) { this.toastr.error("Unrecognized email or password."); this.isLoading = false; } submit() { this.isLoading = true; this.userService.signIn(this.model) .subscribe( data => this.handleSuccess(data.json()), err => this.handleError(err) ); } }
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { SigninModel } from './signin.model'; import { MentiiConfig } from '../../mentii.config'; import { UserService } from '../user.service'; import { AuthHttp } from '../../utils/AuthHttp.service'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; @Component({ moduleId: module.id, selector: 'signin-form', templateUrl: 'signin.html' }) export class SigninComponent { model = new SigninModel('', ''); mentiiConfig = new MentiiConfig(); isLoading = false; constructor(public userService: UserService, public authHttpService: AuthHttp , public router: Router, public toastr: ToastsManager){ } handleSuccess(data) { this.isLoading = false; if (data.payload.token) { this.authHttpService.login(data.payload.token); this.authHttpService.saveRole(data.user.userRole); this.router.navigateByUrl('/dashboard'); } else { alert("Success but no token. False authentication"); } } handleError(err) { this.toastr.error("Sign in failed"); this.isLoading = false; } submit() { this.isLoading = true; this.userService.signIn(this.model) .subscribe( data => this.handleSuccess(data.json()), err => this.handleError(err) ); } }
Revert "Updates message, reorders imports alphabetically"
Revert "Updates message, reorders imports alphabetically" This reverts commit 458aff3644557631c5fc7d37c37313ace6a22765.
TypeScript
mit
mentii/mentii,mentii/mentii,mentii/mentii,mentii/mentii,mentii/mentii
--- +++ @@ -1,10 +1,10 @@ -import { AuthHttp } from '../../utils/AuthHttp.service'; import { Component } from '@angular/core'; -import { MentiiConfig } from '../../mentii.config'; import { Router } from '@angular/router'; import { SigninModel } from './signin.model'; +import { MentiiConfig } from '../../mentii.config'; +import { UserService } from '../user.service'; +import { AuthHttp } from '../../utils/AuthHttp.service'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; -import { UserService } from '../user.service'; @Component({ moduleId: module.id, @@ -27,12 +27,12 @@ this.authHttpService.saveRole(data.user.userRole); this.router.navigateByUrl('/dashboard'); } else { - alert("Success but no token. False authentication."); + alert("Success but no token. False authentication"); } } handleError(err) { - this.toastr.error("Unrecognized email or password."); + this.toastr.error("Sign in failed"); this.isLoading = false; }
74a26d37e42c270e4e28d3c80fec5cbf99edec8e
src/third_party/tsetse/util/pattern_engines/property_write_engine.ts
src/third_party/tsetse/util/pattern_engines/property_write_engine.ts
import * as ts from 'typescript'; import {Checker} from '../../checker'; import {ErrorCode} from '../../error_code'; import {debugLog} from '../ast_tools'; import {Fixer} from '../fixer'; import {PropertyMatcher} from '../property_matcher'; import {matchProperty, PropertyEngine} from './property_engine'; /** Test if an AST node is a matched property write. */ export function matchPropertyWrite( tc: ts.TypeChecker, n: ts.PropertyAccessExpression|ts.ElementAccessExpression, matcher: PropertyMatcher): ts.BinaryExpression|undefined { debugLog(() => `inspecting ${n.parent.getText().trim()}`); if (matchProperty(tc, n, matcher) === undefined) return; const assignment = n.parent; if (!ts.isBinaryExpression(assignment)) return; if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return; if (assignment.left !== n) return; return assignment; } /** * The engine for BANNED_PROPERTY_WRITE. */ export class PropertyWriteEngine extends PropertyEngine { register(checker: Checker) { this.registerWith(checker, matchPropertyWrite); } }
import * as ts from 'typescript'; import {Checker} from '../../checker'; import {ErrorCode} from '../../error_code'; import {debugLog} from '../ast_tools'; import {Fixer} from '../fixer'; import {PropertyMatcher} from '../property_matcher'; import {matchProperty, PropertyEngine} from './property_engine'; /** Test if an AST node is a matched property write. */ export function matchPropertyWrite( tc: ts.TypeChecker, n: ts.PropertyAccessExpression|ts.ElementAccessExpression, matcher: PropertyMatcher): ts.BinaryExpression|undefined { debugLog(() => `inspecting ${n.parent.getText().trim()}`); if (matchProperty(tc, n, matcher) === undefined) return; const assignment = n.parent; if (!ts.isBinaryExpression(assignment)) return; // All properties we track are of the string type, so we only look at // `=` and `+=` operators. if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken && assignment.operatorToken.kind !== ts.SyntaxKind.PlusEqualsToken) { return; } if (assignment.left !== n) return; return assignment; } /** * The engine for BANNED_PROPERTY_WRITE. */ export class PropertyWriteEngine extends PropertyEngine { register(checker: Checker) { this.registerWith(checker, matchPropertyWrite); } }
Make Tsetse property-write pattern track the `+=` operator.
Make Tsetse property-write pattern track the `+=` operator. PiperOrigin-RevId: 330852497
TypeScript
apache-2.0
google/tsec,google/tsec
--- +++ @@ -20,7 +20,12 @@ const assignment = n.parent; if (!ts.isBinaryExpression(assignment)) return; - if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return; + // All properties we track are of the string type, so we only look at + // `=` and `+=` operators. + if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken && + assignment.operatorToken.kind !== ts.SyntaxKind.PlusEqualsToken) { + return; + } if (assignment.left !== n) return; return assignment;
f586e0779bc8b46fad7609768494ee969691a24c
app/src/lib/trampoline/trampoline-ui-helper.ts
app/src/lib/trampoline/trampoline-ui-helper.ts
import { PopupType } from '../../models/popup' import { Dispatcher } from '../../ui/dispatcher' class TrampolineUIHelper { // The dispatcher must be set before this helper can do anything private dispatcher!: Dispatcher public setDispatcher(dispatcher: Dispatcher) { this.dispatcher = dispatcher } public promptAddingSSHHost( host: string, ip: string, fingerprint: string ): Promise<boolean> { return new Promise(resolve => { this.dispatcher.showPopup({ type: PopupType.AddSSHHost, host, ip, fingerprint, onSubmit: resolve, }) }) } public promptSSHKeyPassphrase(keyPath: string): Promise<string | undefined> { return new Promise(resolve => { this.dispatcher.showPopup({ type: PopupType.SSHKeyPassphrase, keyPath, onSubmit: resolve, }) }) } } export const trampolineUIHelper = new TrampolineUIHelper()
import { PopupType } from '../../models/popup' import { Dispatcher } from '../../ui/dispatcher' class TrampolineUIHelper { // The dispatcher must be set before this helper can do anything private dispatcher!: Dispatcher public setDispatcher(dispatcher: Dispatcher) { this.dispatcher = dispatcher } public promptAddingSSHHost( host: string, ip: string, fingerprint: string ): Promise<boolean> { return new Promise(resolve => { this.dispatcher.showPopup({ type: PopupType.AddSSHHost, host, ip, fingerprint, onSubmit: addHost => resolve(addHost), }) }) } public promptSSHKeyPassphrase(keyPath: string): Promise<string | undefined> { return new Promise(resolve => { this.dispatcher.showPopup({ type: PopupType.SSHKeyPassphrase, keyPath, onSubmit: passphrase => resolve(passphrase), }) }) } } export const trampolineUIHelper = new TrampolineUIHelper()
Fix lint checks with some promises
Fix lint checks with some promises
TypeScript
mit
say25/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,shiftkey/desktop,say25/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop
--- +++ @@ -20,7 +20,7 @@ host, ip, fingerprint, - onSubmit: resolve, + onSubmit: addHost => resolve(addHost), }) }) } @@ -30,7 +30,7 @@ this.dispatcher.showPopup({ type: PopupType.SSHKeyPassphrase, keyPath, - onSubmit: resolve, + onSubmit: passphrase => resolve(passphrase), }) }) }
560671921ac9063610cdf9ae551de3d63018b95b
app/src/lib/git/update-ref.ts
app/src/lib/git/update-ref.ts
import { git } from './core' import { Repository } from '../../models/repository' /** * Update the ref to a new value. * * @param repository - The repository in which the ref exists. * @param ref - The ref to update. Must be fully qualified * (e.g., `refs/heads/NAME`). * @param oldValue - The value we expect the ref to have currently. If it * doesn't match, the update will be aborted. * @param newValue - The new value for the ref. * @param reason - The reflog entry. */ export async function updateRef( repository: Repository, ref: string, oldValue: string, newValue: string, reason: string ): Promise<void> { await git( ['update-ref', ref, newValue, oldValue, '-m', reason], repository.path, 'updateRef' ) } /** * Remove a ref. * * @param repository - The repository in which the ref exists. * @param ref - The ref to remove. Should be fully qualified, but may also be 'HEAD'. * @param reason - The reflog entry. */ export async function deleteRef( repository: Repository, ref: string, reason: string | undefined ): Promise<true | undefined> { const args = ['update-ref', '-d', ref] if (reason !== undefined) { args.push('-m', reason) } const result = await git(args, repository.path, 'deleteRef') if (result.exitCode === 0) { return true } return undefined }
import { git } from './core' import { Repository } from '../../models/repository' /** * Update the ref to a new value. * * @param repository - The repository in which the ref exists. * @param ref - The ref to update. Must be fully qualified * (e.g., `refs/heads/NAME`). * @param oldValue - The value we expect the ref to have currently. If it * doesn't match, the update will be aborted. * @param newValue - The new value for the ref. * @param reason - The reflog entry. */ export async function updateRef( repository: Repository, ref: string, oldValue: string, newValue: string, reason: string ): Promise<void> { await git( ['update-ref', ref, newValue, oldValue, '-m', reason], repository.path, 'updateRef' ) } /** * Remove a ref. * * @param repository - The repository in which the ref exists. * @param ref - The ref to remove. Should be fully qualified, but may also be 'HEAD'. * @param reason - The reflog entry. */ export async function deleteRef( repository: Repository, ref: string, reason: string | undefined ): Promise<true> { const args = ['update-ref', '-d', ref] if (reason !== undefined) { args.push('-m', reason) } await git(args, repository.path, 'deleteRef') return true }
Exit code will always be zero or it'll throw
Exit code will always be zero or it'll throw
TypeScript
mit
artivilla/desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus,desktop/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,desktop/desktop,say25/desktop,say25/desktop,artivilla/desktop
--- +++ @@ -37,18 +37,14 @@ repository: Repository, ref: string, reason: string | undefined -): Promise<true | undefined> { +): Promise<true> { const args = ['update-ref', '-d', ref] if (reason !== undefined) { args.push('-m', reason) } - const result = await git(args, repository.path, 'deleteRef') + await git(args, repository.path, 'deleteRef') - if (result.exitCode === 0) { - return true - } - - return undefined + return true }
c187e0a0aa62cdb8c1f5a707dd2a9fccbf7dfb4a
examples/aws/src/LambdaServer.ts
examples/aws/src/LambdaServer.ts
import {ServerLoader} from "@tsed/common"; import * as awsServerlessExpress from "aws-serverless-express"; import {Server} from "./Server"; // NOTE: If you get ERR_CONTENT_DECODING_FAILED in your browser, this is likely // due to a compressed response (e.g. gzip) which has not been handled correctly // by aws-serverless-express and/or API Gateway. Add the necessary MIME types to // binaryMimeTypes below, then redeploy (`npm run package-deploy`) const binaryMimeTypes = [ "application/javascript", "application/json", "application/octet-stream", "application/xml", "font/eot", "font/opentype", "font/otf", "image/jpeg", "image/png", "image/svg+xml", "text/comma-separated-values", "text/css", "text/html", "text/javascript", "text/plain", "text/text", "text/xml" ]; // The function handler to setup on AWS Lambda console -- the name of this function must match the one configured on AWS export async function awsHanlder(event: any, context: any) { const server = await ServerLoader.bootstrap(Server); const lambdaServer = awsServerlessExpress.createServer(server.expressApp, null, binaryMimeTypes); return awsServerlessExpress.proxy(lambdaServer, event, context).promise; }
import {ServerLoader} from "@tsed/common"; import * as awsServerlessExpress from "aws-serverless-express"; import {Server} from "./Server"; // NOTE: If you get ERR_CONTENT_DECODING_FAILED in your browser, this is likely // due to a compressed response (e.g. gzip) which has not been handled correctly // by aws-serverless-express and/or API Gateway. Add the necessary MIME types to // binaryMimeTypes below, then redeploy (`npm run package-deploy`) const binaryMimeTypes = [ "application/javascript", "application/json", "application/octet-stream", "application/xml", "font/eot", "font/opentype", "font/otf", "image/jpeg", "image/png", "image/svg+xml", "text/comma-separated-values", "text/css", "text/html", "text/javascript", "text/plain", "text/text", "text/xml" ]; // The function handler to setup on AWS Lambda console -- the name of this function must match the one configured on AWS export async function awsHanlder(event: any, context: any) { const server = await ServerLoader.bootstrap(Server); const lambdaServer = awsServerlessExpress.createServer(server.expressApp, null, binaryMimeTypes); return awsServerlessExpress.proxy(lambdaServer, event, context, 'PROMISE').promise; }
Add Context resolution mode on aws example
chore: Add Context resolution mode on aws example
TypeScript
mit
Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators
--- +++ @@ -31,5 +31,5 @@ const server = await ServerLoader.bootstrap(Server); const lambdaServer = awsServerlessExpress.createServer(server.expressApp, null, binaryMimeTypes); - return awsServerlessExpress.proxy(lambdaServer, event, context).promise; + return awsServerlessExpress.proxy(lambdaServer, event, context, 'PROMISE').promise; }
4dd05dcff9617923be2f7136ac3b8c236dc10077
pinkyswear/pinkyswear-tests.ts
pinkyswear/pinkyswear-tests.ts
/// <reference path="pinkyswear.d.ts" /> var promise: PinkySwear.Promise = pinkySwear(); promise.then(function(value) { console.log("Success with value " + value + "1"); }, function(value) { console.log("Failure with value " + value + "!"); }); promise(true, [42]); // Promise rejected with multiple values promise = pinkySwear(); promise.then(function(...values) { console.log("Success with value " + Array.from(values).join(',') + "1"); }, function(...values) { console.log("Failure with value " + Array.from(values).join(',') + "!"); }); promise(false, [6, 6, 6]); var state: boolean = promise(); // A PinkySwear-powered timeout function that returns a promise: function promiseTimeout(timeoutMs) { var prom = pinkySwear(); setTimeout(function() { prom(true, []); }, timeoutMs); return prom; } console.log('Starting timeout now.'); promiseTimeout(5000).then(function() { console.log('5s have passed.'); });
/// <reference path="pinkyswear.d.ts" /> var promise: PinkySwear.Promise = pinkySwear(); promise.then(function(value) { console.log("Success with value " + value + "1"); }, function(value) { console.log("Failure with value " + value + "!"); }); promise(true, [42]); // Promise rejected with multiple values promise = pinkySwear(); promise.then(function(...values: any[]) { console.log("Success with value " + values.join(',') + "1"); }, function(...values: any[]) { console.log("Failure with value " + values.join(',') + "!"); }); promise(false, [6, 6, 6]); var state: boolean = promise(); // A PinkySwear-powered timeout function that returns a promise: function promiseTimeout(timeoutMs: number) { var prom = pinkySwear(); setTimeout(function() { prom(true, []); }, timeoutMs); return prom; } console.log('Starting timeout now.'); promiseTimeout(5000).then(function() { console.log('5s have passed.'); });
Resolve errors in pinkyswear tests
Resolve errors in pinkyswear tests
TypeScript
mit
GlennQuirynen/DefinitelyTyped,mcliment/DefinitelyTyped,elisee/DefinitelyTyped,Syati/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,amanmahajan7/DefinitelyTyped,ashwinr/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,EnableSoftware/DefinitelyTyped,PopSugar/DefinitelyTyped,martinduparc/DefinitelyTyped,progre/DefinitelyTyped,OpenMaths/DefinitelyTyped,arusakov/DefinitelyTyped,herrmanno/DefinitelyTyped,mareek/DefinitelyTyped,schmuli/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,arcticwaters/DefinitelyTyped,sandersky/DefinitelyTyped,vagarenko/DefinitelyTyped,jsaelhof/DefinitelyTyped,fredgalvao/DefinitelyTyped,tan9/DefinitelyTyped,Dominator008/DefinitelyTyped,esperco/DefinitelyTyped,pocesar/DefinitelyTyped,mattanja/DefinitelyTyped,Ptival/DefinitelyTyped,chrismbarr/DefinitelyTyped,Pro/DefinitelyTyped,takenet/DefinitelyTyped,mshmelev/DefinitelyTyped,EnableSoftware/DefinitelyTyped,rschmukler/DefinitelyTyped,HPFOD/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,nycdotnet/DefinitelyTyped,greglo/DefinitelyTyped,frogcjn/DefinitelyTyped,paulmorphy/DefinitelyTyped,QuatroCode/DefinitelyTyped,one-pieces/DefinitelyTyped,hellopao/DefinitelyTyped,glenndierckx/DefinitelyTyped,benishouga/DefinitelyTyped,scriby/DefinitelyTyped,subash-a/DefinitelyTyped,flyfishMT/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped,behzad888/DefinitelyTyped,Litee/DefinitelyTyped,egeland/DefinitelyTyped,nmalaguti/DefinitelyTyped,alvarorahul/DefinitelyTyped,minodisk/DefinitelyTyped,alexdresko/DefinitelyTyped,tan9/DefinitelyTyped,davidpricedev/DefinitelyTyped,Karabur/DefinitelyTyped,ryan10132/DefinitelyTyped,xStrom/DefinitelyTyped,nitintutlani/DefinitelyTyped,alexdresko/DefinitelyTyped,danfma/DefinitelyTyped,rolandzwaga/DefinitelyTyped,jraymakers/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,dmoonfire/DefinitelyTyped,Zorgatone/DefinitelyTyped,johan-gorter/DefinitelyTyped,hellopao/DefinitelyTyped,pwelter34/DefinitelyTyped,optical/DefinitelyTyped,subjectix/DefinitelyTyped,mcrawshaw/DefinitelyTyped,MugeSo/DefinitelyTyped,hatz48/DefinitelyTyped,trystanclarke/DefinitelyTyped,gandjustas/DefinitelyTyped,frogcjn/DefinitelyTyped,AgentME/DefinitelyTyped,abner/DefinitelyTyped,drinchev/DefinitelyTyped,elisee/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,nainslie/DefinitelyTyped,dflor003/DefinitelyTyped,UzEE/DefinitelyTyped,jbrantly/DefinitelyTyped,timjk/DefinitelyTyped,martinduparc/DefinitelyTyped,musicist288/DefinitelyTyped,onecentlin/DefinitelyTyped,raijinsetsu/DefinitelyTyped,applesaucers/lodash-invokeMap,gyohk/DefinitelyTyped,schmuli/DefinitelyTyped,martinduparc/DefinitelyTyped,damianog/DefinitelyTyped,pwelter34/DefinitelyTyped,use-strict/DefinitelyTyped,daptiv/DefinitelyTyped,florentpoujol/DefinitelyTyped,chrootsu/DefinitelyTyped,newclear/DefinitelyTyped,mhegazy/DefinitelyTyped,florentpoujol/DefinitelyTyped,zuzusik/DefinitelyTyped,sledorze/DefinitelyTyped,yuit/DefinitelyTyped,alextkachman/DefinitelyTyped,ashwinr/DefinitelyTyped,isman-usoh/DefinitelyTyped,mjjames/DefinitelyTyped,georgemarshall/DefinitelyTyped,jasonswearingen/DefinitelyTyped,mweststrate/DefinitelyTyped,wilfrem/DefinitelyTyped,abbasmhd/DefinitelyTyped,Litee/DefinitelyTyped,UzEE/DefinitelyTyped,stacktracejs/DefinitelyTyped,whoeverest/DefinitelyTyped,Zzzen/DefinitelyTyped,donnut/DefinitelyTyped,arusakov/DefinitelyTyped,nobuoka/DefinitelyTyped,stacktracejs/DefinitelyTyped,emanuelhp/DefinitelyTyped,adamcarr/DefinitelyTyped,nmalaguti/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,QuatroCode/DefinitelyTyped,RX14/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,slavomirvojacek/adbrain-typescript-definitions,reppners/DefinitelyTyped,jimthedev/DefinitelyTyped,dydek/DefinitelyTyped,micurs/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,aciccarello/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,emanuelhp/DefinitelyTyped,RX14/DefinitelyTyped,mjjames/DefinitelyTyped,johan-gorter/DefinitelyTyped,richardTowers/DefinitelyTyped,dmoonfire/DefinitelyTyped,laco0416/DefinitelyTyped,borisyankov/DefinitelyTyped,moonpyk/DefinitelyTyped,dydek/DefinitelyTyped,dsebastien/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,rschmukler/DefinitelyTyped,mhegazy/DefinitelyTyped,raijinsetsu/DefinitelyTyped,chbrown/DefinitelyTyped,optical/DefinitelyTyped,fredgalvao/DefinitelyTyped,markogresak/DefinitelyTyped,Dominator008/DefinitelyTyped,gcastre/DefinitelyTyped,onecentlin/DefinitelyTyped,eugenpodaru/DefinitelyTyped,bilou84/DefinitelyTyped,teves-castro/DefinitelyTyped,amanmahajan7/DefinitelyTyped,shlomiassaf/DefinitelyTyped,KonaTeam/DefinitelyTyped,sixinli/DefinitelyTyped,use-strict/DefinitelyTyped,wilfrem/DefinitelyTyped,Penryn/DefinitelyTyped,subash-a/DefinitelyTyped,bdoss/DefinitelyTyped,giggio/DefinitelyTyped,Zorgatone/DefinitelyTyped,bdoss/DefinitelyTyped,ajtowf/DefinitelyTyped,Zzzen/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,arma-gast/DefinitelyTyped,Penryn/DefinitelyTyped,benishouga/DefinitelyTyped,amir-arad/DefinitelyTyped,AgentME/DefinitelyTyped,gyohk/DefinitelyTyped,nitintutlani/DefinitelyTyped,opichals/DefinitelyTyped,stephenjelfs/DefinitelyTyped,Ptival/DefinitelyTyped,rcchen/DefinitelyTyped,Dashlane/DefinitelyTyped,omidkrad/DefinitelyTyped,stephenjelfs/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,psnider/DefinitelyTyped,progre/DefinitelyTyped,gandjustas/DefinitelyTyped,jraymakers/DefinitelyTyped,mcrawshaw/DefinitelyTyped,syuilo/DefinitelyTyped,hatz48/DefinitelyTyped,pocesar/DefinitelyTyped,scriby/DefinitelyTyped,mshmelev/DefinitelyTyped,schmuli/DefinitelyTyped,Syati/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,evandrewry/DefinitelyTyped,teves-castro/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,aciccarello/DefinitelyTyped,vagarenko/DefinitelyTyped,nobuoka/DefinitelyTyped,donnut/DefinitelyTyped,shlomiassaf/DefinitelyTyped,nakakura/DefinitelyTyped,reppners/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,mattblang/DefinitelyTyped,drinchev/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,nainslie/DefinitelyTyped,newclear/DefinitelyTyped,aindlq/DefinitelyTyped,nfriend/DefinitelyTyped,chrismbarr/DefinitelyTyped,georgemarshall/DefinitelyTyped,sledorze/DefinitelyTyped,bennett000/DefinitelyTyped,zuzusik/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,vasek17/DefinitelyTyped,magny/DefinitelyTyped,jimthedev/DefinitelyTyped,mattblang/DefinitelyTyped,takenet/DefinitelyTyped,jsaelhof/DefinitelyTyped,applesaucers/lodash-invokeMap,OfficeDev/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,minodisk/DefinitelyTyped,sclausen/DefinitelyTyped,damianog/DefinitelyTyped,olemp/DefinitelyTyped,rcchen/DefinitelyTyped,nycdotnet/DefinitelyTyped,smrq/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,esperco/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,isman-usoh/DefinitelyTyped,psnider/DefinitelyTyped,arma-gast/DefinitelyTyped,YousefED/DefinitelyTyped,Pro/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,flyfishMT/DefinitelyTyped,mareek/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,trystanclarke/DefinitelyTyped,YousefED/DefinitelyTyped,arcticwaters/DefinitelyTyped,danfma/DefinitelyTyped,alvarorahul/DefinitelyTyped,olemp/DefinitelyTyped,behzad888/DefinitelyTyped,nakakura/DefinitelyTyped,philippstucki/DefinitelyTyped,philippstucki/DefinitelyTyped,greglo/DefinitelyTyped,sclausen/DefinitelyTyped,gcastre/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,abbasmhd/DefinitelyTyped,egeland/DefinitelyTyped,bennett000/DefinitelyTyped,borisyankov/DefinitelyTyped,pocesar/DefinitelyTyped,jasonswearingen/DefinitelyTyped,xStrom/DefinitelyTyped,erosb/DefinitelyTyped,smrq/DefinitelyTyped,glenndierckx/DefinitelyTyped,magny/DefinitelyTyped,axelcostaspena/DefinitelyTyped,ajtowf/DefinitelyTyped,davidpricedev/DefinitelyTyped,jimthedev/DefinitelyTyped,psnider/DefinitelyTyped,mattanja/DefinitelyTyped,benliddicott/DefinitelyTyped,AgentME/DefinitelyTyped,RedSeal-co/DefinitelyTyped,alainsahli/DefinitelyTyped,hellopao/DefinitelyTyped,HPFOD/DefinitelyTyped,rolandzwaga/DefinitelyTyped,Dashlane/DefinitelyTyped,alextkachman/DefinitelyTyped,Karabur/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,abner/DefinitelyTyped,OpenMaths/DefinitelyTyped,paulmorphy/DefinitelyTyped,lseguin42/DefinitelyTyped,MugeSo/DefinitelyTyped,chrootsu/DefinitelyTyped,aciccarello/DefinitelyTyped,yuit/DefinitelyTyped,syuilo/DefinitelyTyped
--- +++ @@ -14,10 +14,10 @@ promise = pinkySwear(); -promise.then(function(...values) { - console.log("Success with value " + Array.from(values).join(',') + "1"); -}, function(...values) { - console.log("Failure with value " + Array.from(values).join(',') + "!"); +promise.then(function(...values: any[]) { + console.log("Success with value " + values.join(',') + "1"); +}, function(...values: any[]) { + console.log("Failure with value " + values.join(',') + "!"); }); promise(false, [6, 6, 6]); @@ -26,7 +26,7 @@ // A PinkySwear-powered timeout function that returns a promise: -function promiseTimeout(timeoutMs) { +function promiseTimeout(timeoutMs: number) { var prom = pinkySwear(); setTimeout(function() { prom(true, []);
363c641a3f570fd16bd347a36372a8c2abdda695
app/src/lib/open-terminal.ts
app/src/lib/open-terminal.ts
import { spawn } from 'child_process' import { platform } from 'os' export function openTerminal(fullPath: string) { const currentPlatform = platform() let command = '' switch (currentPlatform) { case 'darwin': { command = 'open -a Terminal' break } case 'win32': { command = 'start /D "%cd%" cmd' break } } return spawn('open', [ '-a', 'Terminal', fullPath ]) }
import { spawn } from 'child_process' import { platform } from 'os' class Command { public name: string public args: string[] } export function openTerminal(fullPath: string) { const currentPlatform = platform() const command = new Command() switch (currentPlatform) { case 'darwin': { command.name = 'open' command.args = [ '-a', 'Terminal', fullPath ] break } case 'win32': { command.name = 'start' command.args = [ '/D', '"%cd%"', 'cmd', fullPath ] break } } return spawn(command.name, command.args) }
Clean up open terminal function
Clean up open terminal function
TypeScript
mit
say25/desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,say25/desktop,say25/desktop,BugTesterTest/desktops,hjobrien/desktop,gengjiawen/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,artivilla/desktop,BugTesterTest/desktops,artivilla/desktop,shiftkey/desktop,hjobrien/desktop,gengjiawen/desktop,hjobrien/desktop,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,hjobrien/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,BugTesterTest/desktops,BugTesterTest/desktops,j-f1/forked-desktop
--- +++ @@ -1,20 +1,27 @@ import { spawn } from 'child_process' import { platform } from 'os' +class Command { + public name: string + public args: string[] +} + export function openTerminal(fullPath: string) { const currentPlatform = platform() - let command = '' + const command = new Command() switch (currentPlatform) { case 'darwin': { - command = 'open -a Terminal' + command.name = 'open' + command.args = [ '-a', 'Terminal', fullPath ] break } case 'win32': { - command = 'start /D "%cd%" cmd' + command.name = 'start' + command.args = [ '/D', '"%cd%"', 'cmd', fullPath ] break } } - return spawn('open', [ '-a', 'Terminal', fullPath ]) + return spawn(command.name, command.args) }
75ab7a99f93d51924e7a69b4f36ab78a6325d2ac
src/app/list/todo/todo.module.ts
src/app/list/todo/todo.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { TodoComponent } from './todo.component'; import { FirstUpperPipe } from '../../shared/pipes/first-upper.pipe'; import { DoNothingDirective } from '../../shared/directives/do-nothing.directive'; /** * @ignore */ const COMPONENTS = [ TodoComponent ]; /** * @ignore */ const PIPES_AND_DIRECTIVES = [ FirstUpperPipe, DoNothingDirective ]; /** * The todo module * * Contains the {@link TodoComponent} */ @NgModule({ imports: [ BrowserModule ], declarations: [ TodoComponent, PIPES_AND_DIRECTIVES ], exports: [TodoComponent] }) export class TodoModule { }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { TodoComponent } from './todo.component'; import { FirstUpperPipe } from '../../shared/pipes/first-upper.pipe'; import { DoNothingDirective } from '../../shared/directives/do-nothing.directive'; /** * @ignore */ const COMPONENTS = [TodoComponent]; const PIPES_AND_DIRECTIVES = [FirstUpperPipe, DoNothingDirective]; /** * The todo module * * Contains the {@link TodoComponent} */ @NgModule({ imports: [BrowserModule], declarations: [TodoComponent, PIPES_AND_DIRECTIVES], exports: [TodoComponent] }) export class TodoModule {}
Fix for new menu design
Fix for new menu design
TypeScript
mit
compodoc/compodoc-demo-todomvc-angular2,compodoc/compodoc-demo-todomvc-angular2,compodoc/compodoc-demo-todomvc-angular,compodoc/compodoc-demo-todomvc-angular2,compodoc/compodoc-demo-todomvc-angular
--- +++ @@ -10,17 +10,9 @@ /** * @ignore */ -const COMPONENTS = [ - TodoComponent -]; +const COMPONENTS = [TodoComponent]; -/** - * @ignore - */ -const PIPES_AND_DIRECTIVES = [ - FirstUpperPipe, - DoNothingDirective -]; +const PIPES_AND_DIRECTIVES = [FirstUpperPipe, DoNothingDirective]; /** * The todo module @@ -28,13 +20,8 @@ * Contains the {@link TodoComponent} */ @NgModule({ - imports: [ - BrowserModule - ], - declarations: [ - TodoComponent, - PIPES_AND_DIRECTIVES - ], + imports: [BrowserModule], + declarations: [TodoComponent, PIPES_AND_DIRECTIVES], exports: [TodoComponent] }) -export class TodoModule { } +export class TodoModule {}
d0603a2f7ac0e7a66e779ba5dea09d3b81f760a3
src/themes/elife/index.ts
src/themes/elife/index.ts
export {}
import { first, ready } from '../../util' import DateTimeFormat = Intl.DateTimeFormat function elifeFormatDate(date: Date): string { const formatter: DateTimeFormat = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) return formatter.format(date) } ready(() => { const dateEl: Element | null = first(':--Date') if (!(dateEl instanceof Element)) return const date = new Date(dateEl.innerHTML) const formattedDate: string = elifeFormatDate(date) dateEl.innerHTML = formattedDate })
Format eLife's publication date correctly
feat(Date): Format eLife's publication date correctly
TypeScript
apache-2.0
stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila
--- +++ @@ -1 +1,19 @@ -export {} +import { first, ready } from '../../util' +import DateTimeFormat = Intl.DateTimeFormat + +function elifeFormatDate(date: Date): string { + const formatter: DateTimeFormat = new Intl.DateTimeFormat('en-US', { + month: 'short', + day: 'numeric', + year: 'numeric' + }) + return formatter.format(date) +} + +ready(() => { + const dateEl: Element | null = first(':--Date') + if (!(dateEl instanceof Element)) return + const date = new Date(dateEl.innerHTML) + const formattedDate: string = elifeFormatDate(date) + dateEl.innerHTML = formattedDate +})
a1cd93f7aa6a2d60ea11123be321850a5ee7596d
src/app/core/pet-tag.reducer.ts
src/app/core/pet-tag.reducer.ts
import { ActionReducer, Action } from '@ngrx/store'; import { PetTag, initialTag } from './../core/pet-tag.model'; // Export action types export const SELECT_SHAPE = 'SELECT_SHAPE'; export const SELECT_FONT = 'SELECT_FONT'; export const ADD_TEXT = 'ADD_TEXT'; export const INCLUDE_CLIP = 'INCLUDE_CLIP'; export const ADD_GEMS = 'ADD_GEMS'; export const COMPLETE = 'COMPLETE'; export const RESET = 'RESET'; // Create pet tag reducer export const petTagReducer: ActionReducer<PetTag> = (state: PetTag = initialTag, action: Action) => { switch(action.type) { case SELECT_SHAPE: return Object.assign({}, state, { shape: action.payload }); case SELECT_FONT: return Object.assign({}, state, { font: action.payload }); case ADD_TEXT: return Object.assign({}, state, { text: action.payload }); case INCLUDE_CLIP: return Object.assign({}, state, { clip: action.payload }); case ADD_GEMS: return Object.assign({}, state, { gems: action.payload }); case COMPLETE: return Object.assign({}, state, { complete: action.payload }); case RESET: return Object.assign({}, state, action.payload); default: return state; } }
import { Action } from '@ngrx/store'; import { PetTag, initialTag } from './../core/pet-tag.model'; // Export action types export const SELECT_SHAPE = 'SELECT_SHAPE'; export const SELECT_FONT = 'SELECT_FONT'; export const ADD_TEXT = 'ADD_TEXT'; export const INCLUDE_CLIP = 'INCLUDE_CLIP'; export const ADD_GEMS = 'ADD_GEMS'; export const COMPLETE = 'COMPLETE'; export const RESET = 'RESET'; // Create pet tag reducer export function petTagReducer(state: PetTag = initialTag, action: Action) { switch(action.type) { case SELECT_SHAPE: return Object.assign({}, state, { shape: action.payload }); case SELECT_FONT: return Object.assign({}, state, { font: action.payload }); case ADD_TEXT: return Object.assign({}, state, { text: action.payload }); case INCLUDE_CLIP: return Object.assign({}, state, { clip: action.payload }); case ADD_GEMS: return Object.assign({}, state, { gems: action.payload }); case COMPLETE: return Object.assign({}, state, { complete: action.payload }); case RESET: return Object.assign({}, state, action.payload); default: return state; } }
Fix ng serve compile error.
Fix ng serve compile error.
TypeScript
mit
kmaida/pet-tags-ngrx,auth0-blog/pet-tags-ngrx,auth0-blog/pet-tags-ngrx,auth0-blog/pet-tags-ngrx,kmaida/pet-tags-ngrx,kmaida/pet-tags-ngrx
--- +++ @@ -1,4 +1,4 @@ -import { ActionReducer, Action } from '@ngrx/store'; +import { Action } from '@ngrx/store'; import { PetTag, initialTag } from './../core/pet-tag.model'; // Export action types @@ -11,36 +11,35 @@ export const RESET = 'RESET'; // Create pet tag reducer -export const petTagReducer: ActionReducer<PetTag> = - (state: PetTag = initialTag, action: Action) => { - switch(action.type) { - case SELECT_SHAPE: - return Object.assign({}, state, { - shape: action.payload - }); - case SELECT_FONT: - return Object.assign({}, state, { - font: action.payload - }); - case ADD_TEXT: - return Object.assign({}, state, { - text: action.payload - }); - case INCLUDE_CLIP: - return Object.assign({}, state, { - clip: action.payload - }); - case ADD_GEMS: - return Object.assign({}, state, { - gems: action.payload - }); - case COMPLETE: - return Object.assign({}, state, { - complete: action.payload - }); - case RESET: - return Object.assign({}, state, action.payload); - default: - return state; +export function petTagReducer(state: PetTag = initialTag, action: Action) { + switch(action.type) { + case SELECT_SHAPE: + return Object.assign({}, state, { + shape: action.payload + }); + case SELECT_FONT: + return Object.assign({}, state, { + font: action.payload + }); + case ADD_TEXT: + return Object.assign({}, state, { + text: action.payload + }); + case INCLUDE_CLIP: + return Object.assign({}, state, { + clip: action.payload + }); + case ADD_GEMS: + return Object.assign({}, state, { + gems: action.payload + }); + case COMPLETE: + return Object.assign({}, state, { + complete: action.payload + }); + case RESET: + return Object.assign({}, state, action.payload); + default: + return state; } }
f2480014a73374e6d73e39cb0dc7d649edb39fe1
index.d.ts
index.d.ts
declare namespace SuperError { interface SuperErrorI { name: string; message: string; [k: string]: any; new(...args: any[]): SuperError; } } interface SuperError extends Error { name: string; message: string; cause?: Error; rootCause?: Error; [k: string]: any; subclass(name: string): SuperError.SuperErrorI; subclass(exports: any, name: string): SuperError.SuperErrorI; subclass(exports: any, name: string, subclass_constructor: (this: SuperError, ...args: any[]) => void): SuperError.SuperErrorI; subclass(name: string, subclass_constructor: (this: SuperError, ...args: any[]) => void): SuperError.SuperErrorI; constructor(...args: any[]): SuperError; causedBy(err: Error): this; } declare var SuperError: SuperError; export = SuperError;
declare namespace SuperError { interface SuperErrorI { name: string; message: string; [k: string]: any; new(...args: any[]): SuperError; } } declare class SuperError extends Error { name: string; message: string; cause?: Error; rootCause?: Error; [k: string]: any; subclass(name: string): SuperError.SuperErrorI; subclass(exports: any, name: string): SuperError.SuperErrorI; subclass(exports: any, name: string, subclass_constructor: (this: SuperError, ...args: any[]) => void): SuperError.SuperErrorI; subclass(name: string, subclass_constructor: (this: SuperError, ...args: any[]) => void): SuperError.SuperErrorI; causedBy(err: Error): this; } export = SuperError;
Define SuperError as a class
Define SuperError as a class
TypeScript
mit
busbud/super-error
--- +++ @@ -8,7 +8,7 @@ } } -interface SuperError extends Error { +declare class SuperError extends Error { name: string; message: string; cause?: Error; @@ -20,10 +20,7 @@ subclass(exports: any, name: string, subclass_constructor: (this: SuperError, ...args: any[]) => void): SuperError.SuperErrorI; subclass(name: string, subclass_constructor: (this: SuperError, ...args: any[]) => void): SuperError.SuperErrorI; - constructor(...args: any[]): SuperError; causedBy(err: Error): this; } -declare var SuperError: SuperError; export = SuperError; -
78c00de080094068531c30f189190098168b5c49
app/services/todo.service.ts
app/services/todo.service.ts
import {Injectable} from "@angular/core"; import {Todo} from "../models/todo.model"; const STORAGE_KEY = 'angular2-todo'; @Injectable() export class TodoService { todos:Todo[]; constructor() { const persistedTodos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); this.todos = persistedTodos.map(todo => { return new Todo( todo.id, todo.title, todo.isCompleted ); }); } add(title:string) { let newTodo = new Todo( this.todos.length + 1, title, false ); this.todos.push(newTodo); this.save(); } remove(todo:Todo) { const index = this.todos.indexOf(todo); this.todos.splice(index, 1); this.save(); } toggleComplate(todo:Todo) { this.todos.filter(t => t.id === todo.id) .map(t => t.isCompleted = !t.isCompleted); this.save(); } getComplatedCount():number { // TODO newTodoのInputがchangeするたびに呼び出されている return this.todos.filter(todo => todo.isCompleted).length; } private save() { console.log('saving : ', this.todos); localStorage.setItem(STORAGE_KEY, JSON.stringify(this.todos)); } }
import {Injectable} from "@angular/core"; import {Todo} from "../models/todo.model"; const STORAGE_KEY = 'angular2-todo'; @Injectable() export class TodoService { todos:Todo[]; constructor() { const persistedTodos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); this.todos = persistedTodos.map(todo => { return new Todo( todo.id, todo.title, todo.isCompleted ); }); } add(title:string) { let newTodo = new Todo( Math.floor(Math.random() * 100000), // ランダムにIDを発番する title, false ); this.todos.push(newTodo); this.save(); } remove(todo:Todo) { const index = this.todos.indexOf(todo); this.todos.splice(index, 1); this.save(); } toggleComplate(todo:Todo) { this.todos.filter(t => t.id === todo.id) .map(t => t.isCompleted = !t.isCompleted); this.save(); } getComplatedCount():number { // TODO newTodoのInputがchangeするたびに呼び出されている return this.todos.filter(todo => todo.isCompleted).length; } private save() { console.log('saving : ', this.todos); localStorage.setItem(STORAGE_KEY, JSON.stringify(this.todos)); } }
Change generated id to using random number
:+1: Change generated id to using random number
TypeScript
mit
mitsuruog/angular2-todo-tutorial,mitsuruog/angular2-todo,mitsuruog/angular2-todo,mitsuruog/angular2-todo-tutorial,mitsuruog/angular2-todo-tutorial
--- +++ @@ -21,7 +21,7 @@ add(title:string) { let newTodo = new Todo( - this.todos.length + 1, + Math.floor(Math.random() * 100000), // ランダムにIDを発番する title, false );
4961dac93eef791ac599c18c96327654786df801
src/adhocracy_frontend/adhocracy_frontend/static/js/Packages/Route/Route.ts
src/adhocracy_frontend/adhocracy_frontend/static/js/Packages/Route/Route.ts
import AdhHttp = require("../Http/Http"); import AdhConfig = require("../Config/Config"); import AdhTopLevelState = require("../TopLevelState/TopLevelState"); var notFoundTemplate = "<h1>404 - not Found</h1>"; interface IResourceRouterScope extends ng.IScope { template : string; } export var resourceRouter = ( adhHttp : AdhHttp.Service<any>, adhConfig : AdhConfig.Type, adhTopLevelState : AdhTopLevelState.TopLevelState, $routeParams : ng.route.IRouteParamsService, $scope : IResourceRouterScope ) => { var resourceUrl = adhConfig.rest_url + "/" + $routeParams["path"]; adhHttp.get(resourceUrl).then((resource) => { switch (resource.content_type) { case "adhocracy_core.resources.sample_proposal.IProposal": $scope.template = "<adh-document-workbench></adh-document-workbench>"; break; default: $scope.template = notFoundTemplate; } }, (reason) => { $scope.template = notFoundTemplate; }); };
import AdhHttp = require("../Http/Http"); import AdhConfig = require("../Config/Config"); import AdhTopLevelState = require("../TopLevelState/TopLevelState"); import RIBasicPool = require("Resources_/adhocracy_core/resources/pool/IBasicPool"); import RIMercatorProposal = require("Resources_/adhocracy_core/resources/mercator/IMercatorProposal"); import RIUser = require("Resources_/adhocracy_core/resources/principal/IUser"); import RIUsersService = require("Resources_/adhocracy_core/resources/principal/IUsersService"); var notFoundTemplate = "<h1>404 - not Found</h1>"; interface IResourceRouterScope extends ng.IScope { template : string; } export var resourceRouter = ( adhHttp : AdhHttp.Service<any>, adhConfig : AdhConfig.Type, adhTopLevelState : AdhTopLevelState.TopLevelState, $routeParams : ng.route.IRouteParamsService, $scope : IResourceRouterScope ) => { var resourceUrl = adhConfig.rest_url + "/" + $routeParams["path"]; adhHttp.get(resourceUrl).then((resource) => { switch (resource.content_type) { case RIBasicPool.content_type: $scope.template = "<adh-document-workbench></adh-document-workbench>"; break; case RIMercatorProposal.content_type: $scope.template = "<adh-document-workbench></adh-document-workbench>"; break; case RIUser.content_type: $scope.template = "<h1>User</h1>"; break; case RIUsersService.content_type: $scope.template = "<h1>User List</h1>"; break; default: $scope.template = notFoundTemplate; } }, (reason) => { $scope.template = notFoundTemplate; }); };
Use some actual content types
Use some actual content types
TypeScript
agpl-3.0
liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator
--- +++ @@ -1,6 +1,11 @@ import AdhHttp = require("../Http/Http"); import AdhConfig = require("../Config/Config"); import AdhTopLevelState = require("../TopLevelState/TopLevelState"); + +import RIBasicPool = require("Resources_/adhocracy_core/resources/pool/IBasicPool"); +import RIMercatorProposal = require("Resources_/adhocracy_core/resources/mercator/IMercatorProposal"); +import RIUser = require("Resources_/adhocracy_core/resources/principal/IUser"); +import RIUsersService = require("Resources_/adhocracy_core/resources/principal/IUsersService"); var notFoundTemplate = "<h1>404 - not Found</h1>"; @@ -21,8 +26,17 @@ adhHttp.get(resourceUrl).then((resource) => { switch (resource.content_type) { - case "adhocracy_core.resources.sample_proposal.IProposal": + case RIBasicPool.content_type: $scope.template = "<adh-document-workbench></adh-document-workbench>"; + break; + case RIMercatorProposal.content_type: + $scope.template = "<adh-document-workbench></adh-document-workbench>"; + break; + case RIUser.content_type: + $scope.template = "<h1>User</h1>"; + break; + case RIUsersService.content_type: + $scope.template = "<h1>User List</h1>"; break; default: $scope.template = notFoundTemplate;
d28522fbc04639fb2e26b36c0bf9c35168ae0554
angular/src/app/model/settings.ts
angular/src/app/model/settings.ts
import { Storable } from "./storable"; export class Settings extends Storable { rememberLastQuery = true; showPictures = true; clickInListCentersLocation = true; map = { mapTypeControl: true, zoomControl: false, }; constructor(props: any = {}) { super(); Object.assign(this, props); } }
import { Storable } from "./storable"; export class Settings extends Storable { rememberLastQuery = true; showPictures = true; clickInListCentersLocation = true; map = { mapTypeControl: false, zoomControl: false, }; constructor(props: any = {}) { super(); Object.assign(this, props); } }
Set default for setting mapTypeControl to false
Set default for setting mapTypeControl to false
TypeScript
unknown
Berlin-Vegan/berlin-vegan-map,smeir/berlin-vegan-map,Berlin-Vegan/berlin-vegan-map,Berlin-Vegan/berlin-vegan-map,Berlin-Vegan/berlin-vegan-map,smeir/berlin-vegan-map,smeir/berlin-vegan-map
--- +++ @@ -5,7 +5,7 @@ showPictures = true; clickInListCentersLocation = true; map = { - mapTypeControl: true, + mapTypeControl: false, zoomControl: false, };
2aa4507f8471dca2b985c515c47a132c7cad5d9b
dev-kits/addon-preview-wrapper/src/register.tsx
dev-kits/addon-preview-wrapper/src/register.tsx
import React, { FunctionComponent } from 'react'; import { addons, types } from '@storybook/addons'; import { ADDON_ID } from './constants'; const PreviewWrapper: FunctionComponent<{}> = p => ( <div className="my-edit-wrapper"> <button type="button" onClick={() => {}}> Edit this page </button> {p.children} </div> ); addons.register(ADDON_ID, () => { addons.add(ADDON_ID, { title: 'edit page', type: types.PREVIEW, render: PreviewWrapper as any, }); });
import React, { FunctionComponent } from 'react'; import { addons, types } from '@storybook/addons'; import { ADDON_ID } from './constants'; const PreviewWrapper: FunctionComponent<{}> = p => ( <div style={{ width: '100%', height: '100%', boxSizing: 'border-box', boxShadow: 'inset 0 0 10px black', }} > {p.children} </div> ); addons.register(ADDON_ID, () => { addons.add(ADDON_ID, { title: 'edit page', type: types.PREVIEW, render: PreviewWrapper as any, }); });
CHANGE devtools example for previewWrapper
CHANGE devtools example for previewWrapper
TypeScript
mit
kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook
--- +++ @@ -3,10 +3,14 @@ import { ADDON_ID } from './constants'; const PreviewWrapper: FunctionComponent<{}> = p => ( - <div className="my-edit-wrapper"> - <button type="button" onClick={() => {}}> - Edit this page - </button> + <div + style={{ + width: '100%', + height: '100%', + boxSizing: 'border-box', + boxShadow: 'inset 0 0 10px black', + }} + > {p.children} </div> );
8dd82e1211334e1e1be8249ba32004f8d2a9626d
packages/components/components/editor/rooster/helpers/getRoosterEditorActions.ts
packages/components/components/editor/rooster/helpers/getRoosterEditorActions.ts
import { RefObject } from 'react'; import { Direction, IEditor } from 'roosterjs-editor-types'; import { EditorActions } from '../../interface'; /** * @param editorInstance * @returns set of external actions */ const getRoosterEditorActions = ( editorInstance: IEditor, iframeRef: RefObject<HTMLIFrameElement>, clearUndoHistory: () => void, setTextDirection: (direction: Direction) => void, showModalLink: () => void, openEmojiPicker: () => void ): EditorActions => { return { getContent() { return editorInstance.getContent(); }, isDisposed() { return editorInstance.isDisposed(); }, setContent(value: string) { editorInstance.setContent(value); }, focus() { if (editorInstance.isDisposed()) { return; } editorInstance.focus(); }, insertImage(url: string, attrs: { [key: string]: string } = {}) { const imageNode = document.createElement('img'); Object.entries(attrs).forEach(([key, value]) => { imageNode.setAttribute(key, value); }); imageNode.src = url; imageNode.classList.add('proton-embedded'); editorInstance.insertNode(imageNode); editorInstance.triggerContentChangedEvent(); }, clearUndoHistory, setTextDirection, showModalLink, openEmojiPicker, }; }; export default getRoosterEditorActions;
import { RefObject } from 'react'; import { Direction, IEditor } from 'roosterjs-editor-types'; import { EditorActions } from '../../interface'; /** * @param editorInstance * @returns set of external actions */ const getRoosterEditorActions = ( editorInstance: IEditor, iframeRef: RefObject<HTMLIFrameElement>, clearUndoHistory: () => void, setTextDirection: (direction: Direction) => void, showModalLink: () => void, openEmojiPicker: () => void ): EditorActions => { return { getContent() { return editorInstance.getContent(); }, isDisposed() { return editorInstance.isDisposed(); }, setContent(value: string) { editorInstance.setContent(value); }, focus() { if (editorInstance.isDisposed()) { return; } iframeRef.current?.focus(); editorInstance.focus(); }, insertImage(url: string, attrs: { [key: string]: string } = {}) { const imageNode = document.createElement('img'); Object.entries(attrs).forEach(([key, value]) => { imageNode.setAttribute(key, value); }); imageNode.src = url; imageNode.classList.add('proton-embedded'); editorInstance.insertNode(imageNode); editorInstance.triggerContentChangedEvent(); }, clearUndoHistory, setTextDirection, showModalLink, openEmojiPicker, }; }; export default getRoosterEditorActions;
Fix editor focus on firefox
Fix editor focus on firefox
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -31,6 +31,7 @@ return; } + iframeRef.current?.focus(); editorInstance.focus(); }, insertImage(url: string, attrs: { [key: string]: string } = {}) {
1fd5a7b0db2c2b874ab7c161a6ac5a5c17905d2b
packages/@glimmer/application/src/components/utils.ts
packages/@glimmer/application/src/components/utils.ts
import { Owner } from '@glimmer/di'; import { Option } from '@glimmer/interfaces'; import { ManagerDelegate } from './component-managers/custom'; const MANAGERS: WeakMap<object, ManagerWrapper<unknown>> = new WeakMap(); const getPrototypeOf = Object.getPrototypeOf; export type ManagerFactory<ManagerDelegate> = (owner: Owner) => ManagerDelegate; export interface ManagerWrapper<ManagerDelegate> { factory: ManagerFactory<ManagerDelegate>; internal: boolean; type: 'component' | 'modifier'; } export function setManager<ManagerDelegate>(wrapper: ManagerWrapper<ManagerDelegate>, obj: {}) { MANAGERS.set(obj, wrapper); return obj; } export function getManager<ManagerDelegate>(obj: object): Option<ManagerWrapper<ManagerDelegate>> { let pointer = obj; while (pointer !== undefined && pointer !== null) { let manager = MANAGERS.get(pointer); if (manager !== undefined) { return manager as ManagerWrapper<ManagerDelegate>; } pointer = getPrototypeOf(pointer); } return null; } export function setComponentManager(factory: ManagerFactory<ManagerDelegate<unknown>>, obj: {}) { return setManager({ factory, internal: false, type: 'component' }, obj); } export function getComponentManager<T>(obj: any): undefined | ManagerFactory<ManagerDelegate<T>> { let wrapper = getManager<ManagerDelegate<T>>(obj); if (wrapper && !wrapper.internal && wrapper.type === 'component') { return wrapper.factory; } else { return undefined; } }
import { Owner } from '@glimmer/di'; import { Option } from '@glimmer/interfaces'; import { ManagerDelegate } from './component-managers/custom'; const MANAGERS: WeakMap<object, ManagerWrapper<unknown>> = new WeakMap(); const getPrototypeOf = Object.getPrototypeOf; export type ManagerFactory<ManagerDelegate> = (owner: Owner) => ManagerDelegate; export interface ManagerWrapper<ManagerDelegate> { factory: ManagerFactory<ManagerDelegate>; type: 'component'; } export function setManager<ManagerDelegate>(wrapper: ManagerWrapper<ManagerDelegate>, obj: {}) { MANAGERS.set(obj, wrapper); return obj; } export function getManager<ManagerDelegate>(obj: object): Option<ManagerWrapper<ManagerDelegate>> { let pointer = obj; while (pointer !== undefined && pointer !== null) { let manager = MANAGERS.get(pointer); if (manager !== undefined) { return manager as ManagerWrapper<ManagerDelegate>; } pointer = getPrototypeOf(pointer); } return null; } export function setComponentManager(factory: ManagerFactory<ManagerDelegate<unknown>>, obj: {}) { return setManager({ factory, type: 'component' }, obj); } export function getComponentManager<T>(obj: any): undefined | ManagerFactory<ManagerDelegate<T>> { let wrapper = getManager<ManagerDelegate<T>>(obj); if (wrapper && wrapper.type === 'component') { return wrapper.factory; } else { return undefined; } }
Remove unused `internal` slot on manager wrapper objects
Remove unused `internal` slot on manager wrapper objects
TypeScript
mit
glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js
--- +++ @@ -10,8 +10,7 @@ export interface ManagerWrapper<ManagerDelegate> { factory: ManagerFactory<ManagerDelegate>; - internal: boolean; - type: 'component' | 'modifier'; + type: 'component'; } export function setManager<ManagerDelegate>(wrapper: ManagerWrapper<ManagerDelegate>, obj: {}) { @@ -35,13 +34,13 @@ } export function setComponentManager(factory: ManagerFactory<ManagerDelegate<unknown>>, obj: {}) { - return setManager({ factory, internal: false, type: 'component' }, obj); + return setManager({ factory, type: 'component' }, obj); } export function getComponentManager<T>(obj: any): undefined | ManagerFactory<ManagerDelegate<T>> { let wrapper = getManager<ManagerDelegate<T>>(obj); - if (wrapper && !wrapper.internal && wrapper.type === 'component') { + if (wrapper && wrapper.type === 'component') { return wrapper.factory; } else { return undefined;
2a90c39bc05d253f8ddda1d11916efe0d30d9436
src/notification.type.ts
src/notification.type.ts
import { EventEmitter } from "@angular/core"; export interface Notification { id?: string type: string icon: string title?: string content?: string override?: any html?: any state?: string createdOn?: Date destroyedOn?: Date animate?: string timeOut?: number maxLength?: number pauseOnHover?: boolean clickToClose?: boolean theClass?: string click?: EventEmitter<{}>; }
import { EventEmitter } from '@angular/core'; export interface Notification { id?: string type: string icon: string title?: string content?: string override?: any html?: any state?: string createdOn?: Date destroyedOn?: Date animate?: string timeOut?: number maxLength?: number pauseOnHover?: boolean clickToClose?: boolean theClass?: string click?: EventEmitter<{}>; }
Change double quotes to single quote
Change double quotes to single quote
TypeScript
mit
flauc/angular2-notifications,flauc/angular2-notifications,flauc/angular2-notifications
--- +++ @@ -1,4 +1,4 @@ -import { EventEmitter } from "@angular/core"; +import { EventEmitter } from '@angular/core'; export interface Notification { id?: string
527b8834097e0c303cee9d59c36fa16677951819
buildutils/src/patch-release.ts
buildutils/src/patch-release.ts
/*----------------------------------------------------------------------------- | Copyright (c) Jupyter Development Team. | Distributed under the terms of the Modified BSD License. |----------------------------------------------------------------------------*/ import * as utils from './utils'; // Run pre-bump actions. utils.prebump(); // Version the desired packages const pkgs = process.argv.slice(2).join(','); if (pkgs) { const cmd = `lerna version patch -m \"New version\" --force-publish=${pkgs} --no-push`; utils.run(cmd); } // Patch the python version utils.run('bumpversion patch'); // switches to alpha utils.run('bumpversion release --allow-dirty'); // switches to rc utils.run('bumpversion release --allow-dirty'); // switches to final. // Run post-bump actions. utils.postbump();
/*----------------------------------------------------------------------------- | Copyright (c) Jupyter Development Team. | Distributed under the terms of the Modified BSD License. |----------------------------------------------------------------------------*/ import * as utils from './utils'; // Make sure we can patch release. const pyVersion = utils.getPythonVersion(); if (pyVersion.includes('a') || pyVersion.includes('rc')) { throw new Error('Can only make a patch release from a final version'); } // Run pre-bump actions. utils.prebump(); // Version the desired packages const pkgs = process.argv.slice(2).join(','); if (pkgs) { const cmd = `lerna version patch -m \"New version\" --force-publish=${pkgs} --no-push`; utils.run(cmd); } // Patch the python version utils.run('bumpversion patch'); // switches to alpha utils.run('bumpversion release --allow-dirty'); // switches to rc utils.run('bumpversion release --allow-dirty'); // switches to final. // Run post-bump actions. utils.postbump();
Add a patch release guard
Add a patch release guard
TypeScript
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -4,6 +4,12 @@ |----------------------------------------------------------------------------*/ import * as utils from './utils'; + +// Make sure we can patch release. +const pyVersion = utils.getPythonVersion(); +if (pyVersion.includes('a') || pyVersion.includes('rc')) { + throw new Error('Can only make a patch release from a final version'); +} // Run pre-bump actions. utils.prebump();
b73f719ed4935eb150d5c7ff776980468075c5c0
packages/@orbit/jsonapi/test/support/jsonapi.ts
packages/@orbit/jsonapi/test/support/jsonapi.ts
import Orbit from '@orbit/core'; export function jsonapiResponse(_options: any, body?: any, timeout?: number): Promise<Response> { let options: any; let response: Response; if (typeof _options === 'number') { options = { status: _options }; } else { options = _options || {}; } options.statusText = options.statusText || statusText(options.status); options.headers = options.headers || {}; if (body) { options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/vnd.api+json'; response = new Orbit.globals.Response(JSON.stringify(body), options); } else { response = new Orbit.globals.Response(options); } // console.log('jsonapiResponse', body, options, response.headers.get('Content-Type')); if (timeout) { return new Promise((resolve: (response: Response) => void) => { let timer = Orbit.globals.setTimeout(() => { Orbit.globals.clearTimeout(timer); resolve(response); }, timeout); }); } else { return Promise.resolve(response); } } function statusText(code: number): string { switch (code) { case 200: return 'OK'; case 201: return 'Created'; case 204: return 'No Content'; case 422: return 'Unprocessable Entity'; } }
import Orbit from '@orbit/core'; export function jsonapiResponse(_options: any, body?: any, timeout?: number): Promise<Response> { let options: any; let response: Response; if (typeof _options === 'number') { options = { status: _options }; } else { options = _options || {}; } options.statusText = options.statusText || statusText(options.status); options.headers = options.headers || {}; if (body) { options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/vnd.api+json'; response = new Orbit.globals.Response(JSON.stringify(body), options); } else { response = new Orbit.globals.Response(null, options); } // console.log('jsonapiResponse', body, options, response.headers.get('Content-Type')); if (timeout) { return new Promise((resolve: (response: Response) => void) => { let timer = Orbit.globals.setTimeout(() => { Orbit.globals.clearTimeout(timer); resolve(response); }, timeout); }); } else { return Promise.resolve(response); } } function statusText(code: number): string { switch (code) { case 200: return 'OK'; case 201: return 'Created'; case 204: return 'No Content'; case 422: return 'Unprocessable Entity'; } }
Fix generation of empty responses on tests
Fix generation of empty responses on tests The right syntax to generate a Response without a body is `new Response(new Blob(), initOpts)`. Before this changes, all those invocations were generating 200 OK responses: ``` jsonapiResponse(404) jsonapiResponse({status: 404}); jsonapiResponse({status: 404}, null); jsonapiResponse({status: 404, headers: { 'Content-Type': 'application/vnd.api+json' }, null); ```
TypeScript
mit
orbitjs/orbit.js,orbitjs/orbit-core,orbitjs/orbit.js
--- +++ @@ -16,7 +16,7 @@ options.headers['Content-Type'] = options.headers['Content-Type'] || 'application/vnd.api+json'; response = new Orbit.globals.Response(JSON.stringify(body), options); } else { - response = new Orbit.globals.Response(options); + response = new Orbit.globals.Response(null, options); } // console.log('jsonapiResponse', body, options, response.headers.get('Content-Type'));
55e0c52af846360301e59d6a973a0224bebee1be
docs/_shared/Ad.tsx
docs/_shared/Ad.tsx
import * as React from 'react'; import { loadScript } from 'utils/helpers'; import { Grid, createStyles, Theme, withStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ '@global': { '#codefund': { '& .cf-wrapper': { backgroundColor: theme.palette.type === 'dark' ? theme.palette.background.paper + '! important' : 'auto', }, '& .cf-text': { color: theme.palette.text.primary + '! important', }, }, }, }); const Ad: React.FunctionComponent = () => { React.useEffect(() => { const codefundScriptPosition = document.querySelector('#codefund-script-position'); if (codefundScriptPosition) { loadScript('https://codefund.io/properties/137/funder.js', codefundScriptPosition); } }, []); return ( <Grid container> <span id="codefund-script-position" /> <div id="codefund" /> </Grid> ); }; export default withStyles(styles)(Ad);
import * as React from 'react'; import { loadScript } from 'utils/helpers'; import { Grid, createStyles, Theme, withStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ '@global': { '#codefund': { '& .cf-wrapper': { backgroundColor: theme.palette.type === 'dark' ? theme.palette.background.paper + '! important' : 'auto', }, '& .cf-text': { color: theme.palette.text.primary + '! important', }, }, }, }); const Ad: React.FunctionComponent = () => { React.useEffect(() => { const codefundScriptPosition = document.querySelector('#codefund-script-position'); if (codefundScriptPosition) { loadScript('https://codefund.io/properties/197/funder.js', codefundScriptPosition); } }, []); return ( <Grid container> <span id="codefund-script-position" /> <div id="codefund" /> </Grid> ); }; export default withStyles(styles)(Ad);
Fix incorrect id in codefund script
Fix incorrect id in codefund script
TypeScript
mit
oliviertassinari/material-ui,dmtrKovalenko/material-ui-pickers,callemall/material-ui,mbrookes/material-ui,callemall/material-ui,oliviertassinari/material-ui,rscnt/material-ui,rscnt/material-ui,callemall/material-ui,oliviertassinari/material-ui,mbrookes/material-ui,mui-org/material-ui,callemall/material-ui,mui-org/material-ui,dmtrKovalenko/material-ui-pickers,mbrookes/material-ui,rscnt/material-ui,mui-org/material-ui
--- +++ @@ -22,7 +22,7 @@ const codefundScriptPosition = document.querySelector('#codefund-script-position'); if (codefundScriptPosition) { - loadScript('https://codefund.io/properties/137/funder.js', codefundScriptPosition); + loadScript('https://codefund.io/properties/197/funder.js', codefundScriptPosition); } }, []);
09fcc980bd4ab85a39750d38db7eac8406e7c771
index.d.ts
index.d.ts
// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz> // Leon Yu <https://github.com/leonyu> // BendingBender <https://github.com/BendingBender> // Maple Miao <https://github.com/mapleeit> /// <reference types="node" /> import * as stream from 'stream'; import * as http from 'http'; export = FormData; declare class FormData extends stream.Readable { append(key: string, value: any, options?: FormData.AppendOptions | string): void; getHeaders(): FormData.Headers; submit( params: string | FormData.SubmitOptions, callback?: (error: Error | undefined, response: http.IncomingMessage) => void ): http.ClientRequest; getBuffer(): Buffer; getBoundary(): string; getLength(callback: (err: Error | undefined, length: number) => void): void; getLengthSync(): number; hasKnownLength(): boolean; } declare namespace FormData { interface Headers { [key: string]: any; } interface AppendOptions { header?: string | Headers; knownLength?: number; filename?: string; filepath?: string; contentType?: string; } interface SubmitOptions extends http.RequestOptions { protocol?: 'https:' | 'http:'; } }
// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz> // Leon Yu <https://github.com/leonyu> // BendingBender <https://github.com/BendingBender> // Maple Miao <https://github.com/mapleeit> /// <reference types="node" /> import * as stream from 'stream'; import * as http from 'http'; export = FormData; declare class FormData extends stream.Readable { append(key: string, value: any, options?: FormData.AppendOptions | string): void; getHeaders(): FormData.Headers; submit( params: string | FormData.SubmitOptions, callback?: (error: Error | null, response: http.IncomingMessage) => void ): http.ClientRequest; getBuffer(): Buffer; getBoundary(): string; getLength(callback: (err: Error | null, length: number) => void): void; getLengthSync(): number; hasKnownLength(): boolean; } declare namespace FormData { interface Headers { [key: string]: any; } interface AppendOptions { header?: string | Headers; knownLength?: number; filename?: string; filepath?: string; contentType?: string; } interface SubmitOptions extends http.RequestOptions { protocol?: 'https:' | 'http:'; } }
Fix error in callback signatures
Fix error in callback signatures The functions actually give `null` as the error parameter, and not `undefined`. Without this, `util.promisify` can't be typed correctly on these functions as it expects the callback to receive `Error | null`.
TypeScript
mit
form-data/form-data,felixge/node-form-data
--- +++ @@ -14,11 +14,11 @@ getHeaders(): FormData.Headers; submit( params: string | FormData.SubmitOptions, - callback?: (error: Error | undefined, response: http.IncomingMessage) => void + callback?: (error: Error | null, response: http.IncomingMessage) => void ): http.ClientRequest; getBuffer(): Buffer; getBoundary(): string; - getLength(callback: (err: Error | undefined, length: number) => void): void; + getLength(callback: (err: Error | null, length: number) => void): void; getLengthSync(): number; hasKnownLength(): boolean; }
b16da0bdd9690b8d3af3e70862ec4757ea4b95b8
src/knockout-decorator.ts
src/knockout-decorator.ts
/*! * Knockout decorator * (c) vario * License: MIT (http://www.opensource.org/licenses/mit-license.php) */ namespace variotry.KnockoutDecorator { var storeObservableKey = "__vtKnockoutObservables__"; export function observable( target:any, propertyKey:string ) { var v = target[propertyKey]; var o = ko.observable( v ); Object.defineProperty( target, propertyKey, { get: () => o(), set: ( v ) => o( v ) }); var d = Object.getOwnPropertyDescriptor( target, propertyKey ); } export function observableArray() { } export function computed() { } }
/*! * Knockout decorator * (c) vario * License: MIT (http://www.opensource.org/licenses/mit-license.php) */ namespace variotry.KnockoutDecorator { var storeObservableKey = "__vtKnockoutObservables__"; function pushObservable( target: any, propertyKey: string, o: KnockoutObservable<any> | KnockoutComputed<any> ) { if ( !target[storeObservableKey] ) target[storeObservableKey] = []; var store = target[storeObservableKey]; store[propertyKey] = o; } export function observable( target:any, propertyKey:string ) : void { var v = target[propertyKey]; var o = ko.observable( v ); pushObservable( target, propertyKey, o ); Object.defineProperty( target, propertyKey, { get: o, set: o }); } export function observableArray( target: any, propertyKey: string ): void { /*var v = target[propertyKey]; var o = ko.observableArray();*/ } export function computed(): MethodDecorator export function computed( extend: { [key: string]: any }): MethodDecorator; export function computed( extend?: { [key: string]: any }): MethodDecorator { return ( target: any, propertyKey: string, descriptor: PropertyDescriptor ) => { var getter = descriptor.get; var setter = descriptor.set; var c = ko.computed( { read: () => getter.call( target ), write: setter ? ( v ) => setter.call( target, v ) : null }); if ( extend ) { c.extend( extend ); } pushObservable( target, propertyKey, c ); descriptor.get = c; if ( setter ) { descriptor.set = c; } } } }
Implement computed decorator. Improved observable decorator.
Implement computed decorator. Improved observable decorator.
TypeScript
mit
variotry/knockout-decorator,variotry/knockout-decorator
--- +++ @@ -7,20 +7,57 @@ namespace variotry.KnockoutDecorator { var storeObservableKey = "__vtKnockoutObservables__"; - export function observable( target:any, propertyKey:string ) + function pushObservable( target: any, propertyKey: string, o: KnockoutObservable<any> | KnockoutComputed<any> ) + { + if ( !target[storeObservableKey] ) target[storeObservableKey] = []; + + var store = target[storeObservableKey]; + store[propertyKey] = o; + } + + export function observable( target:any, propertyKey:string ) : void { var v = target[propertyKey]; var o = ko.observable( v ); + pushObservable( target, propertyKey, o ); Object.defineProperty( target, propertyKey, { - get: () => o(), - set: ( v ) => o( v ) + get: o, + set: o }); - var d = Object.getOwnPropertyDescriptor( target, propertyKey ); } - export function observableArray() + + export function observableArray( target: any, propertyKey: string ): void { + /*var v = target[propertyKey]; + var o = ko.observableArray();*/ } - export function computed() + + export function computed(): MethodDecorator + export function computed( extend: { [key: string]: any }): MethodDecorator; + export function computed( extend?: { [key: string]: any }): MethodDecorator { + return ( target: any, propertyKey: string, descriptor: PropertyDescriptor ) => + { + var getter = descriptor.get; + var setter = descriptor.set; + + var c = ko.computed( { + read: () => getter.call( target ), + write: setter ? ( v ) => setter.call( target, v ) : null + }); + + if ( extend ) + { + c.extend( extend ); + } + + pushObservable( target, propertyKey, c ); + + descriptor.get = c; + if ( setter ) + { + descriptor.set = c; + } + } } }
8f55a45f2a60dae53f1bb2b5e9476e4fa68aa5f8
index.d.ts
index.d.ts
import { Observable, components } from 'knockout'; export function setState<T>(state: T): void; export function getState<T>(): Observable<T>; interface ViewModelFactoryFunction { (params?: components.ViewModelParams): components.ViewModel; } interface ViewModelInstantiator extends components.ViewModelConstructor, ViewModelFactoryFunction {} interface MapStateToParamsFn { ( state?: any, ownParams?: components.ViewModelParams ): components.ViewModelParams; } interface MergeParamsFn { ( stateParams: components.ViewModelParams, ownParams: components.ViewModelParams ): components.ViewModelParams; } export function connect( mapStateToParams?: MapStateToParamsFn | null, mergeParams?: MergeParamsFn | null ): ( viewModel: components.ViewModelConstructor | ViewModelFactoryFunction ) => ViewModelInstantiator;
import { Observable, components } from 'knockout'; export function setState<T>(state: T): void; export function getState<T>(): Observable<T>; interface ViewModelFactoryFunction { (params?: components.ViewModelParams): components.ViewModel; } interface ViewModelInstantiator extends components.ViewModelConstructor, ViewModelFactoryFunction {} interface MapStateToParamsFn { <T>( state?: T, ownParams?: components.ViewModelParams ): components.ViewModelParams; } interface MergeParamsFn { ( stateParams: components.ViewModelParams, ownParams: components.ViewModelParams ): components.ViewModelParams; } export function connect( mapStateToParams?: MapStateToParamsFn | null, mergeParams?: MergeParamsFn | null ): ( viewModel: components.ViewModelConstructor | ViewModelFactoryFunction ) => ViewModelInstantiator;
Define MapStateToParamsFn interface with a generic
Define MapStateToParamsFn interface with a generic
TypeScript
mit
Spreetail/knockout-store
--- +++ @@ -13,8 +13,8 @@ ViewModelFactoryFunction {} interface MapStateToParamsFn { - ( - state?: any, + <T>( + state?: T, ownParams?: components.ViewModelParams ): components.ViewModelParams; }
48ec31a2804785072605a247b9dae9f430e6e8f0
src/Settings.ts
src/Settings.ts
// The purpose of this unpleasant hack is to make both `parsing` and `rendering` // settings optional, while still requiring that at least one of the two be provided. export type Settings = { parsing?: Settings.Parsing rendering: Settings.Rendering } | { parsing: Settings.Parsing rendering?: Settings.Rendering } export namespace Settings { export interface Parsing extends SpecializedSettings { createSourceMap?: boolean defaultUrlScheme?: string baseForUrlsStartingWithSlash?: string baseForUrlsStartingWithHashMark?: string fancyEllipsis?: string keywords?: Parsing.Keywords } export namespace Parsing { export interface Keywords { audio?: Keyword image?: Keyword revealable?: Keyword sectionLink?: Keyword table?: Keyword video?: Keyword } export type Keyword = string[] | string } export interface Rendering extends SpecializedSettings { idPrefix?: string renderDangerousContent?: boolean terms?: Rendering.Terms } export namespace Rendering { export interface Terms { footnote?: Term footnoteReference?: Term hide?: Term reveal?: Term sectionReferencedByTableOfContents?: Term } export type Term = string } } // This is another hack to work around TypeScript's type system. // // Both `Settings.Parsing` and `Settings.Rendering` interfaces only have optional // fields. This unfortunately means they're satisfied by every type, including the // `Settings` interface! // // We want to prevent users from accidentally passing `Settings` to a method that // expects `Settings.Parsing` or `Settings.Rendering`. // // Our solution is to extend the `SpecializedSettings` interface, which is incompatible // with `Settings`. export interface SpecializedSettings { rendering?: DoNotProvide parsing?: DoNotProvide } export interface DoNotProvide { DO_NOT_PROVIDE(): void }
// The purpose of this unpleasant hack is to make both `parsing` and `rendering` // settings optional, while still requiring that at least one of the two be provided. export type Settings = { parsing?: Settings.Parsing rendering: Settings.Rendering } | { parsing: Settings.Parsing rendering?: Settings.Rendering } export namespace Settings { export interface Parsing { createSourceMap?: boolean defaultUrlScheme?: string baseForUrlsStartingWithSlash?: string baseForUrlsStartingWithHashMark?: string fancyEllipsis?: string keywords?: Parsing.Keywords } export namespace Parsing { export interface Keywords { audio?: Keyword image?: Keyword revealable?: Keyword sectionLink?: Keyword table?: Keyword video?: Keyword } export type Keyword = string[] | string } export interface Rendering { idPrefix?: string renderDangerousContent?: boolean terms?: Rendering.Terms } export namespace Rendering { export interface Terms { footnote?: Term footnoteReference?: Term hide?: Term reveal?: Term sectionReferencedByTableOfContents?: Term } export type Term = string } }
Remove hack solved by TypeScript 2.4's weak types
Remove hack solved by TypeScript 2.4's weak types
TypeScript
mit
start/up,start/up
--- +++ @@ -10,7 +10,7 @@ } export namespace Settings { - export interface Parsing extends SpecializedSettings { + export interface Parsing { createSourceMap?: boolean defaultUrlScheme?: string baseForUrlsStartingWithSlash?: string @@ -33,7 +33,7 @@ } - export interface Rendering extends SpecializedSettings { + export interface Rendering { idPrefix?: string renderDangerousContent?: boolean terms?: Rendering.Terms @@ -51,24 +51,3 @@ export type Term = string } } - - -// This is another hack to work around TypeScript's type system. -// -// Both `Settings.Parsing` and `Settings.Rendering` interfaces only have optional -// fields. This unfortunately means they're satisfied by every type, including the -// `Settings` interface! -// -// We want to prevent users from accidentally passing `Settings` to a method that -// expects `Settings.Parsing` or `Settings.Rendering`. -// -// Our solution is to extend the `SpecializedSettings` interface, which is incompatible -// with `Settings`. -export interface SpecializedSettings { - rendering?: DoNotProvide - parsing?: DoNotProvide -} - -export interface DoNotProvide { - DO_NOT_PROVIDE(): void -}
74365c9bacfd62c51c89924015d83db533d7291a
cypress/integration/knobs.spec.ts
cypress/integration/knobs.spec.ts
import { clickAddon, visit } from '../helper'; describe('Knobs', () => { beforeEach(() => { visit('official-storybook/?path=/story/addons-knobs-withknobs--tweaks-static-values'); }); it('[text] it should change a string value', () => { clickAddon('Knobs'); cy.get('#Name').clear().type('John Doe'); cy.getStoryElement() .console('info') .find('p') .eq(0) .should('contain.text', 'My name is John Doe'); }); });
import { clickAddon, visit } from '../helper'; describe('Knobs', () => { beforeEach(() => { visit('official-storybook/?path=/story/addons-knobs-withknobs--tweaks-static-values'); }); it('[text] it should change a string value', () => { clickAddon('Knobs'); cy.get('#Name').clear().type('John Doe'); cy.getStoryElement() .console('info') .wait(3000) .find('p') .eq(0) .should('contain.text', 'My name is John Doe'); }); });
ADD a cypress .wait to wait for knobs to have taken effect
ADD a cypress .wait to wait for knobs to have taken effect
TypeScript
mit
storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook
--- +++ @@ -12,6 +12,7 @@ cy.getStoryElement() .console('info') + .wait(3000) .find('p') .eq(0) .should('contain.text', 'My name is John Doe');
2a0151d2e0b1bf9cf9f25f357df93d6fbc6aa9f5
src/dependument.ts
src/dependument.ts
export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } } }
export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } this.source = source; this.output = output; } }
Store source and output paths
Store source and output paths
TypeScript
unlicense
Jameskmonger/dependument,Jameskmonger/dependument,dependument/dependument,dependument/dependument
--- +++ @@ -10,5 +10,8 @@ if (!options.output) { throw new Error("No output path specified in options"); } + + this.source = source; + this.output = output; } }
51d4fe0839983b20f46cb37bc5a52135d6b92f4c
source/WebApp/app/code/code-editor/useServerOptions.ts
source/WebApp/app/code/code-editor/useServerOptions.ts
import { useEffect, useMemo, useState } from 'react'; import type { ServerOptions } from '../../../ts/types/server-options'; import { useOption } from '../../shared/useOption'; export const useServerOptions = ({ initialCached }: { initialCached: boolean }): ServerOptions => { const branch = useOption('branch'); const release = useOption('release'); const target = useOption('target'); const [wasCached, setWasCached] = useState(false); useEffect(() => { // can only happen to first result if (initialCached) setWasCached(true); }, [initialCached]); const noCache = wasCached && (!branch || branch.sharplab?.supportsUnknownOptions); return useMemo(() => ({ 'x-optimize': release ? 'release' : 'debug', 'x-target': target, ...(noCache ? { 'x-no-cache': true } : {}) }), [release, target, noCache]); };
import { useEffect, useMemo, useState } from 'react'; import type { ServerOptions } from '../../../ts/types/server-options'; import { useOption } from '../../shared/useOption'; export const useServerOptions = ({ initialCached }: { initialCached: boolean }): ServerOptions => { const branch = useOption('branch'); const release = useOption('release'); const target = useOption('target'); const [wasCached, setWasCached] = useState(initialCached); useEffect(() => { // can only happen to first result if (initialCached) setWasCached(true); }, [initialCached]); const noCache = wasCached && (!branch || branch.sharplab?.supportsUnknownOptions); return useMemo(() => ({ 'x-optimize': release ? 'release' : 'debug', 'x-target': target, ...(noCache ? { 'x-no-cache': true } : {}) }), [release, target, noCache]); };
Fix server options recalculating unnecessarily
Fix server options recalculating unnecessarily
TypeScript
bsd-2-clause
ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab
--- +++ @@ -6,7 +6,7 @@ const branch = useOption('branch'); const release = useOption('release'); const target = useOption('target'); - const [wasCached, setWasCached] = useState(false); + const [wasCached, setWasCached] = useState(initialCached); useEffect(() => { // can only happen to first result
eddbc0f6c5b6d9f5ac6883fe99378cbf736f52a6
lib/components/src/Button/Button.stories.tsx
lib/components/src/Button/Button.stories.tsx
import React from 'react'; import { storiesOf } from '@storybook/react'; import { Button } from './Button'; import { Icons } from '../icon/icon'; import { Form } from '../form/index'; const { Button: FormButton } = Form; storiesOf('Basics/Button', module).add('all buttons', () => ( <div> <p>Button that is used for forms</p> <FormButton>Form.Button</FormButton> <br /> <p>Buttons that are used for everything else</p> <Button primary>Primary</Button> <Button secondary>Secondary</Button> <Button outline containsIcon title="link"> <Icons icon="link" /> </Button> <br /> <Button outline>Outline</Button> <Button outline primary> Outline primary </Button> <Button outline secondary> Outline secondary </Button> <Button primary disabled> Disabled </Button> <br /> <Button primary small> Primary </Button> <Button secondary small> Secondary </Button> <Button outline small> Outline </Button> <Button primary disabled small> Disabled </Button> <Button outline small containsIcon title="link"> <Icons icon="link" /> </Button> <Button outline small> <Icons icon="link" /> Link </Button> </div> ));
import React from 'react'; import { storiesOf } from '@storybook/react'; import { Button } from './Button'; import { Icons } from '../icon/icon'; import { Form } from '../form/index'; const { Button: FormButton } = Form; storiesOf('Basics/Button', module).add('all buttons', () => ( <div> <p>Button that is used for forms</p> <FormButton>Form.Button</FormButton> <br /> <p>Buttons that are used for everything else</p> <Button primary>Primary</Button> <Button secondary>Secondary</Button> <Button outline containsIcon title="link"> <Icons icon="link" /> </Button> <br /> <Button outline>Outline</Button> <Button outline primary> Outline primary </Button> <Button outline secondary> Outline secondary </Button> <Button primary disabled> Disabled </Button> <br /> <Button primary small> Primary </Button> <Button secondary small> Secondary </Button> <Button gray small> Secondary </Button> <Button outline small> Outline </Button> <Button primary disabled small> Disabled </Button> <Button outline small containsIcon title="link"> <Icons icon="link" /> </Button> <Button outline small> <Icons icon="link" /> Link </Button> </div> ));
ADD gray button to story
ADD gray button to story
TypeScript
mit
storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook
--- +++ @@ -36,6 +36,9 @@ <Button secondary small> Secondary </Button> + <Button gray small> + Secondary + </Button> <Button outline small> Outline </Button>
805b65c408b99bdd87f9ff1ea33a6037ea17aaf8
src/active/active.ts
src/active/active.ts
import * as Logger from "../logging/logger"; interface ActiveUsers { [channelName: string]: { [userId: string]: number; }[]; } export class Active { activeUsers: ActiveUsers; activeTime: number; constructor(activeTime?: number) { if (activeTime != null) { this.activeTime = 4; } else { this.activeTime = activeTime; } } addUser(uuid: string, channel: string) { this.activeUsers[channel].push({ uuid: 0 }); } deleteUser(uuid: string, channel: string) { // TODO } watch() { let time = new Date().getTime(); } }
import * as Logger from "../logging/logger"; interface ActiveUsers { [channelName: string]: { [userId: string]: number; }; } export class Active { activeUsers: ActiveUsers; activeTime: number; constructor(activeTime?: number) { if (activeTime != null) { this.activeTime = 4; } else { this.activeTime = activeTime; } } addUser(uuid: string, channel: string) { this.activeUsers[channel][uuid] = 0; Logger.debug(`Added ${uuid} to ${channel}`); } deleteUser(uuid: string, channel: string) { Object.keys(this.activeUsers).forEach(channelName => { if (channelName === channel) { Object.keys(channel).forEach(user => delete this.activeUsers[channel][user]); } }); Logger.debug(`Removed ${uuid} from ${channel}`); } watch() { let time = new Date().getTime(); } }
Fix adding / removing users (Thanks @UnwrittenFun)
Fix adding / removing users (Thanks @UnwrittenFun)
TypeScript
mit
CactusBot/Sepal,CactusDev/Sepal,CactusDev/Sepal
--- +++ @@ -4,7 +4,7 @@ interface ActiveUsers { [channelName: string]: { [userId: string]: number; - }[]; + }; } export class Active { @@ -20,11 +20,17 @@ } addUser(uuid: string, channel: string) { - this.activeUsers[channel].push({ uuid: 0 }); + this.activeUsers[channel][uuid] = 0; + Logger.debug(`Added ${uuid} to ${channel}`); } deleteUser(uuid: string, channel: string) { - // TODO + Object.keys(this.activeUsers).forEach(channelName => { + if (channelName === channel) { + Object.keys(channel).forEach(user => delete this.activeUsers[channel][user]); + } + }); + Logger.debug(`Removed ${uuid} from ${channel}`); } watch() {
8b34294c9731ef56e787e4485a52f958d6655243
ts/types/MIME.ts
ts/types/MIME.ts
export type MIMEType = string & { _mimeTypeBrand: any }; export const APPLICATION_OCTET_STREAM = 'application/octet-stream' as MIMEType; export const APPLICATION_JSON = 'application/json' as MIMEType; export const AUDIO_AAC = 'audio/aac' as MIMEType; export const AUDIO_MP3 = 'audio/mp3' as MIMEType; export const IMAGE_GIF = 'image/gif' as MIMEType; export const IMAGE_JPEG = 'image/jpeg' as MIMEType; export const IMAGE_PNG = 'image/png' as MIMEType; export const IMAGE_WEBP = 'image/webp' as MIMEType; export const IMAGE_PNG = 'image/png' as MIMEType; export const VIDEO_MP4 = 'video/mp4' as MIMEType; export const VIDEO_QUICKTIME = 'video/quicktime' as MIMEType; export const LONG_MESSAGE = 'text/x-signal-plain' as MIMEType; export const isJPEG = (value: MIMEType): boolean => value === 'image/jpeg'; export const isImage = (value: MIMEType): boolean => value && value.startsWith('image/'); export const isVideo = (value: MIMEType): boolean => value && value.startsWith('video/'); // As of 2020-04-16 aif files do not play in Electron nor Chrome. We should only // recognize them as file attachments. export const isAudio = (value: MIMEType): boolean => value && value.startsWith('audio/') && !value.endsWith('aiff');
export type MIMEType = string & { _mimeTypeBrand: any }; export const APPLICATION_OCTET_STREAM = 'application/octet-stream' as MIMEType; export const APPLICATION_JSON = 'application/json' as MIMEType; export const AUDIO_AAC = 'audio/aac' as MIMEType; export const AUDIO_MP3 = 'audio/mp3' as MIMEType; export const IMAGE_GIF = 'image/gif' as MIMEType; export const IMAGE_JPEG = 'image/jpeg' as MIMEType; export const IMAGE_PNG = 'image/png' as MIMEType; export const IMAGE_WEBP = 'image/webp' as MIMEType; export const VIDEO_MP4 = 'video/mp4' as MIMEType; export const VIDEO_QUICKTIME = 'video/quicktime' as MIMEType; export const LONG_MESSAGE = 'text/x-signal-plain' as MIMEType; export const isJPEG = (value: MIMEType): boolean => value === 'image/jpeg'; export const isImage = (value: MIMEType): boolean => value && value.startsWith('image/'); export const isVideo = (value: MIMEType): boolean => value && value.startsWith('video/'); // As of 2020-04-16 aif files do not play in Electron nor Chrome. We should only // recognize them as file attachments. export const isAudio = (value: MIMEType): boolean => value && value.startsWith('audio/') && !value.endsWith('aiff');
Fix merge conflict in Mime.ts
Fix merge conflict in Mime.ts
TypeScript
agpl-3.0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
--- +++ @@ -8,7 +8,6 @@ export const IMAGE_JPEG = 'image/jpeg' as MIMEType; export const IMAGE_PNG = 'image/png' as MIMEType; export const IMAGE_WEBP = 'image/webp' as MIMEType; -export const IMAGE_PNG = 'image/png' as MIMEType; export const VIDEO_MP4 = 'video/mp4' as MIMEType; export const VIDEO_QUICKTIME = 'video/quicktime' as MIMEType; export const LONG_MESSAGE = 'text/x-signal-plain' as MIMEType;
deb0e207566bf5e0326393bc4f67307bba739928
src/app.ts
src/app.ts
import { createServer } from 'restify'; import { BotConnectorBot } from 'botbuilder'; const appId = process.env['BF_APP_ID']; const appSecret = process.env['BF_APP_SECRET']; const bot = new BotConnectorBot({ appId, appSecret }); bot.add('/', (session) => session.send('Hello World')); const server = createServer(); server.post('/api/messages', bot.verifyBotFramework(), bot.listen()); server.get('/hello', (req, res, next) => res.send('Hello World!')); server.listen(process.env.port || 3978, () => console.log('%s listening to %s', server.name, server.url));
import { createServer } from 'restify'; import { BotConnectorBot } from 'botbuilder'; const appId = process.env['BF_APP_ID']; const appSecret = process.env['BF_APP_SECRET']; const bot = new BotConnectorBot({ appId, appSecret }); bot.add('/', (session) => session.send('Hello World')); const server = createServer(); server.post('/api/messages', bot.verifyBotFramework(), bot.listen()); server.get('/hello', (req, res, next) => res.send('Hello World!')); server.listen(process.env.PORT || 3978, () => console.log('%s listening to %s', server.name, server.url));
Use process.env.PORT instead of process.env.port
Use process.env.PORT instead of process.env.port
TypeScript
mit
duncanmak/mr-robot
--- +++ @@ -11,4 +11,4 @@ server.post('/api/messages', bot.verifyBotFramework(), bot.listen()); server.get('/hello', (req, res, next) => res.send('Hello World!')); -server.listen(process.env.port || 3978, () => console.log('%s listening to %s', server.name, server.url)); +server.listen(process.env.PORT || 3978, () => console.log('%s listening to %s', server.name, server.url));
44e00efc13823b5e739029a3dd455ceff0acf597
src/telemetry.ts
src/telemetry.ts
'use strict'; import { RestClientSettings } from './models/configurationSettings'; import * as Constants from './constants'; import * as appInsights from "applicationinsights"; appInsights.setup(Constants.AiKey) .setAutoCollectDependencies(false) .setAutoCollectPerformance(false) .setAutoCollectRequests(false) .setAutoDependencyCorrelation(false) .start(); export class Telemetry { private static readonly restClientSettings: RestClientSettings = new RestClientSettings(); public static sendEvent(eventName: string, properties?: { [key: string]: string }) { try { if (Telemetry.restClientSettings.enableTelemetry) { appInsights.defaultClient.trackEvent({name: eventName, properties}); } } catch { } } }
'use strict'; import { RestClientSettings } from './models/configurationSettings'; import * as Constants from './constants'; import * as appInsights from "applicationinsights"; appInsights.setup(Constants.AiKey) .setAutoCollectDependencies(false) .setAutoCollectExceptions(false) .setAutoCollectPerformance(false) .setAutoCollectRequests(false) .setAutoCollectDependencies(false) .setAutoDependencyCorrelation(false) .start(); export class Telemetry { private static readonly restClientSettings: RestClientSettings = new RestClientSettings(); public static sendEvent(eventName: string, properties?: { [key: string]: string }) { try { if (Telemetry.restClientSettings.enableTelemetry) { appInsights.defaultClient.trackEvent({name: eventName, properties}); } } catch { } } }
Disable collect exceptions and dependencies
Disable collect exceptions and dependencies
TypeScript
mit
Huachao/vscode-restclient,Huachao/vscode-restclient
--- +++ @@ -6,8 +6,10 @@ appInsights.setup(Constants.AiKey) .setAutoCollectDependencies(false) + .setAutoCollectExceptions(false) .setAutoCollectPerformance(false) .setAutoCollectRequests(false) + .setAutoCollectDependencies(false) .setAutoDependencyCorrelation(false) .start();
43b3f1d78e5e29cdd87127c57affa4fcf6e2e2a5
src/get.ts
src/get.ts
import { ReadConverter } from '../types/index' import { readValue } from './converter' type GetReturn<T> = [T] extends [undefined] ? object & { [property: string]: string } : string | undefined export default function <T extends string | undefined>( key: T, converter: ReadConverter = readValue ): GetReturn<T> { // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. const cookies: string[] = document.cookie.length > 0 ? document.cookie.split('; ') : [] const jar: any = {} for (let i = 0; i < cookies.length; i++) { const parts: string[] = cookies[i].split('=') let value: string = parts.slice(1).join('=') if (value[0] === '"') { value = value.slice(1, -1) } try { const foundKey: string = readValue(parts[0]) jar[foundKey] = converter(value, foundKey) if (key === foundKey) { break } } catch (e) {} } return key != null ? jar[key] : jar }
import { ReadConverter } from '../types/index' import { readValue } from './converter' type GetReturn<T> = [T] extends [undefined] ? object & { [property: string]: string } : string | undefined export default function <T extends string | undefined>( key: T, converter: ReadConverter = readValue ): GetReturn<T> { // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. const cookies: string[] = document.cookie.length > 0 ? document.cookie.split('; ') : [] const jar: any = {} for (let i = 0; i < cookies.length; i++) { const parts: string[] = cookies[i].split('=') let value: string = parts.slice(1).join('=') if (value[0] === '"') { value = value.slice(1, -1) } try { const foundKey: string = decodeURIComponent(parts[0]) jar[foundKey] = converter(value, foundKey) if (key === foundKey) { break } } catch (e) {} } return key != null ? jar[key] : jar }
Use decodeURIComponent() for reading key
Use decodeURIComponent() for reading key `readValue()` appeared to be confusing...
TypeScript
mit
carhartl/js-cookie,carhartl/js-cookie
--- +++ @@ -23,7 +23,7 @@ } try { - const foundKey: string = readValue(parts[0]) + const foundKey: string = decodeURIComponent(parts[0]) jar[foundKey] = converter(value, foundKey) if (key === foundKey) {
7d458f2f0753f0c55b27a0e4059770163d877f97
src/umd.ts
src/umd.ts
import expect from './index'; export default expect;
/* * This file exists purely to ensure that there is a single entry point * for the UMD build. It should do nothing more than import 'expect' * and re-export it as the default export with no other named exports. */ import expect from './index'; export default expect;
Add comment explaining purpose of file
Add comment explaining purpose of file
TypeScript
mit
dylanparry/ceylon,dylanparry/ceylon
--- +++ @@ -1,3 +1,9 @@ +/* + * This file exists purely to ensure that there is a single entry point + * for the UMD build. It should do nothing more than import 'expect' + * and re-export it as the default export with no other named exports. + */ + import expect from './index'; export default expect;
16e28245a8fd113ce648a0b062587e4c244cebdd
src/app/login/login.component.ts
src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; import { Router } from '@angular/router'; //import { AuthHttp } from 'angular2-jwt'; import { contentHeaders } from '../common/headers'; import { confignjs} from '../members/config'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['..//members/members.component.css'] }) export class LoginComponent implements OnInit { constructor(public router: Router,public http: Http) { } someData: string; login(event, username, password) { event.preventDefault(); let h = confignjs.hostlocal; this.someData="init:"; let body = JSON.stringify({ username, password }); this.http.post(h + '/sessions/login', body, { headers: contentHeaders }) .subscribe( response => { localStorage.setItem('id_token', response.json().id_token); this.someData="ok"; this.router.navigate(['/members']); }, error => { this.someData = "error: " + error.text(); console.log(error.text()); } ); } ngOnInit() { } }
import { Component, OnInit, AfterViewInit, ViewChild, ViewChildren } from '@angular/core'; import { Http } from '@angular/http'; import { Router } from '@angular/router'; //import { AuthHttp } from 'angular2-jwt'; import { contentHeaders } from '../common/headers'; import { confignjs} from '../members/config'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['..//members/members.component.css'] }) export class LoginComponent implements OnInit, AfterViewInit { @ViewChildren('username') vc; someData: string; constructor(public router: Router,public http: Http) { } login(event, username, password) { event.preventDefault(); let h = confignjs.hostlocal; this.someData="init:"; let body = JSON.stringify({ username, password }); this.http.post(h + '/sessions/login', body, { headers: contentHeaders }) .subscribe( response => { localStorage.setItem('id_token', response.json().id_token); this.someData="ok"; this.router.navigate(['/members']); }, error => { this.someData = "error: " + error.text(); console.log(error.text()); } ); } ngOnInit() { } ngAfterViewInit() { this.vc.first.nativeElement.focus(); } }
Set focus to username on login page
Set focus to username on login page
TypeScript
mit
secularHub/MembersApp,secularHub/MembersApp,secularHub/MembersApp
--- +++ @@ -1,4 +1,4 @@ -import { Component, OnInit } from '@angular/core'; +import { Component, OnInit, AfterViewInit, ViewChild, ViewChildren } from '@angular/core'; import { Http } from '@angular/http'; import { Router } from '@angular/router'; //import { AuthHttp } from 'angular2-jwt'; @@ -12,10 +12,12 @@ styleUrls: ['..//members/members.component.css'] }) -export class LoginComponent implements OnInit { +export class LoginComponent implements OnInit, AfterViewInit { + @ViewChildren('username') vc; + someData: string; constructor(public router: Router,public http: Http) { } - someData: string; + login(event, username, password) { event.preventDefault(); let h = confignjs.hostlocal; @@ -37,5 +39,7 @@ } ngOnInit() { } - + ngAfterViewInit() { + this.vc.first.nativeElement.focus(); + } }
00dda7aba47e7d785e11ec860cf40046a72f397a
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular/src/tests/share-service.spec.ts
src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular/src/tests/share-service.spec.ts
import { } from 'jasmine'; import { async, inject } from '@angular/core/testing'; import { configureTest } from './config'; import { ContentService, ShareService, ContentSearchRequest, ShareContent, ShareBasicCreateRequest, OutputAccess } from '../lib/api-services'; describe('ShareService', () => { beforeEach(configureTest); it('should create embed share', async(inject([ContentService, ShareService], async (contentService: ContentService, shareService: ShareService) => { // arrange const request = new ContentSearchRequest(); request.searchString = 'm'; const response = await contentService.search(request).toPromise(); // act const contents = response.results.map(i => new ShareContent({ contentId: i.id, outputFormatIds: ['Original'] })); const result = await shareService.create( null, new ShareBasicCreateRequest({ name: 'Share', languageCode: 'en', contents: contents, outputAccess: OutputAccess.Full, suppressNotifications: false })).toPromise(); const share = await shareService.get(result.shareId!).toPromise(); // assert expect(result.shareId).not.toBeNull(); expect(share.id).toEqual(result.shareId!); }))); });
import { } from 'jasmine'; import { async, inject } from '@angular/core/testing'; import { configureTest } from './config'; import { ContentService, ShareService, ContentSearchRequest, ShareContent, ShareBasicCreateRequest, OutputAccess } from '../lib/api-services'; describe('ShareService', () => { beforeEach(configureTest); // [TODO] reenable this test // it('should create embed share', async(inject([ContentService, ShareService], // async (contentService: ContentService, shareService: ShareService) => { // // arrange // const request = new ContentSearchRequest(); // request.searchString = 'm'; // const response = await contentService.search(request).toPromise(); // // act // const contents = response.results.map(i => new ShareContent({ // contentId: i.id, // outputFormatIds: ['Original'] // })); // const result = await shareService.create( null, new ShareBasicCreateRequest({ // name: 'Share', // languageCode: 'en', // contents: contents, // outputAccess: OutputAccess.Full, // suppressNotifications: false // })).toPromise(); // const share = await shareService.get(result.shareId!).toPromise(); // // assert // expect(result.shareId).not.toBeNull(); // expect(share.id).toEqual(result.shareId!); // }))); });
Disable testing for sharing service
Disable testing for sharing service
TypeScript
mit
Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript
--- +++ @@ -7,32 +7,33 @@ describe('ShareService', () => { beforeEach(configureTest); - it('should create embed share', async(inject([ContentService, ShareService], - async (contentService: ContentService, shareService: ShareService) => { - // arrange - const request = new ContentSearchRequest(); - request.searchString = 'm'; + // [TODO] reenable this test + // it('should create embed share', async(inject([ContentService, ShareService], + // async (contentService: ContentService, shareService: ShareService) => { + // // arrange + // const request = new ContentSearchRequest(); + // request.searchString = 'm'; - const response = await contentService.search(request).toPromise(); + // const response = await contentService.search(request).toPromise(); - // act - const contents = response.results.map(i => new ShareContent({ - contentId: i.id, - outputFormatIds: ['Original'] - })); + // // act + // const contents = response.results.map(i => new ShareContent({ + // contentId: i.id, + // outputFormatIds: ['Original'] + // })); - const result = await shareService.create( null, new ShareBasicCreateRequest({ - name: 'Share', - languageCode: 'en', - contents: contents, - outputAccess: OutputAccess.Full, - suppressNotifications: false - })).toPromise(); + // const result = await shareService.create( null, new ShareBasicCreateRequest({ + // name: 'Share', + // languageCode: 'en', + // contents: contents, + // outputAccess: OutputAccess.Full, + // suppressNotifications: false + // })).toPromise(); - const share = await shareService.get(result.shareId!).toPromise(); + // const share = await shareService.get(result.shareId!).toPromise(); - // assert - expect(result.shareId).not.toBeNull(); - expect(share.id).toEqual(result.shareId!); - }))); + // // assert + // expect(result.shareId).not.toBeNull(); + // expect(share.id).toEqual(result.shareId!); + // }))); });
0f469017ae406fadc92bc878fadfee209fcdb623
app/src/lib/fix-emoji-spacing.ts
app/src/lib/fix-emoji-spacing.ts
// This module renders an element with an emoji using // a non system-default font to workaround an Chrome // issue that causes unexpected spacing on emojis. // More info: // https://bugs.chromium.org/p/chromium/issues/detail?id=1113293 const container = document.createElement('div') container.setAttribute( 'style', 'visibility: hidden; font-family: Arial !important;' ) // Keep this array synced with the font size variables // in _variables.scss const fontSizes = [ '--font-size', '--font-size-sm', '--font-size-md', '--font-size-lg', '--font-size-xl', '--font-size-xxl', '--font-size-xs', ] for (const fontSize of fontSizes) { const span = document.createElement('span') span.setAttribute('style', `font-size: var(${fontSize});`) span.innerHTML = '🤦🏿‍♀️' container.appendChild(span) } document.body.appendChild(container) // Read the dimensions of the element to force the browser to do a layout. // eslint-disable-next-line @typescript-eslint/no-unused-expressions container.offsetHeight // Browser has rendered the emojis, now we can remove them. document.body.removeChild(container)
// This module renders an element with an emoji using // a non system-default font to workaround an Chrome // issue that causes unexpected spacing on emojis. // More info: // https://bugs.chromium.org/p/chromium/issues/detail?id=1113293 const container = document.createElement('div') container.setAttribute( 'style', 'visibility: hidden; font-family: Arial !important;' ) // Keep this array synced with the font size variables // in _variables.scss const fontSizes = [ '--font-size', '--font-size-sm', '--font-size-md', '--font-size-lg', '--font-size-xl', '--font-size-xxl', '--font-size-xs', ] for (const fontSize of fontSizes) { const span = document.createElement('span') span.setAttribute('style', `font-size: var(${fontSize});`) span.textContent = '🤦🏿‍♀️' container.appendChild(span) } document.body.appendChild(container) // Read the dimensions of the element to force the browser to do a layout. // eslint-disable-next-line @typescript-eslint/no-unused-expressions container.offsetHeight // Browser has rendered the emojis, now we can remove them. document.body.removeChild(container)
Use textContent instead of innerHTML
Use textContent instead of innerHTML Co-authored-by: Markus Olsson <[email protected]>
TypeScript
mit
j-f1/forked-desktop,say25/desktop,kactus-io/kactus,desktop/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,shiftkey/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop
--- +++ @@ -25,7 +25,7 @@ for (const fontSize of fontSizes) { const span = document.createElement('span') span.setAttribute('style', `font-size: var(${fontSize});`) - span.innerHTML = '🤦🏿‍♀️' + span.textContent = '🤦🏿‍♀️' container.appendChild(span) }
a44d1ae6684148edd4f15d57d0b807866e38e200
src/cli.ts
src/cli.ts
'use strict'; import batch from './batch'; import request = require('request'); import log = require('./log'); import pjson = require('pjson'); const current_version = pjson.version; /* Check if the current version is the latest */ log.info('Crunchy version ' + current_version); request.get({ uri: 'https://raw.githubusercontent.com/Godzil/Crunchy/master/package.json' }, (error: Error, response: any, body: any) => { const onlinepkg = JSON.parse(body); let tmp = current_version.split('.'); const cur = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); tmp = onlinepkg.version.split('.'); const dist = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); if (dist > cur) { log.warn('There is a newer version of crunchy (v' + onlinepkg.version + '), you should update!'); } }); batch(process.argv, (err: any) => { if (err) { if (err.stack) { console.error(err.stack || err); } else { console.error(err); } process.exit(-1); } console.info('Done!'); process.exit(0); });
'use strict'; import batch from './batch'; import request = require('request'); import log = require('./log'); import pjson = require('pjson'); const current_version = pjson.version; /* Check if the current version is the latest */ log.info('Crunchy version ' + current_version); request.get({ uri: 'https://box.godzil.net/getVersion.php?tool=crunchy&v=' + current_version }, (error: Error, response: any, body: any) => { const onlinepkg = JSON.parse(body); if (onlinepkg.status = 'ok') { let tmp = current_version.split('.'); const cur = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); tmp = onlinepkg.version.split('.'); const dist = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); if (dist > cur) { log.warnMore('There is a newer version of crunchy (v' + onlinepkg.version + '), you should update!'); } } }); batch(process.argv, (err: any) => { if (err) { if (err.stack) { console.error(err.stack || err); } else { console.error(err); } process.exit(-1); } console.info('Done!'); process.exit(0); });
Use a more stable and futur proof URL to get current version information
Use a more stable and futur proof URL to get current version information
TypeScript
mit
Godzil/Crunchy,Godzil/crunchyroll.js,Godzil/crunchyroll.js,Godzil/Crunchy,Godzil/Crunchy
--- +++ @@ -8,17 +8,20 @@ /* Check if the current version is the latest */ log.info('Crunchy version ' + current_version); -request.get({ uri: 'https://raw.githubusercontent.com/Godzil/Crunchy/master/package.json' }, +request.get({ uri: 'https://box.godzil.net/getVersion.php?tool=crunchy&v=' + current_version }, (error: Error, response: any, body: any) => { const onlinepkg = JSON.parse(body); - let tmp = current_version.split('.'); - const cur = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); - tmp = onlinepkg.version.split('.'); - const dist = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); - if (dist > cur) + if (onlinepkg.status = 'ok') { - log.warn('There is a newer version of crunchy (v' + onlinepkg.version + '), you should update!'); + let tmp = current_version.split('.'); + const cur = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); + tmp = onlinepkg.version.split('.'); + const dist = (Number(tmp[0]) * 10000) + (Number(tmp[1]) * 100) + Number(tmp[2]); + if (dist > cur) + { + log.warnMore('There is a newer version of crunchy (v' + onlinepkg.version + '), you should update!'); + } } });
f4756fd8ce7abaecc4966d1e5b49873b8221fc3d
src/menu/menuItem.ts
src/menu/menuItem.ts
import { commands } from "vscode"; import { ActionType, IBindingItem } from "../IBindingItem"; import { createQuickPick } from "../utils"; import { IMenuItem } from "./IMenuItem"; export default class MenuItem implements IMenuItem { description: string; label: string; type: ActionType; command?: string; items?: MenuItem[]; constructor(item: IBindingItem) { // Add tab so the description is aligned this.description = `\t${item.name}`; this.label = item.key; this.type = item.type; this.command = item.command; if (this.type === "bindings" && item.bindings) { this.items = MenuItem.createItems(item.bindings); } } action(): Thenable<unknown> { if (this.type === "command" && this.command) { return commands.executeCommand(this.command); } else if (this.type === "bindings" && this.items) { return createQuickPick(this.description, this.items); } return Promise.reject(); } static createItems(items: IBindingItem[]) { return items.map(i => new MenuItem(i)); } }
import { commands } from "vscode"; import { ActionType, IBindingItem } from "../IBindingItem"; import { createQuickPick } from "../utils"; import { IMenuItem } from "./IMenuItem"; export default class MenuItem implements IMenuItem { name: string; label: string; type: ActionType; command?: string; items?: MenuItem[]; constructor(item: IBindingItem) { this.name = item.name; this.label = item.key; this.type = item.type; this.command = item.command; if (this.type === "bindings" && item.bindings) { this.items = MenuItem.createItems(item.bindings); } } get description() { // Add tab so the description is aligned return `\t${this.name}`; } action(): Thenable<unknown> { if (this.type === "command" && this.command) { return commands.executeCommand(this.command); } else if (this.type === "bindings" && this.items) { return createQuickPick(this.name, this.items); } return Promise.reject(); } static createItems(items: IBindingItem[]) { return items.map(i => new MenuItem(i)); } }
Remove the tab added to the title of QuickPick
Remove the tab added to the title of QuickPick
TypeScript
mit
VSpaceCode/VSpaceCode,VSpaceCode/VSpaceCode
--- +++ @@ -4,15 +4,14 @@ import { IMenuItem } from "./IMenuItem"; export default class MenuItem implements IMenuItem { - description: string; + name: string; label: string; type: ActionType; command?: string; items?: MenuItem[]; constructor(item: IBindingItem) { - // Add tab so the description is aligned - this.description = `\t${item.name}`; + this.name = item.name; this.label = item.key; this.type = item.type; this.command = item.command; @@ -21,11 +20,16 @@ } } + get description() { + // Add tab so the description is aligned + return `\t${this.name}`; + } + action(): Thenable<unknown> { if (this.type === "command" && this.command) { return commands.executeCommand(this.command); } else if (this.type === "bindings" && this.items) { - return createQuickPick(this.description, this.items); + return createQuickPick(this.name, this.items); } return Promise.reject();
dae08723793053d283a0a3d127d5e903e4fcee1b
src/app/db-status.service.ts
src/app/db-status.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { CookieService } from './cookie.service'; import { Observable, of } from 'rxjs'; import { map, retry, catchError } from 'rxjs/operators'; import { environment } from '../environments/environment' import { apiURL, apiRetry } from './api-utils' import { FolderStatus, Folder } from './folder' @Injectable({ providedIn: 'root' }) export class DbStatusService { private folderStatus: Object = {}; // TODO why isn't this working? private httpOptions: { headers: HttpHeaders } | { params: HttpParams }; private dbStatusUrl = environment.production ? apiURL + 'rest/db/status' : 'api/dbStatus'; constructor(private http: HttpClient, private cookieService: CookieService) { this.httpOptions = { headers: new HttpHeaders(this.cookieService.getCSRFHeader()) }; } getFolderStatus(id: string): Observable<FolderStatus> { /* if (id) { this.httpOptions["params"] = new HttpParams().set('folder', id); } */ return this.http .get<FolderStatus>(this.dbStatusUrl, this.httpOptions) .pipe( retry(apiRetry), map(res => { return res; }) ); } }
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { CookieService } from './cookie.service'; import { Observable, of } from 'rxjs'; import { map, retry, catchError } from 'rxjs/operators'; import { environment } from '../environments/environment' import { apiURL, apiRetry } from './api-utils' import { FolderStatus, Folder } from './folder' @Injectable({ providedIn: 'root' }) export class DbStatusService { private folderStatus: Object = {}; private headers: HttpHeaders; private dbStatusUrl = environment.production ? apiURL + 'rest/db/status' : 'api/dbStatus'; constructor(private http: HttpClient, private cookieService: CookieService) { this.headers = new HttpHeaders(this.cookieService.getCSRFHeader()) } getFolderStatus(id: string): Observable<FolderStatus> { let httpOptions: { headers: HttpHeaders } | { headers: HttpHeaders, params: HttpParams }; if (id) { httpOptions = { headers: this.headers, params: new HttpParams().set('folder', id) }; } else { httpOptions = { headers: this.headers }; } return this.http .get<FolderStatus>(this.dbStatusUrl, httpOptions) .pipe( retry(apiRetry), map(res => { // Remove from array in developement // in-memory-web-api returns arrays if (!environment.production) { const a: any = res as any; if (a.length > 0) { return res[0]; } } return res; }) ); } }
Remove Folder object from array in development only
Remove Folder object from array in development only
TypeScript
mpl-2.0
wweich/syncthing,syncthing/syncthing,syncthing/syncthing,wweich/syncthing,wweich/syncthing,syncthing/syncthing,wweich/syncthing,syncthing/syncthing,syncthing/syncthing,syncthing/syncthing
--- +++ @@ -14,27 +14,38 @@ }) export class DbStatusService { private folderStatus: Object = {}; - - // TODO why isn't this working? - private httpOptions: { headers: HttpHeaders } | { params: HttpParams }; + private headers: HttpHeaders; private dbStatusUrl = environment.production ? apiURL + 'rest/db/status' : 'api/dbStatus'; constructor(private http: HttpClient, private cookieService: CookieService) { - this.httpOptions = { headers: new HttpHeaders(this.cookieService.getCSRFHeader()) }; + this.headers = new HttpHeaders(this.cookieService.getCSRFHeader()) } getFolderStatus(id: string): Observable<FolderStatus> { - /* + let httpOptions: { headers: HttpHeaders } | + { headers: HttpHeaders, params: HttpParams }; if (id) { - this.httpOptions["params"] = new HttpParams().set('folder', id); + httpOptions = { + headers: this.headers, + params: new HttpParams().set('folder', id) + }; + } else { + httpOptions = { headers: this.headers }; } - */ return this.http - .get<FolderStatus>(this.dbStatusUrl, this.httpOptions) + .get<FolderStatus>(this.dbStatusUrl, httpOptions) .pipe( retry(apiRetry), map(res => { + // Remove from array in developement + // in-memory-web-api returns arrays + if (!environment.production) { + const a: any = res as any; + if (a.length > 0) { + return res[0]; + } + } return res; }) );
349d90061a782f64d9c08044c6a7bfe5ffb3c253
resources/assets/js/settings_repository.ts
resources/assets/js/settings_repository.ts
import _ from 'lodash'; import axios from 'axios'; import toastr from 'toastr'; export default class SettingsRepository { static getSetting(key: string, def: any | null = null): any { let result = _.find(window.Panel.Server.settings, {key: key}); if (result === undefined || result == null) { return def; } return result['value']; } static setSetting(key: string, value: any, persist?: boolean) { let result = _.find(window.Panel.Server.settings, {key: key}); if (result == null) { window.Panel.Server.settings.push({ id: window.Panel.Server.id + '_' + key, guild: window.Panel.Server.id, key: key, value: value }); } else { result.value = value; } if (persist) { axios.patch('/api/guild/' + window.Panel.Server.id + '/setting', { key: key, value: value }).catch(e => { if (e.response.status == 422) { console.warn("Received 422 when attempting to save key " + key); toastr.warning('Key ' + key + ' is not whitelisted for saving'); } }); } } }
import _ from 'lodash'; import axios from 'axios'; import toastr from 'toastr'; export default class SettingsRepository { static getSetting(key: string, def: any | null = null): any { let result = _.find(window.Panel.Server.settings, {key: key}); if (result === undefined || result == null) { return def; } return result['value']; } static setSetting(key: string, value: any, persist?: boolean): Promise<any> { return new Promise((resolve, reject) => { let result = _.find(window.Panel.Server.settings, {key: key}); if (result == null) { window.Panel.Server.settings.push({ id: window.Panel.Server.id + '_' + key, guild: window.Panel.Server.id, key: key, value: value }); } else { result.value = value; } if (persist) { axios.patch('/api/guild/' + window.Panel.Server.id + '/setting', { key: key, value: value }).catch(e => { if (e.response.status == 422) { console.warn("Received 422 when attempting to save key " + key); toastr.warning('Key ' + key + ' is not whitelisted for saving'); } reject(e) }).then(resp => { resolve(resp) }); } else { resolve() } }); } }
Make settings repository return a promise
Make settings repository return a promise
TypeScript
mit
mrkirby153/KirBotPanel,mrkirby153/KirBotPanel,mrkirby153/KirBotPanel,mrkirby153/KirBotPanel
--- +++ @@ -12,29 +12,36 @@ return result['value']; } - static setSetting(key: string, value: any, persist?: boolean) { - let result = _.find(window.Panel.Server.settings, {key: key}); - if (result == null) { - window.Panel.Server.settings.push({ - id: window.Panel.Server.id + '_' + key, - guild: window.Panel.Server.id, - key: key, - value: value - }); - } else { - result.value = value; - } + static setSetting(key: string, value: any, persist?: boolean): Promise<any> { + return new Promise((resolve, reject) => { + let result = _.find(window.Panel.Server.settings, {key: key}); + if (result == null) { + window.Panel.Server.settings.push({ + id: window.Panel.Server.id + '_' + key, + guild: window.Panel.Server.id, + key: key, + value: value + }); + } else { + result.value = value; + } - if (persist) { - axios.patch('/api/guild/' + window.Panel.Server.id + '/setting', { - key: key, - value: value - }).catch(e => { - if (e.response.status == 422) { - console.warn("Received 422 when attempting to save key " + key); - toastr.warning('Key ' + key + ' is not whitelisted for saving'); - } - }); - } + if (persist) { + axios.patch('/api/guild/' + window.Panel.Server.id + '/setting', { + key: key, + value: value + }).catch(e => { + if (e.response.status == 422) { + console.warn("Received 422 when attempting to save key " + key); + toastr.warning('Key ' + key + ' is not whitelisted for saving'); + } + reject(e) + }).then(resp => { + resolve(resp) + }); + } else { + resolve() + } + }); } }
13dd14e3692b478849ee1b041f00ce750ddfb9af
src/xrm-mock/processflow/step/step.mock.ts
src/xrm-mock/processflow/step/step.mock.ts
export class StepMock implements Xrm.ProcessFlow.Step { public required: boolean; public name: string; public attribute: string; constructor(name: string, attribute: string, required: boolean) { this.name = name; this.attribute = attribute; this.required = required; } public getAttribute(): string { return this.attribute; } public getName(): string { return this.name; } public isRequired(): boolean { return this.required; } }
export class StepMock implements Xrm.ProcessFlow.Step { public required: boolean; public name: string; public attribute: string; constructor(name: string, attribute: string, required: boolean) { this.name = name; this.attribute = attribute; this.required = required; } public getAttribute(): string { return this.attribute; } public getName(): string { return this.name; } public isRequired(): boolean { return this.required; } public getProgress(): number { throw new Error("getProgress not implemented"); } public setProgress(stepProgress: number, message: string): string { throw new Error("setProgress not implemented"); } }
Add missing functions in the steps method of formContext.data.process
Add missing functions in the steps method of formContext.data.process
TypeScript
mit
camelCaseDave/xrm-mock,camelCaseDave/xrm-mock
--- +++ @@ -20,4 +20,12 @@ public isRequired(): boolean { return this.required; } + + public getProgress(): number { + throw new Error("getProgress not implemented"); + } + + public setProgress(stepProgress: number, message: string): string { + throw new Error("setProgress not implemented"); + } }
3afe29d7e96b691f74aa7e8ce01f60a2cebdc499
src/Styleguide/Elements/Separator.tsx
src/Styleguide/Elements/Separator.tsx
import React from "react" import styled from "styled-components" import { space, SpaceProps, themeGet } from "styled-system" const HR = styled.div.attrs<SpaceProps>({})` ${space}; border-top: 1px solid ${themeGet("colors.black10")}; width: 100%; ` export class Separator extends React.Component { render() { return <HR mb={2} /> } }
// @ts-ignore import React from "react" import { color } from "@artsy/palette" import styled from "styled-components" import { space, SpaceProps } from "styled-system" interface SeparatorProps extends SpaceProps {} export const Separator = styled.div.attrs<SeparatorProps>({})` ${space}; border-top: 1px solid ${color("black10")}; width: 100%; `
Remove notion of spacing from separator
Remove notion of spacing from separator
TypeScript
mit
artsy/reaction-force,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction
--- +++ @@ -1,15 +1,14 @@ +// @ts-ignore import React from "react" + +import { color } from "@artsy/palette" import styled from "styled-components" -import { space, SpaceProps, themeGet } from "styled-system" +import { space, SpaceProps } from "styled-system" -const HR = styled.div.attrs<SpaceProps>({})` +interface SeparatorProps extends SpaceProps {} + +export const Separator = styled.div.attrs<SeparatorProps>({})` ${space}; - border-top: 1px solid ${themeGet("colors.black10")}; + border-top: 1px solid ${color("black10")}; width: 100%; ` - -export class Separator extends React.Component { - render() { - return <HR mb={2} /> - } -}
1f0e38f6494ee3827aaa79abfbddd7f7d0d4f348
ts/hooks/useKeyboardShortcuts.tsx
ts/hooks/useKeyboardShortcuts.tsx
// Copyright 2021 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import { useEffect } from 'react'; import { get } from 'lodash'; type KeyboardShortcutHandlerType = (ev: KeyboardEvent) => boolean; function isCmdOrCtrl(ev: KeyboardEvent): boolean { const { ctrlKey, metaKey } = ev; const commandKey = get(window, 'platform') === 'darwin' && metaKey; const controlKey = get(window, 'platform') !== 'darwin' && ctrlKey; return commandKey || controlKey; } export function getStartRecordingShortcut( startAudioRecording: () => unknown ): KeyboardShortcutHandlerType { return ev => { const { key, shiftKey } = ev; if (isCmdOrCtrl(ev) && shiftKey && (key === 'v' || key === 'V')) { startAudioRecording(); ev.preventDefault(); ev.stopPropagation(); return true; } return false; }; } export function useKeyboardShortcuts( ...eventHandlers: Array<KeyboardShortcutHandlerType> ): void { useEffect(() => { function handleKeydown(ev: KeyboardEvent): void { eventHandlers.some(eventHandler => eventHandler(ev)); } document.addEventListener('keydown', handleKeydown); return () => { document.removeEventListener('keydown', handleKeydown); }; }, [eventHandlers]); }
// Copyright 2021 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import { useEffect } from 'react'; import { get } from 'lodash'; import * as KeyboardLayout from '../services/keyboardLayout'; type KeyboardShortcutHandlerType = (ev: KeyboardEvent) => boolean; function isCmdOrCtrl(ev: KeyboardEvent): boolean { const { ctrlKey, metaKey } = ev; const commandKey = get(window, 'platform') === 'darwin' && metaKey; const controlKey = get(window, 'platform') !== 'darwin' && ctrlKey; return commandKey || controlKey; } export function getStartRecordingShortcut( startAudioRecording: () => unknown ): KeyboardShortcutHandlerType { return ev => { const { shiftKey } = ev; const key = KeyboardLayout.lookup(ev); if (isCmdOrCtrl(ev) && shiftKey && (key === 'v' || key === 'V')) { startAudioRecording(); ev.preventDefault(); ev.stopPropagation(); return true; } return false; }; } export function useKeyboardShortcuts( ...eventHandlers: Array<KeyboardShortcutHandlerType> ): void { useEffect(() => { function handleKeydown(ev: KeyboardEvent): void { eventHandlers.some(eventHandler => eventHandler(ev)); } document.addEventListener('keydown', handleKeydown); return () => { document.removeEventListener('keydown', handleKeydown); }; }, [eventHandlers]); }
Use physical keys for voice message shortcut
Use physical keys for voice message shortcut
TypeScript
agpl-3.0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
--- +++ @@ -3,6 +3,8 @@ import { useEffect } from 'react'; import { get } from 'lodash'; + +import * as KeyboardLayout from '../services/keyboardLayout'; type KeyboardShortcutHandlerType = (ev: KeyboardEvent) => boolean; @@ -17,7 +19,9 @@ startAudioRecording: () => unknown ): KeyboardShortcutHandlerType { return ev => { - const { key, shiftKey } = ev; + const { shiftKey } = ev; + + const key = KeyboardLayout.lookup(ev); if (isCmdOrCtrl(ev) && shiftKey && (key === 'v' || key === 'V')) { startAudioRecording();
00b34f00d77a3567d12ee496815e58ea354bdd58
src/app/window.service.spec.ts
src/app/window.service.spec.ts
/* tslint:disable:no-unused-variable */ /*! * Window Object Service Test * * Copyright(c) Exequiel Ceasar Navarrete <[email protected]> * Licensed under MIT */ import { TestBed, async, inject } from '@angular/core/testing'; import { WindowService } from './window.service'; describe('Service: Window', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: WindowService, useValue: window } ] }); }); it('should instantiate the service', inject([WindowService], (service: Window) => { expect(service).toBeTruthy(); })); });
/* tslint:disable:no-unused-variable */ /*! * Window Object Service Test * * Copyright(c) Exequiel Ceasar Navarrete <[email protected]> * Licensed under MIT */ import { TestBed, async, inject } from '@angular/core/testing'; import { WindowService } from './window.service'; describe('Service: Window', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: WindowService, useValue: window } ] }); }); it('should instantiate the service', inject([WindowService], (service: Window) => { expect(service).toBeTruthy(); })); it('should be an instance of window object', inject([WindowService], (service: Window) => { expect(service).toBe(window); })); });
Add type check to window service
Add type check to window service
TypeScript
mit
ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2
--- +++ @@ -24,6 +24,10 @@ expect(service).toBeTruthy(); })); + it('should be an instance of window object', inject([WindowService], (service: Window) => { + expect(service).toBe(window); + })); + });
57d5e5fb119e509f01c1d9ec2e11752fa1f8998f
packages/components/containers/password/AskAuthModal.tsx
packages/components/containers/password/AskAuthModal.tsx
import { c } from 'ttag'; import { useState } from 'react'; import { FormModal, Loader } from '../../components'; import PasswordTotpInputs from './PasswordTotpInputs'; import useAskAuth from './useAskAuth'; interface Props { onClose?: () => void; onSubmit: (data: { password: string; totp: string }) => void; error: string; loading?: boolean; [key: string]: any; } const AskAuthModal = ({ onClose, onSubmit, error, loading, ...rest }: Props) => { const [password, setPassword] = useState(''); const [totp, setTotp] = useState(''); const [hasTOTPEnabled, isLoadingAuth] = useAskAuth(); return ( <FormModal onClose={onClose} onSubmit={() => onSubmit({ password, totp })} title={c('Title').t`Sign in again to continue`} close={c('Label').t`Cancel`} submit={c('Label').t`Submit`} error={error} small loading={loading || isLoadingAuth} {...rest} > {isLoadingAuth ? ( <Loader /> ) : ( <PasswordTotpInputs password={password} setPassword={setPassword} passwordError={error} totp={totp} setTotp={setTotp} totpError={error} showTotp={hasTOTPEnabled} /> )} </FormModal> ); }; export default AskAuthModal;
import { c } from 'ttag'; import { useState } from 'react'; import { FormModal, Loader } from '../../components'; import PasswordTotpInputs from './PasswordTotpInputs'; import useAskAuth from './useAskAuth'; interface Props { onClose?: () => void; onSubmit: (data: { password: string; totp: string }) => void; error: string; loading?: boolean; [key: string]: any; } const AskAuthModal = ({ onClose, onSubmit, error, loading, ...rest }: Props) => { const [password, setPassword] = useState(''); const [totp, setTotp] = useState(''); const [hasTOTPEnabled, isLoadingAuth] = useAskAuth(); return ( <FormModal onClose={onClose} onSubmit={() => onSubmit({ password, totp })} title={c('Title').t`Sign in again to continue`} close={c('Label').t`Cancel`} submit={c('Label').t`Submit`} error={error} small noTitleEllipsis loading={loading || isLoadingAuth} {...rest} > {isLoadingAuth ? ( <Loader /> ) : ( <PasswordTotpInputs password={password} setPassword={setPassword} passwordError={error} totp={totp} setTotp={setTotp} totpError={error} showTotp={hasTOTPEnabled} /> )} </FormModal> ); }; export default AskAuthModal;
Remove ellipsis on Auth modal title
Remove ellipsis on Auth modal title For some language like German, we need to display the full title, so no ellipsis there :) L10N-513
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -28,6 +28,7 @@ submit={c('Label').t`Submit`} error={error} small + noTitleEllipsis loading={loading || isLoadingAuth} {...rest} >
a4c3be5e5bc0ea8742c208d5ea6fd6a0244a2bb7
dev/main.ts
dev/main.ts
/// <reference path='../src/sfc.d.ts' /> import Vue from 'vue'; import VueHighlightJS, { Options } from '../src'; import javascript from 'highlight.js/lib/languages/javascript'; import vue from '../lib/languages/vue'; import App from './App.vue'; import 'highlight.js/styles/agate.css'; Vue.use<Options>(VueHighlightJS, { languages: { javascript, vue } }); new Vue({ el: '#app', render: h => h(App) });
/// <reference path='../src/sfc.d.ts' /> import Vue from 'vue'; import VueHighlightJS, { Options } from '../src'; import css from 'highlight.js/lib/languages/css'; import javascript from 'highlight.js/lib/languages/javascript'; import vue from '../lib/languages/vue'; import App from './App.vue'; import 'highlight.js/styles/agate.css'; Vue.use<Options>(VueHighlightJS, { languages: { css, javascript, vue } }); new Vue({ el: '#app', render: h => h(App) });
Fix `<style>` content isn't highlighted
:bug: Fix `<style>` content isn't highlighted
TypeScript
mit
gluons/vue-highlight.js
--- +++ @@ -3,6 +3,7 @@ import Vue from 'vue'; import VueHighlightJS, { Options } from '../src'; +import css from 'highlight.js/lib/languages/css'; import javascript from 'highlight.js/lib/languages/javascript'; import vue from '../lib/languages/vue'; @@ -12,6 +13,7 @@ Vue.use<Options>(VueHighlightJS, { languages: { + css, javascript, vue }
ffb99c43e4f62c5dfeb7a66c70fe293d2f9f3f7a
tools/env/base.ts
tools/env/base.ts
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.12.0', RELEASEVERSION: '0.12.0' }; export = BaseConfig;
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.0', RELEASEVERSION: '0.13.0' }; export = BaseConfig;
Update to pre-release version 0.13.0
Update to pre-release version 0.13.0
TypeScript
mit
nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website
--- +++ @@ -3,8 +3,8 @@ const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', - RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.12.0', - RELEASEVERSION: '0.12.0' + RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.0', + RELEASEVERSION: '0.13.0' }; export = BaseConfig;
1cd1c4bdcc99f7d753081a294546ee46910379cd
app/shared/config.ts
app/shared/config.ts
import {getString, setString} from "application-settings"; import {connectionType, getConnectionType, startMonitoring} from "connectivity"; var Everlive = require("../shared/everlive.all.min"); export class Config { static el = new Everlive({ apiKey: "gwfrtxi1lwt4jcqk", offlineStorage: true }); private static handleOnlineOffline() { if (getConnectionType() == connectionType.none) { Config.el.offline(); } else { Config.el.online(); Config.el.sync(); } } static setupConnectionMonitoring() { startMonitoring(Config.handleOnlineOffline); } static get token():string { return getString("token"); } static set token(theToken: string) { setString("token", theToken); } static hasActiveToken() { return !!getString("token"); } static invalidateToken() { Config.token = ""; } }
import {getString, setString} from "application-settings"; import {connectionType, getConnectionType, startMonitoring} from "connectivity"; var Everlive = require("../shared/everlive.all.min"); export class Config { static el = new Everlive({ apiKey: "gwfrtxi1lwt4jcqk", offlineStorage: true }); private static handleOnlineOffline() { if (getConnectionType() == connectionType.none) { Config.el.offline(); } else { Config.el.online(); Config.el.sync(); } } static setupConnectionMonitoring() { Config.handleOnlineOffline(); startMonitoring(Config.handleOnlineOffline); } static get token():string { return getString("token"); } static set token(theToken: string) { setString("token", theToken); } static hasActiveToken() { return !!getString("token"); } static invalidateToken() { Config.token = ""; } }
Make sure to set the online flag during the setup 👍
Make sure to set the online flag during the setup 👍
TypeScript
mit
anhoev/cms-mobile,qtagtech/nativescript_tutorial,NativeScript/sample-Groceries,qtagtech/nativescript_tutorial,tjvantoll/sample-Groceries,anhoev/cms-mobile,qtagtech/nativescript_tutorial,poly-mer/community,tjvantoll/sample-Groceries,dzfweb/sample-groceries,dzfweb/sample-groceries,poly-mer/community,anhoev/cms-mobile,Icenium/nativescript-sample-groceries,poly-mer/community,NativeScript/sample-Groceries,tjvantoll/sample-Groceries,NativeScript/sample-Groceries,dzfweb/sample-groceries
--- +++ @@ -17,6 +17,7 @@ } } static setupConnectionMonitoring() { + Config.handleOnlineOffline(); startMonitoring(Config.handleOnlineOffline); }
528ba49dee28d4c801522c8cb12b538924e4b3e0
scripts/NotificationManager.ts
scripts/NotificationManager.ts
import Diff from "./Diff" export default class NotificationManager { unseen: number icon: HTMLElement counter: HTMLElement constructor() { this.icon = document.getElementById("notification-icon") this.counter = document.getElementById("notification-count") } async update() { let response = await fetch("/api/count/notifications/unseen", { credentials: "same-origin" }) let body = await response.text() this.unseen = parseInt(body) if(this.unseen > 99) { this.unseen = 99 } this.render() } render() { Diff.mutations.queue(() => { this.counter.textContent = this.unseen.toString() if(this.unseen === 0) { this.counter.classList.add("hidden") this.icon.classList.remove("hidden") } else { this.icon.classList.add("hidden") this.counter.classList.remove("hidden") } }) } }
import Diff from "./Diff" export default class NotificationManager { unseen: number icon: HTMLElement counter: HTMLElement constructor() { this.icon = document.getElementById("notification-icon") this.counter = document.getElementById("notification-count") } async update() { let response = await fetch("/api/count/notifications/unseen", { credentials: "same-origin" }) let body = await response.text() this.unseen = parseInt(body) if(isNaN(this.unseen)) { this.unseen = 0 } if(this.unseen > 99) { this.unseen = 99 } this.render() } render() { Diff.mutations.queue(() => { this.counter.textContent = this.unseen.toString() if(this.unseen === 0) { this.counter.classList.add("hidden") this.icon.classList.remove("hidden") } else { this.icon.classList.add("hidden") this.counter.classList.remove("hidden") } }) } }
Handle NaN case for notification count
Handle NaN case for notification count
TypeScript
mit
animenotifier/notify.moe,animenotifier/notify.moe,animenotifier/notify.moe
--- +++ @@ -17,6 +17,10 @@ let body = await response.text() this.unseen = parseInt(body) + + if(isNaN(this.unseen)) { + this.unseen = 0 + } if(this.unseen > 99) { this.unseen = 99
354c2ef1ab3641c9aa5a4bb9a8bf119244bc6233
spec/regression/helpers.ts
spec/regression/helpers.ts
import {execute, parse} from "graphql"; import {ProxyConfig} from "../../src/config/proxy-configuration"; import {createProxySchema} from "../../src/proxy-schema"; /** * Create a graphql proxy for a configuration and execute a query on it. * @param proxyConfig * @param query * @param variableValues * @returns {Promise<void>} */ export async function testConfigWithQuery(proxyConfig: ProxyConfig, query: string, variableValues: {[name: string]: any}) { const schema = await createProxySchema(proxyConfig); const document = parse(query, {}); const result = await execute(schema, document, {}, {}, variableValues, undefined); return result.data; }
import { execute, parse, validate } from 'graphql'; import {ProxyConfig} from "../../src/config/proxy-configuration"; import {createProxySchema} from "../../src/proxy-schema"; import { assertSuccessfulResponse } from '../../src/endpoints/client'; /** * Create a graphql proxy for a configuration and execute a query on it. * @param proxyConfig * @param query * @param variableValues * @returns {Promise<void>} */ export async function testConfigWithQuery(proxyConfig: ProxyConfig, query: string, variableValues: {[name: string]: any}) { const schema = await createProxySchema(proxyConfig); const document = parse(query, {}); const errors = validate(schema, document); if (errors.length) { throw new Error(JSON.stringify(errors)); } const result = await execute(schema, document, {cariedOnRootValue: true}, {}, variableValues, undefined); assertSuccessfulResponse(result); return result.data; }
Validate queries of regression tests before executing
Validate queries of regression tests before executing
TypeScript
mit
AEB-labs/graphql-weaver,AEB-labs/graphql-weaver
--- +++ @@ -1,6 +1,7 @@ -import {execute, parse} from "graphql"; +import { execute, parse, validate } from 'graphql'; import {ProxyConfig} from "../../src/config/proxy-configuration"; import {createProxySchema} from "../../src/proxy-schema"; +import { assertSuccessfulResponse } from '../../src/endpoints/client'; /** * Create a graphql proxy for a configuration and execute a query on it. @@ -12,6 +13,11 @@ export async function testConfigWithQuery(proxyConfig: ProxyConfig, query: string, variableValues: {[name: string]: any}) { const schema = await createProxySchema(proxyConfig); const document = parse(query, {}); - const result = await execute(schema, document, {}, {}, variableValues, undefined); + const errors = validate(schema, document); + if (errors.length) { + throw new Error(JSON.stringify(errors)); + } + const result = await execute(schema, document, {cariedOnRootValue: true}, {}, variableValues, undefined); + assertSuccessfulResponse(result); return result.data; }
7b19f6875d27ef7e96f0b25d49f01c94c31a9345
packages/core/src/traverseConcat.ts
packages/core/src/traverseConcat.ts
import OperationLog from "./helperFunctions/OperationLog"; function getResultLen(log: OperationLog) { return log.result.type === "string" ? log.result.length : (log.result.primitive + "").length; } export default function traverseConcat( left: OperationLog, right: OperationLog, charIndex: number ) { if ( left.result.primitive === undefined || right.result.primitive === undefined ) { console.log("Can't traverse concat", left.result, right.result); return; } const leftLength = getResultLen(left); if (charIndex < leftLength) { return { operationLog: left, charIndex: charIndex }; } else { return { operationLog: right, charIndex: charIndex - leftLength }; } }
import OperationLog from "./helperFunctions/OperationLog"; function getResultLen(log: OperationLog) { return log.result.type === "string" ? log.result.length : (log.result.primitive + "").length; } export default function traverseConcat( left: OperationLog, right: OperationLog, charIndex: number ) { let leftStr; if (left.result.type === "string") { leftStr = left.result.primitive; } else if (left.result.type === "number") { leftStr = left.result.primitive + ""; } else if (left.result.type === "undefined") { [leftStr === "undefined"]; } if (typeof leftStr !== "string") { console.log("Can't traverse concat", left.result, right.result); return; } const leftLength = leftStr.length; if (charIndex < leftLength) { return { operationLog: left, charIndex: charIndex }; } else { return { operationLog: right, charIndex: charIndex - leftLength }; } }
Fix traverse undefined in string concat
Fix traverse undefined in string concat
TypeScript
mit
mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS
--- +++ @@ -11,15 +11,20 @@ right: OperationLog, charIndex: number ) { - if ( - left.result.primitive === undefined || - right.result.primitive === undefined - ) { + let leftStr; + if (left.result.type === "string") { + leftStr = left.result.primitive; + } else if (left.result.type === "number") { + leftStr = left.result.primitive + ""; + } else if (left.result.type === "undefined") { + [leftStr === "undefined"]; + } + if (typeof leftStr !== "string") { console.log("Can't traverse concat", left.result, right.result); return; } - const leftLength = getResultLen(left); + const leftLength = leftStr.length; if (charIndex < leftLength) { return {
e84a4195546370474de15f8de614c7d56adbd542
src/core/documents/docedit/forms/date.component.ts
src/core/documents/docedit/forms/date.component.ts
import {Component, Input} from '@angular/core'; import {NgbDateParserFormatter, NgbDateStruct} from '@ng-bootstrap/ng-bootstrap'; import {Resource} from '../../../model/resource'; import {DocumentEditChangeMonitor} from '../document-edit-change-monitor'; @Component({ moduleId: module.id, selector: 'dai-date', templateUrl: './date.html' }) export class DateComponent { @Input() resource: Resource; @Input('field') set field(value: any) { this._field = value; this.dateStruct = this.dateFormatter.parse(this.resource[this._field.name]); if (this.resource[this._field.name] && !this.dateStruct) this.dateNotParsed = true; } public dateStruct: NgbDateStruct; public dateNotParsed = false; private _field : any; constructor(private documentEditChangeMonitor: DocumentEditChangeMonitor, public dateFormatter: NgbDateParserFormatter) {} public update(newValue: any) { this.resource[this._field.name] = this.dateFormatter.format(newValue); this.dateNotParsed = false; this.documentEditChangeMonitor.setChanged(); } }
import {Component, Input} from '@angular/core'; import {NgbDateParserFormatter, NgbDateStruct} from '@ng-bootstrap/ng-bootstrap'; import {Resource} from '../../../model/resource'; import {DocumentEditChangeMonitor} from '../document-edit-change-monitor'; @Component({ moduleId: module.id, selector: 'dai-date', templateUrl: './date.html' }) export class DateComponent { @Input() resource: Resource; @Input('field') set field(value: any) { this._field = value; this.dateStruct = this.dateFormatter.parse(this.resource[this._field.name]); if (this.resource[this._field.name] && !this.dateStruct) this.dateNotParsed = true; if (!this.dateStruct.month) this.dateStruct.month = 1; if (!this.dateStruct.day) this.dateStruct.day = 1; } public dateStruct: NgbDateStruct; public dateNotParsed = false; private _field : any; constructor(private documentEditChangeMonitor: DocumentEditChangeMonitor, public dateFormatter: NgbDateParserFormatter) {} public update(newValue: any) { this.resource[this._field.name] = this.dateFormatter.format(newValue); this.dateNotParsed = false; this.documentEditChangeMonitor.setChanged(); } }
Set day and month to 1 if not set
Set day and month to 1 if not set
TypeScript
apache-2.0
dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2
--- +++ @@ -18,6 +18,8 @@ this._field = value; this.dateStruct = this.dateFormatter.parse(this.resource[this._field.name]); if (this.resource[this._field.name] && !this.dateStruct) this.dateNotParsed = true; + if (!this.dateStruct.month) this.dateStruct.month = 1; + if (!this.dateStruct.day) this.dateStruct.day = 1; } public dateStruct: NgbDateStruct;
2e38182131d321b06dee1ed39f9c9f4bb00c16d8
src/HardwareSensorSystem/wwwsrc/app/logout/logout.component.spec.ts
src/HardwareSensorSystem/wwwsrc/app/logout/logout.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { LogoutComponent } from './logout.component'; describe('LogoutComponent', () => { let component: LogoutComponent; let fixture: ComponentFixture<LogoutComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ LogoutComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LogoutComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); });
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { Router } from '@angular/router'; import { LogoutComponent } from './logout.component'; const routerStub = { navigate: (commands: any[]) => { } }; describe('LogoutComponent', () => { let component: LogoutComponent; let fixture: ComponentFixture<LogoutComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [LogoutComponent], providers: [ { provide: Router, useValue: routerStub } ] }); }); beforeEach(() => { fixture = TestBed.createComponent(LogoutComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); });
Improve test setup for logout
Improve test setup for logout
TypeScript
apache-2.0
eKiosk/HardwareSensorSystem,eKiosk/HardwareSensorSystem,eKiosk/HardwareSensorSystem
--- +++ @@ -1,21 +1,27 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { RouterTestingModule } from '@angular/router/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; import { LogoutComponent } from './logout.component'; + +const routerStub = { + navigate: (commands: any[]) => { } +}; describe('LogoutComponent', () => { let component: LogoutComponent; let fixture: ComponentFixture<LogoutComponent>; - beforeEach(async(() => { + beforeEach(() => { TestBed.configureTestingModule({ - imports: [ - RouterTestingModule - ], - declarations: [ LogoutComponent ] - }) - .compileComponents(); - })); + declarations: [LogoutComponent], + providers: [ + { + provide: Router, + useValue: routerStub + } + ] + }); + }); beforeEach(() => { fixture = TestBed.createComponent(LogoutComponent);