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
dfa6fb5d6108c38f7908448edb41aee439a29b73
ts/components/Inbox.tsx
ts/components/Inbox.tsx
import React, { useEffect, useRef } from 'react'; import * as Backbone from 'backbone'; type InboxViewType = Backbone.View & { onEmpty?: () => void; }; type InboxViewOptionsType = Backbone.ViewOptions & { initialLoadComplete: boolean; window: typeof window; }; export type PropsType = { hasInitialLoadCompleted: boolean; }; export const Inbox = ({ hasInitialLoadCompleted }: PropsType): JSX.Element => { const hostRef = useRef<HTMLDivElement | null>(null); const viewRef = useRef<InboxViewType | undefined>(undefined); useEffect(() => { const viewOptions: InboxViewOptionsType = { el: hostRef.current, initialLoadComplete: false, window, }; const view = new window.Whisper.InboxView(viewOptions); viewRef.current = view; return () => { if (!viewRef || !viewRef.current) { return; } viewRef.current.remove(); viewRef.current = undefined; }; }, []); useEffect(() => { if (hasInitialLoadCompleted && viewRef.current && viewRef.current.onEmpty) { viewRef.current.onEmpty(); } }, [hasInitialLoadCompleted, viewRef]); return <div className="inbox index" ref={hostRef} />; };
import React, { useEffect, useRef } from 'react'; import * as Backbone from 'backbone'; type InboxViewType = Backbone.View & { onEmpty?: () => void; }; type InboxViewOptionsType = Backbone.ViewOptions & { initialLoadComplete: boolean; window: typeof window; }; export type PropsType = { hasInitialLoadCompleted: boolean; }; export const Inbox = ({ hasInitialLoadCompleted }: PropsType): JSX.Element => { const hostRef = useRef<HTMLDivElement | null>(null); const viewRef = useRef<InboxViewType | undefined>(undefined); useEffect(() => { const viewOptions: InboxViewOptionsType = { el: hostRef.current, initialLoadComplete: false, window, }; const view = new window.Whisper.InboxView(viewOptions); viewRef.current = view; return () => { // [`Backbone.View.prototype.remove`][0] removes the DOM element and stops listening // to event listeners. Because React will do the first, we only want to do the // second. // [0]: https://github.com/jashkenas/backbone/blob/153dc41616a1f2663e4a86b705fefd412ecb4a7a/backbone.js#L1336-L1342 viewRef.current?.stopListening(); viewRef.current = undefined; }; }, []); useEffect(() => { if (hasInitialLoadCompleted && viewRef.current && viewRef.current.onEmpty) { viewRef.current.onEmpty(); } }, [hasInitialLoadCompleted, viewRef]); return <div className="inbox index" ref={hostRef} />; };
Fix unmounting of inbox view
Fix unmounting of inbox view
TypeScript
agpl-3.0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
--- +++ @@ -29,11 +29,11 @@ viewRef.current = view; return () => { - if (!viewRef || !viewRef.current) { - return; - } - - viewRef.current.remove(); + // [`Backbone.View.prototype.remove`][0] removes the DOM element and stops listening + // to event listeners. Because React will do the first, we only want to do the + // second. + // [0]: https://github.com/jashkenas/backbone/blob/153dc41616a1f2663e4a86b705fefd412ecb4a7a/backbone.js#L1336-L1342 + viewRef.current?.stopListening(); viewRef.current = undefined; }; }, []);
dbb3ce1449223112431cec200dbac2b2b046494a
components/card-list/card-list.ts
components/card-list/card-list.ts
import { Component, Input, ContentChild } from 'angular2/core'; import template from './card-list.html!text'; import { CardHeader } from './header/card-header'; import { CardBody } from './body/card-body'; import { Card } from './card/card'; export { CardHeader, CardBody }; @Component({ selector: 'conf-card-list', template: template, directives: [Card], }) export class CardList { @Input() source: any[]; @ContentChild(CardHeader) head: CardHeader; @ContentChild(CardBody) body: CardBody; }
import { Component, Input, ContentChild, ViewChildren, QueryList } from 'angular2/core'; import template from './card-list.html!text'; import { CardHeader } from './header/card-header'; import { CardBody } from './body/card-body'; import { Card } from './card/card'; export { CardHeader, CardBody }; @Component({ selector: 'conf-card-list', template: template, directives: [Card], }) export class CardList { @Input() source: any[]; @ContentChild(CardHeader) head: CardHeader; @ContentChild(CardBody) body: CardBody; @ViewChildren(Card) cards: QueryList<Card>; collapseAll() { this.cards.map((card: Card) => card.close()); } }
Add a function to the card list for collapsing all child cards
Add a function to the card list for collapsing all child cards
TypeScript
mit
SonofNun15/conf-template-components,SonofNun15/conf-template-components,SonofNun15/conf-template-components
--- +++ @@ -1,4 +1,7 @@ -import { Component, Input, ContentChild } from 'angular2/core'; +import { + Component, Input, + ContentChild, ViewChildren, QueryList +} from 'angular2/core'; import template from './card-list.html!text'; @@ -22,4 +25,11 @@ @ContentChild(CardBody) body: CardBody; + + @ViewChildren(Card) + cards: QueryList<Card>; + + collapseAll() { + this.cards.map((card: Card) => card.close()); + } }
0e3e1b12511972cee484327be504ca9022dabed5
components/EntriesPreviewsGrid.tsx
components/EntriesPreviewsGrid.tsx
import { FunctionComponent, Fragment } from "react" import { PossibleEntries } from "../loaders/EntriesLoader" import AppPreview, { isAppPreview } from "../models/AppPreview" import EntryPreview from "./EntryPreview" interface Props { entries: (PossibleEntries | AppPreview)[] appCampaignName: string } const EntriesPreviewsGrid: FunctionComponent<Props> = ({ entries, appCampaignName, }: Props) => { return ( <Fragment> <div className="entries"> {entries.map((entry) => { const key = isAppPreview(entry) ? entry.downloadURL : entry.url return ( <div className="preview" key={`${entry.type}-${key}-grid-preview`}> <EntryPreview entry={entry} appCampaignName={appCampaignName} /> </div> ) })} </div> <style jsx>{` div.entries { display: grid; grid-template-columns: 100%; grid-template-rows: 1fr; gap: 8px 8px; grid-template-areas: "."; padding: 8px 0; } div.preview { display: flex; flex-direction: column; flex: 1; } @media (min-width: 1024px) { div.entries { grid-template-columns: repeat(2, 50%); grid-template-areas: ". ."; } } `}</style> </Fragment> ) } export default EntriesPreviewsGrid
import { FunctionComponent, Fragment } from "react" import { PossibleEntries } from "../loaders/EntriesLoader" import AppPreview, { isAppPreview } from "../models/AppPreview" import EntryPreview from "./EntryPreview" interface Props { entries: (PossibleEntries | AppPreview)[] appCampaignName: string } const EntriesPreviewsGrid: FunctionComponent<Props> = ({ entries, appCampaignName, }: Props) => { return ( <Fragment> <div className="entries"> {entries.map((entry) => { const key = isAppPreview(entry) ? entry.downloadURL : entry.url return ( <div className="preview" key={`${entry.type}-${key}-grid-preview`}> <EntryPreview entry={entry} appCampaignName={appCampaignName} /> </div> ) })} </div> <style jsx>{` div.entries { --spacing: 8px; display: grid; grid-template-columns: 100%; grid-template-rows: 1fr; gap: var(--spacing) var(--spacing); grid-template-areas: "."; padding: 8px 0; } div.preview { display: flex; flex-direction: column; flex: 1; } @media (min-width: 1024px) { div.entries { grid-template-columns: repeat( 2, calc(50% - calc(var(--spacing) / 2)) ); grid-template-areas: ". ."; } } `}</style> </Fragment> ) } export default EntriesPreviewsGrid
Fix sizing of entries in grid
Fix sizing of entries in grid
TypeScript
mit
JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk
--- +++ @@ -26,10 +26,12 @@ </div> <style jsx>{` div.entries { + --spacing: 8px; + display: grid; grid-template-columns: 100%; grid-template-rows: 1fr; - gap: 8px 8px; + gap: var(--spacing) var(--spacing); grid-template-areas: "."; padding: 8px 0; } @@ -42,7 +44,10 @@ @media (min-width: 1024px) { div.entries { - grid-template-columns: repeat(2, 50%); + grid-template-columns: repeat( + 2, + calc(50% - calc(var(--spacing) / 2)) + ); grid-template-areas: ". ."; } }
1158ff1705a671b697d9813030c3069b19bce34f
test/types/index.ts
test/types/index.ts
/* eslint no-unused-vars: 0 */ /* eslint no-undef: 0 */ import { Packet } from '../../packet' var p = Packet() p = Packet({ cmd: 'publish', topic: 'hello', payload: Buffer.from('world'), qos: 0, dup: false, retain: false, brokerId: 'afds8f', brokerCounter: 10 }) p = Packet({ cmd: 'pingresp', brokerId: 'ab7d9', brokerCounter: 3 })
/* eslint no-unused-vars: 0 */ /* eslint no-undef: 0 */ import { Packet } from '../../packet' let p = Packet() p = Packet({ cmd: 'publish', topic: 'hello', payload: Buffer.from('world'), qos: 0, dup: false, retain: false, brokerId: 'afds8f', brokerCounter: 10 }) p = Packet({ cmd: 'pingresp', brokerId: 'ab7d9', brokerCounter: 3 })
Use let in typescript tests
Use let in typescript tests
TypeScript
mit
mcollina/aedes-packet
--- +++ @@ -3,7 +3,7 @@ import { Packet } from '../../packet' -var p = Packet() +let p = Packet() p = Packet({ cmd: 'publish', topic: 'hello',
051bf949c210014081994aa4bf5697fe3f2189dd
applications/web/pages/_app.tsx
applications/web/pages/_app.tsx
import { createWrapper } from "next-redux-wrapper"; import App from "next/app"; import React from "react"; import { Provider } from "react-redux"; import { Store } from "redux"; import configureStore from "../redux/store"; /** * Next.JS requires all global CSS to be imported here. */ import "@nteract/styles/app.css"; import "@nteract/styles/global-variables.css"; import "@nteract/styles/themes/base.css"; import "@nteract/styles/themes/default.css"; import "@nteract/styles/editor-overrides.css"; import "@nteract/styles/markdown/github.css"; import "codemirror/addon/hint/show-hint.css"; import "codemirror/lib/codemirror.css"; import "../css/prism.css" interface StoreProps { store: Store; } class WebApp extends App<StoreProps> { static async getInitialProps({ Component, ctx }) { const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {}; return { pageProps }; } render() { const { Component, pageProps, store } = this.props; return (<Component {...pageProps} />); } } const wrapper = createWrapper(configureStore, { debug: true }); export default wrapper.withRedux(WebApp);
import { createWrapper } from "next-redux-wrapper"; import App from "next/app"; import React from "react"; import { Provider } from "react-redux"; import { Store } from "redux"; import configureStore from "../redux/store"; /** * Next.JS requires all global CSS to be imported here. * Note: Do not change the order of css */ import "@nteract/styles/app.css"; import "@nteract/styles/global-variables.css"; import "@nteract/styles/themes/base.css"; import "@nteract/styles/themes/default.css"; import "codemirror/addon/hint/show-hint.css"; import "codemirror/lib/codemirror.css"; import "@nteract/styles/editor-overrides.css"; import "@nteract/styles/markdown/github.css"; interface StoreProps { store: Store; } class WebApp extends App<StoreProps> { static async getInitialProps({ Component, ctx }) { const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {}; return { pageProps }; } render() { const { Component, pageProps, store } = this.props; return (<Component {...pageProps} />); } } const wrapper = createWrapper(configureStore, { debug: true }); export default wrapper.withRedux(WebApp);
Fix order of import css
Fix order of import css
TypeScript
bsd-3-clause
nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract
--- +++ @@ -7,18 +7,18 @@ /** * Next.JS requires all global CSS to be imported here. + * Note: Do not change the order of css */ import "@nteract/styles/app.css"; import "@nteract/styles/global-variables.css"; import "@nteract/styles/themes/base.css"; import "@nteract/styles/themes/default.css"; -import "@nteract/styles/editor-overrides.css"; -import "@nteract/styles/markdown/github.css"; import "codemirror/addon/hint/show-hint.css"; import "codemirror/lib/codemirror.css"; -import "../css/prism.css" +import "@nteract/styles/editor-overrides.css"; +import "@nteract/styles/markdown/github.css"; interface StoreProps { store: Store;
2e3a7134cbe7d7f654d8ecfa3a23f0d2be7a3970
lib/typings/CascadeClassifier.d.ts
lib/typings/CascadeClassifier.d.ts
import { Size } from './Size.d'; import { Mat } from './Mat.d'; import { Rect } from './Rect.d'; export class CascadeClassifier { constructor(xmlFilePath: string); detectMultiScale(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): { objects: Rect[], numDetections: number[] }; detectMultiScaleAsync(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Promise<{ objects: Rect[], numDetections: number[] }>; detectMultiScaleGpu(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Rect[]; detectMultiScaleWithRejectLevels(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): { objects: Rect[], rejectLevels: number[], levelWeigths: number[] }; detectMultiScaleWithRejectLevelsAsync(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Promise<{ objects: Rect[], rejectLevels: number[], levelWeigths: number[] }>; }
import { Size } from './Size.d'; import { Mat } from './Mat.d'; import { Rect } from './Rect.d'; export class CascadeClassifier { constructor(xmlFilePath: string); detectMultiScale(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): { objects: Rect[], numDetections: number[] }; detectMultiScaleAsync(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Promise<{ objects: Rect[], numDetections: number[] }>; detectMultiScaleGpu(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Rect[]; detectMultiScaleWithRejectLevels(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): { objects: Rect[], rejectLevels: number[], levelWeights: number[] }; detectMultiScaleWithRejectLevelsAsync(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Promise<{ objects: Rect[], rejectLevels: number[], levelWeights: number[] }>; }
Fix spelling mistake in typings
Fix spelling mistake in typings levelWeigths => levelWeights
TypeScript
mit
justadudewhohacks/opencv4nodejs,justadudewhohacks/opencv4nodejs,justadudewhohacks/opencv4nodejs,justadudewhohacks/opencv4nodejs,justadudewhohacks/opencv4nodejs,justadudewhohacks/opencv4nodejs
--- +++ @@ -7,6 +7,6 @@ detectMultiScale(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): { objects: Rect[], numDetections: number[] }; detectMultiScaleAsync(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Promise<{ objects: Rect[], numDetections: number[] }>; detectMultiScaleGpu(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Rect[]; - detectMultiScaleWithRejectLevels(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): { objects: Rect[], rejectLevels: number[], levelWeigths: number[] }; - detectMultiScaleWithRejectLevelsAsync(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Promise<{ objects: Rect[], rejectLevels: number[], levelWeigths: number[] }>; + detectMultiScaleWithRejectLevels(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): { objects: Rect[], rejectLevels: number[], levelWeights: number[] }; + detectMultiScaleWithRejectLevelsAsync(img: Mat, scaleFactor?: number, minNeighbors?: number, flags?: number, minSize?: Size, maxSize?: Size): Promise<{ objects: Rect[], rejectLevels: number[], levelWeights: number[] }>; }
f83d1ba672fbc5440e82b2839b0202c2eefc4fc4
src/theme/helpers/getSourceFile.ts
src/theme/helpers/getSourceFile.ts
/** * Returns the source file definition */ import { MarkdownEngine } from '../enums/markdown-engine.enum'; import { ThemeService } from '../theme.service'; export function getSourceFile(fileName: string, line: string, url: string) { const options = ThemeService.getOptions(); let md = 'Defined in '; if (ThemeService.getMarkdownEngine() === MarkdownEngine.BITBUCKET && options.mdSourceRepo) { const bitbucketUrl = `${options.mdSourceRepo}/src/master/src/${fileName}`; const bitbucketParams = `fileviewer=file-view-default#${fileName}-${line}`; md += `[${fileName}:${line}](${bitbucketUrl}?${bitbucketParams})`; } else if (url) { md += `[${fileName}:${line}](${url})`; } else { md += `${fileName}:${line}`; } return md; }
/** * Returns the source file definition */ import { MarkdownEngine } from '../enums/markdown-engine.enum'; import { ThemeService } from '../theme.service'; export function getSourceFile(fileName: string, line: string, url: string) { const options = ThemeService.getOptions(); let md = 'Defined in '; if (ThemeService.getMarkdownEngine() === MarkdownEngine.BITBUCKET && options.mdSourceRepo) { const bitbucketUrl = `${options.mdSourceRepo}/src/master/${fileName}`; const bitbucketParams = `fileviewer=file-view-default#${fileName}-${line}`; md += `[${fileName}:${line}](${bitbucketUrl}?${bitbucketParams})`; } else if (url) { md += `[${fileName}:${line}](${url})`; } else { md += `${fileName}:${line}`; } return md; }
Fix bitbucket url not working due to /src after /master
Fix bitbucket url not working due to /src after /master
TypeScript
mit
tgreyuk/typedoc-plugin-markdown,tgreyuk/typedoc-plugin-markdown
--- +++ @@ -8,7 +8,7 @@ const options = ThemeService.getOptions(); let md = 'Defined in '; if (ThemeService.getMarkdownEngine() === MarkdownEngine.BITBUCKET && options.mdSourceRepo) { - const bitbucketUrl = `${options.mdSourceRepo}/src/master/src/${fileName}`; + const bitbucketUrl = `${options.mdSourceRepo}/src/master/${fileName}`; const bitbucketParams = `fileviewer=file-view-default#${fileName}-${line}`; md += `[${fileName}:${line}](${bitbucketUrl}?${bitbucketParams})`; } else if (url) {
2231cdee2a335e7b67beba91d9138df2eceabab9
src/cli.ts
src/cli.ts
import assert from "assert"; import tf, { findTestFiles, component, loadTests, runTests, printResultsToConsole, writeResultsToFile, writeResultsToJunitFile, failureExitCode } from "./index"; const run = tf( component("assert", assert), findTestFiles("./tests/*.test.js"), loadTests, runTests, printResultsToConsole, failureExitCode(), writeResultsToJunitFile("results.xml"), writeResultsToFile("results.json") ); run();
import assert from "assert"; import tf, { findTestFiles, component, loadTests, runTests, printResultsToConsole, writeResultsToFile, writeResultsToJunitFile, failureExitCode } from "./index"; const run = tf( component("assert", assert), findTestFiles("./tests/*.test.js"), loadTests, runTests, printResultsToConsole, writeResultsToJunitFile("results.xml"), writeResultsToFile("results.json"), failureExitCode() ); run();
Move exit code to end
Move exit code to end
TypeScript
mit
testingrequired/tf,testingrequired/tf
--- +++ @@ -16,9 +16,9 @@ loadTests, runTests, printResultsToConsole, - failureExitCode(), writeResultsToJunitFile("results.xml"), - writeResultsToFile("results.json") + writeResultsToFile("results.json"), + failureExitCode() ); run();
35ad311dd02680c1c9b2ee8702330d6346edd7f0
server/routes/ping/ping.router.ts
server/routes/ping/ping.router.ts
import { Router, Request, Response, NextFunction } from 'express'; class PingRouter { router: Router; /** * Initialize the PingRouter */ constructor() { this.router = Router(); this.init(); } /** * GET all Heroes. */ public getApiStatus(req: Request, res: Response, next: NextFunction) { res.json({ message: 'Api working!' }); } /** * Take each handler, and attach to one of the Express.Router's * endpoints. */ init() { this.router.get('/', this.getApiStatus); } } // Export configured router export var pingRouter = new PingRouter().router;
import { Router, Request, Response, NextFunction } from 'express'; class PingRouter { router: Router; /** * Initialize the PingRouter */ constructor() { this.router = Router(); this.init(); } /** * GET all Heroes. */ public getApiStatus(req: Request, res: Response, next: NextFunction) { res.json({ message: 'Api working!' }); } /** * Take each handler, and attach to one of the Express.Router's * endpoints. */ init() { this.router.get('/', this.getApiStatus); } } // Export configured router let pingRouter = new PingRouter().router; export { pingRouter }
Fix linter (use let instead of var)
Fix linter (use let instead of var)
TypeScript
mit
DavidLevayer/countable,DavidLevayer/countable,DavidLevayer/countable
--- +++ @@ -32,4 +32,5 @@ } // Export configured router -export var pingRouter = new PingRouter().router; +let pingRouter = new PingRouter().router; +export { pingRouter }
5e6a410358785f008f708026d0964fe81b047892
ng2-timetable/app/app.component.ts
ng2-timetable/app/app.component.ts
import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from 'angular2/router'; import {HTTP_PROVIDERS} from 'angular2/http'; import {ScheduleComponent} from './schedule/schedule.component'; import {RoomSearchComponent} from './room-search/room-search.component'; import {RegisterComponent} from './register/register.component'; @Component({ selector: 'timetable-app', template: ` <h1>App Component</h1> <nav> <a [routerLink]="['Register']">Рєстрація</a> <a [routerLink]="['RoomSearch']">Пошук вільної аудиторії</a> <a [routerLink]="['Schedule']">Розклад</a> </nav> <router-outlet></router-outlet> `, directives: [ROUTER_DIRECTIVES], providers: [ ROUTER_PROVIDERS, HTTP_PROVIDERS ] }) @RouteConfig([ {path:'/...', name: 'Schedule', component: ScheduleComponent, useAsDefault: true}, {path:'/room-search', name: 'RoomSearch', component: RoomSearchComponent}, {path:'/register/...', name: 'Register', component: RegisterComponent} ]) export class AppComponent { }
import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from 'angular2/router'; import {HTTP_PROVIDERS} from 'angular2/http'; import {MATERIAL_DIRECTIVES} from 'ng2-material/all'; import {ScheduleComponent} from './schedule/schedule.component'; import {RoomSearchComponent} from './room-search/room-search.component'; import {RegisterComponent} from './register/register.component'; @Component({ selector: 'timetable-app', template: ` <h1>App Component</h1> <nav> <a [routerLink]="['Register']">Рєстрація</a> <a [routerLink]="['RoomSearch']">Пошук вільної аудиторії</a> <a [routerLink]="['Schedule']">Розклад</a> </nav> <router-outlet></router-outlet> `, directives: [ ROUTER_DIRECTIVES, MATERIAL_DIRECTIVES ], providers: [ ROUTER_PROVIDERS, HTTP_PROVIDERS ] }) @RouteConfig([ {path:'/...', name: 'Schedule', component: ScheduleComponent, useAsDefault: true}, {path:'/room-search', name: 'RoomSearch', component: RoomSearchComponent}, {path:'/register/...', name: 'Register', component: RegisterComponent} ]) export class AppComponent { }
Add ng2-material directives to AppComponent
Add ng2-material directives to AppComponent
TypeScript
mit
bluebirrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrd/nau-timetable
--- +++ @@ -1,6 +1,7 @@ import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from 'angular2/router'; import {HTTP_PROVIDERS} from 'angular2/http'; +import {MATERIAL_DIRECTIVES} from 'ng2-material/all'; import {ScheduleComponent} from './schedule/schedule.component'; import {RoomSearchComponent} from './room-search/room-search.component'; import {RegisterComponent} from './register/register.component'; @@ -16,7 +17,10 @@ </nav> <router-outlet></router-outlet> `, - directives: [ROUTER_DIRECTIVES], + directives: [ + ROUTER_DIRECTIVES, + MATERIAL_DIRECTIVES + ], providers: [ ROUTER_PROVIDERS, HTTP_PROVIDERS
abddf31fe03e1689de6a0c680cec63e073d06a72
src/shortcut/index.ts
src/shortcut/index.ts
import * as path from 'path'; import xdgBasedir from 'xdg-basedir' import Common from '../common'; abstract class Shortcut { static create( program: string, icon: string, autostart?: boolean ) { if ( process.platform === 'linux' ) { return this.createLinux( program, icon ); } else { throw new Error( 'Not supported' ); } } private static createLinux( program: string, icon: string) { let desktopContents = '[Desktop Entry]\nVersion=1.0\nType=Application\nName=Game Jolt Client\nGenericName=Game Client\nComment=The power of Game Jolt website in your desktop\nExec=' + program + '\nTerminal=false\nIcon=' + icon + '\nCategories=Game;\nKeywords=Play;Games;GJ;GameJolt;Indie;\nHidden=false\nName[en_US]=Game Jolt Client\n'; return Common.fsWriteFile( path.join( xdgBasedir.data, 'application', 'Game Jolt Client.desktop' ), desktopContents ); } } export default Shortcut;
import * as path from 'path'; import xdgBasedir from 'xdg-basedir' import Common from '../common'; abstract class Shortcut { static create( program: string, icon: string ) { if ( process.platform === 'linux' ) { return this.createLinux( program, icon ); } else { throw new Error( 'Not supported' ); } } private static createLinux( program: string, icon: string) { let desktopContents = '[Desktop Entry]\nVersion=1.0\nType=Application\nName=Game Jolt Client\nGenericName=Game Client\nComment=The power of Game Jolt website in your desktop\nExec=' + program + '\nTerminal=false\nIcon=' + icon + '\nCategories=Game;\nKeywords=Play;Games;GJ;GameJolt;Indie;\nHidden=false\nName[en_US]=Game Jolt Client\n'; return Common.fsWriteFile( path.join( xdgBasedir.data, 'application', 'Game Jolt Client.desktop' ), desktopContents ); } } export default Shortcut;
Remove useless option in Shortcut.create
Remove useless option in Shortcut.create
TypeScript
mit
gamejolt/client-voodoo,gamejolt/client-voodoo
--- +++ @@ -4,7 +4,7 @@ abstract class Shortcut { - static create( program: string, icon: string, autostart?: boolean ) + static create( program: string, icon: string ) { if ( process.platform === 'linux' ) { return this.createLinux( program, icon );
73b676ecdc358caa8e67d6e445a0b1aa1540c05e
src/pages/post/[date]/[name]/index.tsx
src/pages/post/[date]/[name]/index.tsx
import {stringify, parse} from "superjson" import type {GetStaticProps} from "next" import {TRPCError} from "@trpc/server" import {useRouter} from "next/router" import type {FC} from "react" import {router} from "server/trpc/route" import {Post} from "server/db/entity/Post" import getEmptyPaths from "lib/util/getEmptyPaths" interface Props { data: string } interface Query { date: string name: string } export const getStaticPaths = getEmptyPaths export const getStaticProps: GetStaticProps<Props> = async ({params}) => { const {date, name} = params as unknown as Query try { const post = await router.createCaller({}).query("post.getBySlug", { slug: [date, name] }) return { props: { data: stringify(post) } } } catch (error) { if (error instanceof TRPCError && error.code === "NOT_FOUND") { return { notFound: true } } throw error } } const PostPage: FC<Props> = ({data}) => { const router = useRouter() // TODO: DO NOT forget to add support for the fallback version of the page: https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-pages if (router.isFallback) { return <div>Loading...</div> } const post = parse<Post>(data) return ( <div>{post.title}</div> ) } export default PostPage
import {stringify, parse} from "superjson" import type {GetStaticProps} from "next" import {TRPCError} from "@trpc/server" import type {FC} from "react" import {router} from "server/trpc/route" import {Post} from "server/db/entity/Post" import getEmptyPaths from "lib/util/getEmptyPaths" interface Props { data: string } interface Query { date: string name: string } export const getStaticPaths = getEmptyPaths export const getStaticProps: GetStaticProps<Props> = async ({params}) => { const {date, name} = params as unknown as Query try { const post = await router.createCaller({}).query("post.getBySlug", { slug: [date, name] }) return { props: { data: stringify(post) } } } catch (error) { if (error instanceof TRPCError && error.code === "NOT_FOUND") { return { notFound: true } } throw error } } const PostPage: FC<Props> = ({data}) => { const post = parse<Post>(data) return ( <div>{post.title}</div> ) } export default PostPage
Remove unnecessary code from post page due to blocking ballback usage
Remove unnecessary code from post page due to blocking ballback usage
TypeScript
mit
octet-stream/eri,octet-stream/eri
--- +++ @@ -1,7 +1,6 @@ import {stringify, parse} from "superjson" import type {GetStaticProps} from "next" import {TRPCError} from "@trpc/server" -import {useRouter} from "next/router" import type {FC} from "react" import {router} from "server/trpc/route" @@ -45,13 +44,6 @@ } const PostPage: FC<Props> = ({data}) => { - const router = useRouter() - - // TODO: DO NOT forget to add support for the fallback version of the page: https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-pages - if (router.isFallback) { - return <div>Loading...</div> - } - const post = parse<Post>(data) return (
c18ce7415e681f5a2e74d2a7d8f54fc69aeb318c
lib/runners/schematic.runner.ts
lib/runners/schematic.runner.ts
import { existsSync } from 'fs'; import { join, sep } from 'path'; import { AbstractRunner } from './abstract.runner'; export class SchematicRunner extends AbstractRunner { constructor() { super(`"${SchematicRunner.findClosestSchematicsBinary(__dirname)}"`); } private static findClosestSchematicsBinary(path: string): string { const segments = path.split(sep); const binaryPath = ['node_modules', '.bin', 'schematics']; const schematicsWhenGlobal = [ sep, ...segments.slice(0, segments.lastIndexOf('cli') + 1), ...binaryPath, ]; const schematicsGlobalPath = join(...schematicsWhenGlobal); const schematicsWhenLocal = [ sep, ...segments.slice(0, segments.lastIndexOf('node_modules')), ...binaryPath, ]; const schematicsLocalPath = join(...schematicsWhenLocal); if (existsSync(schematicsGlobalPath)) { return schematicsGlobalPath; } if (existsSync(schematicsLocalPath)) { return schematicsLocalPath; } return join(__dirname, '../..', 'node_modules/.bin/schematics'); } }
import { existsSync } from 'fs'; import { join, sep } from 'path'; import { AbstractRunner } from './abstract.runner'; export class SchematicRunner extends AbstractRunner { constructor() { super(`"${SchematicRunner.findClosestSchematicsBinary(__dirname)}"`); } public static findClosestSchematicsBinary(path: string): string { const segments = path.split(sep); const binaryPath = ['node_modules', '.bin', 'schematics']; const schematicsWhenGlobal = [ sep, ...segments.slice(0, segments.lastIndexOf('cli') + 1), ...binaryPath, ]; const schematicsGlobalPath = join(...schematicsWhenGlobal); const schematicsWhenLocal = [ sep, ...segments.slice(0, segments.lastIndexOf('node_modules')), ...binaryPath, ]; const schematicsLocalPath = join(...schematicsWhenLocal); if (existsSync(schematicsGlobalPath)) { return schematicsGlobalPath; } if (existsSync(schematicsLocalPath)) { return schematicsLocalPath; } return join(__dirname, '../..', 'node_modules/.bin/schematics'); } }
Make binary resolver method public
fix(SchematicRunner): Make binary resolver method public
TypeScript
mit
ThomRick/nest-cli,ThomRick/nest-cli
--- +++ @@ -7,7 +7,7 @@ super(`"${SchematicRunner.findClosestSchematicsBinary(__dirname)}"`); } - private static findClosestSchematicsBinary(path: string): string { + public static findClosestSchematicsBinary(path: string): string { const segments = path.split(sep); const binaryPath = ['node_modules', '.bin', 'schematics'];
7dc98837ee64b89d68ed3987d9734f3e0c40bda7
src/screens/App/index.tsx
src/screens/App/index.tsx
import React, { ReactElement } from 'react' import { useMatchMedia, useI18n } from 'hooks' import { Header, Title } from 'components/Layout' import Menu, { Item } from 'components/Layout/Menu' import AnimatedPatterns from 'components/AnimatedPatterns' import LanguageSwitcher from 'components/LanguageSwitcher' import styles from './styles.module.sass' export default function App(): ReactElement { const { getAllMessages } = useI18n() const matcheWidth = useMatchMedia('max-width: 500px') const matcheHeight = useMatchMedia('max-height: 320px') const matchMedia = matcheWidth && !matcheHeight const { supporters, literature, software, design, about, contact, } = getAllMessages() return ( <div className="App"> <Header classNames={[styles.header]}> <LanguageSwitcher /> <Title>DALTON MENEZES</Title> <Menu horizontal={!matchMedia} withBullets={!matchMedia} classNames={[styles.menu]} > <Item to="/supporters">{supporters}</Item> <Item to="/literature">{literature}</Item> <Item to="/software">{software}</Item> <Item to="/design">{design}</Item> <Item to="/about">{about}</Item> <Item to="/contact">{contact}</Item> </Menu> </Header> <AnimatedPatterns /> </div> ) }
import React, { ReactElement } from 'react' import { useMatchMedia, useI18n } from 'hooks' import { Header, Title } from 'components/Layout' import Menu, { Item } from 'components/Layout/Menu' import AnimatedPatterns from 'components/AnimatedPatterns' import LanguageSwitcher from 'components/LanguageSwitcher' import styles from './styles.module.sass' export default function App(): ReactElement { const { getAllMessages } = useI18n() const matcheWidth = useMatchMedia('max-width: 500px') const matcheHeight = useMatchMedia('max-height: 320px') const matchMedia = matcheWidth && !matcheHeight const { supporters, literature, software, design, about, contact, } = getAllMessages() return ( <div className="App"> <Header classNames={[styles.header]}> <LanguageSwitcher /> <Title>DALTON MENEZES</Title> <Menu horizontal={!matchMedia} withBullets={!matchMedia} classNames={[styles.menu]} > <Item to="/supporters">{supporters}</Item> <Item to="/literature">{literature}</Item> <Item to="/software">{software}</Item> <Item to="https://en.99designs.com.br/profiles/daltonmenezes"> {design} </Item> <Item to="/about">{about}</Item> <Item to="/contact">{contact}</Item> </Menu> </Header> <AnimatedPatterns /> </div> ) }
Add 99Design profile as design item route
Add 99Design profile as design item route
TypeScript
mit
daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io
--- +++ @@ -37,7 +37,9 @@ <Item to="/supporters">{supporters}</Item> <Item to="/literature">{literature}</Item> <Item to="/software">{software}</Item> - <Item to="/design">{design}</Item> + <Item to="https://en.99designs.com.br/profiles/daltonmenezes"> + {design} + </Item> <Item to="/about">{about}</Item> <Item to="/contact">{contact}</Item> </Menu>
c3de5579581dd3835ce8545e98a6a35f17e6c036
desktop/core/src/desktop/js/vue/webComponentWrapper.ts
desktop/core/src/desktop/js/vue/webComponentWrapper.ts
import Vue from 'vue'; import vueCustomElement from 'vue-custom-element'; Vue.use(vueCustomElement); export const wrap = <T extends Vue>(tag: string, component: { new (): T }): void => { Vue.customElement(tag, new component().$options); };
import axios from 'axios'; import Vue, { ComponentOptions } from 'vue'; import vueCustomElement from 'vue-custom-element'; Vue.use(vueCustomElement); export interface HueComponentOptions<T extends Vue> extends ComponentOptions<T> { hueBaseUrl?: string; } export const wrap = <T extends Vue>(tag: string, component: { new (): T }): void => { Vue.customElement(tag, new component().$options, { connectedCallback() { const element = <HTMLElement>this; const hueBaseUrl = element.getAttribute('hue-base-url'); if (hueBaseUrl) { axios.defaults.baseURL = hueBaseUrl; } } }); };
Add global web component attribute for hue base URL config
[frontend] Add global web component attribute for hue base URL config For now just for axios requests
TypeScript
apache-2.0
kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue
--- +++ @@ -1,8 +1,21 @@ -import Vue from 'vue'; +import axios from 'axios'; +import Vue, { ComponentOptions } from 'vue'; import vueCustomElement from 'vue-custom-element'; Vue.use(vueCustomElement); +export interface HueComponentOptions<T extends Vue> extends ComponentOptions<T> { + hueBaseUrl?: string; +} + export const wrap = <T extends Vue>(tag: string, component: { new (): T }): void => { - Vue.customElement(tag, new component().$options); + Vue.customElement(tag, new component().$options, { + connectedCallback() { + const element = <HTMLElement>this; + const hueBaseUrl = element.getAttribute('hue-base-url'); + if (hueBaseUrl) { + axios.defaults.baseURL = hueBaseUrl; + } + } + }); };
dd0cbbe6d485104416076e27f0fa170dfe6d2b32
src/SyntaxNodes/SpoilerBlockNode.ts
src/SyntaxNodes/SpoilerBlockNode.ts
import { OutlineSyntaxNode } from './OutlineSyntaxNode' export class SpoilerBlockNode { OUTLINE_SYNTAX_NODE(): void { } constructor(public children: OutlineSyntaxNode[] = []) { } protected SPOILER_BLOCK_NODE(): void { } }
import { RichOutlineSyntaxNode } from './RichOutlineSyntaxNode' export class SpoilerBlockNode extends RichOutlineSyntaxNode { protected SPOILER_BLOCK_NODE(): void { } }
Use RichOutlineSyntaxNode for spoiler blocks
Use RichOutlineSyntaxNode for spoiler blocks
TypeScript
mit
start/up,start/up
--- +++ @@ -1,10 +1,6 @@ -import { OutlineSyntaxNode } from './OutlineSyntaxNode' +import { RichOutlineSyntaxNode } from './RichOutlineSyntaxNode' -export class SpoilerBlockNode { - OUTLINE_SYNTAX_NODE(): void { } - - constructor(public children: OutlineSyntaxNode[] = []) { } - +export class SpoilerBlockNode extends RichOutlineSyntaxNode { protected SPOILER_BLOCK_NODE(): void { } }
2f90794978ad9cfc8c8cd61c3592aed6ff2d9ec7
desktop/core/src/desktop/js/ext/aceHelper.ts
desktop/core/src/desktop/js/ext/aceHelper.ts
import 'ext/ace/ace' import 'ext/ace/ext-language_tools'; import 'ext/ace/ext-searchbox'; import 'ext/ace/ext-settings_menu'; import 'ext/ace/mode-bigquery'; import 'ext/ace/mode-druid'; import 'ext/ace/mode-elasticsearch'; import 'ext/ace/mode-flink'; import 'ext/ace/mode-hive'; import 'ext/ace/mode-impala'; import 'ext/ace/mode-ksql'; import 'ext/ace/mode-phoenix'; import 'ext/ace/mode-presto'; import 'ext/ace/mode-sql'; import 'ext/ace/mode-text'; import 'ext/ace/snippets/bigquery'; import 'ext/ace/snippets/druid'; import 'ext/ace/snippets/elasticsearch'; import 'ext/ace/snippets/flink'; import 'ext/ace/snippets/hive'; import 'ext/ace/snippets/impala'; import 'ext/ace/snippets/ksql'; import 'ext/ace/snippets/phoenix'; import 'ext/ace/snippets/presto'; import 'ext/ace/snippets/sql'; import 'ext/ace/snippets/text'; import 'ext/ace/theme-hue'; import 'ext/ace/theme-hue_dark'; import './aceExtensions'; export default (window as any).ace;
import 'ext/ace/ace' import 'ext/ace/ext-language_tools'; import 'ext/ace/ext-searchbox'; import 'ext/ace/ext-settings_menu'; import 'ext/ace/mode-bigquery'; import 'ext/ace/mode-druid'; import 'ext/ace/mode-elasticsearch'; import 'ext/ace/mode-flink'; import 'ext/ace/mode-hive'; import 'ext/ace/mode-impala'; import 'ext/ace/mode-ksql'; import 'ext/ace/mode-phoenix'; import 'ext/ace/mode-presto'; import 'ext/ace/mode-pgsql' import 'ext/ace/mode-sql'; import 'ext/ace/mode-text'; import 'ext/ace/snippets/bigquery'; import 'ext/ace/snippets/druid'; import 'ext/ace/snippets/elasticsearch'; import 'ext/ace/snippets/flink'; import 'ext/ace/snippets/hive'; import 'ext/ace/snippets/impala'; import 'ext/ace/snippets/ksql'; import 'ext/ace/snippets/phoenix'; import 'ext/ace/snippets/presto'; import 'ext/ace/snippets/pgsql'; import 'ext/ace/snippets/sql'; import 'ext/ace/snippets/text'; import 'ext/ace/theme-hue'; import 'ext/ace/theme-hue_dark'; import './aceExtensions'; export default (window as any).ace;
Include the pgsql Ace editor mode
[editor] Include the pgsql Ace editor mode
TypeScript
apache-2.0
cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue,kawamon/hue,kawamon/hue,cloudera/hue,cloudera/hue
--- +++ @@ -11,6 +11,7 @@ import 'ext/ace/mode-ksql'; import 'ext/ace/mode-phoenix'; import 'ext/ace/mode-presto'; +import 'ext/ace/mode-pgsql' import 'ext/ace/mode-sql'; import 'ext/ace/mode-text'; import 'ext/ace/snippets/bigquery'; @@ -22,6 +23,7 @@ import 'ext/ace/snippets/ksql'; import 'ext/ace/snippets/phoenix'; import 'ext/ace/snippets/presto'; +import 'ext/ace/snippets/pgsql'; import 'ext/ace/snippets/sql'; import 'ext/ace/snippets/text'; import 'ext/ace/theme-hue';
81338404e92b2b9a8b4a70b08f5dc9192afb6f68
app/pages/tabs/tabs.ts
app/pages/tabs/tabs.ts
import { Component } from '@angular/core'; import { NavParams } from 'ionic-angular'; import { AboutPage } from '../about/about'; import { MapPage } from '../map/map'; import { SchedulePage } from '../schedule/schedule'; import { SpeakerListPage } from '../speaker-list/speaker-list'; @Component({ templateUrl: 'build/pages/tabs/tabs.html' }) export class TabsPage { // set the root pages for each tab tab1Root: any = SchedulePage; tab2Root: any = SpeakerListPage; tab3Root: any = MapPage; tab4Root: any = AboutPage; mySelectedIndex: number; constructor(navParams: NavParams) { this.mySelectedIndex = navParams.data.tabIndex || 3; } }
import { Component } from '@angular/core'; import { NavParams } from 'ionic-angular'; import { AboutPage } from '../about/about'; import { MapPage } from '../map/map'; import { SchedulePage } from '../schedule/schedule'; import { SpeakerListPage } from '../speaker-list/speaker-list'; @Component({ templateUrl: 'build/pages/tabs/tabs.html' }) export class TabsPage { // set the root pages for each tab tab1Root: any = SchedulePage; tab2Root: any = SpeakerListPage; tab3Root: any = AboutPage; tab4Root: any = AboutPage; mySelectedIndex: number; constructor(navParams: NavParams) { this.mySelectedIndex = navParams.data.tabIndex; } }
Make schedule the default tab
Make schedule the default tab
TypeScript
apache-2.0
nReality/SUGSA-ScrumGathering-App2016,nReality/SUGSA-ScrumGathering-App2016,nReality/SUGSA-ScrumGathering-App2016,nReality/SUGSA-ScrumGathering-App2016,nReality/SUGSA-ScrumGathering-App2016,nReality/SUGSA-ScrumGathering-App2016,nReality/SUGSA-ScrumGathering-App2016
--- +++ @@ -15,11 +15,11 @@ // set the root pages for each tab tab1Root: any = SchedulePage; tab2Root: any = SpeakerListPage; - tab3Root: any = MapPage; + tab3Root: any = AboutPage; tab4Root: any = AboutPage; mySelectedIndex: number; constructor(navParams: NavParams) { - this.mySelectedIndex = navParams.data.tabIndex || 3; + this.mySelectedIndex = navParams.data.tabIndex; } }
6d9bc110db9585f33832e72fe7b901f6c87b7a4b
FormBuilder/src/Modules/Exporter.ts
FormBuilder/src/Modules/Exporter.ts
class Exporter { Export(elements: ISerializable[]): string { return JSON.parse(JSON.stringify(elements, this.escapeJSON)); } private GetSerializedItems(elements: ISerializable[]): any { var result = []; for (var i in elements) { result.push(elements[i].Serialize()); } return result; } private escapeJSON(key: string, val: string): string { if (typeof(val) != "string") { return val; } return val .replace(/[\\]/g, '\\\\') .replace(/[\/]/g, '\\/') .replace(/[\b]/g, '\\b') .replace(/[\f]/g, '\\f') .replace(/[\n]/g, '\\n') .replace(/[\r]/g, '\\r') .replace(/[\t]/g, '\\t') .replace(/[\"]/g, '\\"') .replace(/\\'/g, "\\'"); }; }
class Exporter { Export(elements: ISerializable[]): string { return JSON.parse(JSON.stringify(elements, this.escapeJSON)); } private GetSerializedItems(elements: ISerializable[]): any { var result = []; for (var element of elements) { result.push(element.Serialize()); } return result; } private escapeJSON(key: string, val: string): string { if (typeof(val) != "string") { return val; } return val .replace(/[\\]/g, '\\\\') .replace(/[\/]/g, '\\/') .replace(/[\b]/g, '\\b') .replace(/[\f]/g, '\\f') .replace(/[\n]/g, '\\n') .replace(/[\r]/g, '\\r') .replace(/[\t]/g, '\\t') .replace(/[\"]/g, '\\"') .replace(/\\'/g, "\\'"); }; }
Change 'for in' to 'for of'
Change 'for in' to 'for of'
TypeScript
mit
Soneritics/form-builder,Soneritics/form-builder
--- +++ @@ -8,8 +8,8 @@ private GetSerializedItems(elements: ISerializable[]): any { var result = []; - for (var i in elements) { - result.push(elements[i].Serialize()); + for (var element of elements) { + result.push(element.Serialize()); } return result;
74ba383c9b980c20ca02b00a9ea1e82b9df8fd73
src/js/Interfaces/Models/IGitHubRepository.ts
src/js/Interfaces/Models/IGitHubRepository.ts
///<reference path="./IGitHubUser.ts" /> interface IGitHubRepository { id: number; name: String; fullName: string; private: boolean; htmlUrl: string; owner: IGitHubUser; };
///<reference path="./IGitHubUser.ts" /> interface IGitHubRepository { id: number; name: string; fullName: string; private: boolean; htmlUrl: string; owner: IGitHubUser; };
Fix name String -> string
Fix name String -> string
TypeScript
mit
harksys/HawkEye,harksys/HawkEye,harksys/HawkEye
--- +++ @@ -4,7 +4,7 @@ { id: number; - name: String; + name: string; fullName: string;
dac6901db3ddf69ba6047dc5c456336c46f3f8ee
frontend/src/app/last-login-ip/last-login-ip.component.ts
frontend/src/app/last-login-ip/last-login-ip.component.ts
import { Component } from '@angular/core' import * as jwt_decode from 'jwt-decode' @Component({ selector: 'app-last-login-ip', templateUrl: './last-login-ip.component.html', styleUrls: ['./last-login-ip.component.scss'] }) export class LastLoginIpComponent { lastLoginIp: string = '?' ngOnInit () { try { this.parseAuthToken() } catch (err) { console.log(err) } } parseAuthToken () { let payload = {} as any const token = localStorage.getItem('token') if (token) { payload = jwt_decode(token, { header: true }) if (payload.data.lastLoginIp) { this.lastLoginIp = payload.data.lastLoginIp } } } }
import { Component } from '@angular/core' import * as jwt_decode from 'jwt-decode' @Component({ selector: 'app-last-login-ip', templateUrl: './last-login-ip.component.html', styleUrls: ['./last-login-ip.component.scss'] }) export class LastLoginIpComponent { lastLoginIp: string = '?' ngOnInit () { try { this.parseAuthToken() } catch (err) { console.log(err) } } parseAuthToken () { let payload = {} as any const token = localStorage.getItem('token') if (token) { payload = jwt_decode(token) if (payload.data.lastLoginIp) { this.lastLoginIp = payload.data.lastLoginIp } } } }
Fix login ip not getting displayed
Fix login ip not getting displayed Co-Authored-By: MarcRler <6807ecce60afe4562dda8b75f8e7cd2bee819044@live.de>
TypeScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -24,7 +24,7 @@ let payload = {} as any const token = localStorage.getItem('token') if (token) { - payload = jwt_decode(token, { header: true }) + payload = jwt_decode(token) if (payload.data.lastLoginIp) { this.lastLoginIp = payload.data.lastLoginIp }
24fccd4f60e8eff15a975afdc69241df1a7dbe81
scripts/app.ts
scripts/app.ts
/// <reference path='../typings/tsd.d.ts' /> import Q = require("q"); // Register context menu action VSS.register("vsts-extension-ts-seed-simple-action", { getMenuItems: (context) => { return [<IContributedMenuItem>{ title: "Work Item Menu Action" }]; } });
/// <reference path='../typings/tsd.d.ts' /> // Register context menu action VSS.register("vsts-extension-ts-seed-simple-action", { getMenuItems: (context) => { return [<IContributedMenuItem>{ title: "Work Item Menu Action", action: (actionContext) => { let workItemId = actionContext.id || (actionContext.ids && actionContext.ids.length > 0 && actionContext.ids[0]) || (actionContext.workItemIds && actionContext.workItemIds.length > 0 && actionContext.workItemIds[0]); if (workItemId) { alert(`Selected work item ${workItemId}`); } } }]; } });
Add alert action to work item context menu
Add alert action to work item context menu
TypeScript
mit
ostreifel/vsts-contributions,ostreifel/vsts-contributions,ostreifel/vsts-contributions
--- +++ @@ -1,12 +1,19 @@ /// <reference path='../typings/tsd.d.ts' /> - -import Q = require("q"); // Register context menu action VSS.register("vsts-extension-ts-seed-simple-action", { getMenuItems: (context) => { return [<IContributedMenuItem>{ - title: "Work Item Menu Action" + title: "Work Item Menu Action", + action: (actionContext) => { + let workItemId = actionContext.id + || (actionContext.ids && actionContext.ids.length > 0 && actionContext.ids[0]) + || (actionContext.workItemIds && actionContext.workItemIds.length > 0 && actionContext.workItemIds[0]); + + if (workItemId) { + alert(`Selected work item ${workItemId}`); + } + } }]; } });
6494a057b4159e44d2cfc94c25413aca857c6350
src/pages/playground/playground.ts
src/pages/playground/playground.ts
import { Component } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { NavController } from 'ionic-angular'; import { TimeService } from '../../time/time.service'; @Component({ selector: 'page-playground', templateUrl: 'playground.html' }) export class PlaygroundPage { currentTime: string; constructor(public navCtrl: NavController, private _timeService: TimeService) { Observable.interval(10000).forEach(() => this.enqueTimeUpdate()); } enqueTimeUpdate() : void { console.log('enqueTimeUpdate'); this._timeService.getTime().subscribe( json => this.currentTime = `${json.hours}:${json.minutes}:${json.seconds}`, error => console.error('Error: ' + error) ); } }
import { Component } from '@angular/core'; import { Observable } from 'rxjs/Rx'; import { NavController } from 'ionic-angular'; import { TimeService } from '../../time/time.service'; @Component({ selector: 'page-playground', templateUrl: 'playground.html' }) export class PlaygroundPage { currentTime: string; constructor(public navCtrl: NavController, private _timeService: TimeService) { Observable.timer(0, 10000).forEach(() => this.enqueTimeUpdate()); } enqueTimeUpdate() : void { console.log('enqueTimeUpdate'); this._timeService.getTime().subscribe( json => this.currentTime = `${json.hours}:${json.minutes}:${json.seconds}`, error => console.error('Error: ' + error) ); } }
Use Observable.timer instead of Observable.interval to make first request without delay
Use Observable.timer instead of Observable.interval to make first request without delay
TypeScript
apache-2.0
sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile
--- +++ @@ -13,7 +13,7 @@ constructor(public navCtrl: NavController, private _timeService: TimeService) { - Observable.interval(10000).forEach(() => this.enqueTimeUpdate()); + Observable.timer(0, 10000).forEach(() => this.enqueTimeUpdate()); } enqueTimeUpdate() : void {
71f697612426241601c3916e9b0c1983504bc9bc
src/broccoli/default-module-configuration.ts
src/broccoli/default-module-configuration.ts
export default { types: { application: { definitiveCollection: 'main' }, component: { definitiveCollection: 'components' }, renderer: { definitiveCollection: 'main' }, template: { definitiveCollection: 'components' } }, collections: { main: { types: ['application', 'renderer'] }, components: { group: 'ui', types: ['component', 'template'], defaultType: 'component', privateCollections: ['utils'] }, utils: { unresolvable: true } } };
export default { types: { application: { definitiveCollection: 'main' }, component: { definitiveCollection: 'components' }, helper: { definitiveCollection: 'components' }, renderer: { definitiveCollection: 'main' }, template: { definitiveCollection: 'components' } }, collections: { main: { types: ['application', 'renderer'] }, components: { group: 'ui', types: ['component', 'template', 'helper'], defaultType: 'component', privateCollections: ['utils'] }, utils: { unresolvable: true } } };
Add helpers to the default module configuration
Add helpers to the default module configuration
TypeScript
mit
glimmerjs/glimmer-application-pipeline,glimmerjs/glimmer-application-pipeline,glimmerjs/glimmer-application-pipeline
--- +++ @@ -2,6 +2,7 @@ types: { application: { definitiveCollection: 'main' }, component: { definitiveCollection: 'components' }, + helper: { definitiveCollection: 'components' }, renderer: { definitiveCollection: 'main' }, template: { definitiveCollection: 'components' } }, @@ -11,7 +12,7 @@ }, components: { group: 'ui', - types: ['component', 'template'], + types: ['component', 'template', 'helper'], defaultType: 'component', privateCollections: ['utils'] },
ba74b074c28d6cab42c4b04b4c3c2a3c5f664e26
desktop/app/src/chrome/AppWrapper.tsx
desktop/app/src/chrome/AppWrapper.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import {useEffect} from 'react'; import LegacyApp from './LegacyApp'; import fbConfig from '../fb-stubs/config'; import {isFBEmployee} from '../utils/fbEmployee'; import {Logger} from '../fb-interfaces/Logger'; import isSandyEnabled from '../utils/isSandyEnabled'; import {SandyApp} from '../sandy-chrome/SandyApp'; import {notification} from 'antd'; import isProduction from '../utils/isProduction'; type Props = {logger: Logger}; export default function App(props: Props) { useEffect(() => { if (fbConfig.warnFBEmployees && isProduction()) { isFBEmployee().then(() => { notification.warning({ placement: 'bottomLeft', message: 'Please use Flipper@FB', description: ( <> You are using the open-source version of Flipper. Install the internal build from Managed Software Center to get access to more plugins. </> ), duration: null, }); }); } }, []); return isSandyEnabled() ? <SandyApp /> : <LegacyApp logger={props.logger} />; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import {useEffect} from 'react'; import LegacyApp from './LegacyApp'; import fbConfig from '../fb-stubs/config'; import {isFBEmployee} from '../utils/fbEmployee'; import {Logger} from '../fb-interfaces/Logger'; import isSandyEnabled from '../utils/isSandyEnabled'; import {SandyApp} from '../sandy-chrome/SandyApp'; import {notification} from 'antd'; import isProduction from '../utils/isProduction'; type Props = {logger: Logger}; export default function App(props: Props) { useEffect(() => { if (fbConfig.warnFBEmployees && isProduction()) { isFBEmployee().then((isEmployee) => { if (isEmployee) { notification.warning({ placement: 'bottomLeft', message: 'Please use Flipper@FB', description: ( <> You are using the open-source version of Flipper. Install the internal build from Managed Software Center to get access to more plugins. </> ), duration: null, }); } }); } }, []); return isSandyEnabled() ? <SandyApp /> : <LegacyApp logger={props.logger} />; }
Fix employee detection in OSS version
Fix employee detection in OSS version Summary: Changelog: Fix incorrect warning in OSS builds hinting to install a closed source build. Fixes #1853 Reviewed By: passy Differential Revision: D26019227 fbshipit-source-id: 61a0270997d0aa67d55224e4f6268ed3103099c7
TypeScript
mit
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
--- +++ @@ -23,19 +23,21 @@ export default function App(props: Props) { useEffect(() => { if (fbConfig.warnFBEmployees && isProduction()) { - isFBEmployee().then(() => { - notification.warning({ - placement: 'bottomLeft', - message: 'Please use Flipper@FB', - description: ( - <> - You are using the open-source version of Flipper. Install the - internal build from Managed Software Center to get access to more - plugins. - </> - ), - duration: null, - }); + isFBEmployee().then((isEmployee) => { + if (isEmployee) { + notification.warning({ + placement: 'bottomLeft', + message: 'Please use Flipper@FB', + description: ( + <> + You are using the open-source version of Flipper. Install the + internal build from Managed Software Center to get access to + more plugins. + </> + ), + duration: null, + }); + } }); } }, []);
99185a897d89ad7787430754931a02fed52cf40c
app/src/lib/repository-matching.ts
app/src/lib/repository-matching.ts
import * as URL from 'url' import { GitHubRepository } from '../models/github-repository' import { User } from '../models/user' import { Owner } from '../models/owner' import { getHTMLURL } from './api' /** Try to use the list of users and a remote URL to guess a GitHub repository. */ export function matchGitHubRepository(users: ReadonlyArray<User>, remote: string): GitHubRepository | null { for (const ix in users) { const match = matchRemoteWithUser(users[ix], remote) if (match) { return match } } return null } function matchRemoteWithUser(user: User, remote: string): GitHubRepository | null { const htmlURL = getHTMLURL(user.endpoint) const parsed = URL.parse(htmlURL) const host = parsed.hostname // Examples: // https://github.com/octocat/Hello-World.git // git@github.com:octocat/Hello-World.git // git:github.com/octocat/Hello-World.git const regexes = [ new RegExp(`https://${host}/(.+)/(.+)(?:.git)`), new RegExp(`https://${host}/(.+)/(.+)(?:.git)?`), new RegExp(`git@${host}:(.+)/(.+)(?:.git)`), new RegExp(`git:${host}/(.+)/(.+)(?:.git)`), ] for (const regex of regexes) { const result = remote.match(regex) if (!result) { continue } const login = result[1] const name = result[2] if (login && name) { const owner = new Owner(login, user.endpoint) return new GitHubRepository(name, owner, null) } } return null }
import * as URL from 'url' import { GitHubRepository } from '../models/github-repository' import { User } from '../models/user' import { Owner } from '../models/owner' import { getHTMLURL } from './api' import { parseRemote } from './remote-parsing' /** Try to use the list of users and a remote URL to guess a GitHub repository. */ export function matchGitHubRepository(users: ReadonlyArray<User>, remote: string): GitHubRepository | null { for (const ix in users) { const match = matchRemoteWithUser(users[ix], remote) if (match) { return match } } return null } function matchRemoteWithUser(user: User, remote: string): GitHubRepository | null { const htmlURL = getHTMLURL(user.endpoint) const parsed = URL.parse(htmlURL) const host = parsed.hostname const parsedRemote = parseRemote(remote) if (!parsedRemote) { return null } const owner = parsedRemote.owner const name = parsedRemote.name if (parsedRemote.hostname === host && owner && name) { return new GitHubRepository(name, new Owner(owner, user.endpoint), null) } return null }
Use remote parsing here too
Use remote parsing here too
TypeScript
mit
hjobrien/desktop,gengjiawen/desktop,hjobrien/desktop,artivilla/desktop,j-f1/forked-desktop,gengjiawen/desktop,kactus-io/kactus,BugTesterTest/desktops,gengjiawen/desktop,hjobrien/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,BugTesterTest/desktops,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,hjobrien/desktop,say25/desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,shiftkey/desktop,gengjiawen/desktop,desktop/desktop,BugTesterTest/desktops,BugTesterTest/desktops,kactus-io/kactus
--- +++ @@ -4,6 +4,7 @@ import { User } from '../models/user' import { Owner } from '../models/owner' import { getHTMLURL } from './api' +import { parseRemote } from './remote-parsing' /** Try to use the list of users and a remote URL to guess a GitHub repository. */ export function matchGitHubRepository(users: ReadonlyArray<User>, remote: string): GitHubRepository | null { @@ -20,27 +21,13 @@ const parsed = URL.parse(htmlURL) const host = parsed.hostname - // Examples: - // https://github.com/octocat/Hello-World.git - // git@github.com:octocat/Hello-World.git - // git:github.com/octocat/Hello-World.git - const regexes = [ - new RegExp(`https://${host}/(.+)/(.+)(?:.git)`), - new RegExp(`https://${host}/(.+)/(.+)(?:.git)?`), - new RegExp(`git@${host}:(.+)/(.+)(?:.git)`), - new RegExp(`git:${host}/(.+)/(.+)(?:.git)`), - ] + const parsedRemote = parseRemote(remote) + if (!parsedRemote) { return null } - for (const regex of regexes) { - const result = remote.match(regex) - if (!result) { continue } - - const login = result[1] - const name = result[2] - if (login && name) { - const owner = new Owner(login, user.endpoint) - return new GitHubRepository(name, owner, null) - } + const owner = parsedRemote.owner + const name = parsedRemote.name + if (parsedRemote.hostname === host && owner && name) { + return new GitHubRepository(name, new Owner(owner, user.endpoint), null) } return null
6414d8619e1f8889aea4c094717c3d3454a0ef4a
src/api/post-photoset-bulk-reorder.ts
src/api/post-photoset-bulk-reorder.ts
import * as request from 'superagent' import { getLogger } from '../services/log' import * as API from './types/api' const debugPostPhotosetBulkReorder = getLogger('/api/post-photoset-bulk-reorder.ts').debug export function postPhotosetBulkReorder( nsid: string, setIds: string[], orderBy: API.IOrderByOption, isDesc: boolean, token: string, secret: string, ): request.SuperAgentRequest { debugPostPhotosetBulkReorder(`Bulk reorder photosets: ${setIds}`) return request.post('/api/photosets/bulk_reorder') .send({ nsid, setIds, orderBy, isDesc, token, secret }) }
import * as request from 'superagent' import { getLogger } from '../services/log' import * as API from './types/api' const debugPostPhotosetBulkReorder = getLogger('/api/post-photoset-bulk-reorder.ts').debug export function postPhotosetBulkReorder( nsid: string, setIds: string[], orderBy: API.IOrderByOption, isDesc: boolean, token: string, secret: string, ): request.SuperAgentRequest { debugPostPhotosetBulkReorder(`Bulk reorder photosets: ${setIds}`) return request.post('/api/photosets/bulk_reorder') .set({ 'X-Accel-Buffering': 'no' }) .accept('application/octet-stream') .send({ nsid, setIds, orderBy, isDesc, token, secret }) }
Set HTTP header to disable nginx proxy buffer
Set HTTP header to disable nginx proxy buffer
TypeScript
apache-2.0
whitetrefoil/flickr-simple-reorder,whitetrefoil/flickr-simple-reorder,whitetrefoil/flickr-simple-reorder
--- +++ @@ -16,5 +16,7 @@ debugPostPhotosetBulkReorder(`Bulk reorder photosets: ${setIds}`) return request.post('/api/photosets/bulk_reorder') + .set({ 'X-Accel-Buffering': 'no' }) + .accept('application/octet-stream') .send({ nsid, setIds, orderBy, isDesc, token, secret }) }
6025c368b1164e7fb5c8eed138729abd11299ba4
types/skematic-tests.ts
types/skematic-tests.ts
import * as Skematic from '../'; const demoModel: Skematic.Model = { created: { generate: () => new Date().toISOString() }, name: { default: 'Generic Superhero' }, power: { rules: { min: 4, isBig: (v: any) => v > 10 }, transform: v => v.toNumber(), show: ['admin'], write: ['superadmin'] } }; // Check format() const formatOptions: Skematic.FormatOptions = { scopes: ['admin', 'superadmin'], unscope: false, strict: false, defaults: true, once: true, unlock: true, strip: [undefined] }; Skematic.format(demoModel, { name: 'Zim' }); Skematic.format(demoModel.name, 'Zim'); // Check validate() const validateOptions: Skematic.ValidateOptions = { scopes: ['admin'], unscope: false, strict: true, sparse: true }; Skematic.validate(demoModel, { hello: 'yes' }); Skematic.validate(demoModel.power, 20);
import * as Skematic from '../'; const demoModel: Skematic.Model = { created: { generate: () => new Date().toISOString() }, name: { default: 'Generic Superhero' }, power: { rules: { min: 4, isBig: (v: any) => v > 10 }, transform: v => v.toNumber(), show: ['admin'], write: ['superadmin'] } }; // Check format() const formatOptions: Skematic.FormatOptions = { scopes: ['admin', 'superadmin'], unscope: false, strict: false, defaults: true, once: true, unlock: true, strip: [undefined] }; Skematic.format(demoModel, { name: 'Zim' }); Skematic.format(demoModel.name, 'Zim'); // Check validate() const validateOptions: Skematic.ValidateOptions = { scopes: ['admin'], unscope: false, strict: true, sparse: true }; Skematic.validate(demoModel, { hello: 'yes' }); function chk() { const out = Skematic.validate(demoModel.power, 20); return out.valid ? false : out.errors && out.errors[0]; }
Add test for overloaded Validate returns
Add test for overloaded Validate returns
TypeScript
mpl-2.0
mekanika/skematic,mekanika/skematic,mekanika/skematic
--- +++ @@ -39,4 +39,7 @@ Skematic.validate(demoModel, { hello: 'yes' }); -Skematic.validate(demoModel.power, 20); +function chk() { + const out = Skematic.validate(demoModel.power, 20); + return out.valid ? false : out.errors && out.errors[0]; +}
92c0d12e297d44f8beb3e3f36650372f7ce7e365
examples/table_webpack/src/main.ts
examples/table_webpack/src/main.ts
import {h} from '@soil/dom' import {table, ColDef} from './table' type DataRow = { text: string count: number } const colDefs: ColDef<DataRow>[] = [{ headerCell: () => h.th({}, ['Text']), bodyCell: row => h.td({}, [row.text]), bodyCellUpdate: (row, cell) => cell.textContent = row.text }, { headerCell: () => h.th({}, ['Count']), bodyCell: row => h.td({}, ['' + row.count]), bodyCellUpdate: (row, cell) => cell.textContent = '' + row.count, footerCell: data => h.td({}, [ '' + data.map(row => row.count).reduce((a, b) => a + b, 0) ]) }] const $table = table(colDefs) document.body.appendChild($table) setInterval(() => { $table.update( Array(10).fill(0).map(() => ({ text: Math.random().toString(36).substr(2), count: Math.random() })) ) }, 256)
import {h} from '@soil/dom' import {table, ColDef} from './table' type DataRow = { text: string count: number } const colDefs: ColDef<DataRow>[] = [{ headerCell: () => h.th({}, ['Text']), bodyCell: row => h.td({}, [row.text]), bodyCellUpdate: (row, cell) => cell.textContent = row.text }, { headerCell: () => h.th({}, ['Count']), bodyCell: row => h.td({}, ['' + row.count]), bodyCellUpdate: (row, cell) => cell.textContent = '' + row.count, footerCell: data => h.td({}, [ '' + data.map(row => row.count).reduce((a, b) => a + b, 0) ]) }] const $table = table(colDefs) document.body.appendChild($table) const rndInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min setInterval(() => { $table.update( Array(rdnInt(5, 25)).fill(0).map(() => ({ text: Math.random().toString(36).substr(2), count: Math.random() })) ) }, 256)
Make the table size randomly vary
Make the table size randomly vary
TypeScript
agpl-3.0
inad9300/Soil,inad9300/Soil
--- +++ @@ -23,9 +23,11 @@ document.body.appendChild($table) +const rndInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min + setInterval(() => { $table.update( - Array(10).fill(0).map(() => ({ + Array(rdnInt(5, 25)).fill(0).map(() => ({ text: Math.random().toString(36).substr(2), count: Math.random() }))
ec9a5a5ca8336c52be537ecc28e30acd838101b5
lib/cypher/builders/WhereBuilder.ts
lib/cypher/builders/WhereBuilder.ts
import {WhereLiteralQueryPart} from "../match/WhereLiteralQueryPart"; export class WhereBuilder { literal(queryPart:string):WhereLiteralQueryPart { return new WhereLiteralQueryPart(queryPart) } }
import {WhereLiteralQueryPart} from "../match/WhereLiteralQueryPart"; export class WhereBuilder<T = any> { literal(queryPart:string):WhereLiteralQueryPart { return new WhereLiteralQueryPart(queryPart) } //TODO: attribute<K extends keyof T>(prop:T) {} // where(w => [w.attribute('id').in([1,2,3,4,])] }
Add todo to where builder
Add todo to where builder
TypeScript
mit
robak86/neography
--- +++ @@ -1,7 +1,12 @@ import {WhereLiteralQueryPart} from "../match/WhereLiteralQueryPart"; -export class WhereBuilder { + + +export class WhereBuilder<T = any> { literal(queryPart:string):WhereLiteralQueryPart { return new WhereLiteralQueryPart(queryPart) } + + //TODO: + attribute<K extends keyof T>(prop:T) {} // where(w => [w.attribute('id').in([1,2,3,4,])] }
a836fbc36f2af749bdbac2e3e7dc972d4bb0939c
src/metadata/index.ts
src/metadata/index.ts
import { IRocketletAuthorInfo } from './IRocketletAuthorInfo'; import { IRocketletInfo } from './IRocketletInfo'; export { IRocketletAuthorInfo, IRocketletInfo };
import { IRocketletAuthorInfo } from './IRocketletAuthorInfo'; import { IRocketletInfo } from './IRocketletInfo'; import { RocketChatAssociationModel } from './RocketChatAssociationModel'; export { IRocketletAuthorInfo, IRocketletInfo, RocketChatAssociationModel };
Add the RocketChatAssociationModel back in
Add the RocketChatAssociationModel back in
TypeScript
mit
graywolf336/temporary-rocketlets-ts-definition,graywolf336/temporary-rocketlets-ts-definition
--- +++ @@ -1,4 +1,5 @@ import { IRocketletAuthorInfo } from './IRocketletAuthorInfo'; import { IRocketletInfo } from './IRocketletInfo'; +import { RocketChatAssociationModel } from './RocketChatAssociationModel'; -export { IRocketletAuthorInfo, IRocketletInfo }; +export { IRocketletAuthorInfo, IRocketletInfo, RocketChatAssociationModel };
ece020830dd1b409bd4737f5f0234bff29c3f471
src/file-picker.directive.ts
src/file-picker.directive.ts
import { Directive, ElementRef, EventEmitter, HostListener, OnInit, Output, Renderer } from '@angular/core'; @Directive({ selector: '[appFilePicker]' }) export class FilePickerDirective implements OnInit { @Output() public filePick = new EventEmitter(); private input: any; constructor(private el: ElementRef, private renderer: Renderer) { } ngOnInit() { this.input = this.renderer.createElement(this.el.nativeElement.parentNode, 'input'); this.renderer.setElementAttribute(this.input, 'type', 'file'); this.renderer.setElementStyle(this.input, 'display', 'none'); this.renderer.listen(this.input, 'change', (event: any) => { this.filePick.emit(event.target.files[0]); }); } @HostListener('click') browse() { this.renderer.invokeElementMethod(this.input, 'click'); } }
import { Directive, ElementRef, EventEmitter, HostListener, OnInit, Output, Renderer } from '@angular/core'; @Directive({ selector: '[ngFilePicker]' }) export class FilePickerDirective implements OnInit { @Output() public filePick = new EventEmitter(); private input: any; constructor(private el: ElementRef, private renderer: Renderer) { } ngOnInit() { this.input = this.renderer.createElement(this.el.nativeElement.parentNode, 'input'); this.renderer.setElementAttribute(this.input, 'type', 'file'); this.renderer.setElementStyle(this.input, 'display', 'none'); this.renderer.listen(this.input, 'change', (event: any) => { this.filePick.emit(event.target.files[0]); }); } @HostListener('click') browse() { this.renderer.invokeElementMethod(this.input, 'click'); } }
Replace app prefix with ng
Replace app prefix with ng
TypeScript
mit
fvilers/angular-file-picker,fvilers/angular-file-picker,fvilers/angular-file-picker
--- +++ @@ -1,7 +1,7 @@ import { Directive, ElementRef, EventEmitter, HostListener, OnInit, Output, Renderer } from '@angular/core'; @Directive({ - selector: '[appFilePicker]' + selector: '[ngFilePicker]' }) export class FilePickerDirective implements OnInit { @Output()
4d15d13ea5693f84e72f6b530604e866716214a7
src/routes/databaseRouter.ts
src/routes/databaseRouter.ts
/** * This class contains API definitions for companies database connections * Created by Davide Polonio on 03/05/16. */ import * as express from "express"; class DatabaseRouter { private expressRef : express.Express; constructor(expressRef : express.Express) { this.expressRef = expressRef; } } // I have to export something here?
/** * This class contains API definitions for companies database connections * * Created by Davide Polonio on 03/05/16. */ import * as express from "express"; class DatabaseRouter { private expressRef : express.Express; constructor(expressRef : express.Express) { this.expressRef = expressRef; } } // I have to export something here?
Add a space in the comments
Add a space in the comments
TypeScript
mit
BugBusterSWE/MaaS,BugBusterSWE/MaaS,BugBusterSWE/MaaS,BugBusterSWE/MaaS
--- +++ @@ -1,5 +1,6 @@ /** * This class contains API definitions for companies database connections + * * Created by Davide Polonio on 03/05/16. */
4de47b37a11ba28d60de8279bc25b82cb2104ec5
webpack/history.tsx
webpack/history.tsx
import { navigate } from "takeme"; import { maybeStripLegacyUrl } from "./link"; export const push = (url: string) => navigate(maybeStripLegacyUrl(url)); export const getPathArray = () => location.pathname.split("/"); /** This is a stub from the `react-router` days. Don't use it anymore. */ export const history = { push, getCurrentLocation: () => window.location };
import { navigate } from "takeme"; import { maybeStripLegacyUrl } from "./link"; export const push = (url: string) => navigate(maybeStripLegacyUrl(url)); export function getPathArray() { return location.pathname.split("/"); } /** This is a stub from the `react-router` days. Don't use it anymore. */ export const history = { push, getCurrentLocation: () => window.location };
Use non-arrow fn, just to be safe.
Use non-arrow fn, just to be safe.
TypeScript
mit
FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API
--- +++ @@ -3,7 +3,9 @@ export const push = (url: string) => navigate(maybeStripLegacyUrl(url)); -export const getPathArray = () => location.pathname.split("/"); +export function getPathArray() { + return location.pathname.split("/"); +} /** This is a stub from the `react-router` days. Don't use it anymore. */ export const history = { push, getCurrentLocation: () => window.location };
6ca7f95af41cafb8124274d352704ddd018280e4
Models/ModernPlaylist.ts
Models/ModernPlaylist.ts
/** * @license * * ModernPlaylist.ts: Data structure for modern SoundManager2 playlist * ----------------------------------------------- * Copyright (c) 2016 - 2017, The Little Moe New LLC. All rights reserved. * * This file is part of the project 'Sm2Shim'. * Code released under BSD-2-Clause license. * */ namespace Sm2Shim.Player.Models { export interface IModernPlaylist { schemaVersion: number; loop: boolean; autoPlay: boolean; isPlaylistOpen: boolean; playlist: Array<IModernPlaylistItem>; compactMode: boolean; } interface IModernPlaylistItem { audioFileUrl: string; lrcFileUrl: string; title: string; album: string; artist: string; isExplicit: boolean; navigationUrl: string; coverImageUrl: string; } }
/** * @license * * ModernPlaylist.ts: Data structure for modern SoundManager2 playlist * ----------------------------------------------- * Copyright (c) 2016 - 2017, The Little Moe New LLC. All rights reserved. * * This file is part of the project 'Sm2Shim'. * Code released under BSD-2-Clause license. * */ namespace Sm2Shim.Player.Models { export interface IModernPlaylist { schemaVersion: number; loop: boolean; autoPlay: boolean; isPlaylistOpen: boolean; playlist: Array<IModernPlaylistItem>; compactMode: boolean; backgroundColor: string; foregroundColor: string; } interface IModernPlaylistItem { audioFileUrl: string; lrcFileUrl: string; title: string; album: string; artist: string; isExplicit: boolean; navigationUrl: string; coverImageUrl: string; lrcFileOffset: number; } }
Add foreground settings to playlist model.
Add foreground settings to playlist model.
TypeScript
bsd-2-clause
imbushuo/MediaWiki-Sm2Shim,imbushuo/MediaWiki-Sm2Shim,imbushuo/MediaWiki-Sm2Shim,imbushuo/MediaWiki-Sm2Shim,imbushuo/MediaWiki-Sm2Shim
--- +++ @@ -20,6 +20,8 @@ isPlaylistOpen: boolean; playlist: Array<IModernPlaylistItem>; compactMode: boolean; + backgroundColor: string; + foregroundColor: string; } interface IModernPlaylistItem @@ -32,5 +34,6 @@ isExplicit: boolean; navigationUrl: string; coverImageUrl: string; + lrcFileOffset: number; } }
edc8c56c4752aa10473a88ee7d3950b1087b00b7
components/Header.tsx
components/Header.tsx
import Link from "next/link" import { Fragment } from "react" import HorizontalRule from "./HorizontalRule" const Header = () => ( <Fragment> <header> <nav> <Link href="/"> <a>Home</a> </Link> <Link href="/apps"> <a>Apps</a> </Link> <Link href="/posts"> <a>Posts</a> </Link> </nav> <div className="horizontal-rule-container"> <HorizontalRule /> </div> </header> <style jsx>{` header { width: 100vw; padding-top: 8px; display: flex; flex-direction: column; } nav { display: inline-flex; align-self: center; overflow-x: scroll; max-width: 100%; } nav a:first-child { margin-left: var(--content-padding-x); } nav a:last-child { margin-right: var(--content-padding-x); } a { padding: 8px; font-size: 1.5em; white-space: nowrap; } .horizontal-rule-container { width: var(--content-width); margin: 0 auto; } `}</style> </Fragment> ) export default Header
import Link from "next/link" import { Fragment } from "react" import HorizontalRule from "./HorizontalRule" const Header = () => ( <Fragment> <header> <nav> <Link href="/"> <a>Home</a> </Link> <Link href="/apps"> <a>Apps</a> </Link> <Link href="/posts"> <a>Posts</a> </Link> <Link href="/open-source"> <a>Open Source</a> </Link> </nav> <div className="horizontal-rule-container"> <HorizontalRule /> </div> </header> <style jsx>{` header { width: 100vw; padding-top: 8px; display: flex; flex-direction: column; } nav { display: inline-flex; align-self: center; overflow-x: scroll; max-width: 100%; } nav a:first-child { margin-left: var(--content-padding-x); } nav a:last-child { margin-right: var(--content-padding-x); } a { padding: 8px; font-size: 1.5em; white-space: nowrap; } .horizontal-rule-container { width: var(--content-width); margin: 0 auto; } `}</style> </Fragment> ) export default Header
Add open source link to header
Add open source link to header
TypeScript
mit
JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk
--- +++ @@ -14,6 +14,9 @@ </Link> <Link href="/posts"> <a>Posts</a> + </Link> + <Link href="/open-source"> + <a>Open Source</a> </Link> </nav> <div className="horizontal-rule-container">
a10bad0248e918c9badc42f5710b14a61cd667bf
ui/src/admin/components/DeprecationWarning.tsx
ui/src/admin/components/DeprecationWarning.tsx
import React, {SFC} from 'react' interface Props { message: string } const DeprecationWarning: SFC<Props> = ({message}) => ( <div className="alert alert-primary"> <span className="icon stop" /> <div className="alert-message">{message}</div> </div> ) export default DeprecationWarning
import React, {SFC} from 'react' interface Props { message: string } const DeprecationWarning: SFC<Props> = ({message}) => ( <div className="alert alert-primary"> <span className="icon octagon" /> <div className="alert-message">{message}</div> </div> ) export default DeprecationWarning
Use octagon icon in deprecation warning alert
Use octagon icon in deprecation warning alert
TypeScript
mit
nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,li-ang/influxdb
--- +++ @@ -6,7 +6,7 @@ const DeprecationWarning: SFC<Props> = ({message}) => ( <div className="alert alert-primary"> - <span className="icon stop" /> + <span className="icon octagon" /> <div className="alert-message">{message}</div> </div> )
6390a987082ce50e9c4cdb742ab8a8fe4665b9fe
src/app/navbar/navbar.component.ts
src/app/navbar/navbar.component.ts
import { AuthService } from 'ng2-ui-auth'; import { Component, OnInit, OnChanges } from '@angular/core'; import { Router } from '@angular/router'; import { LogoutService } from './../shared/logout.service'; import { Logout } from '../loginComponents/logout'; import { TrackLoginService } from './../shared/track-login.service'; import { UserService } from './../loginComponents/user.service'; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'], providers: [UserService] }) export class NavbarComponent extends Logout { private user; constructor (trackLoginService: TrackLoginService, logoutService: LogoutService, router: Router, userService: UserService) { super(trackLoginService, logoutService, router); userService.getUser().subscribe(user => { this.user = user; }); } }
import { AuthService } from 'ng2-ui-auth'; import { Component, OnInit, OnChanges } from '@angular/core'; import { Router } from '@angular/router'; import { LogoutService } from './../shared/logout.service'; import { Logout } from '../loginComponents/logout'; import { TrackLoginService } from './../shared/track-login.service'; import { UserService } from './../loginComponents/user.service'; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'], }) export class NavbarComponent extends Logout { private user; constructor (trackLoginService: TrackLoginService, logoutService: LogoutService, router: Router, userService: UserService) { super(trackLoginService, logoutService, router); userService.user$.subscribe(user => { this.user = user; }); } }
Fix for username not always showing up
Fix for username not always showing up
TypeScript
apache-2.0
dockstore/dockstore-ui2,dockstore/dockstore-ui2,dockstore/dockstore-ui2,dockstore/dockstore-ui2
--- +++ @@ -12,13 +12,12 @@ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'], - providers: [UserService] }) export class NavbarComponent extends Logout { private user; constructor (trackLoginService: TrackLoginService, logoutService: LogoutService, router: Router, userService: UserService) { super(trackLoginService, logoutService, router); - userService.getUser().subscribe(user => { + userService.user$.subscribe(user => { this.user = user; }); }
ca4e68f0f7ccc9de0b1d76e92e808bcc0c3db864
mangarack-component-core/src/providers/mangafox/default.ts
mangarack-component-core/src/providers/mangafox/default.ts
import * as mio from '../../default'; import {createSeriesAsync} from './series'; /** * Represents the provider. */ export let mangafox: mio.IProvider = {isSupported: isSupported, name: 'mangafox', seriesAsync: seriesAsync}; /** * Determines whether the address is a supported address. * @param address The address. * @return Indicates whether the address is a supported address. */ function isSupported(address: string): boolean { return /^http:\/\/mangafox\.me\/manga\/.+\/$/i.test(address); } /** * Promises the series. * @param address The address. * @return The promise for the series. */ function seriesAsync(address: string): Promise<mio.ISeries> { if (isSupported) { return createSeriesAsync(address); } else { throw new Error(`Invalid series address: ${address}`); } }
import * as mio from '../../default'; import {createSeriesAsync} from './series'; /** * Represents the provider. */ export let mangafox: mio.IProvider = {isSupported: isSupported, name: 'mangafox', seriesAsync: seriesAsync}; /** * Determines whether the address is a supported address. * @param address The address. * @return Indicates whether the address is a supported address. */ function isSupported(address: string): boolean { return /^https?:\/\/mangafox\.me\/manga\/.+\/$/i.test(address); } /** * Promises the series. * @param address The address. * @return The promise for the series. */ function seriesAsync(address: string): Promise<mio.ISeries> { let normalizedAddress = normalizeAddress(address); if (isSupported(normalizedAddress)) { return createSeriesAsync(normalizedAddress); } else { throw new Error(`Invalid series address: ${address}`); } } /** * Normalizes the address. * @param address The address. * @return The normalized address. */ function normalizeAddress(address: string): string { if (/^http:\/\//i.test(address)) { return `https://${address.substr(7)}`; } else { return address; } }
Convert HTTP to HTTPS and support HTTPS URLs
MangaFox: Convert HTTP to HTTPS and support HTTPS URLs
TypeScript
mit
Deathspike/mangarack.js,MangaRack/mangarack,MangaRack/mangarack,Deathspike/mangarack.js,MangaRack/mangarack,Deathspike/mangarack.js
--- +++ @@ -12,7 +12,7 @@ * @return Indicates whether the address is a supported address. */ function isSupported(address: string): boolean { - return /^http:\/\/mangafox\.me\/manga\/.+\/$/i.test(address); + return /^https?:\/\/mangafox\.me\/manga\/.+\/$/i.test(address); } /** @@ -21,9 +21,23 @@ * @return The promise for the series. */ function seriesAsync(address: string): Promise<mio.ISeries> { - if (isSupported) { - return createSeriesAsync(address); + let normalizedAddress = normalizeAddress(address); + if (isSupported(normalizedAddress)) { + return createSeriesAsync(normalizedAddress); } else { throw new Error(`Invalid series address: ${address}`); } } + +/** + * Normalizes the address. + * @param address The address. + * @return The normalized address. + */ +function normalizeAddress(address: string): string { + if (/^http:\/\//i.test(address)) { + return `https://${address.substr(7)}`; + } else { + return address; + } +}
6841030aeb35df51d6279d5bd8ede7c7056a0c83
packages/truffle-db/src/loaders/test/index.ts
packages/truffle-db/src/loaders/test/index.ts
import fs from "fs"; import path from "path"; import { TruffleDB } from "truffle-db"; const fixturesDirectory = path.join( __dirname, // truffle-db/src/loaders/test "..", // truffle-db/src/loaders "..", // truffle-db/src "..", // truffle-db "test", "fixtures" ); // minimal config const config = { contracts_build_directory: fixturesDirectory }; const db = new TruffleDB(config); const Migrations = require(path.join(fixturesDirectory, "Migrations.json")); const GetContractNames = ` query GetContractNames { artifactsLoader { contractNames } } `; it("lists artifact contract names", async () => { const result = await db.query(GetContractNames); expect(result).toHaveProperty("data"); const { data } = result; expect(data).toHaveProperty("artifactsLoader"); const { artifactsLoader } = data; expect(artifactsLoader).toHaveProperty("contractNames"); const { contractNames } = artifactsLoader; expect(contractNames).toContain("Migrations"); }); const GetSource = ` query GetSource() { artifactsLoader { source { id contents sourcePath } } }`; it.skip("gets source correctly ", async () => { const result = await db.query(GetSource); expect(result).toHaveProperty("data"); });
import fs from "fs"; import path from "path"; import gql from "graphql-tag"; import { TruffleDB } from "truffle-db"; const fixturesDirectory = path.join(__dirname, "..", "artifacts", "test"); // minimal config const config = { contracts_build_directory: path.join(fixturesDirectory, "build"), contracts_directory: path.join(fixturesDirectory, "compilationSources"), all: true }; const db = new TruffleDB(config); const Build = require(path.join(fixturesDirectory, "build", "SimpleStorage.json")); const Load = gql ` mutation LoadArtifacts { loaders { artifactsLoad { success } } } ` it("loads artifacts and returns true ", async () => { const { data: { loaders: { artifactsLoad: { success } } } } = await db.query(Load); expect(success).toEqual(true); });
Add basic test for loader mutation
Add basic test for loader mutation
TypeScript
mit
ConsenSys/truffle
--- +++ @@ -1,61 +1,42 @@ import fs from "fs"; import path from "path"; +import gql from "graphql-tag"; import { TruffleDB } from "truffle-db"; -const fixturesDirectory = path.join( - __dirname, // truffle-db/src/loaders/test - "..", // truffle-db/src/loaders - "..", // truffle-db/src - "..", // truffle-db - "test", - "fixtures" -); + +const fixturesDirectory = path.join(__dirname, "..", "artifacts", "test"); // minimal config const config = { - contracts_build_directory: fixturesDirectory + contracts_build_directory: path.join(fixturesDirectory, "build"), + contracts_directory: path.join(fixturesDirectory, "compilationSources"), + all: true }; const db = new TruffleDB(config); -const Migrations = require(path.join(fixturesDirectory, "Migrations.json")); +const Build = require(path.join(fixturesDirectory, "build", "SimpleStorage.json")); -const GetContractNames = ` -query GetContractNames { - artifactsLoader { - contractNames - } -} -`; - -it("lists artifact contract names", async () => { - const result = await db.query(GetContractNames); - expect(result).toHaveProperty("data"); - - const { data } = result; - expect(data).toHaveProperty("artifactsLoader"); - - const { artifactsLoader } = data; - expect(artifactsLoader).toHaveProperty("contractNames"); - - const { contractNames } = artifactsLoader; - expect(contractNames).toContain("Migrations"); -}); - - -const GetSource = ` -query GetSource() { - artifactsLoader { - source { - id - contents - sourcePath +const Load = gql ` + mutation LoadArtifacts { + loaders { + artifactsLoad { + success + } } } -}`; +` -it.skip("gets source correctly ", async () => { - const result = await db.query(GetSource); - expect(result).toHaveProperty("data"); +it("loads artifacts and returns true ", async () => { + const { + data: { + loaders: { + artifactsLoad: { + success + } + } + } + } = await db.query(Load); + expect(success).toEqual(true); });
c15e4323a1eb1277cde39e6305d416ab06c18eb0
src/renderer/global-styles/base.ts
src/renderer/global-styles/base.ts
import { css, theme } from "renderer/styles"; import env from "common/env"; const testDisables = () => { if (!env.integrationTests) { return css``; } return css` * { transition-property: none !important; -o-transition-property: none !important; -moz-transition-property: none !important; -ms-transition-property: none !important; -webkit-transition-property: none !important; animation: none !important; -o-animation: none !important; -moz-animation: none !important; -ms-animation: none !important; -webkit-animation: none !important; } `; }; export default css` html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; user-select: none; font-family: LatoWeb, sans-serif; color: ${theme.baseText}; } img.emojione { width: 20px; margin-bottom: -4px; } a { color: ${theme.accent}; &[href^="itch:"] { color: ${theme.baseText}; text-decoration: none; &:hover { cursor: pointer; } &:active { transform: translateY(1px); } } } ${testDisables()}; `;
import { css, theme } from "renderer/styles"; import env from "common/env"; const testDisables = () => { if (!env.integrationTests) { return css``; } return css` * { transition-property: none !important; -o-transition-property: none !important; -moz-transition-property: none !important; -ms-transition-property: none !important; -webkit-transition-property: none !important; animation: none !important; -o-animation: none !important; -moz-animation: none !important; -ms-animation: none !important; -webkit-animation: none !important; } `; }; export default css` html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; user-select: none; font-family: LatoWeb, sans-serif; color: ${theme.baseText}; } img.emojione { width: 20px; margin-bottom: -4px; } img { user-drag: none; } a { color: ${theme.accent}; &[href^="itch:"] { color: ${theme.baseText}; text-decoration: none; &:hover { cursor: pointer; } &:active { transform: translateY(1px); } } } ${testDisables()}; `;
Make all images non-draggable by default
Make all images non-draggable by default
TypeScript
mit
itchio/itch,itchio/itch,itchio/itchio-app,itchio/itch,itchio/itchio-app,itchio/itch,itchio/itchio-app,itchio/itch,itchio/itch,leafo/itchio-app,leafo/itchio-app,leafo/itchio-app
--- +++ @@ -41,6 +41,10 @@ margin-bottom: -4px; } + img { + user-drag: none; + } + a { color: ${theme.accent};
fec904d5b163c4ba7bc247d4fc7ee527b072b648
packages/xstate-immer/src/index.ts
packages/xstate-immer/src/index.ts
import { EventObject, OmniEventObject, ActionObject } from 'xstate'; import { produce, Draft } from 'immer'; import { actionTypes } from 'xstate/lib/actions'; export type ImmerAssigner<TContext, TEvent extends EventObject> = ( context: Draft<TContext>, event: TEvent ) => void; export interface ImmerAssignAction<TContext, TEvent extends EventObject> extends ActionObject<TContext, TEvent> { assignment: ImmerAssigner<TContext, TEvent>; } export function assign<TContext, TEvent extends EventObject = EventObject>( assignment: ImmerAssigner<TContext, TEvent> ): ImmerAssignAction<TContext, TEvent> { return { type: actionTypes.assign, assignment }; } export function updater<TContext, TEvent extends EventObject>( context: TContext, event: OmniEventObject<TEvent>, assignActions: Array<ImmerAssignAction<TContext, TEvent>> ): TContext { const updatedContext = context ? assignActions.reduce((acc, assignAction) => { const { assignment } = assignAction as ImmerAssignAction< TContext, OmniEventObject<TEvent> >; const update = produce(acc, interim => void assignment(interim, event)); return update; }, context) : context; return updatedContext as TContext; }
import { EventObject, ActionObject } from 'xstate'; import { produce, Draft } from 'immer'; import { actionTypes } from 'xstate/lib/actions'; export type ImmerAssigner<TContext, TEvent extends EventObject> = ( context: Draft<TContext>, event: TEvent ) => void; export interface ImmerAssignAction<TContext, TEvent extends EventObject> extends ActionObject<TContext, TEvent> { assignment: ImmerAssigner<TContext, TEvent>; } export function assign<TContext, TEvent extends EventObject = EventObject>( assignment: ImmerAssigner<TContext, TEvent> ): ImmerAssignAction<TContext, TEvent> { return { type: actionTypes.assign, assignment }; } export function updater<TContext, TEvent extends EventObject>( context: TContext, event: TEvent, assignActions: Array<ImmerAssignAction<TContext, TEvent>> ): TContext { const updatedContext = context ? assignActions.reduce((acc, assignAction) => { const { assignment } = assignAction as ImmerAssignAction< TContext, TEvent >; const update = produce(acc, interim => void assignment(interim, event)); return update; }, context) : context; return updatedContext as TContext; }
Remove OmniEventObject usage from @xstate/immer
Remove OmniEventObject usage from @xstate/immer
TypeScript
mit
davidkpiano/xstate,davidkpiano/xstate,davidkpiano/xstate
--- +++ @@ -1,4 +1,4 @@ -import { EventObject, OmniEventObject, ActionObject } from 'xstate'; +import { EventObject, ActionObject } from 'xstate'; import { produce, Draft } from 'immer'; import { actionTypes } from 'xstate/lib/actions'; @@ -23,14 +23,14 @@ export function updater<TContext, TEvent extends EventObject>( context: TContext, - event: OmniEventObject<TEvent>, + event: TEvent, assignActions: Array<ImmerAssignAction<TContext, TEvent>> ): TContext { const updatedContext = context ? assignActions.reduce((acc, assignAction) => { const { assignment } = assignAction as ImmerAssignAction< TContext, - OmniEventObject<TEvent> + TEvent >; const update = produce(acc, interim => void assignment(interim, event));
dc953b5b73964f08cbebc1709b017a881cf6024a
resources/assets/js/dash_routes.ts
resources/assets/js/dash_routes.ts
import {RouteProps} from "react-router"; interface Route extends RouteProps { name: string } const routes: Route[] = [ { path: '/', exact: true, component: require('./components/dashboard/General').default, name: 'General' }, { path: '/permissions', component: require('./components/dashboard/Permissions').default, name: 'Permissions' }, { path: '/commands', component: require('./components/dashboard/Commands').default, name: 'Custom Commands' }, { path: '/music', component: require('./components/dashboard/Music').default, name: 'Music' }, { path: '/infractions', component: require('./components/dashboard/Infractions').default, name: 'Infractions' }, { path: '/spam', component: require('./components/dashboard/Spam').default, name: 'Spam' }, { path: '/raid', component: require('./components/Dashboard/AntiRaid').default, name: 'Anti-Raid' } ]; export default routes;
import {RouteProps} from "react-router"; interface Route extends RouteProps { name: string } const routes: Route[] = [ { path: '/', exact: true, component: require('./components/dashboard/General').default, name: 'General' }, { path: '/permissions', component: require('./components/dashboard/Permissions').default, name: 'Permissions' }, { path: '/commands', component: require('./components/dashboard/Commands').default, name: 'Custom Commands' }, { path: '/music', component: require('./components/dashboard/Music').default, name: 'Music' }, { path: '/infractions', component: require('./components/dashboard/Infractions').default, name: 'Infractions' }, { path: '/spam', component: require('./components/dashboard/Spam').default, name: 'Spam' }, { path: '/raid', component: require('./components/dashboard/AntiRaid').default, name: 'Anti-Raid' } ]; export default routes;
Fix capitalization on anti-raid route
Fix capitalization on anti-raid route
TypeScript
mit
mrkirby153/KirBotPanel,mrkirby153/KirBotPanel,mrkirby153/KirBotPanel,mrkirby153/KirBotPanel
--- +++ @@ -38,7 +38,7 @@ }, { path: '/raid', - component: require('./components/Dashboard/AntiRaid').default, + component: require('./components/dashboard/AntiRaid').default, name: 'Anti-Raid' } ];
9e7a63e1b2dbcc177f228d03a18ed3fa7962d40a
src/shared/utils/resolveDatabases.ts
src/shared/utils/resolveDatabases.ts
import { resolveRoot } from './resolveRoot' import { join } from 'path' export function resolveDatabases() { if (process.env.NODE_ENV === 'development') { return join(resolveRoot(), 'databases') } else { return join(resolveRoot(), '..', 'databases') } }
import { resolveRoot } from './resolveRoot' import { join } from 'path' import * as fs from 'fs' export function resolveDatabases() { let databasesFolder: string if (process.env.NODE_ENV === 'development') { databasesFolder = join(resolveRoot(), 'databases') } else { databasesFolder = join(resolveRoot(), '..', 'databases') } if (!fs.existsSync(databasesFolder)) { fs.mkdirSync(databasesFolder) } return databasesFolder }
Create db folder in none
Create db folder in none
TypeScript
mit
wasd171/chatinder,wasd171/chatinder,wasd171/chatinder
--- +++ @@ -1,10 +1,18 @@ import { resolveRoot } from './resolveRoot' import { join } from 'path' +import * as fs from 'fs' export function resolveDatabases() { + let databasesFolder: string if (process.env.NODE_ENV === 'development') { - return join(resolveRoot(), 'databases') + databasesFolder = join(resolveRoot(), 'databases') } else { - return join(resolveRoot(), '..', 'databases') + databasesFolder = join(resolveRoot(), '..', 'databases') } + + if (!fs.existsSync(databasesFolder)) { + fs.mkdirSync(databasesFolder) + } + + return databasesFolder }
edd63bf98d0fcaff5ff252b7156d6905fb97d69d
src/isaac-generator.ts
src/isaac-generator.ts
export class IsaacGenerator { private _count: number; constructor() { this._count = 0; } public getValue(): number { return 0; } private _randomise(): void { } }
export class IsaacGenerator { private _count: number; constructor() { this._count = 0; } public getValue(): number { if (this._count === 0) { this._randomise(); } return 0; } private _randomise(): void { } }
Call randomise if no results
Call randomise if no results
TypeScript
mit
Jameskmonger/isaac-crypto
--- +++ @@ -6,6 +6,10 @@ } public getValue(): number { + if (this._count === 0) { + this._randomise(); + } + return 0; }
82422a6f99ce63b1b8228f77da44fd64965c4167
server.ts
server.ts
"use strict"; /* Import libraries **********************************************************/ import * as express from 'express'; import * as winston from 'winston'; import * as hello from './hello'; /* Set up Winston for logging ************************************************/ let logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return (new Date).toISOString(); }, handleExceptions: true }) ] }); logger.info('Hello starting'); /* Set up doing something useful *********************************************/ let app = express(); app.get("/", function(request, response) { response.send(hello.greeting()); }); let server = app.listen(8080); /* Set up exit handler *******************************************************/ process.on('exit', function() { logger.info('Hello stopping'); if(server !== undefined) { server.close(); } }); process.on('SIGINT', function() { process.exit(0); }); process.on('SIGTERM', function() { process.exit(0); }); /* Done, process held open by I/O ********************************************/ logger.info('Hello started');
"use strict"; /* Import libraries **********************************************************/ import * as express from 'express'; import * as winston from 'winston'; import * as hello from './hello'; /* Set up Winston for logging ************************************************/ let logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: () => { return (new Date).toISOString(); }, handleExceptions: true }) ] }); logger.info('Hello starting'); /* Set up doing something useful *********************************************/ let app = express(); app.get("/", (request, response) => { response.send(hello.greeting()); }); let server = app.listen(8080); /* Set up exit handler *******************************************************/ process.on('exit', () => { logger.info('Hello stopping'); if(server !== undefined) { server.close(); } }); process.on('SIGINT', () => { process.exit(0); }); process.on('SIGTERM', () => { process.exit(0); }); /* Done, process held open by I/O ********************************************/ logger.info('Hello started');
Switch anonymous functions to arrow syntax
Switch anonymous functions to arrow syntax It's a little cleaner, and has less surprising behaviour so is safer to default to.
TypeScript
unlicense
LionsPhil/typescript-service-container-template
--- +++ @@ -12,7 +12,7 @@ let logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ - timestamp: function() { + timestamp: () => { return (new Date).toISOString(); }, handleExceptions: true @@ -26,7 +26,7 @@ let app = express(); -app.get("/", function(request, response) { +app.get("/", (request, response) => { response.send(hello.greeting()); }); @@ -34,7 +34,7 @@ /* Set up exit handler *******************************************************/ -process.on('exit', function() { +process.on('exit', () => { logger.info('Hello stopping'); if(server !== undefined) { @@ -42,8 +42,8 @@ } }); -process.on('SIGINT', function() { process.exit(0); }); -process.on('SIGTERM', function() { process.exit(0); }); +process.on('SIGINT', () => { process.exit(0); }); +process.on('SIGTERM', () => { process.exit(0); }); /* Done, process held open by I/O ********************************************/
770af7605b9489c4fe76a46d6dbc4a770a4b7cac
test/components/error.spec.tsx
test/components/error.spec.tsx
import * as React from "react"; import { shallow, mount, render } from "enzyme"; import { MgError } from "../../src/api/error"; import { Error } from "../../src/components/error"; function throwme() { throw new MgError("Uh oh!"); } function captureError() { let err: any; try { throwme(); } catch (e) { err = e; } return err; } describe("components/error", () => { it("renders a MgError with stack", () => { const err = captureError(); const wrapper = shallow(<Error error={err} />); expect(wrapper.find(".bp3-callout")).toHaveLength(1); expect(wrapper.find(".bp3-callout .error-header")).toHaveLength(1); expect(wrapper.find(".bp3-callout .error-header").text()).toBe(err.message); expect(wrapper.find(".bp3-callout .error-stack")).toHaveLength(1); }); it("renders a string without a stack", () => { const err = "Uh oh!"; const wrapper = shallow(<Error error={err} />); expect(wrapper.find(".bp3-callout")).toHaveLength(1); expect(wrapper.find(".bp3-callout .error-header")).toHaveLength(1); expect(wrapper.find(".bp3-callout .error-header").text()).toBe(err); expect(wrapper.find(".bp3-callout .error-stack")).toHaveLength(0); }); });
import * as React from "react"; import { shallow, mount, render } from "enzyme"; import { MgError } from "../../src/api/error"; import { Error } from "../../src/components/error"; function throwme() { throw new MgError("Uh oh!"); } function captureError() { let err: any; try { throwme(); } catch (e) { err = e; } return err; } describe("components/error", () => { it("renders a MgError with stack", () => { const err = captureError(); const wrapper = render(<Error error={err} />); expect(wrapper.find(".error-header")).toHaveLength(1); expect(wrapper.find(".error-header").text()).toBe(err.message); expect(wrapper.find(".error-stack")).toHaveLength(1); }); it("renders a string without a stack", () => { const err = "Uh oh!"; const wrapper = render(<Error error={err} />); expect(wrapper.find(".error-header")).toHaveLength(1); expect(wrapper.find(".error-header").text()).toBe(err); expect(wrapper.find(".error-stack")).toHaveLength(0); }); });
Fix failing enzyme tests to due structural change in Error component
Fix failing enzyme tests to due structural change in Error component
TypeScript
mit
jumpinjackie/mapguide-react-layout,jumpinjackie/mapguide-react-layout,jumpinjackie/mapguide-react-layout,jumpinjackie/mapguide-react-layout,jumpinjackie/mapguide-react-layout
--- +++ @@ -20,18 +20,16 @@ describe("components/error", () => { it("renders a MgError with stack", () => { const err = captureError(); - const wrapper = shallow(<Error error={err} />); - expect(wrapper.find(".bp3-callout")).toHaveLength(1); - expect(wrapper.find(".bp3-callout .error-header")).toHaveLength(1); - expect(wrapper.find(".bp3-callout .error-header").text()).toBe(err.message); - expect(wrapper.find(".bp3-callout .error-stack")).toHaveLength(1); + const wrapper = render(<Error error={err} />); + expect(wrapper.find(".error-header")).toHaveLength(1); + expect(wrapper.find(".error-header").text()).toBe(err.message); + expect(wrapper.find(".error-stack")).toHaveLength(1); }); it("renders a string without a stack", () => { const err = "Uh oh!"; - const wrapper = shallow(<Error error={err} />); - expect(wrapper.find(".bp3-callout")).toHaveLength(1); - expect(wrapper.find(".bp3-callout .error-header")).toHaveLength(1); - expect(wrapper.find(".bp3-callout .error-header").text()).toBe(err); - expect(wrapper.find(".bp3-callout .error-stack")).toHaveLength(0); + const wrapper = render(<Error error={err} />); + expect(wrapper.find(".error-header")).toHaveLength(1); + expect(wrapper.find(".error-header").text()).toBe(err); + expect(wrapper.find(".error-stack")).toHaveLength(0); }); });
8bbd08db0536bd6359347a42ae48f0769c805878
src/sagas/playAudio.ts
src/sagas/playAudio.ts
import { call, select } from 'redux-saga/effects'; import { PlayAudio } from '../actions/audio'; import { RootState } from '../types'; const playAudioFile = async (file: HTMLAudioElement, volume: number) => { try { file.volume = volume; return await file.play(); } catch (e) { console.warn(e); } }; export function* playAudio(action: PlayAudio) { const audioEnabled: boolean = yield select( (state: RootState) => state.audioSettingsV1.enabled ); try { if (audioEnabled) { const volume: number = yield select( (state: RootState) => state.audioSettingsV1.volume ); yield (action.file.volume = volume); yield call(playAudioFile, action.file, volume); } } catch (e) { console.warn('Playing audio failed.'); } }
import { call, select } from 'redux-saga/effects'; import { PlayAudio } from '../actions/audio'; import { RootState } from '../types'; const playAudioFile = async (file: HTMLAudioElement, volume: number) => { try { file.volume = volume; return await file.play(); } catch (e) { console.warn(e); } }; export function* playAudio(action: PlayAudio) { const audioEnabled: boolean = yield select( (state: RootState) => state.audioSettingsV1.enabled ); try { if (audioEnabled) { const volume: number = yield select( (state: RootState) => state.audioSettingsV1.volume ); yield call(playAudioFile, action.file, volume); } } catch (e) { console.warn('Playing audio failed.'); } }
Fix redundant setting of file volume.
Fix redundant setting of file volume.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -21,7 +21,6 @@ const volume: number = yield select( (state: RootState) => state.audioSettingsV1.volume ); - yield (action.file.volume = volume); yield call(playAudioFile, action.file, volume); } } catch (e) {
e83c75c3add24f4121780f55c0a274a880ea24e9
test/typescript/hubspot.ts
test/typescript/hubspot.ts
import Hubspot, { ApiOptions, AccessTokenOptions, HubspotError, } from '../..'; import { RequestError } from 'request-promise/errors'; const apiKeyOptions: ApiOptions = { apiKey: 'apiKey' }; const tokenOptions: AccessTokenOptions = { accessToken: 'token' }; const baseUrlOptions: AccessTokenOptions = { accessToken: 'token', baseUrl: 'http://some-url' }; const handleResponse = (response) => { console.log(response); } const handleError = (requestError: RequestError) => { const error = requestError.error as HubspotError; console.log(error.status); console.log(error.message); console.log(error.correlationId); console.log(error.requestId); } const hubspot = new Hubspot(apiKeyOptions); // Promise hubspot.companies.get( { limit: 1 }) .then(handleResponse) .catch(handleError) // Callback hubspot.companies.properties.groups.get((err: HubspotError, results) => { if (err) { console.error(err) } console.log(results); });
import Hubspot, { ApiOptions, HubspotError, } from '../..'; import { RequestError } from 'request-promise/errors'; const apiKeyOptions: ApiOptions = { apiKey: 'demo' }; const handleResponse = (response) => { console.log(response); } const handleError = (requestError: RequestError) => { const error = requestError.error as HubspotError; console.log(error.status); console.log(error.message); console.log(error.correlationId); console.log(error.requestId); } const hubspot = new Hubspot(apiKeyOptions); // Promise hubspot.companies.get( { limit: 1 }) .then(handleResponse) .catch(handleError) // Callback hubspot.companies.properties.groups.get((err: HubspotError, results) => { if (err) { console.error(err) } console.log(results); });
Remove unused parameters in typescript test file
Remove unused parameters in typescript test file Unfortunately, you can't ignore this compiler option like a lint option. See [here](https://github.com/Microsoft/TypeScript/issues/11051). While it would be nice to prove out that the access option defintion is working, there's a lot of things that aren't included in this test file anyways so it needs to be revisited. This also switches the hapi key to something that actually works. This PR is the completion of: https://github.com/brainflake/node-hubspot/pull/97
TypeScript
mit
brainflake/node-hubspot,brainflake/node-hubspot
--- +++ @@ -1,13 +1,10 @@ import Hubspot, { ApiOptions, - AccessTokenOptions, HubspotError, } from '../..'; import { RequestError } from 'request-promise/errors'; -const apiKeyOptions: ApiOptions = { apiKey: 'apiKey' }; -const tokenOptions: AccessTokenOptions = { accessToken: 'token' }; -const baseUrlOptions: AccessTokenOptions = { accessToken: 'token', baseUrl: 'http://some-url' }; +const apiKeyOptions: ApiOptions = { apiKey: 'demo' }; const handleResponse = (response) => { console.log(response);
ad6e109dec4d5813ca931a9978dee9dcda1b2eb8
lib/appbuilder-cli.ts
lib/appbuilder-cli.ts
require("./bootstrap"); import * as shelljs from "shelljs"; shelljs.config.silent = true; import { installUncaughtExceptionListener } from "./common/errors"; installUncaughtExceptionListener(process.exit); (async () => { let commandDispatcher: ICommandDispatcher = $injector.resolve("commandDispatcher"); let config: Config.IConfig = $injector.resolve("$config"); let errors: IErrors = $injector.resolve("$errors"); errors.printCallStack = config.DEBUG; let messages = <IMessagesService>$injector.resolve("$messagesService"); messages.pathsToMessageJsonFiles = [/* Place client-specific json message file paths here */]; if (process.argv[2] === "completion") { await commandDispatcher.completeCommand(); } else { await commandDispatcher.dispatchCommand(); } })();
require("./bootstrap"); import * as shelljs from "shelljs"; shelljs.config.silent = true; import { installUncaughtExceptionListener } from "./common/errors"; installUncaughtExceptionListener(process.exit); (async () => { let commandDispatcher: ICommandDispatcher = $injector.resolve("commandDispatcher"); // let config: Config.IConfig = $injector.resolve("$config"); // let errors: IErrors = $injector.resolve("$errors"); // errors.printCallStack = config.DEBUG; // let messages = <IMessagesService>$injector.resolve("$messagesService"); // messages.pathsToMessageJsonFiles = [/* Place client-specific json message file paths here */]; if (process.argv[2] === "completion") { await commandDispatcher.completeCommand(); } else { await commandDispatcher.dispatchCommand(); } $injector.dispose(); })();
Call injector.dispose at the end of entry point in order to break the process once we finish our work
Call injector.dispose at the end of entry point in order to break the process once we finish our work
TypeScript
apache-2.0
Icenium/icenium-cli,Icenium/icenium-cli
--- +++ @@ -7,16 +7,18 @@ (async () => { let commandDispatcher: ICommandDispatcher = $injector.resolve("commandDispatcher"); - let config: Config.IConfig = $injector.resolve("$config"); - let errors: IErrors = $injector.resolve("$errors"); - errors.printCallStack = config.DEBUG; + // let config: Config.IConfig = $injector.resolve("$config"); + // let errors: IErrors = $injector.resolve("$errors"); + // errors.printCallStack = config.DEBUG; - let messages = <IMessagesService>$injector.resolve("$messagesService"); - messages.pathsToMessageJsonFiles = [/* Place client-specific json message file paths here */]; + // let messages = <IMessagesService>$injector.resolve("$messagesService"); + // messages.pathsToMessageJsonFiles = [/* Place client-specific json message file paths here */]; if (process.argv[2] === "completion") { await commandDispatcher.completeCommand(); } else { await commandDispatcher.dispatchCommand(); } + + $injector.dispose(); })();
c1c0c6149dc32754bd9962df2c434642b2a7deb2
packages/@sanity/structure/src/StructureNodes.ts
packages/@sanity/structure/src/StructureNodes.ts
import {DocumentListBuilder, DocumentList} from './DocumentList' import {EditorBuilder} from './Editor' import {ListItemBuilder} from './ListItem' import {ListBuilder, List} from './List' import {MenuItemBuilder} from './MenuItem' import {MenuItemGroupBuilder} from './MenuItemGroup' import {Component, ComponentBuilder} from './Component' import {DocumentListItemBuilder} from './DocumentListItem' import {ChildResolver} from './ChildResolver' import {DocumentTypeListBuilder} from './DocumentTypeList' export interface StructureNode { id: string title?: string type?: string } export interface EditorNode extends StructureNode { options: { id: string type?: string template?: string } parameters?: { [key: string]: any } } export interface Divider { id: string type: 'divider' } export type SerializePath = (string | number)[] export interface SerializeOptions { path: SerializePath index?: number hint?: string } export interface Serializable { serialize(options: SerializeOptions): {} } export type Collection = List | DocumentList | EditorNode | Component export type CollectionBuilder = | ListBuilder | DocumentListBuilder | DocumentTypeListBuilder | EditorBuilder | ComponentBuilder export type Child = Collection | CollectionBuilder | ChildResolver export type Builder = | CollectionBuilder | ComponentBuilder | DocumentListBuilder | DocumentListItemBuilder | ListItemBuilder | MenuItemBuilder | MenuItemGroupBuilder
import {DocumentListBuilder, DocumentList} from './DocumentList' import {EditorBuilder} from './Editor' import {ListItemBuilder} from './ListItem' import {ListBuilder, List} from './List' import {MenuItemBuilder} from './MenuItem' import {MenuItemGroupBuilder} from './MenuItemGroup' import {Component, ComponentBuilder} from './Component' import {DocumentListItemBuilder} from './DocumentListItem' import {ChildResolver} from './ChildResolver' import {DocumentTypeListBuilder} from './DocumentTypeList' export interface StructureNode { id: string title?: string type?: string } export interface EditorNode extends StructureNode { options: { id: string type?: string template?: string } parameters?: { [key: string]: any } initialValueTemplates?: InitialValueTemplateConfig[] } export type InitialValueTemplateConfig = { id: string parameters?: {[key: string]: any} } export interface Divider { id: string type: 'divider' } export type SerializePath = (string | number)[] export interface SerializeOptions { path: SerializePath index?: number hint?: string } export interface Serializable { serialize(options: SerializeOptions): {} } export type Collection = List | DocumentList | EditorNode | Component export type CollectionBuilder = | ListBuilder | DocumentListBuilder | DocumentTypeListBuilder | EditorBuilder | ComponentBuilder export type Child = Collection | CollectionBuilder | ChildResolver export type Builder = | CollectionBuilder | ComponentBuilder | DocumentListBuilder | DocumentListItemBuilder | ListItemBuilder | MenuItemBuilder | MenuItemGroupBuilder
Add initial value templates to editor spec
[structure] Add initial value templates to editor spec
TypeScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -24,6 +24,12 @@ parameters?: { [key: string]: any } + initialValueTemplates?: InitialValueTemplateConfig[] +} + +export type InitialValueTemplateConfig = { + id: string + parameters?: {[key: string]: any} } export interface Divider {
e69285191917bb034b56440c309607cacda31223
packages/ionic/src/controls/enum/enum-control.ts
packages/ionic/src/controls/enum/enum-control.ts
import { Component } from '@angular/core'; import { NgRedux } from '@angular-redux/store'; import { isEnumControl, JsonFormsState, RankedTester, rankWith } from '@jsonforms/core'; import { JsonFormsControl } from '@jsonforms/angular'; @Component({ selector: 'jsonforms-enum-control', template: ` <ion-item> <ion-label>{{label}}</ion-label> <ion-label stacked *ngIf="error" color="errora">{{error}}</ion-label> <ion-select [ngModel]="data" (ionChange)="onChange($event)"> <ion-option *ngFor="let option of options" value="{{option}}"> {{option}} </ion-option> </ion-select> </ion-item> ` }) export class EnumControlRenderer extends JsonFormsControl { options: any[]; constructor(ngRedux: NgRedux<JsonFormsState>) { super(ngRedux); } mapAdditionalProps() { this.options = this.scopedSchema.enum; } } export const enumControlTester: RankedTester = rankWith( 2, isEnumControl );
import { Component } from '@angular/core'; import { NgRedux } from '@angular-redux/store'; import { isEnumControl, JsonFormsState, RankedTester, rankWith } from '@jsonforms/core'; import { JsonFormsControl } from '@jsonforms/angular'; @Component({ selector: 'jsonforms-enum-control', template: ` <ion-item> <ion-label>{{label}}</ion-label> <ion-label stacked *ngIf="error" color="error">{{error}}</ion-label> <ion-select [ngModel]="data" (ionChange)="onChange($event)"> <ion-option *ngFor="let option of options" value="{{option}}"> {{option}} </ion-option> </ion-select> </ion-item> ` }) export class EnumControlRenderer extends JsonFormsControl { options: any[]; constructor(ngRedux: NgRedux<JsonFormsState>) { super(ngRedux); } mapAdditionalProps() { this.options = this.scopedSchema.enum; } getEventValue = (ev: any) => ev; } export const enumControlTester: RankedTester = rankWith( 2, isEnumControl );
Fix getEventValue & fix color in enum control
[ionic] Fix getEventValue & fix color in enum control
TypeScript
mit
qb-project/jsonforms,qb-project/jsonforms,qb-project/jsonforms
--- +++ @@ -8,7 +8,7 @@ template: ` <ion-item> <ion-label>{{label}}</ion-label> - <ion-label stacked *ngIf="error" color="errora">{{error}}</ion-label> + <ion-label stacked *ngIf="error" color="error">{{error}}</ion-label> <ion-select [ngModel]="data" (ionChange)="onChange($event)"> <ion-option *ngFor="let option of options" value="{{option}}"> {{option}} @@ -28,6 +28,8 @@ mapAdditionalProps() { this.options = this.scopedSchema.enum; } + + getEventValue = (ev: any) => ev; } export const enumControlTester: RankedTester = rankWith(
c8690c242939fbb19d5302e0848c466db3e8d92e
app/Operations/MoveBlockOperation.ts
app/Operations/MoveBlockOperation.ts
import IUndoableOperation = require("../Core/Operations/IUndoableOperation"); import ICompoundOperation = require("../Core/Operations/ICompoundOperation"); import CompoundOperation = require("../Core/Operations/CompoundOperation"); import ChangePropertyOperation = require("../Core/Operations/ChangePropertyOperation"); import IBlock = require("../Blocks/IBlock"); class MoveBlockOperation<IBlock> extends CompoundOperation<IBlock> implements IUndoableOperation, ICompoundOperation { private _Block: IBlock; // todo: why is it necessary to cast block as 'any'?? constructor(block: IBlock) { super(); this._Block = block; this.Operations.push(new ChangePropertyOperation<IBlock>(block, "Position", (<any>this._Block).LastPosition.Clone(), (<any>this._Block).Position.Clone())); } Do(): Promise<IBlock> { return super.Do(); } Undo(): Promise<IBlock> { return super.Undo(); } Dispose(): void { // if the block isn't in the display list, dispose of it if (!App.BlocksSketch.DisplayList.Contains(this._Block)){ (<any>this._Block).Dispose(); this._Block = null; } } } export = MoveBlockOperation;
import IUndoableOperation = require("../Core/Operations/IUndoableOperation"); import ICompoundOperation = require("../Core/Operations/ICompoundOperation"); import CompoundOperation = require("../Core/Operations/CompoundOperation"); import ChangePropertyOperation = require("../Core/Operations/ChangePropertyOperation"); import IBlock = require("../Blocks/IBlock"); class MoveBlockOperation<IBlock> extends CompoundOperation<IBlock> implements IUndoableOperation, ICompoundOperation { private _Block: IBlock; // todo: why is it necessary to cast block as 'any'?? constructor(block: IBlock) { super(); this._Block = block; this.Operations.push(new ChangePropertyOperation<IBlock>(block, "Position", (<any>this._Block).LastPosition.Clone(), (<any>this._Block).Position.Clone())); } Do(): Promise<IBlock> { return super.Do(); } Undo(): Promise<IBlock> { return super.Undo(); } Dispose(): void { //TODO: I don't think we shouldn't be disposing of the blocks in the move operation //// if the block isn't in the display list, dispose of it //if (!App.BlocksSketch.DisplayList.Contains(this._Block)){ // (<any>this._Block).Dispose(); // this._Block = null; //} } } export = MoveBlockOperation;
Move operations shouldn't be disposing blocks
Move operations shouldn't be disposing blocks
TypeScript
mit
BlokDust/BlokDust,BlokDust/BlokDust,BlokDust/BlokDust,BlokDust/BlokDust,BlokDust/BlokDust
--- +++ @@ -25,11 +25,12 @@ } Dispose(): void { - // if the block isn't in the display list, dispose of it - if (!App.BlocksSketch.DisplayList.Contains(this._Block)){ - (<any>this._Block).Dispose(); - this._Block = null; - } + //TODO: I don't think we shouldn't be disposing of the blocks in the move operation + //// if the block isn't in the display list, dispose of it + //if (!App.BlocksSketch.DisplayList.Contains(this._Block)){ + // (<any>this._Block).Dispose(); + // this._Block = null; + //} } }
e0a1e60159c1d14ef8ab5f8ed06d7d01f47eb54f
src/lift.ts
src/lift.ts
import * as React from 'react' import {Stream, Unsubscribe} from 'slope' interface Props<T> { stream: Stream<T> } interface State<T> { value: T } class Observable<T> extends React.Component<Props<T>, State<T>>{ private unsubscribe: Unsubscribe constructor (props: Props<T>) { super(props) this.state = {value: null} } componentWillMount () { this.unsubscribe = this.props.stream( value => this.setState({value}), () => this.unsubscribe() ) } componentWillUnmount () { this.unsubscribe() } render () { return (this.state.value as any) } } export function lift<T>(stream: Stream<T>): any { return React.createElement(Observable, {stream}) }
import * as React from 'react' import {Stream, Unsubscribe} from 'slope' interface Props<T> { stream: Stream<T> } interface State<T> { value: T } class Observable<T> extends React.Component<Props<T>, State<T>>{ private unsubscribe: Unsubscribe constructor (props: Props<T>) { super(props) this.state = {value: null} } componentWillMount () { this.unsubscribe = this.props.stream( value => this.setState({value}), () => this.unsubscribe && this.unsubscribe() ) } componentWillUnmount () { this.unsubscribe() } render () { return (this.state.value as any) } } export function lift<T>(stream: Stream<T>): any { return React.createElement(Observable, {stream}) }
Check if unsubscribe is defined
Check if unsubscribe is defined
TypeScript
mit
juhohei/slope-react
--- +++ @@ -21,7 +21,7 @@ componentWillMount () { this.unsubscribe = this.props.stream( value => this.setState({value}), - () => this.unsubscribe() + () => this.unsubscribe && this.unsubscribe() ) }
d9d29ab260de70e4b1466ca57d283c78f44be625
src/pages/post/[date]/[name]/index.tsx
src/pages/post/[date]/[name]/index.tsx
import type {GetStaticProps} from "next" import {TRPCError} from "@trpc/server" import type {FC} from "react" import {router} from "server/trpc/route" import {Post} from "server/db/entity/Post" import getEmptyPaths from "lib/util/getEmptyPaths" interface Props { post: Post } interface Query { date: string name: string } export const getStaticPaths = getEmptyPaths export const getStaticProps: GetStaticProps<Props> = async ({params}) => { const {date, name} = params as unknown as Query try { const post = await router.createCaller({}).query("post.getBySlug", { slug: [date, name].join("/") }) return { props: { post } } } catch (error) { if (error instanceof TRPCError && error.code === "NOT_FOUND") { return { notFound: true } } throw error } } const PostPage: FC<Props> = () => ( <div>Post will be here</div> ) export default PostPage
import type {GetStaticProps} from "next" import {TRPCError} from "@trpc/server" import {useRouter} from "next/router" import type {FC} from "react" import {router} from "server/trpc/route" import {Post} from "server/db/entity/Post" import getEmptyPaths from "lib/util/getEmptyPaths" interface Props { post: Post } interface Query { date: string name: string } export const getStaticPaths = getEmptyPaths export const getStaticProps: GetStaticProps<Props> = async ({params}) => { const {date, name} = params as unknown as Query try { const post = await router.createCaller({}).query("post.getBySlug", { slug: [date, name].join("/") }) return { props: { post } } } catch (error) { if (error instanceof TRPCError && error.code === "NOT_FOUND") { return { notFound: true } } throw error } } const PostPage: FC<Props> = () => { const router = useRouter() // TODO: DO NOT forget to add support for the fallback version of the page: https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-pages if (router.isFallback) { return <div>Loading...</div> } return ( <div>Post will be here</div> ) } export default PostPage
Add fallback check in blog post page
Add fallback check in blog post page
TypeScript
mit
octet-stream/eri,octet-stream/eri
--- +++ @@ -1,5 +1,6 @@ import type {GetStaticProps} from "next" import {TRPCError} from "@trpc/server" +import {useRouter} from "next/router" import type {FC} from "react" import {router} from "server/trpc/route" @@ -42,8 +43,17 @@ } } -const PostPage: FC<Props> = () => ( - <div>Post will be here</div> -) +const PostPage: FC<Props> = () => { + const router = useRouter() + + // TODO: DO NOT forget to add support for the fallback version of the page: https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-pages + if (router.isFallback) { + return <div>Loading...</div> + } + + return ( + <div>Post will be here</div> + ) +} export default PostPage
7e4aeb7dc81cc27719274514f19fd2be60393616
idai-components-2.ts
idai-components-2.ts
export {ConfigLoader} from './lib/app/object-edit/config-loader'; export {Entity} from './lib/app/core-services/entity'; export {PersistenceManager} from './lib/app/object-edit/persistence-manager'; export {Datastore} from './lib/app/datastore/datastore'; export {ReadDatastore} from './lib/app/datastore/read-datastore'; export {ProjectConfiguration} from './lib/app/object-edit/project-configuration'; export {ObjectEditComponent} from './lib/app/object-edit/object-edit.component'; export {RelationsConfiguration} from './lib/app/object-edit/relations-configuration'; export {MessagesComponent} from './lib/app/core-services/messages.component'; export {Messages} from './lib/app/core-services/messages'; export {Message} from './lib/app/core-services/message'; export {MD} from './lib/app/core-services/md';
export {ConfigLoader} from './lib/app/object-edit/config-loader'; export {Entity} from './lib/app/core-services/entity'; export {PersistenceManager} from './lib/app/object-edit/persistence-manager'; export {Datastore} from './lib/app/datastore/datastore'; export {ReadDatastore} from './lib/app/datastore/read-datastore'; export {ProjectConfiguration} from './lib/app/object-edit/project-configuration'; export {ObjectEditComponent} from './lib/app/object-edit/object-edit.component'; export {RelationsConfiguration} from './lib/app/object-edit/relations-configuration'; export {MessagesComponent} from './lib/app/core-services/messages.component'; export {Messages} from './lib/app/core-services/messages'; export {LoadAndSaveService} from './lib/app/object-edit/load-and-save-service'; export {LoadAndSaveInterceptor} from './lib/app/object-edit/load-and-save-interceptor'; export {Message} from './lib/app/core-services/message'; export {MD} from './lib/app/core-services/md';
Add exports for new classes.
Add exports for new classes.
TypeScript
apache-2.0
dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2
--- +++ @@ -8,5 +8,7 @@ export {RelationsConfiguration} from './lib/app/object-edit/relations-configuration'; export {MessagesComponent} from './lib/app/core-services/messages.component'; export {Messages} from './lib/app/core-services/messages'; +export {LoadAndSaveService} from './lib/app/object-edit/load-and-save-service'; +export {LoadAndSaveInterceptor} from './lib/app/object-edit/load-and-save-interceptor'; export {Message} from './lib/app/core-services/message'; export {MD} from './lib/app/core-services/md';
c3706116a862c7d729784cba70bb0ab58f2f83fc
src/app/store/index.ts
src/app/store/index.ts
import Vue from 'vue'; import Vuex, { MutationTree, ActionTree, GetterTree, Dispatch, DispatchOptions } from 'vuex'; import { ModulState } from './modul-state'; import * as ModulActions from './actions'; import * as ModulGetters from './getters'; import * as ModulMutations from './mutations'; import { components } from './modules/components/components'; import { pages } from './modules/pages/pages'; Vue.use(Vuex); class ModulStore extends Vuex.Store<ModulState> { public async dispatchAsync(type: string, payload?: any, options?: DispatchOptions): Promise<any[]> { return await this.dispatch(type, payload, options); } } const store: ModulStore = new ModulStore({ strict: true, // TODO debug mode only modules: { components: components, standards: pages } }); export default store;
import Vue from 'vue'; import Vuex, { MutationTree, ActionTree, GetterTree, Dispatch, DispatchOptions } from 'vuex'; import { ModulState } from './modul-state'; import * as ModulActions from './actions'; import * as ModulGetters from './getters'; import * as ModulMutations from './mutations'; import { components } from './modules/components/components'; import { pages } from './modules/pages/pages'; Vue.use(Vuex); class ModulStore extends Vuex.Store<any> { public async dispatchAsync(type: string, payload?: any, options?: DispatchOptions): Promise<any[]> { return await this.dispatch(type, payload, options); } } const store: ModulStore = new ModulStore({ strict: true, // TODO debug mode only modules: { components: components, standards: pages } }); export default store;
Change type the store is expecting to temporary fix a bug
Change type the store is expecting to temporary fix a bug
TypeScript
apache-2.0
ulaval/modul-website,ulaval/modul-website,ulaval/modul-website
--- +++ @@ -9,7 +9,7 @@ Vue.use(Vuex); -class ModulStore extends Vuex.Store<ModulState> { +class ModulStore extends Vuex.Store<any> { public async dispatchAsync(type: string, payload?: any, options?: DispatchOptions): Promise<any[]> { return await this.dispatch(type, payload, options); }
4caf290eddb00399ca35a659007d9c4ad17d0c20
app/scripts/components/marketplace/details/FeatureSection.tsx
app/scripts/components/marketplace/details/FeatureSection.tsx
import * as React from 'react'; import { ListCell } from '@waldur/marketplace/common/ListCell'; import { Section, Offering } from '@waldur/marketplace/types'; interface FeatureSectionProps { section: Section; offering: Offering; hideHeader: boolean; } const getOptions = attribute => attribute.options.reduce((map, item) => ({...map, [item.key]: item.title}), {}); const AttributeRow = ({ offering, attribute }) => { let value = offering.attributes[attribute.key]; if (attribute.type === 'list' && typeof value === 'object') { const options = getOptions(attribute); value = value.map(item => options[item]); value = ListCell(value); } else if (attribute.type === 'choice') { const options = getOptions(attribute); value = options[value]; } return ( <tr> <td className="col-md-3"> {attribute.title} </td> <td className="col-md-9"> {value} </td> </tr> ); }; export const FeatureSection = (props: FeatureSectionProps) => ( <> <tr className="gray-bg"> <th>{props.section.title}</th> <th/> </tr> {props.section.attributes .filter(attr => props.offering.attributes.hasOwnProperty(attr.key)) .map((attr, index) => ( <AttributeRow key={index} offering={props.offering} attribute={attr}/> ))} </> );
import * as React from 'react'; import { ListCell } from '@waldur/marketplace/common/ListCell'; import { Section, Offering } from '@waldur/marketplace/types'; interface FeatureSectionProps { section: Section; offering: Offering; hideHeader: boolean; } const getOptions = attribute => attribute.options.reduce((map, item) => ({...map, [item.key]: item.title}), {}); const AttributeRow = ({ offering, attribute }) => { let value = offering.attributes[attribute.key]; if (attribute.type === 'list' && typeof value === 'object') { const options = getOptions(attribute); value = value.map(item => options[item]); value = ListCell(value); } else if (attribute.type === 'choice') { const options = getOptions(attribute); value = options[value]; } return ( <tr> <td className="col-md-3"> {attribute.title} </td> <td className="col-md-9"> {value} </td> </tr> ); }; export const FeatureSection = (props: FeatureSectionProps) => ( <> {!props.hideHeader && ( <tr className="gray-bg"> <th>{props.section.title}</th> <th/> </tr> )} {props.section.attributes .filter(attr => props.offering.attributes.hasOwnProperty(attr.key)) .map((attr, index) => ( <AttributeRow key={index} offering={props.offering} attribute={attr}/> ))} </> );
Hide marketplace offering section header if there's only one section in the tab.
Hide marketplace offering section header if there's only one section in the tab.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -36,10 +36,12 @@ export const FeatureSection = (props: FeatureSectionProps) => ( <> - <tr className="gray-bg"> - <th>{props.section.title}</th> - <th/> - </tr> + {!props.hideHeader && ( + <tr className="gray-bg"> + <th>{props.section.title}</th> + <th/> + </tr> + )} {props.section.attributes .filter(attr => props.offering.attributes.hasOwnProperty(attr.key)) .map((attr, index) => (
d095c67aa93626f02bf72bd5b8a2886870496fdb
highcharts-ng/highcharts-ng-tests.ts
highcharts-ng/highcharts-ng-tests.ts
/// <reference types="angular" /> var app = angular.module('app', ['highcharts-ng']); class AppController { chartConfig: HighChartsNGConfig = { options: { chart: { type: 'bar' }, tooltip: { style: { padding: 10, fontWeight: 'bold' } }, credits: { enabled: false }, plotOptions: {} }, series: [ { data: [10, 15, 12, 8, 7] }, { data: [[0, 10], [1, 15], [2, 12], [3, 8], [4, 7]] }, { data: [{ name: "A", y: 10 }, { name: "B", y: 15 }, { name: "C", y: 12 }, { name: "D", y: 8 }, { name: "E", y: 7 }] } ], title: { text: 'My Awesome Chart' }, loading: true }; constructor($timeout: ng.ITimeoutService) { var vm = this; $timeout(function() { //Some async action vm.chartConfig.loading = false; }); } } app.controller("AppController", AppController);
/// <reference types="angular" /> var app = angular.module('app', ['highcharts-ng']); class AppController { chartConfig: HighChartsNGConfig = { options: { chart: { type: 'bar' }, tooltip: { style: { padding: 10, fontWeight: 'bold' } }, credits: { enabled: false }, plotOptions: {} }, series: [ { data: [10, 15, 12, 8, 7] }, { data: [[0, 10], [1, 15], [2, 12], [3, 8], [4, 7]] }, { data: [{ name: "A", y: 10 }, { name: "B", y: 15 }, { name: "C", y: 12 }, { name: "D", y: 8 }, { name: "E", y: 7 }] } ], title: { text: 'My Awesome Chart' }, loading: true, noData: 'No data here' }; constructor($timeout: ng.ITimeoutService) { var vm = this; $timeout(function() { //Some async action vm.chartConfig.loading = false; }); } } app.controller("AppController", AppController);
Add missing property 'noData' to HighChartsNGConfig
Add missing property 'noData' to HighChartsNGConfig HighChartsNGConfig is missing noData property implemented since highcharts-ng#0.0.6 : https://github.com/pablojim/highcharts-ng#version-006
TypeScript
mit
alexdresko/DefinitelyTyped,mcliment/DefinitelyTyped,johan-gorter/DefinitelyTyped,aciccarello/DefinitelyTyped,mcrawshaw/DefinitelyTyped,benliddicott/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,georgemarshall/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,ashwinr/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,abbasmhd/DefinitelyTyped,QuatroCode/DefinitelyTyped,jimthedev/DefinitelyTyped,borisyankov/DefinitelyTyped,abbasmhd/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,magny/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,benishouga/DefinitelyTyped,mcrawshaw/DefinitelyTyped,AgentME/DefinitelyTyped,rolandzwaga/DefinitelyTyped,one-pieces/DefinitelyTyped,nycdotnet/DefinitelyTyped,aciccarello/DefinitelyTyped,smrq/DefinitelyTyped,isman-usoh/DefinitelyTyped,minodisk/DefinitelyTyped,zuzusik/DefinitelyTyped,nycdotnet/DefinitelyTyped,amir-arad/DefinitelyTyped,borisyankov/DefinitelyTyped,benishouga/DefinitelyTyped,aciccarello/DefinitelyTyped,georgemarshall/DefinitelyTyped,jimthedev/DefinitelyTyped,johan-gorter/DefinitelyTyped,isman-usoh/DefinitelyTyped,progre/DefinitelyTyped,YousefED/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,smrq/DefinitelyTyped,rolandzwaga/DefinitelyTyped,jimthedev/DefinitelyTyped,arusakov/DefinitelyTyped,arusakov/DefinitelyTyped,AgentME/DefinitelyTyped,chrootsu/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrootsu/DefinitelyTyped,AgentME/DefinitelyTyped,alexdresko/DefinitelyTyped,dsebastien/DefinitelyTyped,YousefED/DefinitelyTyped,zuzusik/DefinitelyTyped,QuatroCode/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,minodisk/DefinitelyTyped,arusakov/DefinitelyTyped,progre/DefinitelyTyped,georgemarshall/DefinitelyTyped,ashwinr/DefinitelyTyped,benishouga/DefinitelyTyped,magny/DefinitelyTyped
--- +++ @@ -33,7 +33,8 @@ title: { text: 'My Awesome Chart' }, - loading: true + loading: true, + noData: 'No data here' }; constructor($timeout: ng.ITimeoutService) { var vm = this;
74debd310cb808bdba999332e05e89ac27853eff
src/requirePrettier.ts
src/requirePrettier.ts
const path = require('path'); const readPkgUp = require('read-pkg-up'); interface Prettier { format: (string, PrettierConfig?) => string; readonly version: string; } /** * Recursively search for a package.json upwards containing prettier * as a dependency or devDependency. * @param {string} fspath file system path to start searching from * @returns {string} resolved path to prettier */ function readFromPkg(fspath: string): string | undefined { const res = readPkgUp.sync({ cwd: fspath }) if (res.pkg && (res.pkg.dependencies.prettier || res.pkg.devDependencies.prettier)) { return path.resolve(res.path, '..', 'node_modules/prettier'); } else if (res.path) { return readFromPkg(path.resolve(path.dirname(res.path), '..')); } } /** * Require 'prettier' explicitely installed relative to given path. * Fallback to packaged one if no prettier was found bottom up. * @param {string} fspath file system path starting point to resolve 'prettier' * @returns {Prettier} prettier */ function requirePrettier(fspath: string): Prettier { const prettierPath = readFromPkg(fspath); if (prettierPath !== void 0) { try { return require(prettierPath); } catch (e) { console.error(e.message); } } return require('prettier'); } export default requirePrettier;
const path = require('path'); const readPkgUp = require('read-pkg-up'); interface Prettier { format: (string, PrettierConfig?) => string; readonly version: string; } /** * Recursively search for a package.json upwards containing prettier * as a dependency or devDependency. * @param {string} fspath file system path to start searching from * @returns {string} resolved path to prettier */ function readFromPkg(fspath: string): string | undefined { const res = readPkgUp.sync({ cwd: fspath }) if (res.pkg && (res.pkg.dependencies.prettier || res.pkg.devDependencies.prettier)) { return path.resolve(res.path, '..', 'node_modules/prettier'); } else if (res.path) { return readFromPkg(path.resolve(path.dirname(res.path), '..')); } } /** * Require 'prettier' explicitely installed relative to given path. * Fallback to packaged one if no prettier was found bottom up. * @param {string} fspath file system path starting point to resolve 'prettier' * @returns {Prettier} prettier */ function requirePrettier(fspath: string): Prettier { const prettierPath = readFromPkg(fspath); if (prettierPath !== void 0) { try { const resolvedPrettier: Prettier = require(prettierPath); console.log("Using prettier", resolvedPrettier.version, "from", prettierPath); return resolvedPrettier; } catch (e) { console.error(e.message); } } return require('prettier'); } export default requirePrettier;
Add console.log to help debug
Add console.log to help debug
TypeScript
mit
esbenp/prettier-vscode,CiGit/prettier-vscode,CiGit/prettier-vscode
--- +++ @@ -30,7 +30,9 @@ const prettierPath = readFromPkg(fspath); if (prettierPath !== void 0) { try { - return require(prettierPath); + const resolvedPrettier: Prettier = require(prettierPath); + console.log("Using prettier", resolvedPrettier.version, "from", prettierPath); + return resolvedPrettier; } catch (e) { console.error(e.message); }
52b1d4afe955fcc057232d66b1a9b1f8aabbc42f
src/test/dutch.spec.ts
src/test/dutch.spec.ts
import {expect} from 'chai'; import * as cspell from '../index'; import * as path from 'path'; import * as fsp from 'fs-extra'; import * as dutchDict from 'cspell-dict-nl-nl'; import * as util from '../util/util'; const sampleFilename = path.join(__dirname, '..', '..', 'samples', 'Dutch.txt'); const sampleFile = fsp.readFile(sampleFilename, 'UTF-8').then(buffer => buffer.toString()); const dutchConfig = dutchDict.getConfigLocation(); describe('Validate that Dutch text is correctly checked.', () => { it('Tests the default configuration', () => { return sampleFile.then(text => { expect(text).to.not.be.empty; const ext = path.extname(sampleFilename); const languageIds = cspell.getLanguagesForExt(ext); const dutchSettings = cspell.readSettings(dutchConfig); const settings = cspell.mergeSettings(cspell.getDefaultSettings(), dutchSettings, { language: 'en,nl' }); const fileSettings = cspell.combineTextAndLanguageSettings(settings, text, languageIds); return cspell.validateText(text, fileSettings) .then(results => { /* cspell:ignore ANBI RABO RABONL unported */ expect(results.map(a => a.text).filter(util.uniqueFn()).sort()).deep.equals(['ANBI', 'RABO', 'RABONL', 'unported']); }); }); }); });
import {expect} from 'chai'; import * as cspell from '../index'; import * as path from 'path'; import * as fsp from 'fs-extra'; import * as dutchDict from 'cspell-dict-nl-nl'; import * as util from '../util/util'; const sampleFilename = path.join(__dirname, '..', '..', 'samples', 'Dutch.txt'); const sampleFile = fsp.readFile(sampleFilename, 'UTF-8').then(buffer => buffer.toString()); const dutchConfig = dutchDict.getConfigLocation(); describe('Validate that Dutch text is correctly checked.', function() { this.timeout(5000); it('Tests the default configuration', () => { return sampleFile.then(text => { expect(text).to.not.be.empty; const ext = path.extname(sampleFilename); const languageIds = cspell.getLanguagesForExt(ext); const dutchSettings = cspell.readSettings(dutchConfig); const settings = cspell.mergeSettings(cspell.getDefaultSettings(), dutchSettings, { language: 'en,nl' }); const fileSettings = cspell.combineTextAndLanguageSettings(settings, text, languageIds); return cspell.validateText(text, fileSettings) .then(results => { /* cspell:ignore ANBI RABO RABONL unported */ expect(results.map(a => a.text).filter(util.uniqueFn()).sort()).deep.equals(['ANBI', 'RABO', 'RABONL', 'unported']); }); }); }); });
Update the timeout for the dutch test.
Update the timeout for the dutch test.
TypeScript
mit
Jason3S/cspell,Jason3S/cspell,Jason3S/cspell,Jason3S/cspell,Jason3S/cspell
--- +++ @@ -9,7 +9,9 @@ const sampleFile = fsp.readFile(sampleFilename, 'UTF-8').then(buffer => buffer.toString()); const dutchConfig = dutchDict.getConfigLocation(); -describe('Validate that Dutch text is correctly checked.', () => { +describe('Validate that Dutch text is correctly checked.', function() { + this.timeout(5000); + it('Tests the default configuration', () => { return sampleFile.then(text => { expect(text).to.not.be.empty;
6886dbcc9bd6c6ad776fe5bfccc329c5846a279e
cypress/integration/shows.spec.ts
cypress/integration/shows.spec.ts
/* eslint-disable jest/expect-expect */ import { visitWithStatusRetries } from "../helpers/visitWithStatusRetries" describe("Shows", () => { it("/shows", () => { visitWithStatusRetries("shows2") cy.get("h1").should("contain", "Featured Shows") cy.title().should("eq", "Art Gallery Shows and Museum Exhibitions | Artsy") }) })
/* eslint-disable jest/expect-expect */ import { visitWithStatusRetries } from "../helpers/visitWithStatusRetries" describe("Shows", () => { it("/shows", () => { visitWithStatusRetries("shows") cy.get("h1").should("contain", "Featured Shows") cy.title().should("eq", "Art Gallery Shows and Museum Exhibitions | Artsy") visitWithStatusRetries("shows2") cy.get("h1").should("contain", "Featured Shows") cy.title().should("eq", "Art Gallery Shows and Museum Exhibitions | Artsy") }) })
Add cypress test of /shows route
Add cypress test of /shows route
TypeScript
mit
artsy/force,artsy/force-public,artsy/force-public,artsy/force,artsy/force,artsy/force
--- +++ @@ -3,6 +3,10 @@ describe("Shows", () => { it("/shows", () => { + visitWithStatusRetries("shows") + cy.get("h1").should("contain", "Featured Shows") + cy.title().should("eq", "Art Gallery Shows and Museum Exhibitions | Artsy") + visitWithStatusRetries("shows2") cy.get("h1").should("contain", "Featured Shows") cy.title().should("eq", "Art Gallery Shows and Museum Exhibitions | Artsy")
5afdf86f90f0af08b0214424e791229e3721c3e0
packages/jest-enzyme/src/index.d.ts
packages/jest-enzyme/src/index.d.ts
/// <reference types="react" /> declare namespace jest { interface Matchers { toBeChecked(): void; toBeDisabled(): void; toBeEmpty(): void; toBePresent(): void; toContainReact(component: React.Component<any, any>): void; toHaveClassName(className: string): void; toHaveHTML(html: string): void; toHaveProp(propKey: string, propValue?: any): void; toHaveRef(refName: string): void; toHaveState(stateKey: string, stateValue?: any): void; toHaveStyle(styleKey: string, styleValue?: any): void; toHaveTagName(tagName: string): void; toHaveText(text: string): void; toIncludeText(text: string): void; toHaveValue(value: any): void; toMatchElement(element: ReactElement<any>): void; toMatchSelector(selector: string): void; } }
/// <reference types="react" /> declare namespace jest { interface Matchers { toBeChecked(): void; toBeDisabled(): void; toBeEmpty(): void; toBePresent(): void; toContainReact(component: ReactElement<any>): void; toHaveClassName(className: string): void; toHaveHTML(html: string): void; toHaveProp(propKey: string, propValue?: any): void; toHaveRef(refName: string): void; toHaveState(stateKey: string, stateValue?: any): void; toHaveStyle(styleKey: string, styleValue?: any): void; toHaveTagName(tagName: string): void; toHaveText(text: string): void; toIncludeText(text: string): void; toHaveValue(value: any): void; toMatchElement(element: ReactElement<any>): void; toMatchSelector(selector: string): void; } }
Fix typescript type of toContainReact argument
Fix typescript type of toContainReact argument The documentation suggests that it takes a rendered element, not just the component class. Without the fix: ``` const child = <div id="child" /> const element = enzyme.shallow(<div>{child}</div>); expect(element).toContainReact(child); ``` ``` Argument of type 'Element' is not assignable to parameter of type 'Component<any, any>'. Property 'setState' is missing in type 'Element'.' ``` With the fix: Compiles and runs!
TypeScript
mit
blainekasten/enzyme-matchers
--- +++ @@ -6,7 +6,7 @@ toBeDisabled(): void; toBeEmpty(): void; toBePresent(): void; - toContainReact(component: React.Component<any, any>): void; + toContainReact(component: ReactElement<any>): void; toHaveClassName(className: string): void; toHaveHTML(html: string): void; toHaveProp(propKey: string, propValue?: any): void;
a2b02d3c894110e1b6b7b003322f220b24ca90a5
web-ng/src/app/components/layer-dialog/layer-dialog.component.ts
web-ng/src/app/components/layer-dialog/layer-dialog.component.ts
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-layer-dialog', templateUrl: './layer-dialog.component.html', styleUrls: ['./layer-dialog.component.css'], }) export class LayerDialogComponent implements OnInit { private layerId: string; constructor( @Inject(MAT_DIALOG_DATA) data: any, private dialogRef: MatDialogRef<LayerDialogComponent> ) { this.layerId = data.layerId!; // Disable closing on clicks outside of dialog. dialogRef.disableClose = true; } ngOnInit() {} closeDialog() { this.dialogRef.close('Result'); } }
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-layer-dialog', templateUrl: './layer-dialog.component.html', styleUrls: ['./layer-dialog.component.css'], }) export class LayerDialogComponent implements OnInit { layerId: string; constructor( @Inject(MAT_DIALOG_DATA) data: any, private dialogRef: MatDialogRef<LayerDialogComponent> ) { this.layerId = data.layerId!; // Disable closing on clicks outside of dialog. dialogRef.disableClose = true; } ngOnInit() {} closeDialog() { this.dialogRef.close('Result'); } }
Make layerId visible to template
Make layerId visible to template
TypeScript
apache-2.0
google/ground-platform,google/ground-platform,google/ground-platform,google/ground-platform
--- +++ @@ -23,7 +23,7 @@ styleUrls: ['./layer-dialog.component.css'], }) export class LayerDialogComponent implements OnInit { - private layerId: string; + layerId: string; constructor( @Inject(MAT_DIALOG_DATA) data: any,
22787692655fb32cfa5ed671a3a9b3546adaf12d
desktop/app/src/reducers/user.tsx
desktop/app/src/reducers/user.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import {Actions} from './'; export const USER_UNAUTHORIZED = 'Unauthorized.'; export const USER_NOT_SIGNEDIN = 'Not signed in.'; export type User = { name?: string; profile_picture?: { uri: string; }; }; export type State = User; export type Action = | { type: 'LOGIN'; payload: User; } | { type: 'LOGOUT'; }; const INITIAL_STATE: State = {}; export default function reducer( state: State = INITIAL_STATE, action: Actions, ): State { if (action.type === 'LOGOUT') { return {}; } else if (action.type === 'LOGIN') { return { ...state, ...action.payload, }; } else { return state; } } export const login = (payload: User): Action => ({ type: 'LOGIN', payload, }); export const logout = (): Action => ({ type: 'LOGOUT', });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import {Actions} from './'; export const USER_UNAUTHORIZED = 'Unauthorized.'; export const USER_NOT_SIGNEDIN = 'Not signed in.'; export type User = { id?: string; name?: string; profile_picture?: { uri: string; }; }; export type State = User; export type Action = | { type: 'LOGIN'; payload: User; } | { type: 'LOGOUT'; }; const INITIAL_STATE: State = {}; export default function reducer( state: State = INITIAL_STATE, action: Actions, ): State { if (action.type === 'LOGOUT') { return {}; } else if (action.type === 'LOGIN') { return { ...state, ...action.payload, }; } else { return state; } } export const login = (payload: User): Action => ({ type: 'LOGIN', payload, }); export const logout = (): Action => ({ type: 'LOGOUT', });
Include ID for logged-in User
Include ID for logged-in User Summary: Adding id field for the currently logged in user in the store's state Reviewed By: passy Differential Revision: D20928642 fbshipit-source-id: eff5373bd88ed8fd228193b47649f586cf20b585
TypeScript
mit
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
--- +++ @@ -13,6 +13,7 @@ export const USER_NOT_SIGNEDIN = 'Not signed in.'; export type User = { + id?: string; name?: string; profile_picture?: { uri: string;
19c5fbbc3136740c82884b820015952fed4e4b7a
src/internal/util/lift.ts
src/internal/util/lift.ts
/** @prettier */ import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { OperatorFunction, TeardownLogic } from '../types'; /** * Used to determine if an object is an Observable with a lift function. */ export function hasLift(source: any): source is { lift: InstanceType<typeof Observable>['lift'] } { return typeof source?.lift === 'function'; } /** * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way. * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription. */ export function operate<T, R>(init: (liftedSource: Observable<T>, subscriber: Subscriber<R>) => TeardownLogic): OperatorFunction<T, R> { return (source: Observable<T>) => { if (hasLift(source)) { return source.lift(function (this: Subscriber<R>, liftedSource: Observable<T>) { try { return init(liftedSource, this); } catch (err) { this.error(err); } }); } throw new TypeError('Unable to lift unknown Observable type'); }; }
/** @prettier */ import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { OperatorFunction } from '../types'; /** * Used to determine if an object is an Observable with a lift function. */ export function hasLift(source: any): source is { lift: InstanceType<typeof Observable>['lift'] } { return typeof source?.lift === 'function'; } /** * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way. * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription. */ export function operate<T, R>( init: (liftedSource: Observable<T>, subscriber: Subscriber<R>) => (() => void) | void ): OperatorFunction<T, R> { return (source: Observable<T>) => { if (hasLift(source)) { return source.lift(function (this: Subscriber<R>, liftedSource: Observable<T>) { try { return init(liftedSource, this); } catch (err) { this.error(err); } }); } throw new TypeError('Unable to lift unknown Observable type'); }; }
Tweak init return type so Subscribers and Subscriptions can no longer be returned
refactor(operate): Tweak init return type so Subscribers and Subscriptions can no longer be returned This will help force us to make sure we are using the subscriber and subscription chaining in the most efficient way possible. Although it could result in anti-patterns where users return a function that calls unsubscribe on a subscription if we release this to the public.
TypeScript
apache-2.0
kwonoj/RxJS,ReactiveX/RxJS,benlesh/RxJS,benlesh/RxJS,martinsik/rxjs,martinsik/rxjs,kwonoj/RxJS,kwonoj/RxJS,ReactiveX/rxjs,ReactiveX/RxJS,martinsik/rxjs,ReactiveX/rxjs,ReactiveX/RxJS,ReactiveX/RxJS,ReactiveX/rxjs,martinsik/rxjs,benlesh/RxJS,kwonoj/RxJS,benlesh/RxJS,ReactiveX/rxjs
--- +++ @@ -1,7 +1,7 @@ /** @prettier */ import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; -import { OperatorFunction, TeardownLogic } from '../types'; +import { OperatorFunction } from '../types'; /** * Used to determine if an object is an Observable with a lift function. @@ -14,7 +14,9 @@ * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way. * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription. */ -export function operate<T, R>(init: (liftedSource: Observable<T>, subscriber: Subscriber<R>) => TeardownLogic): OperatorFunction<T, R> { +export function operate<T, R>( + init: (liftedSource: Observable<T>, subscriber: Subscriber<R>) => (() => void) | void +): OperatorFunction<T, R> { return (source: Observable<T>) => { if (hasLift(source)) { return source.lift(function (this: Subscriber<R>, liftedSource: Observable<T>) {
17883672e8c883eaada0cc93aebc0b4c6c1e2461
src/app/datastore/read-datastore.ts
src/app/datastore/read-datastore.ts
import {Document} from "../model/document"; import {Query} from "./query"; /** * The interface providing read access methods * for datastores supporting the idai-components document model. * For full access see <code>Datastore</code> * * Implementations guarantee that any of methods declared here * have no effect on any of the documents within the datastore. * * @author Sebastian Cuy * @author Daniel de Oliveira */ export abstract class ReadDatastore { /** * @param id the desired document's id * @returns {Promise<T>} resolve -> {Document}, * reject -> the error message or a message key. */ abstract get(id: string): Promise<Document>; /** * @param query * @returns {Promise<T>} resolve -> {Document[]}, * reject -> the error message or a message key. */ abstract find(query: Query): Promise<Document[]>; abstract all(options: any): Promise<Document[]>; /** * Gets the specified object without using the cache * @param id the desired document's id * @returns {Promise<T>} resolve -> {Document}, * reject -> the error message or a message key. */ abstract refresh(id: string): Promise<Document>; }
import {Document} from "../model/document"; import {Query} from "./query"; /** * The interface providing read access methods * for datastores supporting the idai-components document model. * For full access see <code>Datastore</code> * * Implementations guarantee that any of methods declared here * have no effect on any of the documents within the datastore. * * @author Sebastian Cuy * @author Daniel de Oliveira */ export abstract class ReadDatastore { /** * @param id the desired document's id * @returns {Promise<T>} resolve -> {Document}, * reject -> the error message or a message key. */ abstract get(id: string): Promise<Document>; /** * @param query * @returns {Promise<T>} resolve -> {Document[]}, * reject -> the error message or a message key. */ abstract find(query: Query,fieldName?:string): Promise<Document[]>; abstract all(options: any): Promise<Document[]>; /** * Gets the specified object without using the cache * @param id the desired document's id * @returns {Promise<T>} resolve -> {Document}, * reject -> the error message or a message key. */ abstract refresh(id: string): Promise<Document>; }
Add optional param fieldName to ReadDatastore interface.
Add optional param fieldName to ReadDatastore interface.
TypeScript
apache-2.0
dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2
--- +++ @@ -26,7 +26,7 @@ * @returns {Promise<T>} resolve -> {Document[]}, * reject -> the error message or a message key. */ - abstract find(query: Query): Promise<Document[]>; + abstract find(query: Query,fieldName?:string): Promise<Document[]>; abstract all(options: any): Promise<Document[]>;
68d9e4019d82cc6cf55d708a14f50249ed5974b9
src/helpers/__tests__/genericify.ts
src/helpers/__tests__/genericify.ts
import {GenericType} from '../../elements/types/generic'; import {genericify} from '../genericify'; it('should return empty string while generics is empty', () => { expect(genericify([], null)).toBe(''); }); it('should return joined string from emitted generics', () => { const name_a = 'T'; const name_b = 'U'; const generic_a = new GenericType({name: name_a}); const generic_b = new GenericType({name: name_b}); expect(genericify([generic_a, generic_b], null)).toBe(`<[GenericType ${name_a}], [GenericType ${name_b}]>`); });
import {GenericType} from '../../elements/types/generic'; import {genericify} from '../genericify'; const container = null as any; it('should return empty string while generics is empty', () => { expect(genericify([], container)).toBe(''); }); it('should return joined string from emitted generics', () => { const name_a = 'T'; const name_b = 'U'; const generic_a = new GenericType({name: name_a}); const generic_b = new GenericType({name: name_b}); expect(genericify([generic_a, generic_b], container)).toBe(`<[GenericType ${name_a}], [GenericType ${name_b}]>`); });
Fix type err container is unnecessary here
Fix type err container is unnecessary here
TypeScript
mit
ikatyang/dts-element,ikatyang/dts-element
--- +++ @@ -1,8 +1,10 @@ import {GenericType} from '../../elements/types/generic'; import {genericify} from '../genericify'; +const container = null as any; + it('should return empty string while generics is empty', () => { - expect(genericify([], null)).toBe(''); + expect(genericify([], container)).toBe(''); }); it('should return joined string from emitted generics', () => { @@ -10,5 +12,5 @@ const name_b = 'U'; const generic_a = new GenericType({name: name_a}); const generic_b = new GenericType({name: name_b}); - expect(genericify([generic_a, generic_b], null)).toBe(`<[GenericType ${name_a}], [GenericType ${name_b}]>`); + expect(genericify([generic_a, generic_b], container)).toBe(`<[GenericType ${name_a}], [GenericType ${name_b}]>`); });
6c9e5ee64502a2ab9b1d2b1020c28a63bf358c44
app/test/unit/git/stash-test.ts
app/test/unit/git/stash-test.ts
import * as FSE from 'fs-extra' import * as path from 'path' import { Repository } from '../../../src/models/repository' import { setupEmptyRepository } from '../../helpers/repositories' import { GitProcess } from 'dugite' import { MagicStashString, getStashEntries } from '../../../src/lib/git/stash' describe('git/stash', () => { describe('getStashEntries', () => { let repository: Repository let readme: string beforeEach(async () => { repository = await setupEmptyRepository() readme = path.join(repository.path, 'README.md') await FSE.writeFile(readme, '') await GitProcess.exec(['add', 'README.md'], repository.path) await GitProcess.exec(['commit', '-m', 'initial commit'], repository.path) }) it('returns all stash entries created by Desktop', async () => { const stashEntries = await getDesktopStashEntries(repository) expect(stashEntries).toHaveLength(1) }) }) }) async function stash(repository: Repository) { await GitProcess.exec( ['stash', 'push', '-m', `${MagicStashString}:some-branch`], repository.path ) }
import * as FSE from 'fs-extra' import * as path from 'path' import { Repository } from '../../../src/models/repository' import { setupEmptyRepository } from '../../helpers/repositories' import { GitProcess } from 'dugite' import { MagicStashString, getStashEntries } from '../../../src/lib/git/stash' describe('git/stash', () => { describe('getStashEntries', () => { let repository: Repository let readme: string beforeEach(async () => { repository = await setupEmptyRepository() readme = path.join(repository.path, 'README.md') await FSE.writeFile(readme, '') await GitProcess.exec(['add', 'README.md'], repository.path) await GitProcess.exec(['commit', '-m', 'initial commit'], repository.path) }) it('returns all stash entries created by Desktop', async () => { await generateTestStashEntries(repository) const stashEntries = await getDesktopStashEntries(repository) expect(stashEntries).toHaveLength(1) }) }) }) async function stash(repository: Repository) { await GitProcess.exec( ['stash', 'push', '-m', `${MagicStashString}:some-branch`], repository.path ) } async function generateTestStashEntries(repository: Repository) { const readme = path.join(repository.path, 'README.md') // simulate stashing from CLI await FSE.appendFile(readme, '1') await stash(repository, 'should get filtered') await FSE.appendFile(readme, '2') await stash(repository, 'should also get filtered') // simulate stashing from Desktop await FSE.appendFile(readme, '2') await stash(repository) }
Add function to make test setup easier
Add function to make test setup easier
TypeScript
mit
j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,j-f1/forked-desktop,say25/desktop,say25/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop
--- +++ @@ -19,6 +19,7 @@ }) it('returns all stash entries created by Desktop', async () => { + await generateTestStashEntries(repository) const stashEntries = await getDesktopStashEntries(repository) @@ -33,3 +34,18 @@ repository.path ) } + +async function generateTestStashEntries(repository: Repository) { + const readme = path.join(repository.path, 'README.md') + + // simulate stashing from CLI + await FSE.appendFile(readme, '1') + await stash(repository, 'should get filtered') + + await FSE.appendFile(readme, '2') + await stash(repository, 'should also get filtered') + + // simulate stashing from Desktop + await FSE.appendFile(readme, '2') + await stash(repository) +}
ac28ef0b9dcde816c6c58968856043e9deb8c729
src/algorithms/depth-first-search.ts
src/algorithms/depth-first-search.ts
import Node from '../node'; /** * Depth First Search algorithm */ export default class DepthFirstSearch<N, E> { private _root: Node<N, E>; constructor(root: Node<N, E>) { this._root = root; } [Symbol.iterator]() { let stack = [{node: this._root, d: 0}]; let visited: Array<Node<N, E>> = [this._root]; let iterator = { next() { if (stack.length === 0) { return {value: undefined, done: true}; } let current = stack.shift(); if (visited.indexOf(current.node) === -1) { visited.push(current.node); let successors = current.node.directSuccessors().map((adj) => { if (visited.indexOf(adj) === -1) { visited.push(adj); return {node: adj, d: current.d + 1}; } }) .filter((adj) => adj !== undefined); stack.unshift.apply(stack, successors); } else { return this.next(); } return { value: { node: current.node, d: current.d }, done: false }; } }; return iterator; } };
import Node from '../node'; /** * Depth First Search algorithm */ export default class DepthFirstSearch<N, E> { private _root: Node<N, E>; constructor(root: Node<N, E>) { this._root = root; } [Symbol.iterator]() { let stack = [{node: this._root, d: 0}]; let visited: Array<Node<N, E>> = [this._root]; let iterator = { next() { if (stack.length === 0) { return {value: undefined, done: true}; } let current = stack.shift(); if (visited.indexOf(current.node) === -1) { visited.push(current.node); let successors = current.node.directSuccessors().map((adj) => { return {node: adj, d: current.d + 1}; }); stack.unshift.apply(stack, successors); } else { return this.next(); } return { value: { node: current.node, d: current.d }, done: false }; } }; return iterator; } };
Fix Depth First Search algorithm
Fix Depth First Search algorithm
TypeScript
mit
jledentu/konigsberg,jledentu/konigsberg
--- +++ @@ -25,12 +25,8 @@ if (visited.indexOf(current.node) === -1) { visited.push(current.node); let successors = current.node.directSuccessors().map((adj) => { - if (visited.indexOf(adj) === -1) { - visited.push(adj); - return {node: adj, d: current.d + 1}; - } - }) - .filter((adj) => adj !== undefined); + return {node: adj, d: current.d + 1}; + }); stack.unshift.apply(stack, successors); } else { return this.next();
647c95842bdfadae4975d24f53e9d2f5cc40b747
packages/resolver/lib/sources/abi.ts
packages/resolver/lib/sources/abi.ts
import path from "path"; import { ContractObject } from "@truffle/contract-schema/spec"; import { generateSolidity } from "abi-to-sol"; import { FS } from "./fs"; export class ABI extends FS { // requiring artifacts is out of scope for this ResolverSource // just return `null` here and let another ResolverSource handle it require(): ContractObject | null { return null; } async resolve(importPath: string, importedFrom: string = "") { let filePath: string | undefined; let body: string | undefined; if (!importPath.endsWith(".json")) { return { filePath, body }; } const resolution = await super.resolve(importPath, importedFrom); if (!resolution) { return { filePath, body }; } ({ filePath, body } = resolution); // extract basename twice to support .json and .abi.json const name = path.basename(path.basename(filePath, ".json"), ".abi"); try { const abi = JSON.parse(body); const soliditySource = generateSolidity({ name, abi, license: "MIT" // as per the rest of Truffle }); return { filePath, body: soliditySource }; } catch (e) { return { filePath, body }; } } }
import path from "path"; import { ContractObject } from "@truffle/contract-schema/spec"; import { generateSolidity } from "abi-to-sol"; import { FS } from "./fs"; export class ABI extends FS { // requiring artifacts is out of scope for this ResolverSource // just return `null` here and let another ResolverSource handle it require(): ContractObject | null { return null; } async resolve(importPath: string, importedFrom: string = "") { let filePath: string | undefined; let body: string | undefined; if (!importPath.endsWith(".json")) { return { filePath, body }; } const resolution = await super.resolve(importPath, importedFrom); if (!resolution.body) { return { filePath, body }; } ({ filePath, body } = resolution); // extract basename twice to support .json and .abi.json const name = path.basename(path.basename(filePath, ".json"), ".abi"); try { const abi = JSON.parse(body); const soliditySource = generateSolidity({ name, abi, license: "MIT" // as per the rest of Truffle }); return { filePath, body: soliditySource }; } catch (e) { return { filePath, body }; } } }
Use resolution.body to check whether a source was successfully resolved
Use resolution.body to check whether a source was successfully resolved
TypeScript
mit
ConsenSys/truffle
--- +++ @@ -20,7 +20,7 @@ } const resolution = await super.resolve(importPath, importedFrom); - if (!resolution) { + if (!resolution.body) { return { filePath, body }; }
9f6c3d29ee5ca1847fab7937399d68960f1d821e
src/command_table.ts
src/command_table.ts
import { Command } from "./command"; export class CommandTable { private name: string; private inherit: CommandTable[] = []; private commands: Map<string, Command> = new Map(); constructor (name: string, inherit: CommandTable[]) { this.name = name; this.inherit = inherit; } }
import { Command } from "./command"; export class CommandTableEntry { name: string; command: Command; } export class CommandTable { private name: string; private inherit: CommandTable[] = []; private commands: CommandTableEntry[] = []; constructor (name: string, inherit: CommandTable[]) { this.name = name; this.inherit = inherit; } }
Store an array of entries rather than a map.
CommandTable: Store an array of entries rather than a map.
TypeScript
mit
debugworkbench/workbench-commands
--- +++ @@ -1,9 +1,14 @@ import { Command } from "./command"; + +export class CommandTableEntry { + name: string; + command: Command; +} export class CommandTable { private name: string; private inherit: CommandTable[] = []; - private commands: Map<string, Command> = new Map(); + private commands: CommandTableEntry[] = []; constructor (name: string, inherit: CommandTable[]) { this.name = name;
2f7d3e6bedffa223a164743cb87c6281996192b1
src/app/inventory/ItemPopupTrigger.tsx
src/app/inventory/ItemPopupTrigger.tsx
import { settingsSelector } from 'app/dim-api/selectors'; import React, { useCallback, useRef } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { CompareService } from '../compare/compare.service'; import { ItemPopupExtraInfo, showItemPopup } from '../item-popup/item-popup'; import { clearNewItem } from './actions'; import { DimItem } from './item-types'; interface Props { item: DimItem; extraData?: ItemPopupExtraInfo; children(ref: React.Ref<HTMLDivElement>, onClick: (e: React.MouseEvent) => void): React.ReactNode; } /** * This wraps its children in a div which, when clicked, will show the move popup for the provided item. */ export default function ItemPopupTrigger({ item, extraData, children }: Props): JSX.Element { const ref = useRef<HTMLDivElement>(null); const disableConfetti = useSelector(settingsSelector).disableConfetti; const dispatch = useDispatch(); const clicked = useCallback( (e: React.MouseEvent) => { if (disableConfetti) { e.stopPropagation(); } dispatch(clearNewItem(item.id)); // TODO: a dispatcher based on store state? if (CompareService.dialogOpen) { CompareService.addItemsToCompare([item]); } else { showItemPopup(item, ref.current!, extraData); return false; } }, [dispatch, extraData, item, disableConfetti] ); return children(ref, clicked) as JSX.Element; }
import React, { useCallback, useRef } from 'react'; import { useDispatch } from 'react-redux'; import { CompareService } from '../compare/compare.service'; import { ItemPopupExtraInfo, showItemPopup } from '../item-popup/item-popup'; import { clearNewItem } from './actions'; import { DimItem } from './item-types'; interface Props { item: DimItem; extraData?: ItemPopupExtraInfo; children(ref: React.Ref<HTMLDivElement>, onClick: (e: React.MouseEvent) => void): React.ReactNode; } /** * This wraps its children in a div which, when clicked, will show the move popup for the provided item. */ export default function ItemPopupTrigger({ item, extraData, children }: Props): JSX.Element { const ref = useRef<HTMLDivElement>(null); const dispatch = useDispatch(); const clicked = useCallback(() => { dispatch(clearNewItem(item.id)); // TODO: a dispatcher based on store state? if (CompareService.dialogOpen) { CompareService.addItemsToCompare([item]); } else { showItemPopup(item, ref.current!, extraData); return false; } }, [dispatch, extraData, item]); return children(ref, clicked) as JSX.Element; }
Remove confetti work around for click events
Remove confetti work around for click events
TypeScript
mit
delphiactual/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,delphiactual/DIM,DestinyItemManager/DIM,delphiactual/DIM,delphiactual/DIM
--- +++ @@ -1,6 +1,5 @@ -import { settingsSelector } from 'app/dim-api/selectors'; import React, { useCallback, useRef } from 'react'; -import { useDispatch, useSelector } from 'react-redux'; +import { useDispatch } from 'react-redux'; import { CompareService } from '../compare/compare.service'; import { ItemPopupExtraInfo, showItemPopup } from '../item-popup/item-popup'; import { clearNewItem } from './actions'; @@ -17,27 +16,19 @@ */ export default function ItemPopupTrigger({ item, extraData, children }: Props): JSX.Element { const ref = useRef<HTMLDivElement>(null); - const disableConfetti = useSelector(settingsSelector).disableConfetti; const dispatch = useDispatch(); - const clicked = useCallback( - (e: React.MouseEvent) => { - if (disableConfetti) { - e.stopPropagation(); - } + const clicked = useCallback(() => { + dispatch(clearNewItem(item.id)); - dispatch(clearNewItem(item.id)); - - // TODO: a dispatcher based on store state? - if (CompareService.dialogOpen) { - CompareService.addItemsToCompare([item]); - } else { - showItemPopup(item, ref.current!, extraData); - return false; - } - }, - [dispatch, extraData, item, disableConfetti] - ); + // TODO: a dispatcher based on store state? + if (CompareService.dialogOpen) { + CompareService.addItemsToCompare([item]); + } else { + showItemPopup(item, ref.current!, extraData); + return false; + } + }, [dispatch, extraData, item]); return children(ref, clicked) as JSX.Element; }
abc8ca78389de43ceee01fdf15ad28f9a1cdd9d0
Orange/RegionManager.ts
Orange/RegionManager.ts
/// <reference path="Reference.d.ts"/> module Orange.Modularity { export class RegionManager { constructor(public container: Orange.Modularity.Container) { } public disposeRegions(root: HTMLElement) { var attr = root.getAttribute("data-view"); if (attr == null || attr == "") { if (typeof root.children !== "undefined") { for (var i = 0; i < root.children.length; i++) this.disposeRegions(<HTMLElement>root.children[i]); } } else { var view = <Infviz.Controls.Control>root["instance"]; view.dispose(); } } public initializeRegions(root: HTMLElement): void { var attr = root.getAttribute("data-view"); if (attr == null || attr == "") { if (typeof root.children !== "undefined") { for (var i = 0; i < root.children.length; i++) this.initializeRegions(<HTMLElement>root.children[i]); } } else { var viewType = eval(attr); var view = this.container.resolve(viewType); if (typeof view.element !== "undefined") view.element = root; var idAttr = root.getAttribute("data-view-id"); if (idAttr != null && attr != "") { if (view.setViewId !== "undefined") { view.setViewId(idAttr); } } root["instance"] = view; } } } }
/// <reference path="Reference.d.ts"/> module Orange.Modularity { export class RegionManager { constructor(public container: Orange.Modularity.Container) { } public disposeRegions(root: HTMLElement) { var attr = root.getAttribute("data-view"); if (attr == null || attr == "") { if (typeof root.children !== "undefined") { for (var i = 0; i < root.children.length; i++) this.disposeRegions(<HTMLElement>root.children[i]); } } else { var view = <any>root["instance"]; if (typeof view.dispose === 'function') view.dispose(); } } public initializeRegions(root: HTMLElement): void { var attr = root.getAttribute("data-view"); if (attr == null || attr == "") { if (typeof root.children !== "undefined") { for (var i = 0; i < root.children.length; i++) this.initializeRegions(<HTMLElement>root.children[i]); } } else { var viewType = eval(attr); var view = this.container.resolve(viewType); if (typeof view.element !== "undefined") view.element = root; var idAttr = root.getAttribute("data-view-id"); if (idAttr != null && attr != "") { if (view.setViewId !== "undefined") { view.setViewId(idAttr); } } root["instance"] = view; } } } }
Remove reference to Infviz Toolkit
Remove reference to Infviz Toolkit
TypeScript
mit
Infviz/Orange,Infviz/Orange,Infviz/Orange,Infviz/Orange
--- +++ @@ -15,8 +15,9 @@ } } else { - var view = <Infviz.Controls.Control>root["instance"]; - view.dispose(); + var view = <any>root["instance"]; + if (typeof view.dispose === 'function') + view.dispose(); } }
77ebfa68f39305701c66c776277d5f6ec062c2e5
packages/lesswrong/components/tagging/TagPreviewDescription.tsx
packages/lesswrong/components/tagging/TagPreviewDescription.tsx
import React from 'react'; import { Components, registerComponent } from '../../lib/vulcan-lib'; import { commentBodyStyles } from '../../themes/stylePiping' import { truncate } from '../../lib/editor/ellipsize'; const styles = (theme: ThemeType): JssStyles => ({ root: { ...commentBodyStyles(theme) } }); const TagPreviewDescription = ({tag, classes}: { tag: TagPreviewFragment, classes: ClassesType }) => { const { ContentItemBody } = Components; if (!tag) return null const highlight = truncate(tag.description?.htmlHighlight, 1, "paragraphs", "") if (tag.description?.htmlHighlight) return <ContentItemBody className={classes.root} dangerouslySetInnerHTML={{__html: highlight}} description={`tag ${tag.name}`} /> return <div className={classes.root}><b>{tag.name}</b></div> } const TagPreviewDescriptionComponent = registerComponent("TagPreviewDescription", TagPreviewDescription, {styles}); declare global { interface ComponentTypes { TagPreviewDescription: typeof TagPreviewDescriptionComponent } }
import React from 'react'; import { Components, registerComponent } from '../../lib/vulcan-lib'; import { commentBodyStyles } from '../../themes/stylePiping' import { truncate } from '../../lib/editor/ellipsize'; const styles = (theme: ThemeType): JssStyles => ({ root: { ...commentBodyStyles(theme), "& .read-more a": { fontSize: ".85em", color: theme.palette.grey[600] }, } }); const TagPreviewDescription = ({tag, classes}: { tag: TagPreviewFragment, classes: ClassesType }) => { const { ContentItemBody } = Components; if (!tag) return null const highlight = truncate(tag.description?.htmlHighlight, 1, "paragraphs", '... <span class="read-more"><a>(read more)</a></span>') if (tag.description?.htmlHighlight) { return <ContentItemBody className={classes.root} dangerouslySetInnerHTML={{__html: highlight}} description={`tag ${tag.name}`} /> } return <div className={classes.root}><b>{tag.name}</b></div> } const TagPreviewDescriptionComponent = registerComponent("TagPreviewDescription", TagPreviewDescription, {styles}); declare global { interface ComponentTypes { TagPreviewDescription: typeof TagPreviewDescriptionComponent } }
Tag previews have a "(read more)" if they're truncated
Tag previews have a "(read more)" if they're truncated
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -5,7 +5,11 @@ const styles = (theme: ThemeType): JssStyles => ({ root: { - ...commentBodyStyles(theme) + ...commentBodyStyles(theme), + "& .read-more a": { + fontSize: ".85em", + color: theme.palette.grey[600] + }, } }); @@ -17,13 +21,17 @@ const { ContentItemBody } = Components; if (!tag) return null - const highlight = truncate(tag.description?.htmlHighlight, 1, "paragraphs", "") + + const highlight = truncate(tag.description?.htmlHighlight, 1, "paragraphs", + '... <span class="read-more"><a>(read more)</a></span>') - if (tag.description?.htmlHighlight) return <ContentItemBody + if (tag.description?.htmlHighlight) { + return <ContentItemBody className={classes.root} dangerouslySetInnerHTML={{__html: highlight}} description={`tag ${tag.name}`} /> + } return <div className={classes.root}><b>{tag.name}</b></div> }
0cce91fe3f27563c47fe4d16dd8dd293fabe2494
src/pages/tabs/tabs.ts
src/pages/tabs/tabs.ts
import { Component } from '@angular/core'; import { MapPage } from '../map/map'; import { SettingsPage } from '../settings/settings'; import { StatsPage } from '../stats/stats'; import { TripsPage } from '../trips/trips'; import { Trip } from '../../app/trip'; @Component({ templateUrl: 'tabs.html' }) export class TabsPage { mapRoot: any = MapPage; settingsRoot: any = SettingsPage; statsRoot: any = StatsPage; tripsRoot: any = TripsPage; unsubmittedTripsCount: number; constructor() { } ionViewWillEnter() { this.updateTripsBadge(); } public updateTripsBadge() { Trip.objects.count('submitted = 0') .then((count) => this.unsubmittedTripsCount = (count > 0) ? count : null); } }
import { Component } from '@angular/core'; import { MapPage } from '../map/map'; import { SettingsPage } from '../settings/settings'; import { StatsPage } from '../stats/stats'; import { TripsPage } from '../trips/trips'; import { Trip } from '../../app/trip'; import { Geo } from '../../app/geo'; @Component({ templateUrl: 'tabs.html' }) export class TabsPage { mapRoot: any = MapPage; settingsRoot: any = SettingsPage; statsRoot: any = StatsPage; tripsRoot: any = TripsPage; unsubmittedTripsCount: number; constructor(private geo: Geo) { geo.motion.subscribe(this.onMotion.bind(this)); } ionViewWillEnter() { this.updateTripsBadge(); } onMotion(moving) { if (!moving) this.updateTripsBadge(); } public updateTripsBadge() { Trip.objects.count('submitted = 0') .then((count) => this.unsubmittedTripsCount = (count > 0) ? count : null); } }
Update the trips badge when a trip ends.
Update the trips badge when a trip ends.
TypeScript
bsd-3-clause
CUUATS/bikemoves-v2,CUUATS/bikemoves-v2,CUUATS/bikemoves,CUUATS/bikemoves,CUUATS/bikemoves-v2,CUUATS/bikemoves
--- +++ @@ -5,6 +5,7 @@ import { StatsPage } from '../stats/stats'; import { TripsPage } from '../trips/trips'; import { Trip } from '../../app/trip'; +import { Geo } from '../../app/geo'; @Component({ templateUrl: 'tabs.html' @@ -16,11 +17,16 @@ tripsRoot: any = TripsPage; unsubmittedTripsCount: number; - constructor() { + constructor(private geo: Geo) { + geo.motion.subscribe(this.onMotion.bind(this)); } ionViewWillEnter() { this.updateTripsBadge(); + } + + onMotion(moving) { + if (!moving) this.updateTripsBadge(); } public updateTripsBadge() {
0fce0c290eb7b88a9778eb032b64f7f4ba521d92
src/build/generateDefinitionFile.ts
src/build/generateDefinitionFile.ts
import * as path from "path"; import * as fs from "fs"; import {getInfoFromFiles} from "./../main"; export function generateDefinitionFile() { const fileInfo = getInfoFromFiles([ path.join(__dirname, "../../src/main.ts"), path.join(__dirname, "../../src/typings/index.d.ts") ], { showDebugMessages: true }).getFile("main.ts"); fileInfo.getExports().forEach(def => { // todo: once typescript supports it type-wise, this should be merged into one if statement if (def.isClassDefinition()) { def.methods = def.methods.filter(m => m.name !== "addDefinitions" && m.name.indexOf("fill") === -1 && m.name !== "addType"); def.properties = def.properties.filter(p => p.name.indexOf("fill") === -1 && p.name !== "addType"); } else if (def.isInterfaceDefinition()) { def.methods = def.methods.filter(m => m.name !== "addDefinitions" && m.name.indexOf("fill") === -1 && m.name !== "addType"); def.properties = def.properties.filter(p => p.name.indexOf("fill") === -1 && p.name !== "addType"); } }); const definitionFileText = fileInfo.writeExportsAsDefinitionFile({ imports: [{ defaultImport: "CodeBlockWriter", moduleSpecifier: "code-block-writer" }] }); fs.writeFile(path.join(__dirname, "../../ts-type-info.d.ts"), definitionFileText); }
import * as path from "path"; import * as fs from "fs"; import {getInfoFromFiles} from "./../main"; export function generateDefinitionFile() { const fileInfo = getInfoFromFiles([ path.join(__dirname, "../../src/main.ts"), path.join(__dirname, "../../src/typings/index.d.ts") ], { showDebugMessages: true }).getFile("main.ts"); const definitionFileText = fileInfo.writeExportsAsDefinitionFile({ imports: [{ defaultImport: "CodeBlockWriter", moduleSpecifier: "code-block-writer" }] }); fs.writeFile(path.join(__dirname, "../../ts-type-info.d.ts"), definitionFileText); }
Remove old unnecessary code used when generating definition file
Remove old unnecessary code used when generating definition file
TypeScript
mit
dsherret/type-info-ts,dsherret/type-info-ts,dsherret/ts-type-info,dsherret/ts-type-info
--- +++ @@ -8,22 +8,6 @@ path.join(__dirname, "../../src/typings/index.d.ts") ], { showDebugMessages: true }).getFile("main.ts"); - fileInfo.getExports().forEach(def => { - // todo: once typescript supports it type-wise, this should be merged into one if statement - if (def.isClassDefinition()) { - def.methods = def.methods.filter(m => m.name !== "addDefinitions" && - m.name.indexOf("fill") === -1 && - m.name !== "addType"); - def.properties = def.properties.filter(p => p.name.indexOf("fill") === -1 && p.name !== "addType"); - } - else if (def.isInterfaceDefinition()) { - def.methods = def.methods.filter(m => m.name !== "addDefinitions" && - m.name.indexOf("fill") === -1 && - m.name !== "addType"); - def.properties = def.properties.filter(p => p.name.indexOf("fill") === -1 && p.name !== "addType"); - } - }); - const definitionFileText = fileInfo.writeExportsAsDefinitionFile({ imports: [{ defaultImport: "CodeBlockWriter",
5723bfc477e73538f5a756a237680e0816b04b4c
src/compiler/syntax/parseOptions.ts
src/compiler/syntax/parseOptions.ts
///<reference path='references.ts' /> module TypeScript { export class ParseOptions { private _allowAutomaticSemicolonInsertion: boolean; private _allowModuleKeywordInExternalModuleReference: boolean; constructor(allowAutomaticSemicolonInsertion, allowModuleKeywordInExternalModuleReference) { this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; this._allowModuleKeywordInExternalModuleReference = allowModuleKeywordInExternalModuleReference; } public toJSON(key) { return { allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion, allowModuleKeywordInExternalModuleReference: this._allowModuleKeywordInExternalModuleReference }; } public allowAutomaticSemicolonInsertion(): boolean { return this._allowAutomaticSemicolonInsertion; } public allowModuleKeywordInExternalModuleReference(): boolean { return this._allowModuleKeywordInExternalModuleReference; } } }
///<reference path='references.ts' /> module TypeScript { export class ParseOptions { private _allowAutomaticSemicolonInsertion: boolean; private _allowModuleKeywordInExternalModuleReference: boolean; constructor(allowAutomaticSemicolonInsertion: boolean, allowModuleKeywordInExternalModuleReference: boolean) { this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; this._allowModuleKeywordInExternalModuleReference = allowModuleKeywordInExternalModuleReference; } public toJSON(key) { return { allowAutomaticSemicolonInsertion: this._allowAutomaticSemicolonInsertion, allowModuleKeywordInExternalModuleReference: this._allowModuleKeywordInExternalModuleReference }; } public allowAutomaticSemicolonInsertion(): boolean { return this._allowAutomaticSemicolonInsertion; } public allowModuleKeywordInExternalModuleReference(): boolean { return this._allowModuleKeywordInExternalModuleReference; } } }
Add type annotations to ParseOptions ctor
Add type annotations to ParseOptions ctor
TypeScript
apache-2.0
fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts,hippich/typescript,mbebenita/shumway.ts,popravich/typescript,mbebenita/shumway.ts,hippich/typescript,mbrowne/typescript-dci,fdecampredon/jsx-typescript-old-version,popravich/typescript,mbrowne/typescript-dci,hippich/typescript,mbrowne/typescript-dci,mbrowne/typescript-dci,popravich/typescript
--- +++ @@ -5,7 +5,7 @@ private _allowAutomaticSemicolonInsertion: boolean; private _allowModuleKeywordInExternalModuleReference: boolean; - constructor(allowAutomaticSemicolonInsertion, allowModuleKeywordInExternalModuleReference) { + constructor(allowAutomaticSemicolonInsertion: boolean, allowModuleKeywordInExternalModuleReference: boolean) { this._allowAutomaticSemicolonInsertion = allowAutomaticSemicolonInsertion; this._allowModuleKeywordInExternalModuleReference = allowModuleKeywordInExternalModuleReference; }
cf0ad8f3afc3ce66252b6964dd841d77a8d00498
src/ApiEdgeDefinition.ts
src/ApiEdgeDefinition.ts
import {ApiEdgeRelation} from "./relations/ApiEdgeRelation"; import {ApiEdgeQueryContext} from "./ApiEdgeQueryContext"; export interface ApiEdgeDefinition { name: string; methods: Object; relations: ApiEdgeRelation[]; getEntry: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; listEntries: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; createEntry: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; updateEntry: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; updateEntries: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; removeEntry: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; removeEntries: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse[]>; exists: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; callMethod: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; }
import {ApiEdgeRelation} from "./relations/ApiEdgeRelation"; import {ApiEdgeQueryContext} from "./ApiEdgeQueryContext"; export interface ApiEdgeDefinition { name: string; pluralName: string; methods: Object; relations: ApiEdgeRelation[]; getEntry: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; listEntries: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; createEntry: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; updateEntry: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; updateEntries: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; removeEntry: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; removeEntries: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse[]>; exists: (context: ApiEdgeQueryContext) => Promise<ApiEdgeQueryResponse>; callMethod: (context: ApiEdgeQueryContext, entryFields: any) => Promise<ApiEdgeQueryResponse>; }
Add plural name for edges
Add plural name for edges
TypeScript
mit
ajuhos/api-core
--- +++ @@ -4,6 +4,8 @@ export interface ApiEdgeDefinition { name: string; + pluralName: string; + methods: Object; relations: ApiEdgeRelation[];
27e170e75e71aa319054c41919226e36f1aeaf8d
src/app/app.component.ts
src/app/app.component.ts
import { Component, NgModule } from '@angular/core'; import { VolunteerSignupComponent } from './VolunteerSignup/volunteer-signup.component'; import { JobSignupComponent } from './JobSignup/job-signup.component'; import { OrganisationSignupComponent } from './OrganisationSignup/organisation-signup.component'; import { VolunteerQueryComponent } from './Volunteer-query/volunteer-query.component' import { VolunteerListComponent } from './VolunteerList/volunteer-list.component' import { JobListComponent } from './JobList/job-list.component' @Component({ selector: 'my-app', // templateUrl: './app/app.component.html', // template:'<VolunteerQuery></VolunteerQuery>' //template:'<VolunteerSignup></VolunteerSignup>' //template:'<JobSignup></JobSignup>' template:'<VolunteerList></VolunteerList>' //template:'<JobList></JobList>' }) export class AppComponent {}
import { Component, NgModule } from '@angular/core'; import { VolunteerSignupComponent } from './VolunteerSignup/volunteer-signup.component'; import { JobSignupComponent } from './JobSignup/job-signup.component'; import { OrganisationSignupComponent } from './OrganisationSignup/organisation-signup.component'; import { VolunteerQueryComponent } from './Volunteer-query/volunteer-query.component' import { VolunteerListComponent } from './VolunteerList/volunteer-list.component' import { JobListComponent } from './JobList/job-list.component' @Component({ selector: 'my-app', // templateUrl: './app/app.component.html', // template:'<VolunteerQuery></VolunteerQuery>' //template:'<VolunteerSignup></VolunteerSignup>' //template:'<JobSignup></JobSignup>' //template:'<VolunteerList></VolunteerList>' template:'<JobList></JobList>' }) export class AppComponent {}
Change app template back to joblist
Change app template back to joblist
TypeScript
mit
astro8891/CommunityComms,astro8891/CommunityComms,astro8891/CommunityComms
--- +++ @@ -19,8 +19,8 @@ // template:'<VolunteerQuery></VolunteerQuery>' //template:'<VolunteerSignup></VolunteerSignup>' //template:'<JobSignup></JobSignup>' - template:'<VolunteerList></VolunteerList>' - //template:'<JobList></JobList>' + //template:'<VolunteerList></VolunteerList>' + template:'<JobList></JobList>' })
ca02e53b036b70d9c8c9012b40eb649220f3151d
src/app/utils/plugins.ts
src/app/utils/plugins.ts
import wpm from 'wexond-package-manager'; import Store from '../store'; import Theme from '../models/theme'; import Tab from '../components/Tab'; import React from 'react'; import PluginAPI from '../models/plugin-api'; export const loadPlugins = async () => { const wexondAPI = { setTheme: (theme: Theme) => { Store.theme.set(theme); }, }; const plugins = await wpm.list(); for (const plugin of plugins) { const data: PluginAPI = await wpm.run(plugin.namespace, wexondAPI, { fs: {}, react: React, }); Store.decoratedTab = data.decorateTab(Tab); wpm.update(plugin.namespace, false); } };
import wpm from 'wexond-package-manager'; import Store from '../store'; import Theme from '../models/theme'; import Tab from '../components/Tab'; import React from 'react'; import PluginAPI from '../models/plugin-api'; export const loadPlugins = async () => { const wexondAPI = { setTheme: (theme: Theme) => { Store.theme.set(theme); }, }; const plugins = await wpm.list(); for (const plugin of plugins) { const data: PluginAPI = await wpm.run(plugin.namespace, wexondAPI, { fs: {}, react: React, }); if (typeof data.decorateTab === 'function' && data.decorateTab.length === 1) { Store.decoratedTab = data.decorateTab(Tab); } wpm.update(plugin.namespace, false); } };
Check type of decorateTab function
:bug: Check type of decorateTab function
TypeScript
apache-2.0
Nersent/Wexond,Nersent/Wexond
--- +++ @@ -20,7 +20,10 @@ react: React, }); - Store.decoratedTab = data.decorateTab(Tab); + if (typeof data.decorateTab === 'function' && data.decorateTab.length === 1) { + Store.decoratedTab = data.decorateTab(Tab); + } + wpm.update(plugin.namespace, false); } };
ce78b20c89c3e4dc350ea83d9d5b9320a909f23a
src/auth/auth.service.ts
src/auth/auth.service.ts
import {Injectable} from '@angular/core'; import {KeycloakInstance, KeycloakProfile} from 'keycloak-js'; import {Observable} from 'rxjs/Observable'; import {fromPromise} from 'rxjs/observable/fromPromise'; import {of} from 'rxjs/observable/of'; import {HttpHeaders} from '@angular/common/http'; @Injectable() export class AuthService { keycloak: KeycloakInstance; public login(): void { this.keycloak.login(); } public logout(): void { this.keycloak.logout(); } public authenticated(): boolean { return this.keycloak.authenticated; } public refreshToken(minValidity: number = 5): Promise<boolean> { return new Promise((resolve, reject) => { this.keycloak.updateToken(minValidity) .success(resolve) .error(reject); }); } public getToken(): string { return this.keycloak.token; } public getAuthHeader(): HttpHeaders { const authToken = this.getToken(); return new HttpHeaders().set('Authorization', `Bearer ${authToken}`); } public getUserInfo(): Observable<KeycloakProfile | undefined> { if (!this.authenticated() || this.keycloak.profile) { return of(this.keycloak.profile); } return fromPromise(new Promise((resolve, reject) => { this.keycloak.loadUserProfile() .success(resolve) .error(err => reject(err)); })); } }
import {Injectable} from '@angular/core'; import {KeycloakInstance, KeycloakLoginOptions, KeycloakProfile} from 'keycloak-js'; import {Observable} from 'rxjs/Observable'; import {fromPromise} from 'rxjs/observable/fromPromise'; import {of} from 'rxjs/observable/of'; import {HttpHeaders} from '@angular/common/http'; @Injectable() export class AuthService { keycloak: KeycloakInstance; public login(options?: KeycloakLoginOptions): void { this.keycloak.login(options); } public logout(options?: any): void { this.keycloak.logout(options); } public authenticated(): boolean { return this.keycloak.authenticated; } public refreshToken(minValidity: number = 5): Promise<boolean> { return new Promise((resolve, reject) => { this.keycloak.updateToken(minValidity) .success(resolve) .error(reject); }); } public getToken(): string { return this.keycloak.token; } public getAuthHeader(): HttpHeaders { const authToken = this.getToken(); return new HttpHeaders().set('Authorization', `Bearer ${authToken}`); } public getUserInfo(): Observable<KeycloakProfile | undefined> { if (!this.authenticated() || this.keycloak.profile) { return of(this.keycloak.profile); } return fromPromise(new Promise((resolve, reject) => { this.keycloak.loadUserProfile() .success(resolve) .error(err => reject(err)); })); } }
Allow options to be passedπ
Allow options to be passedπ
TypeScript
apache-2.0
SchweizerischeBundesbahnen/esta-webjs-extensions,SchweizerischeBundesbahnen/esta-webjs-extensions,SchweizerischeBundesbahnen/esta-webjs-extensions
--- +++ @@ -1,5 +1,5 @@ import {Injectable} from '@angular/core'; -import {KeycloakInstance, KeycloakProfile} from 'keycloak-js'; +import {KeycloakInstance, KeycloakLoginOptions, KeycloakProfile} from 'keycloak-js'; import {Observable} from 'rxjs/Observable'; import {fromPromise} from 'rxjs/observable/fromPromise'; import {of} from 'rxjs/observable/of'; @@ -10,12 +10,12 @@ keycloak: KeycloakInstance; - public login(): void { - this.keycloak.login(); + public login(options?: KeycloakLoginOptions): void { + this.keycloak.login(options); } - public logout(): void { - this.keycloak.logout(); + public logout(options?: any): void { + this.keycloak.logout(options); } public authenticated(): boolean {
25cc59be7b6212de1185e6e0e3ea4fe8dbdad529
packages/styletron-client/index.d.ts
packages/styletron-client/index.d.ts
import StyletronCore from "styletron-core"; declare class StyletronClient extends StyletronCore { constructor(els: HTMLCollection | HTMLElement[]); } export default StyletronClient;
import StyletronCore from "styletron-core"; declare class StyletronClient extends StyletronCore { constructor(els?: HTMLCollection | HTMLElement[]); } export default StyletronClient;
Make argument for `StyletronClient` constructor optional
Make argument for `StyletronClient` constructor optional
TypeScript
mit
rtsao/styletron
--- +++ @@ -1,7 +1,7 @@ import StyletronCore from "styletron-core"; declare class StyletronClient extends StyletronCore { - constructor(els: HTMLCollection | HTMLElement[]); + constructor(els?: HTMLCollection | HTMLElement[]); } export default StyletronClient;
f2cad694d8fabeab4cfac2fb55a4ad30db11c0c0
client/app/components/tasks/tasks.ts
client/app/components/tasks/tasks.ts
/** * Created by siriscac on 18/07/16. */ import {Component, OnInit} from '@angular/core'; import {AuthService} from "../../services/auth"; import {Task, TaskService} from "../../services/task-service"; @Component({ styleUrls: ['./tasks.css'], templateUrl: './tasks.html' }) export class TaskComponent implements OnInit { private tasks: Task[]; constructor(private authService: AuthService, private taskService: TaskService) { } ngOnInit() { this.taskService.getTasks() .then(tasks => { this.tasks = tasks; if (tasks.length < 0) { this.taskService.fetchTasks(null); } }); } get authenticated() { return this.authService.isAuthenticated(); } statusTag(status) { if (status == "Success") return "tag-success"; else if (status == "Failed") return "tag-failure"; else return "tag-progress"; } }
/** * Created by siriscac on 18/07/16. */ import {Component, OnInit} from '@angular/core'; import {AuthService} from "../../services/auth"; import {Task, TaskService} from "../../services/task-service"; @Component({ styleUrls: ['./tasks.css'], templateUrl: './tasks.html' }) export class TaskComponent implements OnInit { private tasks: Task[]; constructor(private authService: AuthService, private taskService: TaskService) { } ngOnInit() { this.taskService.getTasks() .then(tasks => { this.tasks = tasks; if (tasks.length < 0) { this.taskService.fetchTasks(null); } }); } get authenticated() { return this.authService.isAuthenticated(); } statusTag(status) { if (status == "Success") return "tag-success"; else if (status == "Failure") return "tag-failure"; else return "tag-progress"; } }
Fix deploy failure tag color
Fix deploy failure tag color
TypeScript
apache-2.0
siriscac/apigee-seed-ui,siriscac/apigee-seed-ui,siriscac/apigee-seed-ui
--- +++ @@ -38,7 +38,7 @@ statusTag(status) { if (status == "Success") return "tag-success"; - else if (status == "Failed") + else if (status == "Failure") return "tag-failure"; else return "tag-progress";
215f8c99ace4a0415ec0397d662a911ece84bdf8
react-relay/react-relay-tests.tsx
react-relay/react-relay-tests.tsx
import * as React from "react" import * as Relay from "react-relay" interface Props { text: string userId: string } interface Response { } export default class AddTweetMutation extends Relay.Mutation<Props, Response> { getMutation () { return Relay.QL`mutation{addTweet}` } getFatQuery () { return Relay.QL` fragment on AddTweetPayload { tweetEdge user } ` } getConfigs () { return [{ type: "RANGE_ADD", parentName: "user", parentID: this.props.userId, connectionName: "tweets", edgeName: "tweetEdge", rangeBehaviors: { "": "append", }, }] } getVariables () { return this.props } }
import * as React from "react" import * as Relay from "react-relay" interface Props { text: string userId: string } interface Response { } export default class AddTweetMutation extends Relay.Mutation<Props, Response> { getMutation () { return Relay.QL`mutation{addTweet}` } getFatQuery () { return Relay.QL` fragment on AddTweetPayload { tweetEdge user } ` } getConfigs () { return [{ type: "RANGE_ADD", parentName: "user", parentID: this.props.userId, connectionName: "tweets", edgeName: "tweetEdge", rangeBehaviors: { "": "append", }, }] } getVariables () { return this.props } } interface ArtworkProps { artwork: { title: string } } class Artwork extends React.Component<ArtworkProps, null> { render() { return <p>{this.props.artwork.title}</p> } } const ArtworkContainer = Relay.createContainer(Artwork, { fragments: { artwork: () => Relay.QL` fragment on Artwork { title } ` } }) class StubbedArtwork extends React.Component<null, null> { render() { return <ArtworkContainer artwork={{ title: "CHAMPAGNE FORMICA FLAG" }} /> } }
Add example of stubbing data into Relay container.
[react-relay] Add example of stubbing data into Relay container.
TypeScript
mit
borisyankov/DefinitelyTyped,aciccarello/DefinitelyTyped,one-pieces/DefinitelyTyped,mcrawshaw/DefinitelyTyped,smrq/DefinitelyTyped,alexdresko/DefinitelyTyped,mcliment/DefinitelyTyped,QuatroCode/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,nycdotnet/DefinitelyTyped,QuatroCode/DefinitelyTyped,abbasmhd/DefinitelyTyped,YousefED/DefinitelyTyped,magny/DefinitelyTyped,chrootsu/DefinitelyTyped,benishouga/DefinitelyTyped,AgentME/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,minodisk/DefinitelyTyped,isman-usoh/DefinitelyTyped,borisyankov/DefinitelyTyped,markogresak/DefinitelyTyped,amir-arad/DefinitelyTyped,abbasmhd/DefinitelyTyped,AgentME/DefinitelyTyped,jimthedev/DefinitelyTyped,johan-gorter/DefinitelyTyped,progre/DefinitelyTyped,dsebastien/DefinitelyTyped,chrootsu/DefinitelyTyped,benishouga/DefinitelyTyped,ashwinr/DefinitelyTyped,zuzusik/DefinitelyTyped,minodisk/DefinitelyTyped,aciccarello/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,progre/DefinitelyTyped,dsebastien/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,jimthedev/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,rolandzwaga/DefinitelyTyped,benliddicott/DefinitelyTyped,jimthedev/DefinitelyTyped,zuzusik/DefinitelyTyped,YousefED/DefinitelyTyped,nycdotnet/DefinitelyTyped,georgemarshall/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,georgemarshall/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,magny/DefinitelyTyped,smrq/DefinitelyTyped,mcrawshaw/DefinitelyTyped,isman-usoh/DefinitelyTyped,benishouga/DefinitelyTyped,alexdresko/DefinitelyTyped,aciccarello/DefinitelyTyped,ashwinr/DefinitelyTyped,georgemarshall/DefinitelyTyped,johan-gorter/DefinitelyTyped,arusakov/DefinitelyTyped,arusakov/DefinitelyTyped,rolandzwaga/DefinitelyTyped
--- +++ @@ -41,3 +41,31 @@ return this.props } } + +interface ArtworkProps { + artwork: { + title: string + } +} + +class Artwork extends React.Component<ArtworkProps, null> { + render() { + return <p>{this.props.artwork.title}</p> + } +} + +const ArtworkContainer = Relay.createContainer(Artwork, { + fragments: { + artwork: () => Relay.QL` + fragment on Artwork { + title + } + ` + } +}) + +class StubbedArtwork extends React.Component<null, null> { + render() { + return <ArtworkContainer artwork={{ title: "CHAMPAGNE FORMICA FLAG" }} /> + } +}
2895bbb268c8d19596eee3ef777a35e700c3db4c
ui/src/shared/decorators/errors.tsx
ui/src/shared/decorators/errors.tsx
/* tslint:disable no-console */ import React from 'react' export function ErrorHandling< P, S, T extends {new (...args: any[]): React.Component<P, S>} >(constructor: T) { class Wrapped extends constructor { private error: boolean = false public componentDidCatch(error, info) { console.error(error) console.warn(info) this.error = true this.forceUpdate() } public render() { if (this.error) { return ( <p className="error"> A Chronograf error has occurred. Please report the issue <a href="https://github.com/influxdata/chronograf/issues">here</a> </p> ) } return super.render() } } return Wrapped }
/* tslint:disable no-console */ import React from 'react' export function ErrorHandling< P, S, T extends {new (...args: any[]): React.Component<P, S>} >(constructor: T) { class Wrapped extends constructor { private error: boolean = false public componentDidCatch(error, info) { console.error(error) console.warn(info) this.error = true this.forceUpdate() } public render() { if (this.error) { return ( <p className="error"> A Chronograf error has occurred. Please report the issue&nbsp; <a href="https://github.com/influxdata/chronograf/issues">here</a>. </p> ) } return super.render() } } return Wrapped }
Fix error message grammer and style
Fix error message grammer and style
TypeScript
mit
mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb
--- +++ @@ -20,8 +20,8 @@ if (this.error) { return ( <p className="error"> - A Chronograf error has occurred. Please report the issue - <a href="https://github.com/influxdata/chronograf/issues">here</a> + A Chronograf error has occurred. Please report the issue&nbsp; + <a href="https://github.com/influxdata/chronograf/issues">here</a>. </p> ) }
022249de73519f4ae22b6918d62215a6ec784e02
src/lib/tests/renderWithWrappers.tsx
src/lib/tests/renderWithWrappers.tsx
import { AppStoreProvider } from "lib/store/AppStore" import { Theme } from "palette" import React from "react" import ReactTestRenderer from "react-test-renderer" import { ReactElement } from "simple-markdown" /** * Renders a React Component with our page wrappers * only <Theme> for now * @param component */ export const renderWithWrappers = (component: ReactElement) => { const wrappedComponent = componentWithWrappers(component) // tslint:disable-next-line:use-wrapped-components const renderedComponent = ReactTestRenderer.create(wrappedComponent) // monkey patch update method to wrap components const originalUpdate = renderedComponent.update renderedComponent.update = (nextElement: ReactElement) => { originalUpdate(componentWithWrappers(nextElement)) } return renderedComponent } /** * Returns given component wrapped with our page wrappers * only <Theme> for now * @param component */ export const componentWithWrappers = (component: ReactElement) => { return ( <AppStoreProvider> <Theme>{component}</Theme> </AppStoreProvider> ) }
import { AppStoreProvider } from "lib/store/AppStore" import { Theme } from "palette" import React from "react" import ReactTestRenderer from "react-test-renderer" import { ReactElement } from "simple-markdown" /** * Renders a React Component with our page wrappers * only <Theme> for now * @param component */ export const renderWithWrappers = (component: ReactElement) => { const wrappedComponent = componentWithWrappers(component) try { // tslint:disable-next-line:use-wrapped-components const renderedComponent = ReactTestRenderer.create(wrappedComponent) // monkey patch update method to wrap components const originalUpdate = renderedComponent.update renderedComponent.update = (nextElement: ReactElement) => { originalUpdate(componentWithWrappers(nextElement)) } return renderedComponent } catch (error) { if (error.message.includes("Element type is invalid")) { throw new Error( 'Error: Relay test component failed to render. Did you forget to add `jest.unmock("react-relay")` at the top ' + "of your test?" + "\n\n" + error ) } else { throw new Error(error.message) } } } /** * Returns given component wrapped with our page wrappers * only <Theme> for now * @param component */ export const componentWithWrappers = (component: ReactElement) => { return ( <AppStoreProvider> <Theme>{component}</Theme> </AppStoreProvider> ) }
Make mocked relay error more obvious
Make mocked relay error more obvious
TypeScript
mit
artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen
--- +++ @@ -11,16 +11,29 @@ */ export const renderWithWrappers = (component: ReactElement) => { const wrappedComponent = componentWithWrappers(component) - // tslint:disable-next-line:use-wrapped-components - const renderedComponent = ReactTestRenderer.create(wrappedComponent) + try { + // tslint:disable-next-line:use-wrapped-components + const renderedComponent = ReactTestRenderer.create(wrappedComponent) - // monkey patch update method to wrap components - const originalUpdate = renderedComponent.update - renderedComponent.update = (nextElement: ReactElement) => { - originalUpdate(componentWithWrappers(nextElement)) + // monkey patch update method to wrap components + const originalUpdate = renderedComponent.update + renderedComponent.update = (nextElement: ReactElement) => { + originalUpdate(componentWithWrappers(nextElement)) + } + + return renderedComponent + } catch (error) { + if (error.message.includes("Element type is invalid")) { + throw new Error( + 'Error: Relay test component failed to render. Did you forget to add `jest.unmock("react-relay")` at the top ' + + "of your test?" + + "\n\n" + + error + ) + } else { + throw new Error(error.message) + } } - - return renderedComponent } /**
bd299d8c233913f85ac9e66e4882314dd7b00c0e
demo/global-panzoom.ts
demo/global-panzoom.ts
import Panzoom from '../src/panzoom' console.log('This is a demo version of Panzoom for testing.') console.log('It exposes a global (window.Panzoom) and should not be used in production.') window.Panzoom = Panzoom
import Panzoom from '../src/panzoom' console.log('This is a demo version of Panzoom for testing.') console.log('It exposes a global (window.Panzoom) and should not be used in production.') declare global { interface Window { Panzoom: typeof Panzoom } } window.Panzoom = Panzoom
Revert "docs(demo): remove unnecessary window declaration"
Revert "docs(demo): remove unnecessary window declaration" This reverts commit ba5e2a949b43020a58df08346834014d56d5f4b7.
TypeScript
mit
timmywil/jquery.panzoom,timmywil/jquery.panzoom,timmywil/jquery.panzoom
--- +++ @@ -3,4 +3,9 @@ console.log('This is a demo version of Panzoom for testing.') console.log('It exposes a global (window.Panzoom) and should not be used in production.') +declare global { + interface Window { + Panzoom: typeof Panzoom + } +} window.Panzoom = Panzoom
d7e19af60224112b58ace18937eb3778a4896d67
src/Parsing/Inline/TokenizerState.ts
src/Parsing/Inline/TokenizerState.ts
import { RichSandwichTracker } from './RichSandwichTracker' import { TextConsumer } from '../TextConsumer' import { Token } from './Token' interface Args { consumer?: TextConsumer, tokens?: Token[], sandwichTrackers?: RichSandwichTracker[] } export class TokenizerState { public consumer: TextConsumer public tokens: Token[] public sandwichTrackers: RichSandwichTracker[] constructor(args?: Args) { if (!args) { return } this.consumer = args.consumer this.tokens = args.tokens this.sandwichTrackers = args.sandwichTrackers } clone(): TokenizerState { return new TokenizerState({ consumer: this.consumer.clone(), tokens: this.tokens.slice(), sandwichTrackers: this.sandwichTrackers.map(tracker => tracker.clone()) }) } }
import { RichSandwichTracker } from './RichSandwichTracker' import { TextConsumer } from '../TextConsumer' import { Token } from './Token' interface Args { consumer?: TextConsumer, tokens?: Token[], sandwichTrackers?: RichSandwichTracker[] } export class TokenizerState { public consumer: TextConsumer public tokens: Token[] public sandwichTrackers: RichSandwichTracker[] constructor(args?: Args) { if (!args) { return } this.consumer = args.consumer this.tokens = args.tokens this.sandwichTrackers = args.sandwichTrackers } clone(): TokenizerState { return new TokenizerState({ consumer: this.consumer.clone(), tokens: this.tokens.slice(), sandwichTrackers: this.sandwichTrackers.map(tracker => tracker.clone()) }) } }
Fix formatting in tokenizer state file
Fix formatting in tokenizer state file
TypeScript
mit
start/up,start/up
--- +++ @@ -3,26 +3,26 @@ import { Token } from './Token' interface Args { - consumer?: TextConsumer, - tokens?: Token[], - sandwichTrackers?: RichSandwichTracker[] + consumer?: TextConsumer, + tokens?: Token[], + sandwichTrackers?: RichSandwichTracker[] } export class TokenizerState { public consumer: TextConsumer - public tokens: Token[] - public sandwichTrackers: RichSandwichTracker[] - + public tokens: Token[] + public sandwichTrackers: RichSandwichTracker[] + constructor(args?: Args) { if (!args) { return } - + this.consumer = args.consumer this.tokens = args.tokens this.sandwichTrackers = args.sandwichTrackers } - + clone(): TokenizerState { return new TokenizerState({ consumer: this.consumer.clone(),
913096dd1fbe70551bd77c210c6a761c484ef66d
src/js/server/routes/apply-router.ts
src/js/server/routes/apply-router.ts
import { Request, Router } from 'express'; import { logout, requireAuth } from 'js/server/auth'; import { dashboardController, hackerApplicationsController, rsvpsController, teamsController } from 'js/server/controllers/apply'; import { applicationsMiddleware } from 'js/server/middleware'; import { HackerInstance } from 'js/server/models'; const applyRouter = Router(); export interface UserRequest extends Request { user: HackerInstance; } applyRouter.get('/', (req: UserRequest, res) => { req.user ? res.redirect('dashboard') : res.redirect('login'); }); applyRouter.get('/login', (_req: UserRequest, res) => res.render('apply/login')); applyRouter.use(requireAuth); applyRouter.get('/logout', logout, (_req: UserRequest, res) => res.redirect('/')); applyRouter.get('/dashboard', requireAuth, dashboardController.showDashboard); applyRouter.route('/form') .all(applicationsMiddleware.goBackIfApplied, applicationsMiddleware.goBackIfApplicationsClosed) .get(hackerApplicationsController.newHackerApplication) .post(hackerApplicationsController.createHackerApplication); applyRouter.route('/team') .all(applicationsMiddleware.goBackIfApplicationsClosed) .get(teamsController.newTeam) .post(teamsController.createTeam); // Process the RSVP response applyRouter.post('/rsvp', requireAuth, rsvpsController.createRsvp); export default applyRouter;
import { Request, Router } from 'express'; import { logout, requireAuth } from 'js/server/auth'; import { dashboardController, hackerApplicationsController, rsvpsController, teamsController } from 'js/server/controllers/apply'; import { applicationsMiddleware } from 'js/server/middleware'; import { HackerInstance } from 'js/server/models'; const applyRouter = Router(); export interface UserRequest extends Request { user: HackerInstance; } applyRouter.get('/', (req: UserRequest, res) => { req.user ? res.redirect('apply/dashboard') : res.redirect('apply/login'); }); applyRouter.get('/login', (_req: UserRequest, res) => res.render('apply/login')); applyRouter.use(requireAuth); applyRouter.get('/logout', logout, (_req: UserRequest, res) => res.redirect('/')); applyRouter.get('/dashboard', requireAuth, dashboardController.showDashboard); applyRouter.route('/form') .all(applicationsMiddleware.goBackIfApplied, applicationsMiddleware.goBackIfApplicationsClosed) .get(hackerApplicationsController.newHackerApplication) .post(hackerApplicationsController.createHackerApplication); applyRouter.route('/team') .all(applicationsMiddleware.goBackIfApplicationsClosed) .get(teamsController.newTeam) .post(teamsController.createTeam); // Process the RSVP response applyRouter.post('/rsvp', requireAuth, rsvpsController.createRsvp); export default applyRouter;
Fix routes in apply router
Fix routes in apply router
TypeScript
mit
hackcambridge/hack-cambridge-website,hackcambridge/hack-cambridge-website,hackcambridge/hack-cambridge-website,hackcambridge/hack-cambridge-website
--- +++ @@ -12,7 +12,7 @@ } applyRouter.get('/', (req: UserRequest, res) => { - req.user ? res.redirect('dashboard') : res.redirect('login'); + req.user ? res.redirect('apply/dashboard') : res.redirect('apply/login'); }); applyRouter.get('/login', (_req: UserRequest, res) => res.render('apply/login'));
dcc8c089aa29d4152f368d04b9b4abdd74288151
src/schema/v2/sorts/article_sorts.ts
src/schema/v2/sorts/article_sorts.ts
import { GraphQLEnumType } from "graphql" export const ARTICLE_SORTS = { PUBLISHED_AT_ASC: { value: "published_at", }, PUBLISHED_AT_DESC: { value: "-published_at", }, } as const const ArticleSorts = { type: new GraphQLEnumType({ name: "ArticleSorts", values: ARTICLE_SORTS, }), } export type ArticleSort = typeof ARTICLE_SORTS[keyof typeof ARTICLE_SORTS]["value"] export default ArticleSorts
import { GraphQLEnumType } from "graphql" export const ARTICLE_SORTS = { PUBLISHED_AT_ASC: { value: "published_at", }, PUBLISHED_AT_DESC: { value: "-published_at", }, } const ArticleSorts = { type: new GraphQLEnumType({ name: "ArticleSorts", values: ARTICLE_SORTS, }), } export type ArticleSort = typeof ARTICLE_SORTS[keyof typeof ARTICLE_SORTS]["value"] export default ArticleSorts
Remove `as const` from article sorts export constant
Remove `as const` from article sorts export constant
TypeScript
mit
artsy/metaphysics,artsy/metaphysics,artsy/metaphysics
--- +++ @@ -7,7 +7,7 @@ PUBLISHED_AT_DESC: { value: "-published_at", }, -} as const +} const ArticleSorts = { type: new GraphQLEnumType({
ae902fcbf502f9edc382517af380dc374744a402
packages/@sanity/field/src/diff/annotations/DiffAnnotation.tsx
packages/@sanity/field/src/diff/annotations/DiffAnnotation.tsx
import * as React from 'react' import {useUserColorManager} from '@sanity/base/user-color' import {Annotation, Diff, Path} from '../types' import {DiffAnnotationTooltip} from './DiffAnnotationTooltip' import {getAnnotationForPath, getAnnotationColor} from './helpers' export interface AnnotationProps { annotation: Annotation } export interface AnnotatedDiffProps { diff: Diff path?: Path | string } interface BaseAnnotationProps { as?: string className?: string children: React.ReactNode } export type DiffAnnotationProps = (AnnotationProps | AnnotatedDiffProps) & BaseAnnotationProps export function DiffAnnotation(props: DiffAnnotationProps) { const colorManager = useUserColorManager() const {as = 'span', children, className} = props const annotation = 'diff' in props ? getAnnotationForPath(props.diff, props.path || []) : props.annotation if (!annotation) { return React.createElement(as, {className}, children) } const color = getAnnotationColor(colorManager, annotation) const style = {background: color.background, color: color.text} return ( <DiffAnnotationTooltip annotation={annotation}> {React.createElement(as, {className, style}, children)} </DiffAnnotationTooltip> ) }
import * as React from 'react' import {useUserColorManager} from '@sanity/base/user-color' import {Annotation, Diff, Path} from '../types' import {DiffAnnotationTooltip} from './DiffAnnotationTooltip' import {getAnnotationForPath, getAnnotationColor} from './helpers' export interface AnnotationProps { annotation: Annotation } export interface AnnotatedDiffProps { diff: Diff path?: Path | string } interface BaseAnnotationProps { as?: React.ElementType | keyof JSX.IntrinsicElements className?: string children: React.ReactNode } export type DiffAnnotationProps = (AnnotationProps | AnnotatedDiffProps) & BaseAnnotationProps export function DiffAnnotation(props: DiffAnnotationProps) { const colorManager = useUserColorManager() const {as = 'span', children, className} = props const annotation = 'diff' in props ? getAnnotationForPath(props.diff, props.path || []) : props.annotation if (!annotation) { return React.createElement(as, {className}, children) } const color = getAnnotationColor(colorManager, annotation) const style = {background: color.background, color: color.text} return ( <DiffAnnotationTooltip annotation={annotation}> {React.createElement(as, {className, style}, children)} </DiffAnnotationTooltip> ) }
Improve typing for "as" property
[field] Improve typing for "as" property
TypeScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -14,7 +14,7 @@ } interface BaseAnnotationProps { - as?: string + as?: React.ElementType | keyof JSX.IntrinsicElements className?: string children: React.ReactNode }
aaa467f6a101d0d8e18b28573f49cb7385988a4d
bids-validator/src/compat/fulltest.ts
bids-validator/src/compat/fulltest.ts
/** Adapter to run Node.js bids-validator fullTest with minimal changes from Deno */ import { ValidatorOptions } from '../setup/options.ts' import { FileTree } from '../types/filetree.ts' import { walkFileTree } from '../schema/walk.ts' import { FullTestIssuesReturn } from '../types/issues.ts' import validate from '../../dist/esm/index.js' import { AdapterFile } from './adapter-file.ts' export interface FullTestAdapterReturn { issues: FullTestIssuesReturn summary: Record<string, any> } export async function fullTestAdapter( tree: FileTree, options: ValidatorOptions, ): Promise<FullTestAdapterReturn> { const fileList: Array<AdapterFile> = [] for await (const context of walkFileTree(tree)) { const stream = await context.file.stream const file = new AdapterFile(context.datasetPath, context.file, stream) fileList.push(file) } return new Promise((resolve) => { validate.BIDS( fileList, options, (issues: FullTestIssuesReturn, summary: Record<string, any>) => { resolve({ issues, summary }) }, ) }) }
/** Adapter to run Node.js bids-validator fullTest with minimal changes from Deno */ import { ValidatorOptions } from '../setup/options.ts' import { FileTree } from '../types/filetree.ts' import { walkFileTree } from '../schema/walk.ts' import { FullTestIssuesReturn } from '../types/issues.ts' import validate from '../../dist/esm/index.js' import { AdapterFile } from './adapter-file.ts' export interface FullTestAdapterReturn { issues: FullTestIssuesReturn summary: Record<string, any> } export async function fullTestAdapter( tree: FileTree, options: ValidatorOptions, ): Promise<FullTestAdapterReturn> { const fileList: Array<AdapterFile> = [] for await (const context of walkFileTree(tree, undefined)) { const stream = await context.file.stream const file = new AdapterFile(context.datasetPath, context.file, stream) fileList.push(file) } return new Promise((resolve) => { validate.BIDS( fileList, options, (issues: FullTestIssuesReturn, summary: Record<string, any>) => { resolve({ issues, summary }) }, ) }) }
Add missing argument to walkFileTree in fullTestAdapter
fix: Add missing argument to walkFileTree in fullTestAdapter
TypeScript
mit
nellh/bids-validator,nellh/bids-validator,nellh/bids-validator
--- +++ @@ -16,7 +16,7 @@ options: ValidatorOptions, ): Promise<FullTestAdapterReturn> { const fileList: Array<AdapterFile> = [] - for await (const context of walkFileTree(tree)) { + for await (const context of walkFileTree(tree, undefined)) { const stream = await context.file.stream const file = new AdapterFile(context.datasetPath, context.file, stream) fileList.push(file)
ada35c6149f028525799375991ea3863d54feaa0
test/unit/location.spec.ts
test/unit/location.spec.ts
import * as location from 'location' const dispatch = (fn: any, args: any) => fn(undefined, args) describe('location module', () => { it('updateLocation updates window.location', () => { location.updateLocation('/some/path').execute(dispatch) expect(window.location.pathname).toBe('/some/path') }) it('updateLocation serializes parameters', () => { location.updateLocation('/some/path', { foo: 'bar', baz: 1 }).execute(dispatch) expect(window.location.search).toBe('?foo=bar&baz=1') }) })
import * as location from 'location' const dispatch = (fn: any, args: any) => fn(undefined, args) describe('location module', () => { afterEach(() => { window.location.pathname = '/' }) it('updateLocation updates window.location', () => { location.updateLocation('/some/path').execute(dispatch) expect(window.location.pathname).toBe('/some/path') }) it('updateLocation serializes parameters', () => { location.updateLocation('/some/path', { foo: 'bar', baz: 1 }).execute(dispatch) expect(window.location.search).toBe('?foo=bar&baz=1') }) })
Reset location after location tests
Reset location after location tests
TypeScript
mit
jhdrn/myra,jhdrn/myra
--- +++ @@ -4,6 +4,10 @@ const dispatch = (fn: any, args: any) => fn(undefined, args) describe('location module', () => { + + afterEach(() => { + window.location.pathname = '/' + }) it('updateLocation updates window.location', () => {
1527dec1655120cf52796dd0b2ada6db243a55f6
src/renderers/floating-renderer.tsx
src/renderers/floating-renderer.tsx
import * as React from 'react'; import * as RenderersModel from '../renderers-model'; export class FloatingRenderer<T> extends React.PureComponent<RenderersModel.FloatingRendererProps<T>, never> { public render() { return <div style={{ display: 'grid', gridTemplateRows: '20px 1fr' }}> <this.props.floatyRenderers.floatingTabRenderer floatyManager={this.props.floatyManager} stackItem={this.props.floating} /> <this.props.floatyRenderers.floatingContentRenderer floatyManager={this.props.floatyManager} stackItem={this.props.floating} /> </div>; } }
import * as React from 'react'; import * as RenderersModel from '../renderers-model'; export class FloatingRenderer<T> extends React.PureComponent<RenderersModel.FloatingRendererProps<T>, never> { public render() { return <div style={{ display: 'grid', gridTemplateRows: 'minmax(min-content, max-content) 1fr' }}> <this.props.floatyRenderers.floatingTabRenderer floatyManager={this.props.floatyManager} stackItem={this.props.floating} /> <this.props.floatyRenderers.floatingContentRenderer floatyManager={this.props.floatyManager} stackItem={this.props.floating} /> </div>; } }
Allow floating tab to be any size
Allow floating tab to be any size
TypeScript
mit
woutervh-/floaty,woutervh-/floaty
--- +++ @@ -3,7 +3,7 @@ export class FloatingRenderer<T> extends React.PureComponent<RenderersModel.FloatingRendererProps<T>, never> { public render() { - return <div style={{ display: 'grid', gridTemplateRows: '20px 1fr' }}> + return <div style={{ display: 'grid', gridTemplateRows: 'minmax(min-content, max-content) 1fr' }}> <this.props.floatyRenderers.floatingTabRenderer floatyManager={this.props.floatyManager} stackItem={this.props.floating} /> <this.props.floatyRenderers.floatingContentRenderer floatyManager={this.props.floatyManager} stackItem={this.props.floating} /> </div>;
a5686bfebe3daa9b510e23020873ab573b3197d6
src/services/slack/emoji.service.ts
src/services/slack/emoji.service.ts
import { defaultEmojis } from './default_emoji'; import { SlackClient } from './slack-client'; import * as emojione from 'emojione'; export class EmojiService { emojiList: { string: string }; defaultEmojis = defaultEmojis; get allEmojis(): string[] { return defaultEmojis.concat(Object.keys(this.emojiList)); } constructor(private client: SlackClient) { this.initExternalEmojis(); } async initExternalEmojis(): Promise<void> { if (!this.emojiList) { this.emojiList = await this.client.getEmoji(); } } convertEmoji(emoji: string): string { if (emoji !== emojione.shortnameToImage(emoji)) { return emojione.shortnameToImage(emoji); } else if (this.emojiList && !!this.emojiList[emoji.substr(1, emoji.length - 2)]) { let image_url = this.emojiList[emoji.substr(1, emoji.length - 2)]; if (image_url.substr(0, 6) === 'alias:') { return this.convertEmoji(`:${image_url.substr(6)}:`); } else { return `<img class="emojione" src="${image_url}" />`; } } else { return emoji; } } }
import { defaultEmojis } from './default_emoji'; import { SlackClient } from './slack-client'; import * as emojione from 'emojione'; export class EmojiService { emojiList: { string: string }; defaultEmojis = defaultEmojis; get allEmojis(): string[] { return defaultEmojis.concat(Object.keys(this.emojiList)); } constructor(private client: SlackClient) { this.initExternalEmojis(); } async initExternalEmojis(): Promise<void> { if (!this.emojiList) { this.emojiList = await this.client.getEmoji(); } } convertEmoji(emoji: string): string { if (this.emojiList && !!this.emojiList[emoji.substr(1, emoji.length - 2)]) { let image_url = this.emojiList[emoji.substr(1, emoji.length - 2)]; if (image_url.substr(0, 6) === 'alias:') { return this.convertEmoji(`:${image_url.substr(6)}:`); } else { return `<img class="emojione" src="${image_url}" />`; } } else if (emoji !== emojione.shortnameToImage(emoji)) { return emojione.shortnameToImage(emoji); } else { return emoji; } } }
Fix issue about custom emoji.
Fix issue about custom emoji. If both custom emoji and emojione's emoji exist, custom emoji should be shown.
TypeScript
mit
mazun/ASlack-Stream,mazun/ASlack-Stream,mazun/SlackStream,mazun/SlackStream,mazun/ASlack-Stream,mazun/SlackStream,mazun/ASlack-Stream,mazun/SlackStream
--- +++ @@ -22,15 +22,15 @@ } convertEmoji(emoji: string): string { - if (emoji !== emojione.shortnameToImage(emoji)) { - return emojione.shortnameToImage(emoji); - } else if (this.emojiList && !!this.emojiList[emoji.substr(1, emoji.length - 2)]) { + if (this.emojiList && !!this.emojiList[emoji.substr(1, emoji.length - 2)]) { let image_url = this.emojiList[emoji.substr(1, emoji.length - 2)]; if (image_url.substr(0, 6) === 'alias:') { return this.convertEmoji(`:${image_url.substr(6)}:`); } else { return `<img class="emojione" src="${image_url}" />`; } + } else if (emoji !== emojione.shortnameToImage(emoji)) { + return emojione.shortnameToImage(emoji); } else { return emoji; }
aead41f1e0c89a52218f61fc62915b2d318dc612
src/Interfaces/IOption.d.ts
src/Interfaces/IOption.d.ts
/** * Option model interface * @author Islam Attrash */ export interface IOption { /** * Text for the option */ text: string; /** * The option value */ value: any; //Any other dynamic user selection [key: string]: any; }
/** * Option model interface * @author Islam Attrash */ export interface IOption { /** * Text for the option */ text: string; /** * The option value */ value: any; /** * Any other OPTIONAL dynamic user properties */ [key: string]: any; }
Correct string for the IOption interface
Correct string for the IOption interface
TypeScript
mit
Attrash-Islam/infinite-autocomplete,Attrash-Islam/infinite-autocomplete
--- +++ @@ -11,6 +11,8 @@ * The option value */ value: any; - //Any other dynamic user selection + /** + * Any other OPTIONAL dynamic user properties + */ [key: string]: any; }
02e17ea6f029292a171a830b7609747e91ed04d8
src/Places/PlaceDetailed.ts
src/Places/PlaceDetailed.ts
import { Media } from '../Media/Media'; export interface PlaceDetail { tags: Tag[]; address: string; admission: string; description: Description; email: string; duration: number; openingHours: string; phone: string; media: Media; references: Reference[]; } export interface Reference { id: number; title: string; type: string; languageId: string; url: string; offlineFile?: any; supplier: string; priority: number; isPremium: boolean; currency: string; price?: number; flags: any[]; } export interface Tag { key: string; name: string; } export interface Description { text: string; provider: string; translationProvider?: string; url?: string; }
import { PlaceDetailMedia } from '../Media/Media'; export interface PlaceDetail { tags: Tag[]; address: string; admission: string; description: Description; email: string; duration: number; openingHours: string; phone: string; media: PlaceDetailMedia; references: Reference[]; } export interface Reference { id: number; title: string; type: string; languageId: string; url: string; offlineFile?: any; supplier: string; priority: number; isPremium: boolean; currency: string; price?: number; flags: any[]; } export interface Tag { key: string; name: string; } export interface Description { text: string; provider: string; translationProvider?: string; url?: string; }
Fix data type of media in place detail
Fix data type of media in place detail
TypeScript
mit
sygic-travel/js-sdk,sygic-travel/js-sdk,sygic-travel/js-sdk
--- +++ @@ -1,4 +1,4 @@ -import { Media } from '../Media/Media'; +import { PlaceDetailMedia } from '../Media/Media'; export interface PlaceDetail { tags: Tag[]; @@ -9,7 +9,7 @@ duration: number; openingHours: string; phone: string; - media: Media; + media: PlaceDetailMedia; references: Reference[]; }
c98906e0d1bd2649992a66e9f236acdfcfc9e863
src/View/Settings/Index.tsx
src/View/Settings/Index.tsx
import * as React from 'react'; class SettingsIndex extends React.Component<any, any> { render() { return ( <div> {'Settings'} </div> ); } }; export default SettingsIndex;
import * as React from 'react'; import { getElectron } from 'Helpers/System/Electron'; class SettingsIndex extends React.Component<any, any> { render() { return ( <div> {'Settings'} <a href="#" onClick={this.handleClick.bind(this)}> {'Add User'} </a> </div> ); } handleClick(e) { e.preventDefault(); let BrowserWindow = getElectron().remote.BrowserWindow; let authWindow = new BrowserWindow({ width : 800, height : 600, show : true, webPreferences : { nodeIntegration : false } }); var url = 'https://harksys.com'; authWindow.loadURL(url); authWindow.on('close', () => { authWindow.destroy(); }); authWindow.webContents.on('will-navigate', (e, u) => { console.log(u); }); } }; export default SettingsIndex;
Test getElectron method future GitHub auth work.
Test getElectron method future GitHub auth work.
TypeScript
mit
harksys/HawkEye,harksys/HawkEye,harksys/HawkEye
--- +++ @@ -1,4 +1,5 @@ import * as React from 'react'; +import { getElectron } from 'Helpers/System/Electron'; class SettingsIndex extends React.Component<any, any> { @@ -7,8 +8,40 @@ return ( <div> {'Settings'} + <a href="#" + onClick={this.handleClick.bind(this)}> + {'Add User'} + </a> </div> ); + } + + handleClick(e) + { + e.preventDefault(); + + let BrowserWindow = getElectron().remote.BrowserWindow; + let authWindow = new BrowserWindow({ + width : 800, + height : 600, + show : true, + webPreferences : { + nodeIntegration : false + } + }); + + var url = 'https://harksys.com'; + authWindow.loadURL(url); + + authWindow.on('close', () => + { + authWindow.destroy(); + }); + + authWindow.webContents.on('will-navigate', (e, u) => + { + console.log(u); + }); } };
95f24db73ea5d779ef931500978d731fd0eb509f
src/test/dutch.spec.ts
src/test/dutch.spec.ts
import {expect} from 'chai'; import * as cspell from '../index'; import * as path from 'path'; import * as fsp from 'fs-extra'; import * as dutchDict from 'cspell-dict-nl-nl'; import * as util from '../util/util'; const sampleFilename = path.join(__dirname, '..', '..', 'samples', 'Dutch.txt'); const sampleFile = fsp.readFile(sampleFilename, 'UTF-8').then(buffer => buffer.toString()); const dutchConfig = dutchDict.getConfigLocation(); describe('Validate that Dutch text is correctly checked.', function() { it('Tests the default configuration', function() { this.timeout(5000); return sampleFile.then(text => { expect(text).to.not.be.empty; const ext = path.extname(sampleFilename); const languageIds = cspell.getLanguagesForExt(ext); const dutchSettings = cspell.readSettings(dutchConfig); const settings = cspell.mergeSettings(cspell.getDefaultSettings(), dutchSettings, { language: 'en,nl' }); const fileSettings = cspell.combineTextAndLanguageSettings(settings, text, languageIds); return cspell.validateText(text, fileSettings) .then(results => { /* cspell:ignore ANBI RABO RABONL unported */ expect(results.map(a => a.text).filter(util.uniqueFn()).sort()).deep.equals(['ANBI', 'RABO', 'RABONL', 'unported']); }); }); }); });
import {expect} from 'chai'; import * as cspell from '../index'; import * as path from 'path'; import * as fsp from 'fs-extra'; import * as dutchDict from 'cspell-dict-nl-nl'; import * as util from '../util/util'; const sampleFilename = path.join(__dirname, '..', '..', 'samples', 'Dutch.txt'); const sampleFile = fsp.readFile(sampleFilename, 'UTF-8').then(buffer => buffer.toString()); const dutchConfig = dutchDict.getConfigLocation(); describe('Validate that Dutch text is correctly checked.', function() { it('Tests the default configuration', function() { this.timeout(30000); return sampleFile.then(text => { expect(text).to.not.be.empty; const ext = path.extname(sampleFilename); const languageIds = cspell.getLanguagesForExt(ext); const dutchSettings = cspell.readSettings(dutchConfig); const settings = cspell.mergeSettings(cspell.getDefaultSettings(), dutchSettings, { language: 'en,nl' }); const fileSettings = cspell.combineTextAndLanguageSettings(settings, text, languageIds); return cspell.validateText(text, fileSettings) .then(results => { /* cspell:ignore ANBI RABO RABONL unported */ expect(results.map(a => a.text).filter(util.uniqueFn()).sort()).deep.equals(['ANBI', 'RABO', 'RABONL', 'unported']); }); }); }); });
Increase the timeout for Dutch
Increase the timeout for Dutch This is to account for the time it takes to load the dictionary.
TypeScript
mit
Jason3S/cspell,Jason3S/cspell,Jason3S/cspell,Jason3S/cspell,Jason3S/cspell
--- +++ @@ -12,7 +12,8 @@ describe('Validate that Dutch text is correctly checked.', function() { it('Tests the default configuration', function() { - this.timeout(5000); + this.timeout(30000); + return sampleFile.then(text => { expect(text).to.not.be.empty; const ext = path.extname(sampleFilename);