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
6d567c93ceb391d2714e1d1750bfe38e4890b83a
game/hud/src/components/Watermark.tsx
game/hud/src/components/Watermark.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import styled from 'react-emotion'; const Watermark = styled('i')` width: 340px; height: 20px; line-height: 20px; position: fixed; left: 50%; top: 15px; transform: translateX(-50%); color: #FFF; font-size: 13px; font-family: 'Merriweather Sans', sans-serif; fotn-weight: bold; text-align: right; text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; -webkit-touch-callout: none; user-select: none; cursor: default; `; export interface WatermarkStyle { watermark: React.CSSProperties; } export default (props: { style?: Partial<WatermarkStyle>; }) => { return <Watermark>Engine/Tech Alpha - Do not stream or distribute.</Watermark>; };
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import styled from 'react-emotion'; const Watermark = styled('i')` width: 340px; height: 20px; line-height: 20px; position: fixed; left: 5px; top: 55px; color: #FFF; font-size: 13px; font-family: 'Merriweather Sans', sans-serif; font-weight: bold; text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; -webkit-touch-callout: none; user-select: none; cursor: default; z-index: 9999; `; export interface WatermarkStyle { watermark: React.CSSProperties; } export default (props: { style?: Partial<WatermarkStyle>; }) => { return <Watermark>Engine/Tech Alpha - Do not stream or distribute.</Watermark>; };
Move watermark above zone name widget and increase z-index.
Move watermark above zone name widget and increase z-index.
TypeScript
mpl-2.0
Mehuge/Camelot-Unchained,saddieeiddas/Camelot-Unchained,Mehuge/Camelot-Unchained,csegames/Camelot-Unchained,saddieeiddas/Camelot-Unchained,csegames/Camelot-Unchained,csegames/Camelot-Unchained,CUModSquad/Camelot-Unchained,CUModSquad/Camelot-Unchained,Mehuge/Camelot-Unchained,Ajackster/Camelot-Unchained,saddieeiddas/Camelot-Unchained,CUModSquad/Camelot-Unchained,Ajackster/Camelot-Unchained,Ajackster/Camelot-Unchained
--- +++ @@ -12,18 +12,17 @@ height: 20px; line-height: 20px; position: fixed; - left: 50%; - top: 15px; - transform: translateX(-50%); + left: 5px; + top: 55px; color: #FFF; font-size: 13px; font-family: 'Merriweather Sans', sans-serif; - fotn-weight: bold; - text-align: right; + font-weight: bold; text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; -webkit-touch-callout: none; user-select: none; cursor: default; + z-index: 9999; `; export interface WatermarkStyle {
24effdf252d7c865b34b841acd4f40276e9cc9e5
api/utils/cancellable_promise.ts
api/utils/cancellable_promise.ts
import { EventEmitter } from "events"; export class CancellablePromise<T> implements PromiseLike<T> { private static readonly CANCEL_EVENT = "cancel"; private readonly emitter = new EventEmitter(); private readonly promise: Promise<T>; private cancelled = false; constructor( method: ( resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void, onCancel?: (handleCancel: () => void) => void ) => void ) { this.promise = new Promise<T>((resolve, reject) => method(resolve, reject, handleCancel => { if (this.cancelled) { handleCancel(); } else { this.emitter.on(CancellablePromise.CANCEL_EVENT, handleCancel); } }) ); } public then<S>( onfulfilled?: (value: T) => S | PromiseLike<S>, onrejected?: (reason: any) => PromiseLike<never> ): Promise<S> { return this.promise.then(onfulfilled, onrejected); } public catch(onRejected?: (reason: any) => PromiseLike<never>): Promise<T> { return this.promise.catch(onRejected); } public cancel(): void { this.cancelled = true; this.emitter.emit(CancellablePromise.CANCEL_EVENT); } }
import { EventEmitter } from "events"; export class CancellablePromise<T> implements PromiseLike<T> { private static readonly CANCEL_EVENT = "cancel"; private readonly emitter = new EventEmitter(); private readonly promise: Promise<T>; private cancelled = false; constructor( method: ( resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void, onCancel?: (handleCancel: () => void) => void ) => void ) { this.promise = new Promise<T>((resolve, reject) => method(resolve, reject, handleCancel => { if (this.cancelled) { handleCancel(); } else { this.emitter.on(CancellablePromise.CANCEL_EVENT, handleCancel); } }) ); } public then<S>( onfulfilled?: (value: T) => S | PromiseLike<S>, onrejected?: (reason: any) => never | PromiseLike<never> ): Promise<S> { return this.promise.then(onfulfilled, onrejected); } public catch(onRejected?: (reason: any) => PromiseLike<never>): Promise<T> { return this.promise.catch(onRejected); } public cancel(): void { this.cancelled = true; this.emitter.emit(CancellablePromise.CANCEL_EVENT); } }
Fix missed compilation issue that's crept in somewhere somehow.
Fix missed compilation issue that's crept in somewhere somehow.
TypeScript
mit
dataform-co/dataform,dataform-co/dataform,dataform-co/dataform,dataform-co/dataform,dataform-co/dataform
--- +++ @@ -28,7 +28,7 @@ public then<S>( onfulfilled?: (value: T) => S | PromiseLike<S>, - onrejected?: (reason: any) => PromiseLike<never> + onrejected?: (reason: any) => never | PromiseLike<never> ): Promise<S> { return this.promise.then(onfulfilled, onrejected); }
7dbccd31f1d8595fd900374847d40542a6f39ae9
src/index.tsx
src/index.tsx
import React from "react" import Bugsnag from '@bugsnag/js' import BugsnagPluginReact from '@bugsnag/plugin-react' import ReactDOM from "react-dom" import "./index.scss" import App from "./App" import reportWebVitals from "./reportWebVitals" Bugsnag.start({ apiKey: 'a65916528275f084a1754a59797a36b3', plugins: [new BugsnagPluginReact()], redactedKeys: ['Authorization'], enabledReleaseStages: [ 'production', 'staging' ], onError: function (event) { event.request.url = "[REDACTED]" // Don't send access tokens } }) const ErrorBoundary = Bugsnag.getPlugin('react')!.createErrorBoundary(React) ReactDOM.render( <React.StrictMode> <ErrorBoundary> <App /> </ErrorBoundary> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
import React from "react" import Bugsnag from '@bugsnag/js' import BugsnagPluginReact from '@bugsnag/plugin-react' import ReactDOM from "react-dom" import "./index.scss" import App from "./App" import reportWebVitals from "./reportWebVitals" Bugsnag.start({ apiKey: 'a65916528275f084a1754a59797a36b3', plugins: [new BugsnagPluginReact()], redactedKeys: ['Authorization'], enabledReleaseStages: [ 'production', 'staging' ], onError: function (event) { event.request.url = "[REDACTED]" // Don't send access tokens if (event.originalError.isAxiosError) { event.groupingHash = event.originalError.message } } }) const ErrorBoundary = Bugsnag.getPlugin('react')!.createErrorBoundary(React) ReactDOM.render( <React.StrictMode> <ErrorBoundary> <App /> </ErrorBoundary> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
Improve error monitoring for Axios errors
Improve error monitoring for Axios errors
TypeScript
mit
watsonbox/exportify,watsonbox/exportify,watsonbox/exportify
--- +++ @@ -13,6 +13,10 @@ enabledReleaseStages: [ 'production', 'staging' ], onError: function (event) { event.request.url = "[REDACTED]" // Don't send access tokens + + if (event.originalError.isAxiosError) { + event.groupingHash = event.originalError.message + } } })
c03bb9a2cdf844efbf2c1874cac3ccf036b2f44c
src/create-http-client.ts
src/create-http-client.ts
import path from 'path'; import fs from 'fs'; import https from 'https'; import axios, { AxiosRequestConfig } from 'axios'; import qs from 'qs'; // @ts-ignore import cert from './cacert.pem'; // @ts-ignore import { version } from '../package.json'; interface MollieRequestConfig extends AxiosRequestConfig { apiKey?: string; } declare let window: any; /** * Create pre-configured httpClient instance * @private */ export default function createHttpClient(options: MollieRequestConfig = {}) { options.baseURL = 'https://api.mollie.com:443/v2/'; options.headers = Object.assign({}, options.headers, { Authorization: `Bearer ${options.apiKey}`, 'Accept-Encoding': 'gzip', 'Content-Type': 'application/json', 'User-Agent': `node.js/${process.version}`, 'X-Mollie-User-Agent': `mollie/${version}`, }); if (typeof window === 'undefined') { options.httpsAgent = new https.Agent({ cert: fs.readFileSync(path.resolve(__dirname, cert), 'utf8'), }); } options.paramsSerializer = options.paramsSerializer || qs.stringify; return axios.create(options); }
import fs from 'fs'; import https from 'https'; import axios, { AxiosRequestConfig } from 'axios'; import qs from 'qs'; // @ts-ignore import cert from './cacert.pem'; // @ts-ignore import { version } from '../package.json'; interface MollieRequestConfig extends AxiosRequestConfig { apiKey?: string; } declare let window: any; /** * Create pre-configured httpClient instance * @private */ export default function createHttpClient(options: MollieRequestConfig = {}) { options.baseURL = 'https://api.mollie.com:443/v2/'; options.headers = Object.assign({}, options.headers, { Authorization: `Bearer ${options.apiKey}`, 'Accept-Encoding': 'gzip', 'Content-Type': 'application/json', 'User-Agent': `node.js/${process.version}`, 'X-Mollie-User-Agent': `mollie/${version}`, }); if (typeof window === 'undefined') { options.httpsAgent = new https.Agent({ cert: fs.readFileSync(cert, 'utf8'), }); } options.paramsSerializer = options.paramsSerializer || qs.stringify; return axios.create(options); }
Use relative path for cert file
Use relative path for cert file
TypeScript
bsd-3-clause
mollie/mollie-api-node,mollie/mollie-api-node,mollie/mollie-api-node
--- +++ @@ -1,4 +1,3 @@ -import path from 'path'; import fs from 'fs'; import https from 'https'; import axios, { AxiosRequestConfig } from 'axios'; @@ -32,7 +31,7 @@ if (typeof window === 'undefined') { options.httpsAgent = new https.Agent({ - cert: fs.readFileSync(path.resolve(__dirname, cert), 'utf8'), + cert: fs.readFileSync(cert, 'utf8'), }); }
cfdae484e2d7e889873adfa1226fdb545c85a1d2
app/src/main-process/shell.ts
app/src/main-process/shell.ts
import * as Url from 'url' import { shell } from 'electron' /** * Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS. * * When opening a folder in Finder, the window will appear behind the application * window, which may confuse users. As a workaround, we will fallback to using * shell.openExternal for macOS until it can be fixed upstream. * * CAUTION: This method should never be used to open user-provided or derived * paths. It's sole use is to open _directories_ that we know to be safe, no * verification is performed to ensure that the provided path isn't actually * an executable. * * @param path directory to open */ export function UNSAFE_openDirectory(path: string) { if (__DARWIN__) { const directoryURL = Url.format({ pathname: path, protocol: 'file:', slashes: true, }) shell .openExternal(directoryURL) .catch(err => log.error(`Failed to open directory (${path})`, err)) } else { shell.openItem(path) } }
import * as Url from 'url' import * as Path from 'path' import { shell } from 'electron' /** * Wraps the inbuilt shell.openItem path to address a focus issue that affects macOS. * * When opening a folder in Finder, the window will appear behind the application * window, which may confuse users. As a workaround, we will fallback to using * shell.openExternal for macOS until it can be fixed upstream. * * CAUTION: This method should never be used to open user-provided or derived * paths. It's sole use is to open _directories_ that we know to be safe, no * verification is performed to ensure that the provided path isn't actually * an executable. * * @param path directory to open */ export function UNSAFE_openDirectory(path: string) { if (__DARWIN__) { const directoryURL = Url.format({ pathname: path, protocol: 'file:', slashes: true, }) shell .openExternal(directoryURL) .catch(err => log.error(`Failed to open directory (${path})`, err)) } else { // Add a trailing slash to the directory path. // // In Windows, if there's a file and a directory with the // same name (e.g `C:\MyFolder\foo` and `C:\MyFolder\foo.exe`), // when executing shell.openItem(`C:\MyFolder\foo`) then the EXE file // will get opened. // We can avoid this by adding a final backslash at the end of the path. const pathname = path[path.length - 1] !== Path.sep ? path + Path.sep : path shell.openItem(pathname) } }
Add backslash when trying to open folders in Windows
Add backslash when trying to open folders in Windows
TypeScript
mit
j-f1/forked-desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,say25/desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus,say25/desktop,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,kactus-io/kactus
--- +++ @@ -1,4 +1,5 @@ import * as Url from 'url' +import * as Path from 'path' import { shell } from 'electron' /** @@ -27,6 +28,15 @@ .openExternal(directoryURL) .catch(err => log.error(`Failed to open directory (${path})`, err)) } else { - shell.openItem(path) + // Add a trailing slash to the directory path. + // + // In Windows, if there's a file and a directory with the + // same name (e.g `C:\MyFolder\foo` and `C:\MyFolder\foo.exe`), + // when executing shell.openItem(`C:\MyFolder\foo`) then the EXE file + // will get opened. + // We can avoid this by adding a final backslash at the end of the path. + const pathname = path[path.length - 1] !== Path.sep ? path + Path.sep : path + + shell.openItem(pathname) } }
384c54c570e37449bdfb3f81422163cd12fc1f36
src/dependument.ts
src/dependument.ts
/// <reference path="../typings/node/node.d.ts" /> import * as fs from 'fs'; export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options) { throw new Error("No options provided"); } if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } this.source = options.source; this.output = options.output; } public process() { this.readDependencies((deps: string[][]) => { //this.writeOutput(deps); }); } private readDependencies(success: (info: string[][]) => void) { fs.readFile(this.source, (err, data: Buffer) => { if (err) { throw err; } }); } private writeOutput(output: string) { fs.writeFile(this.output, output, (err) => { if (err) throw err; console.log(`Output written to ${this.output}`); }); } }
/// <reference path="../typings/node/node.d.ts" /> import * as fs from 'fs'; export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options) { throw new Error("No options provided"); } if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } this.source = options.source; this.output = options.output; } public process() { this.readDependencies((deps: string[][]) => { this.writeDependencies(deps); }); } private readDependencies(success: (info: string[][]) => void) { fs.readFile(this.source, (err, data: Buffer) => { if (err) { throw err; } let json = JSON.stringify(data.toString()); let deps: string[][] = []; deps["dependencies"] = json["dependencies"]; deps["devDependencies"] = json["devDependencies"]; success(deps); }); } private writeDependencies(deps: string[][]) { let output = `${deps["dependencies"]}\n${deps["devDependencies"]}`; fs.writeFile(this.output, output, (err) => { if (err) throw err; console.log(`Output written to ${this.output}`); }); } }
Select dependencies and dev dependencies
Select dependencies and dev dependencies
TypeScript
unlicense
Jameskmonger/dependument,dependument/dependument,dependument/dependument,Jameskmonger/dependument
--- +++ @@ -25,7 +25,7 @@ public process() { this.readDependencies((deps: string[][]) => { - //this.writeOutput(deps); + this.writeDependencies(deps); }); } @@ -35,10 +35,20 @@ throw err; } + let json = JSON.stringify(data.toString()); + + let deps: string[][] = []; + + deps["dependencies"] = json["dependencies"]; + deps["devDependencies"] = json["devDependencies"]; + + success(deps); }); } - private writeOutput(output: string) { + private writeDependencies(deps: string[][]) { + let output = `${deps["dependencies"]}\n${deps["devDependencies"]}`; + fs.writeFile(this.output, output, (err) => { if (err) throw err; console.log(`Output written to ${this.output}`);
1ab8e527f32ed379a337fa9acbdb5daf0d6a3730
src/utils/index.ts
src/utils/index.ts
import { Grid, Row, Column, Diagonal } from '../definitions'; export function getRows(grid: Grid): Row[] { const length = Math.sqrt(grid.length); const copy = grid.concat([]); return getArray(length).map(() => copy.splice(0, length)); } export function getColumns(grid: Grid): Column[] { return getRows(transpose(grid)); } export function getDiagonals(grid: Grid): Diagonal[] { // TODO: Make it work return []; } function getArray(length: number) { return Array.apply(null, { length }).map(Number.call, Number); } export function transpose<T>(grid: Array<T>): Array<T> { const size = Math.sqrt(grid.length); var i, j; var transposed = grid.filter(() => false); for (j = 0; j < size; ++j) { for (i = 0; i < size; ++i) { transposed.push(grid[j + (i * size)]); } } return transposed; }
import { Grid, Row, Column, Diagonal } from '../definitions'; export function getRows(grid: Grid): Row[] { const length = Math.sqrt(grid.length); const copy = grid.concat([]); return getArray(length).map(() => copy.splice(0, length)); } export function getColumns(grid: Grid): Column[] { return getRows(transpose(grid)); } export function getDiagonals(grid: Grid): Diagonal[] { // TODO: Make it work return []; } function getArray(length: number) { return Array.apply(null, { length }).map(Number.call, Number); } export function transpose<T>(grid: Array<T>): Array<T> { const size = Math.sqrt(grid.length); var transposed = grid.filter(() => false); for (let j = 0; j < size; ++j) { for (let i = 0; i < size; ++i) { transposed.push(grid[j + (i * size)]); } } return transposed; }
Use let instead of var
Use let instead of var
TypeScript
mit
artfuldev/tictactoe-ai,artfuldev/tictactoe-ai
--- +++ @@ -21,10 +21,9 @@ export function transpose<T>(grid: Array<T>): Array<T> { const size = Math.sqrt(grid.length); - var i, j; var transposed = grid.filter(() => false); - for (j = 0; j < size; ++j) { - for (i = 0; i < size; ++i) { + for (let j = 0; j < size; ++j) { + for (let i = 0; i < size; ++i) { transposed.push(grid[j + (i * size)]); } }
a78163b7be7b1bd9155d4cd466d6e651b999eab0
src/app/service/diff-mode.service.ts
src/app/service/diff-mode.service.ts
import {Injectable} from '@angular/core'; @Injectable() export class DiffModeService { timeDiff(data: any[]) { let result = ''; const dateOrigin = new Date(data[0].timestamp); data.forEach(log => { log.timestamp = ((new Date(log.timestamp)).valueOf() - (dateOrigin).valueOf()).toString(); result += (log.timestamp + ' [' + log.thread_name + '] ' + log.level + ' ' + log.logger_name + '' + ' ' + log.formatted_message) + '\n' }); return result; } noTimestampDiff() { } }
import {Injectable} from '@angular/core'; @Injectable() export class DiffModeService { timeDiff(data: any[]) { let result = ''; const dateOrigin = new Date(data[0].timestamp); data.forEach(log => { log.timestamp = ((new Date(log.timestamp)).valueOf() - (dateOrigin).valueOf()).toString(); result += (log.timestamp + ' [' + log.thread_name + '] ' + log.level + ' ' + log.logger_name + '' + ' ' + log.formatted_message) + '\n' }); return result; } noTimestampDiff(data: any[]) { let result = ''; data.forEach(log => { log.timestamp = ''; result += (log.timestamp + ' [' + log.thread_name + '] ' + log.level + ' ' + log.logger_name + '' + ' ' + log.formatted_message) + '\n' }); return result; } }
Update No timestamp diff method.
Update No timestamp diff method.
TypeScript
apache-2.0
cvazquezlos/LOGANALYZER,cvazquezlos/LOGANALYZER,cvazquezlos/LOGANALYZER,cvazquezlos/LOGANALYZER
--- +++ @@ -14,8 +14,14 @@ return result; } - noTimestampDiff() { - + noTimestampDiff(data: any[]) { + let result = ''; + data.forEach(log => { + log.timestamp = ''; + result += (log.timestamp + ' [' + log.thread_name + '] ' + log.level + ' ' + log.logger_name + '' + + ' ' + log.formatted_message) + '\n' + }); + return result; } }
db02004ac47920d28625d6907f550525c1406e5f
dev/YouTube/youtube-player.component.ts
dev/YouTube/youtube-player.component.ts
/// <reference path="../../typings/globals/youtube/index.d.ts" /> import {Component, OnInit} from '@angular/core'; import { window } from '@angular/platform-browser/src/facade/browser'; @Component({ selector: 'youtube-player', template: ` <h1> the youtube player ! </h1> <div id="player"></div> ` }) export class YouTubePlayerComponent implements OnInit { private player: YT.Player; ngOnInit() { this.setupPlayer(); } setupPlayer() { window['onYouTubeIframeAPIReady'] = () => { this.createPlayer(); } if (window.YT && window.YT.Player) { this.createPlayer(); } } createPlayer() { console.log("Create player !"); this.player = new window.YT.Player("player", { height: '390', width: '640', videoId: 'M7lc1UVf-VE' }); } }
/// <reference path="../../typings/globals/youtube/index.d.ts" /> import {Component, OnInit} from '@angular/core'; import { window } from '@angular/platform-browser/src/facade/browser'; @Component({ selector: 'youtube-player', template: ` <h1> the youtube player ! </h1> <div id="player" style="pointer-events: none"></div> ` }) export class YouTubePlayerComponent implements OnInit { private player: YT.Player; ngOnInit() { this.setupPlayer(); } setupPlayer() { window['onYouTubeIframeAPIReady'] = () => { this.createPlayer(); } if (window.YT && window.YT.Player) { this.createPlayer(); } } createPlayer() { console.log("Create player !"); this.player = new window.YT.Player("player", { height: '390', width: '640', videoId: '' }); } }
Disable event on youtube video
Disable event on youtube video
TypeScript
mit
lb-v/minstrel-web,lb-v/minstrel-web,lb-v/minstrel-web
--- +++ @@ -6,7 +6,7 @@ selector: 'youtube-player', template: ` <h1> the youtube player ! </h1> - <div id="player"></div> + <div id="player" style="pointer-events: none"></div> ` }) @@ -31,7 +31,7 @@ this.player = new window.YT.Player("player", { height: '390', width: '640', - videoId: 'M7lc1UVf-VE' + videoId: '' }); } }
6ca40a013c547d85c285df97d15f7fdbca3c50cf
src/app/core/datastore/index/result-sets.ts
src/app/core/datastore/index/result-sets.ts
import {intersection, union, subtract, flow, cond, isNot, empty} from 'tsfun'; import {Resource} from 'idai-components-2'; export interface ResultSets { addSets: Array<Array<Resource.Id>>, subtractSets: Array<Array<Resource.Id>>, } /** * @author Daniel de Oliveira * @author Thomas Kleinke */ export module ResultSets { export function make(): ResultSets { return { addSets: [], subtractSets: [] } ; } export function isEmpty(resultSets: ResultSets): boolean { return resultSets.addSets.length === 0 && resultSets.subtractSets.length === 0; } export function containsOnlyEmptyAddSets(resultSets: ResultSets): boolean { if (resultSets.addSets.length === 0) return false; return !resultSets.addSets .some(addSet => addSet.length > 0); } export function combine(resultSets: ResultSets, ids: Array<Resource.Id>, subtract: undefined|true = undefined): void { (!subtract ? resultSets.addSets : resultSets.subtractSets) .push(ids); } export function collapse(resultSets: ResultSets): Array<Resource.Id> { return flow( intersection(resultSets.addSets), cond( isNot(empty)(resultSets.subtractSets), subtract(union(resultSets.subtractSets)))); } export function unify(resultSets: ResultSets): Array<Resource.Id> { // TODO get rid of this function return union(resultSets.addSets); } }
import {intersection, union, subtract, flow, cond, isNot, empty} from 'tsfun'; export interface ResultSets { addSets: Array<Array<string>>, subtractSets: Array<Array<string>>, } /** * @author Daniel de Oliveira * @author Thomas Kleinke */ export module ResultSets { export function make(): ResultSets { return { addSets: [], subtractSets: [] } ; } export function isEmpty(resultSets: ResultSets): boolean { return resultSets.addSets.length === 0 && resultSets.subtractSets.length === 0; } export function containsOnlyEmptyAddSets(resultSets: ResultSets): boolean { if (resultSets.addSets.length === 0) return false; return !resultSets.addSets .some(addSet => addSet.length > 0); } export function combine(resultSets: ResultSets, ids: Array<string>, subtract: undefined|true = undefined): void { (!subtract ? resultSets.addSets : resultSets.subtractSets) .push(ids); } export function collapse(resultSets: ResultSets): Array<string> { return flow( intersection(resultSets.addSets), cond( isNot(empty)(resultSets.subtractSets), subtract(union(resultSets.subtractSets)))); } export function unify(resultSets: ResultSets): Array<string> { return union(resultSets.addSets); } }
Generalize by typing simply to string instead of Resource.Id; remove todo
Generalize by typing simply to string instead of Resource.Id; remove todo
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -1,11 +1,10 @@ import {intersection, union, subtract, flow, cond, isNot, empty} from 'tsfun'; -import {Resource} from 'idai-components-2'; export interface ResultSets { - addSets: Array<Array<Resource.Id>>, - subtractSets: Array<Array<Resource.Id>>, + addSets: Array<Array<string>>, + subtractSets: Array<Array<string>>, } @@ -37,7 +36,7 @@ export function combine(resultSets: ResultSets, - ids: Array<Resource.Id>, + ids: Array<string>, subtract: undefined|true = undefined): void { (!subtract @@ -47,7 +46,7 @@ } - export function collapse(resultSets: ResultSets): Array<Resource.Id> { + export function collapse(resultSets: ResultSets): Array<string> { return flow( intersection(resultSets.addSets), @@ -57,7 +56,7 @@ } - export function unify(resultSets: ResultSets): Array<Resource.Id> { // TODO get rid of this function + export function unify(resultSets: ResultSets): Array<string> { return union(resultSets.addSets); }
b83e84539cbec4263760edf92eecb44c703b6749
source/boreholes/boreholesmanager.ts
source/boreholes/boreholesmanager.ts
import { BoreholesLoader } from "./boreholesloader"; declare var proj4; export class BoreholesManager { boreholes; lines; constructor(public options: any) { } parse() { this.boreholes = new BoreholesLoader(this.options); return this.boreholes.load().then(data => { if (!data || !data.length) { return null; } let lineMaterial = new THREE.LineBasicMaterial({color: 0xffaaaa, linewidth: 1}); let lineGeom = new THREE.Geometry(); let bbox = this.options.bbox; data.filter(hole => hole.lon > bbox[0] && hole.lon <= bbox[2] && hole.lat > bbox[1] && hole.lat <= bbox[3]) .forEach(hole => { let coord = proj4("EPSG:4326", "EPSG:3857", [hole.lon, hole.lat]); let length = hole.length != null ? hole.length : 10; let elevation = hole.elevation < -90000 ? 0 : hole.elevation; lineGeom.vertices.push(new THREE.Vector3( coord[0], coord[1], elevation )); lineGeom.vertices.push(new THREE.Vector3( coord[0], coord[1], elevation - length )); }); lineGeom.computeBoundingSphere(); return this.lines = new THREE.LineSegments( lineGeom, lineMaterial ); }); } destroy() { } }
import { BoreholesLoader } from "./boreholesloader"; declare var proj4; export class BoreholesManager { boreholes; lines; constructor(public options: any) { } parse() { this.boreholes = new BoreholesLoader(this.options); return this.boreholes.load().then(data => { if (!data || !data.length) { return null; } let lineMaterial = new THREE.LineBasicMaterial({color: 0xffaaaa, linewidth: 1}); let lineGeom = new THREE.Geometry(); let bbox = this.options.bbox; data.filter(hole => hole.lon > bbox[0] && hole.lon <= bbox[2] && hole.lat > bbox[1] && hole.lat <= bbox[3]) .forEach(hole => { let coord = proj4("EPSG:4283", "EPSG:3857", [hole.lon, hole.lat]); let length = hole.length != null ? hole.length : 10; let elevation = hole.elevation < -90000 ? 0 : hole.elevation; lineGeom.vertices.push(new THREE.Vector3( coord[0], coord[1], elevation )); lineGeom.vertices.push(new THREE.Vector3( coord[0], coord[1], elevation - length )); }); lineGeom.computeBoundingSphere(); return this.lines = new THREE.LineSegments( lineGeom, lineMaterial ); }); } destroy() { } }
Use EPSG:4283 to EPSG:3857 reporject on boreholes
Use EPSG:4283 to EPSG:3857 reporject on boreholes
TypeScript
apache-2.0
Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d
--- +++ @@ -22,7 +22,7 @@ let bbox = this.options.bbox; data.filter(hole => hole.lon > bbox[0] && hole.lon <= bbox[2] && hole.lat > bbox[1] && hole.lat <= bbox[3]) .forEach(hole => { - let coord = proj4("EPSG:4326", "EPSG:3857", [hole.lon, hole.lat]); + let coord = proj4("EPSG:4283", "EPSG:3857", [hole.lon, hole.lat]); let length = hole.length != null ? hole.length : 10; let elevation = hole.elevation < -90000 ? 0 : hole.elevation;
2cbabed7f3682e81e9b650f259525dda06745f95
pages/index.tsx
pages/index.tsx
import { Text, Title } from "components" import classnames from "classnames" import Head from "next/head" export default function Home() { return ( <> <Head> <title>ReiffLabs</title> </Head> <main className={classnames("grid", "text-center")} style={{ placeItems: "center", height: "100vh" }} > <div> <Title>Big things are coming soon</Title> <Text> <b>ReiffLabs</b> technology company. </Text> </div> </main> </> ) }
import { Text, Title } from "components" import classnames from "classnames" import Head from "next/head" export default function Home() { return ( <> <Head> <title>ReiffLabs</title> </Head> <main className={classnames("grid", "text-center")} style={{ placeItems: "center", height: "100vh" }} > <div> <Title>Big things are coming soon</Title> <Text> <b>ReiffLabs</b> a technology company. </Text> </div> </main> </> ) }
Update text on home page
Update text on home page
TypeScript
mit
reiff12/reifflabs.com,reiff12/reifflabs.com,reiff12/reifflabs.com
--- +++ @@ -15,7 +15,7 @@ <div> <Title>Big things are coming soon</Title> <Text> - <b>ReiffLabs</b> technology company. + <b>ReiffLabs</b> a technology company. </Text> </div> </main>
ec7b96e7503e75e42ecf5287fa4c11b588bef799
src/components/basics/gif-marker.tsx
src/components/basics/gif-marker.tsx
import * as React from "react"; import styled from "../styles"; const GifMarkerSpan = styled.span` position: absolute; top: 5px; right: 5px; background: #333333; color: rgba(253, 253, 253, 0.74); font-size: 12px; padding: 2px 4px; border-radius: 2px; font-weight: bold; opacity: .8; `; class GifMarker extends React.PureComponent { render() { return <GifMarkerSpan>GIF</GifMarkerSpan>; } } export default GifMarker;
import * as React from "react"; import styled from "../styles"; const GifMarkerSpan = styled.span` position: absolute; top: 5px; right: 5px; background: #333333; color: rgba(253, 253, 253, 0.74); font-size: 12px; padding: 4px; border-radius: 2px; font-weight: bold; opacity: .8; z-index: 2; `; class GifMarker extends React.PureComponent { render() { return <GifMarkerSpan>GIF</GifMarkerSpan>; } } export default GifMarker;
Make gif marker visible again
Make gif marker visible again
TypeScript
mit
itchio/itch,leafo/itchio-app,itchio/itch,itchio/itch,itchio/itchio-app,leafo/itchio-app,leafo/itchio-app,itchio/itchio-app,itchio/itch,itchio/itchio-app,itchio/itch,itchio/itch
--- +++ @@ -8,10 +8,11 @@ background: #333333; color: rgba(253, 253, 253, 0.74); font-size: 12px; - padding: 2px 4px; + padding: 4px; border-radius: 2px; font-weight: bold; opacity: .8; + z-index: 2; `; class GifMarker extends React.PureComponent {
bc632af2fe1472bb75abdd29f216f3ec3af33941
src/auth/callbacks/AuthLoginCompleted.tsx
src/auth/callbacks/AuthLoginCompleted.tsx
import { useCurrentStateAndParams, useRouter } from '@uirouter/react'; import * as React from 'react'; import { LoadingSpinner } from '@waldur/core/LoadingSpinner'; import { translate } from '@waldur/i18n'; import { AuthService } from '../AuthService'; export const AuthLoginCompleted = () => { const router = useRouter(); const { params } = useCurrentStateAndParams(); React.useEffect(() => { AuthService.loginSuccess({ data: { token: params.token, method: params.method }, }); router.stateService.go('profile.details'); }, [router.stateService, params.token, params.method]); return ( <div className="middle-box text-center"> <LoadingSpinner /> <h3>{translate('Logging user in')}</h3> </div> ); };
import { useCurrentStateAndParams, useRouter } from '@uirouter/react'; import * as React from 'react'; import { LoadingSpinner } from '@waldur/core/LoadingSpinner'; import { translate } from '@waldur/i18n'; import { UsersService } from '@waldur/user/UsersService'; import { AuthService } from '../AuthService'; export const AuthLoginCompleted = () => { const router = useRouter(); const { params } = useCurrentStateAndParams(); const completeAuth = React.useCallback( async (token, method) => { AuthService.setAuthHeader(token); const user = await UsersService.getCurrentUser(); AuthService.loginSuccess({ data: { ...user, method }, }); router.stateService.go('profile.details'); }, [router.stateService], ); React.useEffect(() => { completeAuth(params.token, params.method); }, [completeAuth, params]); return ( <div className="middle-box text-center"> <LoadingSpinner /> <h3>{translate('Logging user in')}</h3> </div> ); };
Fix auth login completed callback view.
Fix auth login completed callback view.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -3,18 +3,27 @@ import { LoadingSpinner } from '@waldur/core/LoadingSpinner'; import { translate } from '@waldur/i18n'; +import { UsersService } from '@waldur/user/UsersService'; import { AuthService } from '../AuthService'; export const AuthLoginCompleted = () => { const router = useRouter(); const { params } = useCurrentStateAndParams(); + const completeAuth = React.useCallback( + async (token, method) => { + AuthService.setAuthHeader(token); + const user = await UsersService.getCurrentUser(); + AuthService.loginSuccess({ + data: { ...user, method }, + }); + router.stateService.go('profile.details'); + }, + [router.stateService], + ); React.useEffect(() => { - AuthService.loginSuccess({ - data: { token: params.token, method: params.method }, - }); - router.stateService.go('profile.details'); - }, [router.stateService, params.token, params.method]); + completeAuth(params.token, params.method); + }, [completeAuth, params]); return ( <div className="middle-box text-center">
bda7aa3aef5ff30ce174c436983aad4747170abe
src/app/kata-player/kata-player.module.ts
src/app/kata-player/kata-player.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule } from './../material/material.module'; import { CoreModule } from './../core'; import { ChronometerComponent } from './chronometer/chronometer.component'; import { KataEditorComponent } from './kata-editor/kata-editor/kata-editor.component'; import { KataPlayerComponent } from './kata-player.component'; // Third party module import { CodemirrorModule } from 'ng2-codemirror'; @NgModule({ imports: [ CommonModule, CodemirrorModule, CoreModule, FormsModule, HttpModule, MaterialModule ], declarations: [ ChronometerComponent, KataEditorComponent, KataPlayerComponent ], exports: [ ChronometerComponent, KataEditorComponent, KataPlayerComponent ], entryComponents: [] }) export class KataPlayerModule { static forRoot(): ModuleWithProviders { return { ngModule: KataPlayerModule, providers: [] } } }
import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { MaterialModule } from './../material/material.module'; import { CoreModule } from './../core'; import { ChronometerComponent } from './chronometer/chronometer.component'; import { KataEditorComponent } from './kata-editor/kata-editor/kata-editor.component'; import { KataPlayerComponent } from './kata-player.component'; // Third party module import { CodemirrorModule } from 'ng2-codemirror'; import 'codemirror/mode/cobol/cobol'; import 'codemirror/mode/mumps/mumps'; @NgModule({ imports: [ CommonModule, CodemirrorModule, CoreModule, FormsModule, HttpModule, MaterialModule ], declarations: [ ChronometerComponent, KataEditorComponent, KataPlayerComponent ], exports: [ ChronometerComponent, KataEditorComponent, KataPlayerComponent ], entryComponents: [] }) export class KataPlayerModule { static forRoot(): ModuleWithProviders { return { ngModule: KataPlayerModule, providers: [] } } }
Add Cobol & MUMPS language modes
Add Cobol & MUMPS language modes
TypeScript
mit
semagarcia/javascript-kata-player,semagarcia/javascript-kata-player,semagarcia/javascript-kata-player
--- +++ @@ -11,6 +11,8 @@ // Third party module import { CodemirrorModule } from 'ng2-codemirror'; +import 'codemirror/mode/cobol/cobol'; +import 'codemirror/mode/mumps/mumps'; @NgModule({ imports: [
c93de0ec628c650d37edbcea606cb866ad6ac12d
projects/droplit-plugin-local-ts-example/src/DroplitLocalPluginExample.ts
projects/droplit-plugin-local-ts-example/src/DroplitLocalPluginExample.ts
import * as droplit from 'droplit-plugin'; export class DroplitLocalPluginExample extends droplit.DroplitLocalPlugin { services: any; motd: any = 'My first local Droplit plugin'; constructor() { super(); this.services = { Host: { get_motd: this.getMotd, set_motd: this.setMotd, announce: this.announceMotd } }; } // Get: Get MOTD value public getMotd(localId: string, cb: (value: any) => any) { cb(this.motd); return true; } // Set: Set MOTD value public setMotd(localId: any, value: any) { this.motd = value; const propChanges: any = { localId, member: 'service', service: 'Host', value: this.motd }; this.onPropertiesChanged([propChanges]); return true; } // Method: Annnounce MOTD across the hub public announceMotd(localId: any) { console.log(this.motd); return true; } }
import * as droplit from 'droplit-plugin'; export class DroplitLocalPluginExample extends droplit.DroplitLocalPlugin { services: any; motd: any = 'My first local Droplit plugin'; constructor() { super(); this.services = { Host: { get_motd: this.getMotd, set_motd: this.setMotd, announce: this.announceMotd } }; } // Get: Get MOTD value public getMotd(localId: string, cb: (value: any) => any) { cb(this.motd); return true; } // Set: Set MOTD value public setMotd(localId: any, value: any, index: string) { this.motd = value; const propChanges: droplit.DeviceServiceMember = { localId, member: 'service', service: 'Host', index: index, value: this.motd }; this.onPropertiesChanged([propChanges]); return true; } // Method: Annnounce MOTD across the hub public announceMotd(localId: any) { console.log(this.motd); return true; } }
Revert proChanges to droplit.DeviceServiceMember type
Revert proChanges to droplit.DeviceServiceMember type
TypeScript
isc
droplit/droplit.io-edge,droplit/droplit.io-edge,droplit/droplit.io-edge
--- +++ @@ -23,12 +23,13 @@ } // Set: Set MOTD value - public setMotd(localId: any, value: any) { + public setMotd(localId: any, value: any, index: string) { this.motd = value; - const propChanges: any = { + const propChanges: droplit.DeviceServiceMember = { localId, member: 'service', service: 'Host', + index: index, value: this.motd }; this.onPropertiesChanged([propChanges]);
4b903ca90e878164bced13eddb6e6729dd935746
app/src/component/Screenshots.tsx
app/src/component/Screenshots.tsx
import * as React from "react"; import Slider from "react-slick"; import "slick-carousel/slick/slick-theme.css"; import "slick-carousel/slick/slick.css"; import "./style/Screenshots.css"; const images: string[] = [ require("../images/screenshots/tasks.png"), require("../images/screenshots/articles.png"), require("../images/screenshots/videos.png"), require("../images/screenshots/books.png"), ]; export default class extends React.Component { public render() { return ( <div className="Screenshots-container"> <div className="Screenshots-title">Screenshots</div> <Slider dots={true} adaptiveHeight={true} arrows={false} autoplay={true}> {images.map((path) => // Image component is not available here somehow. <a key={path} href={path} target="_blank"> <img className="Screenshots-image" src={path} /> </a>)} </Slider> </div> ); } }
import * as React from "react"; import { connect } from "react-redux"; import Slider from "react-slick"; import "slick-carousel/slick/slick-theme.css"; import "slick-carousel/slick/slick.css"; import "./style/Screenshots.css"; const images: string[] = [ require("../images/screenshots/tasks.png"), require("../images/screenshots/articles.png"), require("../images/screenshots/videos.png"), require("../images/screenshots/books.png"), ]; const mobileImages: string[] = [ require("../images/screenshots/mobile_tasks.png"), require("../images/screenshots/mobile_menu.png"), require("../images/screenshots/mobile_articles.png"), require("../images/screenshots/mobile_trending.png"), ]; interface IProps { isSmallWindow: boolean; } class Screenshots extends React.Component<IProps> { public render() { const { isSmallWindow } = this.props; return ( <div className="Screenshots-container"> <div className="Screenshots-title">Screenshots</div> <Slider dots={true} adaptiveHeight={true} arrows={false} autoplay={true}> {(isSmallWindow ? mobileImages : images).map((path) => // Image component is not available here somehow. <a key={path} href={path} target="_blank"> <img className="Screenshots-image" src={path} /> </a>)} </Slider> </div> ); } } export default connect(({ environment }) => environment)(Screenshots);
Use mobile screenshots on small devices
Use mobile screenshots on small devices
TypeScript
mit
raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d
--- +++ @@ -1,4 +1,5 @@ import * as React from "react"; +import { connect } from "react-redux"; import Slider from "react-slick"; import "slick-carousel/slick/slick-theme.css"; import "slick-carousel/slick/slick.css"; @@ -12,13 +13,26 @@ require("../images/screenshots/books.png"), ]; -export default class extends React.Component { +const mobileImages: string[] = [ + require("../images/screenshots/mobile_tasks.png"), + require("../images/screenshots/mobile_menu.png"), + require("../images/screenshots/mobile_articles.png"), + require("../images/screenshots/mobile_trending.png"), +]; + +interface IProps { + isSmallWindow: boolean; +} + +class Screenshots extends React.Component<IProps> { public render() { + const { isSmallWindow } = this.props; + return ( <div className="Screenshots-container"> <div className="Screenshots-title">Screenshots</div> <Slider dots={true} adaptiveHeight={true} arrows={false} autoplay={true}> - {images.map((path) => + {(isSmallWindow ? mobileImages : images).map((path) => // Image component is not available here somehow. <a key={path} href={path} target="_blank"> <img className="Screenshots-image" src={path} /> @@ -28,3 +42,5 @@ ); } } + +export default connect(({ environment }) => environment)(Screenshots);
df3a0e7670d601f81c6a4020cc4d7fb3cf4eee13
skills/streamcheck.ts
skills/streamcheck.ts
import inspect from "logspect"; import { Twitch } from "../modules/api"; import * as Db from "../modules/database"; import * as Constants from "../modules/constants"; export default async function configure(alexa) { alexa.intent("summaryIntent", {}, function (request, response) { (async function () { // The accessToken is the CouchDB doc's id, use it to grab the user's twitch token. const accessToken = request.sessionDetails.accessToken; const user = await Db.TwitchAuthDb.get(accessToken); // Refresh the API with the user's access token const api = new Twitch(Constants.TWITCH_CLIENT_ID, Constants.TWITCH_CLIENT_SECRET, user.twitch_token); try { const streams = await api.listFollowerStreams({}); const responses: string[] = []; if (streams._total === 0) { responses.push(`None of the channels you follow are streaming right now.`); } else { if (streams._total > 1) { responses.push(`${streams._total} streamers you follow are streaming right now.`); } streams.streams.forEach(stream => { responses.push(`${stream.channel.display_name} is streaming ${stream.channel.status}`); }) } response.say(responses.join(". ")); } catch (_e) { inspect("Error retrieving followed streams", _e); response.say(`There was an error retrieving your followed streams. Sorry about that.`); } response.send(); } ()); // alexa-app package requires async functions to return false. return false; }); }
import inspect from "logspect"; import { Twitch } from "../modules/api"; import * as Db from "../modules/database"; import * as Constants from "../modules/constants"; export default async function configure(alexa) { alexa.intent("summaryIntent", {}, function (request, response) { (async function () { // The accessToken is the CouchDB doc's id, use it to grab the user's twitch token. const accessToken = request.sessionDetails.accessToken; const user = await Db.TwitchAuthDb.get(accessToken); // Refresh the API with the user's access token const api = new Twitch(Constants.TWITCH_CLIENT_ID, Constants.TWITCH_CLIENT_SECRET, user.twitch_token); try { const streams = await api.listFollowerStreams({}); const responses: string[] = []; if (streams._total === 0) { responses.push(`None of the channels you follow are streaming right now.`); } else { if (streams._total > 1) { responses.push(`${streams._total} streamers you follow are streaming right now`); } streams.streams.forEach(stream => { responses.push(`${stream.channel.display_name} is streaming ${stream.channel.status}`); }) } response.say(responses.join(". ")); } catch (_e) { inspect("Error retrieving followed streams", _e); response.say(`There was an error retrieving your followed streams. Sorry about that.`); } response.send(); } ()); // alexa-app package requires async functions to return false. return false; }); }
Remove extra periods when there are multiple streamers
Remove extra periods when there are multiple streamers
TypeScript
mit
nozzlegear/alexa-skills
--- +++ @@ -21,7 +21,7 @@ responses.push(`None of the channels you follow are streaming right now.`); } else { if (streams._total > 1) { - responses.push(`${streams._total} streamers you follow are streaming right now.`); + responses.push(`${streams._total} streamers you follow are streaming right now`); } streams.streams.forEach(stream => {
0e54de7c8b9b26c32126441d3f42adf7d6f7a1f7
src/lib/constants.ts
src/lib/constants.ts
/** * Delay time before close autocomplete. * * (This prevent autocomplete DOM get detroyed before access data.) */ export const AUTOCOMPLETE_CLOSE_DELAY = 250; /** * Allowed attributes that can be passed to internal input. */ export const ALLOWED_ATTRS = [ 'autofocus', 'disabled', 'id', 'inputmode', 'list', 'maxlength', 'minlength', 'name', 'pattern', 'placeholder', 'readonly', 'required', 'required', 'size', 'spellcheck', 'tabindex', 'title' ];
/** * Delay time before close autocomplete. * * (This prevent autocomplete DOM get detroyed before access data.) */ export const AUTOCOMPLETE_CLOSE_DELAY = 250; /** * Allowed attributes that can be passed to internal input. */ export const ALLOWED_ATTRS = [ 'autofocus', 'disabled', 'form', 'id', 'inputmode', 'list', 'maxlength', 'minlength', 'name', 'pattern', 'placeholder', 'readonly', 'required', 'required', 'size', 'spellcheck', 'tabindex', 'title' ];
Add `form` attribute to allowed list
:wrench: Add `form` attribute to allowed list
TypeScript
mit
gluons/vue-thailand-address
--- +++ @@ -11,6 +11,7 @@ export const ALLOWED_ATTRS = [ 'autofocus', 'disabled', + 'form', 'id', 'inputmode', 'list',
16efa68d06938acdddc316b7241a95a4a197cb2a
src/app/core/auth/auth-guard.service.spec.ts
src/app/core/auth/auth-guard.service.spec.ts
import { TestBed } from '@angular/core/testing'; import { AppState } from '@app/core'; import { Store, StoreModule } from '@ngrx/store'; import { MockStore, provideMockStore } from '../../../testing/utils'; import { AuthGuardService } from './auth-guard.service'; import { AuthState } from './auth.models'; describe('AuthGuardService', () => { let authGuardService: AuthGuardService; let store: MockStore<AppState>; const authState: AuthState = { isAuthenticated: true }; const state = createState(authState); beforeEach(() => { TestBed.configureTestingModule({ imports: [StoreModule.forRoot({})], providers: [AuthGuardService, provideMockStore()] }); authGuardService = TestBed.get(AuthGuardService); store = TestBed.get(Store); store.setState(state); }); it('should be created', () => { expect(authGuardService).toBeTruthy(); }); it('should return isAuthenticated from authState', () => { authGuardService.canActivate().subscribe(canActivate => { expect(canActivate).toBe(state.auth.isAuthenticated); }); }); }); function createState(authState: AuthState) { return { auth: authState }; }
import { TestBed } from '@angular/core/testing'; import { AppState } from '@app/core'; import { Store, StoreModule } from '@ngrx/store'; import { MockStore, provideMockStore } from '@testing/utils'; import { AuthGuardService } from './auth-guard.service'; import { AuthState } from './auth.models'; describe('AuthGuardService', () => { let authGuardService: AuthGuardService; let store: MockStore<AppState>; const authState: AuthState = { isAuthenticated: true }; const state = createState(authState); beforeEach(() => { TestBed.configureTestingModule({ imports: [StoreModule.forRoot({})], providers: [AuthGuardService, provideMockStore()] }); authGuardService = TestBed.get(AuthGuardService); store = TestBed.get(Store); store.setState(state); }); it('should be created', () => { expect(authGuardService).toBeTruthy(); }); it('should return isAuthenticated from authState', () => { authGuardService.canActivate().subscribe(canActivate => { expect(canActivate).toBe(state.auth.isAuthenticated); }); }); }); function createState(authState: AuthState) { return { auth: authState }; }
Optimize import paths for testing utils
test(auth): Optimize import paths for testing utils
TypeScript
mit
tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter
--- +++ @@ -1,7 +1,7 @@ import { TestBed } from '@angular/core/testing'; import { AppState } from '@app/core'; import { Store, StoreModule } from '@ngrx/store'; -import { MockStore, provideMockStore } from '../../../testing/utils'; +import { MockStore, provideMockStore } from '@testing/utils'; import { AuthGuardService } from './auth-guard.service'; import { AuthState } from './auth.models';
7f55255a5d6ed5e67e24675aacb0ad1f4e806f8d
src/utils/notifications.ts
src/utils/notifications.ts
import { SearchResult } from '../types'; import { formatAsCurrency } from './formatting'; import { secondsToMinutes } from './dates'; export var requestNotificationPermission = async (): Promise< NotificationPermission > => { try { return await Notification.requestPermission(); } catch (e) { console.warn(e); return 'denied'; } }; export const createNotificationFromSearchResult = ( hit: SearchResult ): Notification => { const { title, reward, description, timeAllottedInSeconds } = hit; const notification = new Notification( `${formatAsCurrency(reward)} - ${title}`, { body: `Click to accept - ${secondsToMinutes( timeAllottedInSeconds )} minutes allotted - ${description}` } ); notification.onclick = acceptHitOnClick(hit); return notification; }; export const acceptHitOnClick = ({ groupId }: SearchResult) => () => window.open( `https://worker.mturk.com/projects/${groupId}/tasks/accept_random` );
import { SearchResult } from '../types'; import { formatAsCurrency } from './formatting'; import { secondsToMinutes } from './dates'; export const requestNotificationPermission = async (): Promise< NotificationPermission > => { try { return await Notification.requestPermission(); } catch (e) { console.warn(e); return 'denied'; } }; export const createNotificationFromSearchResult = ( hit: SearchResult ): Notification => { const { title, reward, description, timeAllottedInSeconds } = hit; const notification = new Notification( `${formatAsCurrency(reward)} - ${title}`, { body: `Click to accept - ${secondsToMinutes( timeAllottedInSeconds )} minutes allotted - ${description}` } ); notification.onclick = acceptHitOnClick(hit); return notification; }; export const acceptHitOnClick = ({ groupId }: SearchResult) => () => window.open( `https://worker.mturk.com/projects/${groupId}/tasks/accept_random` );
Change var declaration to const.
Change var declaration to const.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -2,7 +2,7 @@ import { formatAsCurrency } from './formatting'; import { secondsToMinutes } from './dates'; -export var requestNotificationPermission = async (): Promise< +export const requestNotificationPermission = async (): Promise< NotificationPermission > => { try {
32fe107c057805523855e5617e3bcf7b24504c0e
static-config-base.ts
static-config-base.ts
///<reference path="../.d.ts"/> "use strict"; import path = require("path"); import util = require("util"); export class StaticConfigBase implements Config.IStaticConfig { public PROJECT_FILE_NAME: string = null; public CLIENT_NAME: string = null; public ANALYTICS_API_KEY: string = null; public ANALYTICS_INSTALLATION_ID_SETTING_NAME: string = null; public TRACK_FEATURE_USAGE_SETTING_NAME: string = null; public START_PACKAGE_ACTIVITY_NAME: string = null; public version: string = null; public get helpTextPath(): string { return null; } public get sevenZipFilePath(): string { return path.join(__dirname, util.format("resources/platform-tools/unzip/%s/7za", process.platform)); } public get adbFilePath(): string { return path.join(__dirname, util.format("resources/platform-tools/android/%s/adb", process.platform)); } }
///<reference path="../.d.ts"/> "use strict"; import path = require("path"); import util = require("util"); export class StaticConfigBase implements Config.IStaticConfig { public PROJECT_FILE_NAME: string = null; public CLIENT_NAME: string = null; public ANALYTICS_API_KEY: string = null; public ANALYTICS_INSTALLATION_ID_SETTING_NAME: string = null; public TRACK_FEATURE_USAGE_SETTING_NAME: string = null; public START_PACKAGE_ACTIVITY_NAME: string; public version: string = null; public get helpTextPath(): string { return null; } public get sevenZipFilePath(): string { return path.join(__dirname, util.format("resources/platform-tools/unzip/%s/7za", process.platform)); } public get adbFilePath(): string { return path.join(__dirname, util.format("resources/platform-tools/android/%s/adb", process.platform)); } }
Remove default value for START_PACKAGE_ACTIVITY
Remove default value for START_PACKAGE_ACTIVITY The default value doesn't allow us to use constructions like public get START_PACKAGE_ACTIVITY_NAME(): string { ... } in each CLI's. We need such construction in appbuilder-cli to support different start package activity names, based on the project type.
TypeScript
apache-2.0
telerik/mobile-cli-lib,telerik/mobile-cli-lib
--- +++ @@ -10,7 +10,7 @@ public ANALYTICS_API_KEY: string = null; public ANALYTICS_INSTALLATION_ID_SETTING_NAME: string = null; public TRACK_FEATURE_USAGE_SETTING_NAME: string = null; - public START_PACKAGE_ACTIVITY_NAME: string = null; + public START_PACKAGE_ACTIVITY_NAME: string; public version: string = null; public get helpTextPath(): string { return null;
824fd09b52ad03ad6ae80bf0e984b737127b25f5
src/core/testUtils.ts
src/core/testUtils.ts
import { run, deepmerge, Module } from '../core' export const ChildComp = { state: { count: 0 }, inputs: F => ({ inc: async () => { await F.toAct('Inc') await F.toIt('changed', F.stateOf().count) }, changed: async value => {}, }), actions: { Inc: () => s => { s.count++ return s }, }, interfaces: {}, } export const createApp = (comp?): Promise<Module> => { const Root = { state: { result: '' }, inputs: F => ({}), actions: {}, interfaces: {}, } const DEV = true return run({ Root: deepmerge(Root, comp || {}), record: DEV, log: DEV, interfaces: {}, }) }
import { run, deepmerge, Module } from '../core' export const ChildComp = { state: { count: 0 }, inputs: F => ({ inc: async () => { await F.toAct('Inc') await F.toIt('changed', F.stateOf().count) }, changed: async value => {}, }), actions: { Inc: () => s => { s.count++ return s }, }, interfaces: {}, } export const createApp = (comp?, mod?): Promise<Module> => { const Root = { state: { result: '' }, inputs: F => ({}), actions: {}, interfaces: {}, } const DEV = true return run(deepmerge({ Root: deepmerge(Root, comp || {}), record: DEV, log: DEV, interfaces: {}, }, mod || {})) }
Add option to modify module in createApp mocking function
Add option to modify module in createApp mocking function
TypeScript
mit
FractalBlocks/Fractal,FractalBlocks/Fractal,FractalBlocks/Fractal
--- +++ @@ -18,7 +18,7 @@ interfaces: {}, } -export const createApp = (comp?): Promise<Module> => { +export const createApp = (comp?, mod?): Promise<Module> => { const Root = { state: { result: '' }, @@ -29,11 +29,11 @@ const DEV = true - return run({ + return run(deepmerge({ Root: deepmerge(Root, comp || {}), record: DEV, log: DEV, interfaces: {}, - }) + }, mod || {})) }
ccc14c0062a63f16fd2c7a0f1671e159623c451b
app/javascript/lca/components/characterEditor/weapons/WeaponRow.tsx
app/javascript/lca/components/characterEditor/weapons/WeaponRow.tsx
import React from 'react' import { useDispatch } from 'react-redux' import { Box, IconButton, Theme } from '@material-ui/core' import { Edit, RemoveCircle } from '@material-ui/icons' import WeaponLine from 'components/characters/weapons/WeaponLine.jsx' import Handle from 'components/shared/GrabHandle' import { destroyWeapon } from 'ducks/actions' import { Character, Weapon } from 'types' interface WeaponRowProps { character: Character weapon: Weapon setId: (id: number) => void } const WeaponRow = (props: WeaponRowProps) => { const { character, weapon } = props const setId = () => props.setId(weapon.id) const dispatch = useDispatch() return ( <Box display="flex" alignItems="center"> <Handle /> <IconButton onClick={setId}> <Edit /> </IconButton> <WeaponLine weapon={weapon} /> <IconButton onClick={() => dispatch(destroyWeapon(character.id, weapon.id))} > <RemoveCircle /> </IconButton> </Box> ) } export default WeaponRow
import React from 'react' import { useDispatch } from 'react-redux' import { Box, IconButton, Theme } from '@material-ui/core' import { Edit, RemoveCircle } from '@material-ui/icons' import WeaponLine from 'components/characters/weapons/WeaponLine.jsx' import Handle from 'components/shared/GrabHandle' import { destroyWeapon } from 'ducks/actions' import { Character, Weapon } from 'types' interface WeaponRowProps { character: Character weapon: Weapon setId: (id: number) => void } const WeaponRow = (props: WeaponRowProps) => { const { character, weapon } = props const setId = () => props.setId(weapon.id) const dispatch = useDispatch() return ( <Box display="flex" alignItems="center"> <Handle /> <IconButton onClick={setId}> <Edit /> </IconButton> <WeaponLine weapon={weapon} /> <IconButton onClick={() => dispatch(destroyWeapon(weapon.id, character.id))} > <RemoveCircle /> </IconButton> </Box> ) } export default WeaponRow
Fix weapons not deleting properly
Fix weapons not deleting properly
TypeScript
agpl-3.0
makzu/lotcastingatemi,makzu/lotcastingatemi,makzu/lotcastingatemi,makzu/lotcastingatemi,makzu/lotcastingatemi
--- +++ @@ -30,7 +30,7 @@ <WeaponLine weapon={weapon} /> <IconButton - onClick={() => dispatch(destroyWeapon(character.id, weapon.id))} + onClick={() => dispatch(destroyWeapon(weapon.id, character.id))} > <RemoveCircle /> </IconButton>
b98b8e164c9b45a9cf68debb202560ded49dc4cf
saleor/static/dashboard-next/pages/index.tsx
saleor/static/dashboard-next/pages/index.tsx
import { parse as parseQs } from "qs"; import * as React from "react"; import { Route, RouteComponentProps, Switch } from "react-router-dom"; import { WindowTitle } from "../components/WindowTitle"; import i18n from "../i18n"; import PageCreate from "./views/PageCreate"; import PageDetailsComponent from "./views/PageDetails"; import PageListComponent, { PageListQueryParams } from "./views/PageList"; const PageList: React.StatelessComponent<RouteComponentProps<any>> = ({ location }) => { const qs = parseQs(location.search.substr(1)); const params: PageListQueryParams = { after: qs.after, before: qs.before }; return <PageListComponent params={params} />; }; const PageDetails: React.StatelessComponent<RouteComponentProps<any>> = ({ match }) => { return <PageDetailsComponent id={match.params.id} />; }; const Component = ({ match }) => ( <> <WindowTitle title={i18n.t("Pages")} /> <Switch> <Route exact path={match.url} component={PageList} /> <Route exact path={`${match.url}/add/`} component={PageCreate} /> <Route exact path={`${match.url}/:id/`} component={PageDetails} /> </Switch> </> ); export default Component;
import { parse as parseQs } from "qs"; import * as React from "react"; import { Route, RouteComponentProps, Switch } from "react-router-dom"; import { WindowTitle } from "../components/WindowTitle"; import i18n from "../i18n"; import { pageAddUrl, pageListUrl, pageUrl } from "./urls"; import PageCreate from "./views/PageCreate"; import PageDetailsComponent from "./views/PageDetails"; import PageListComponent, { PageListQueryParams } from "./views/PageList"; const PageList: React.StatelessComponent<RouteComponentProps<any>> = ({ location }) => { const qs = parseQs(location.search.substr(1)); const params: PageListQueryParams = { after: qs.after, before: qs.before }; return <PageListComponent params={params} />; }; const PageDetails: React.StatelessComponent<RouteComponentProps<any>> = ({ match }) => { return <PageDetailsComponent id={match.params.id} />; }; const Component = () => ( <> <WindowTitle title={i18n.t("Pages")} /> <Switch> <Route exact path={pageListUrl} component={PageList} /> <Route exact path={pageAddUrl} component={PageCreate} /> <Route exact path={pageUrl(":id")} component={PageDetails} /> </Switch> </> ); export default Component;
Use predefined paths in router
Use predefined paths in router
TypeScript
bsd-3-clause
mociepka/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor
--- +++ @@ -4,6 +4,7 @@ import { WindowTitle } from "../components/WindowTitle"; import i18n from "../i18n"; +import { pageAddUrl, pageListUrl, pageUrl } from "./urls"; import PageCreate from "./views/PageCreate"; import PageDetailsComponent from "./views/PageDetails"; import PageListComponent, { PageListQueryParams } from "./views/PageList"; @@ -24,13 +25,13 @@ return <PageDetailsComponent id={match.params.id} />; }; -const Component = ({ match }) => ( +const Component = () => ( <> <WindowTitle title={i18n.t("Pages")} /> <Switch> - <Route exact path={match.url} component={PageList} /> - <Route exact path={`${match.url}/add/`} component={PageCreate} /> - <Route exact path={`${match.url}/:id/`} component={PageDetails} /> + <Route exact path={pageListUrl} component={PageList} /> + <Route exact path={pageAddUrl} component={PageCreate} /> + <Route exact path={pageUrl(":id")} component={PageDetails} /> </Switch> </> );
918830f9750a43567f1dbc01bc6492481d267ed6
lib/msal-core/src/index.ts
lib/msal-core/src/index.ts
export { UserAgentApplication } from "./UserAgentApplication"; export { Logger } from "./Logger"; export { LogLevel } from "./Logger"; export { Account } from "./Account"; export { Constants, TemporaryCacheKeys } from "./utils/Constants"; export { Authority } from "./authority/Authority"; export { CacheResult } from "./UserAgentApplication"; export { CacheLocation, Configuration } from "./Configuration"; export { AuthenticationParameters } from "./AuthenticationParameters"; export { AuthResponse } from "./AuthResponse"; export { CryptoUtils } from "./utils/CryptoUtils"; // Errors export { AuthError } from "./error/AuthError"; export { ClientAuthError } from "./error/ClientAuthError"; export { ServerError } from "./error/ServerError"; export { ClientConfigurationError } from "./error/ClientConfigurationError"; export { InteractionRequiredAuthError } from "./error/InteractionRequiredAuthError";
export { UserAgentApplication } from "./UserAgentApplication"; export { Logger } from "./Logger"; export { LogLevel } from "./Logger"; export { Account } from "./Account"; export { Constants } from "./utils/Constants"; export { Authority } from "./authority/Authority"; export { CacheResult } from "./UserAgentApplication"; export { CacheLocation, Configuration } from "./Configuration"; export { AuthenticationParameters } from "./AuthenticationParameters"; export { AuthResponse } from "./AuthResponse"; export { CryptoUtils } from "./utils/CryptoUtils"; // Errors export { AuthError } from "./error/AuthError"; export { ClientAuthError } from "./error/ClientAuthError"; export { ServerError } from "./error/ServerError"; export { ClientConfigurationError } from "./error/ClientConfigurationError"; export { InteractionRequiredAuthError } from "./error/InteractionRequiredAuthError";
Revert exporting TemporaryCacheKeys from msal
Revert exporting TemporaryCacheKeys from msal
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -2,7 +2,7 @@ export { Logger } from "./Logger"; export { LogLevel } from "./Logger"; export { Account } from "./Account"; -export { Constants, TemporaryCacheKeys } from "./utils/Constants"; +export { Constants } from "./utils/Constants"; export { Authority } from "./authority/Authority"; export { CacheResult } from "./UserAgentApplication"; export { CacheLocation, Configuration } from "./Configuration";
d7fdf33426596e5cc97fb568a4f6ca5ebd80cf18
transpiler/src/emitter/source.ts
transpiler/src/emitter/source.ts
import { EmitResult, emit } from './'; import { Context } from '../contexts'; import { SourceFile } from 'typescript'; export const emitSourceFile = (node: SourceFile, context): EmitResult => node.statements .reduce((result, node) => { const emit_result = emit(node, context); emit_result.emitted_string = result.emitted_string + '\n' + emit_result.emitted_string; return emit_result; }, { context, emitted_string: '' });
import { EmitResult, emit } from './'; import { Context } from '../contexts'; import { SourceFile } from 'typescript'; export const emitSourceFile = (node: SourceFile, context: Context): EmitResult => node.statements .reduce<EmitResult>(({ context, emitted_string }, node) => { const result = emit(node, context); result.emitted_string = emitted_string + '\n' + result.emitted_string; return result; }, { context, emitted_string: '' });
Fix issue with context not being updated
Fix issue with context not being updated
TypeScript
mit
artfuldev/RIoT
--- +++ @@ -2,10 +2,10 @@ import { Context } from '../contexts'; import { SourceFile } from 'typescript'; -export const emitSourceFile = (node: SourceFile, context): EmitResult => +export const emitSourceFile = (node: SourceFile, context: Context): EmitResult => node.statements - .reduce((result, node) => { - const emit_result = emit(node, context); - emit_result.emitted_string = result.emitted_string + '\n' + emit_result.emitted_string; - return emit_result; + .reduce<EmitResult>(({ context, emitted_string }, node) => { + const result = emit(node, context); + result.emitted_string = emitted_string + '\n' + result.emitted_string; + return result; }, { context, emitted_string: '' });
255bbc9ea33f867602979f019791679dc32a6b6a
web/browser/components/SafetyBox.tsx
web/browser/components/SafetyBox.tsx
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2016 Jacob Peddicord <[email protected]> */ import * as React from 'react'; interface State { armed: boolean; } export default class SafetyBox extends React.Component<{}, State> { state = { armed: false, }; timeout: any = null; componentWillUnmount() { clearTimeout(this.timeout); } arm = (e: any) => { this.setState({armed: true}); this.timeout = setTimeout(() => { this.setState({armed: false}); }, 10 * 1000); } render() { const { children } = this.props; return ( <div style={{position: 'relative'}}> { this.state.armed ? '' : <div className="caution-stripes" onDoubleClick={this.arm} title="Control is locked. Double-click to arm."/> } {children} </div> ); } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2016 Jacob Peddicord <[email protected]> */ import * as React from 'react'; interface State { armed: boolean; } export default class SafetyBox extends React.Component<{}, State> { state = { armed: false, }; timeout: any = null; componentWillUnmount() { clearTimeout(this.timeout); } arm = (e: any) => { this.setState({armed: true}); this.timeout = setTimeout(() => { this.setState({armed: false}); }, 10 * 1000); } render() { const { children } = this.props; return ( <div style={{position: 'relative', padding: '10px'}}> { this.state.armed ? '' : <div className="caution-stripes" onDoubleClick={this.arm} title="Control is locked. Double-click to arm."/> } {children} </div> ); } }
Add some padding around safety boxes
Add some padding around safety boxes
TypeScript
mpl-2.0
jpeddicord/progcon,jpeddicord/progcon,jpeddicord/progcon,jpeddicord/progcon,jpeddicord/progcon
--- +++ @@ -33,7 +33,7 @@ const { children } = this.props; return ( - <div style={{position: 'relative'}}> + <div style={{position: 'relative', padding: '10px'}}> { this.state.armed ? '' : <div className="caution-stripes" onDoubleClick={this.arm} title="Control is locked. Double-click to arm."/> }
99103ef2973e3b85f93c007313322de47edb50a5
src/isaac-generator.ts
src/isaac-generator.ts
export class IsaacGenerator { private _count: number; constructor() { this._count = 0; } public getValue(): number { if (this._count === 0) { this._randomise(); } 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 { } }
Use <= rather than === for count
Use <= rather than === for count
TypeScript
mit
Jameskmonger/isaac-crypto
--- +++ @@ -6,7 +6,7 @@ } public getValue(): number { - if (this._count === 0) { + if (this._count <= 0) { this._randomise(); }
6a8a25d94392596a73af69fd11ef69c7264a080c
frontend/terminal/index.tsx
frontend/terminal/index.tsx
import "xterm/css/xterm.css"; import { getCredentials, attachTerminal } from "./support"; import { TerminalSession } from "./terminal_session"; const { password, username, url } = getCredentials(); const session = new TerminalSession(url, username, password, attachTerminal()); session.connect();
import "xterm/css/xterm.css"; import { getCredentials, attachTerminal } from "./support"; import { TerminalSession } from "./terminal_session"; const { password, username, url } = getCredentials(); const session = new TerminalSession(url, username, password, attachTerminal()); // eslint-disable-next-line @typescript-eslint/no-explicit-any (window as any).terminal_session = session; session.connect();
Attach terminal_session to `window` object
Attach terminal_session to `window` object
TypeScript
mit
FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API
--- +++ @@ -4,5 +4,7 @@ const { password, username, url } = getCredentials(); const session = new TerminalSession(url, username, password, attachTerminal()); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +(window as any).terminal_session = session; +session.connect(); -session.connect();
0a5903a986bfe6f78a36aa35297b1b1c353bba76
client/src/environments/environment.prod.ts
client/src/environments/environment.prod.ts
export const environment = { production: true, baseURL: 'https://www.buddyduel.net', };
export const environment = { production: true, baseURL: 'https://buddyduel.net', };
Update baseUrl to remove www
Update baseUrl to remove www
TypeScript
mit
lentz/buddyduel,lentz/buddyduel,lentz/buddyduel
--- +++ @@ -1,4 +1,4 @@ export const environment = { production: true, - baseURL: 'https://www.buddyduel.net', + baseURL: 'https://buddyduel.net', };
df57d942246aa1179f259f248a239822aa74f8d5
src/sanitizer/index.ts
src/sanitizer/index.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import * as sanitize from 'sanitize-html'; export interface ISanitizer { /** * Sanitize an HTML string. */ sanitize(dirty: string): string; } /** * A class to sanitize HTML strings. */ class Sanitizer implements ISanitizer { /** * Sanitize an HTML string. */ sanitize(dirty: string): string { return sanitize(dirty, this._options); } private _options: sanitize.IOptions = { allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'), allowedAttributes: { // Allow the "rel" attribute for <a> tags. 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), // Allow the "src" attribute for <img> tags. 'img': ['src'] }, transformTags: { // Set the "rel" attribute for <a> tags to "nofollow". 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }) } }; } /** * The default instance of an `ISanitizer` meant for use by user code. */ export const defaultSanitizer: ISanitizer = new Sanitizer();
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import * as sanitize from 'sanitize-html'; export interface ISanitizer { /** * Sanitize an HTML string. */ sanitize(dirty: string): string; } /** * A class to sanitize HTML strings. */ class Sanitizer implements ISanitizer { /** * Sanitize an HTML string. */ sanitize(dirty: string): string { return sanitize(dirty, this._options); } private _options: sanitize.IOptions = { allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'), allowedAttributes: { // Allow the "rel" attribute for <a> tags. 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), // Allow the "src" attribute for <img> tags. 'img': ['src', 'height', 'width', 'alt'] }, transformTags: { // Set the "rel" attribute for <a> tags to "nofollow". 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }) } }; } /** * The default instance of an `ISanitizer` meant for use by user code. */ export const defaultSanitizer: ISanitizer = new Sanitizer();
Support height, width, and alt attributes for images in Markdown images.
Support height, width, and alt attributes for images in Markdown images.
TypeScript
bsd-3-clause
TypeFox/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab
--- +++ @@ -29,7 +29,7 @@ // Allow the "rel" attribute for <a> tags. 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), // Allow the "src" attribute for <img> tags. - 'img': ['src'] + 'img': ['src', 'height', 'width', 'alt'] }, transformTags: { // Set the "rel" attribute for <a> tags to "nofollow".
bb7f6a4e995b8dc834bb88f7ed54d97e1bf3b244
src/parse-engines/parse-engine-registry.ts
src/parse-engines/parse-engine-registry.ts
import ParseEngine from './common/parse-engine'; import CssParseEngine from './types/css-parse-engine'; class ParseEngineRegistry { private static _supportedLanguagesIds: string[]; private static _registry: ParseEngine[] = [ new CssParseEngine() ]; public static get supportedLanguagesIds(): string[] { if (!ParseEngineRegistry._supportedLanguagesIds) { ParseEngineRegistry._supportedLanguagesIds = ParseEngineRegistry._registry.reduce<string[]>( (previousValue: string[], currentValue: ParseEngine, currentIndex: number, array: ParseEngine[]) => { previousValue.push(currentValue.languageId) return previousValue; }, []); } return ParseEngineRegistry._supportedLanguagesIds; } public static getParseEngine(languageId: string): ParseEngine { let foundParseEngine: ParseEngine = ParseEngineRegistry._registry.find((value: ParseEngine, index: number, obj: ParseEngine[]) => { return value.languageId === languageId; }); if (!foundParseEngine) { throw `Could not find a parse engine for the provided language id ("${languageId}").`; } return foundParseEngine; } } export default ParseEngineRegistry;
import ParseEngine from './common/parse-engine'; import CssParseEngine from './types/css-parse-engine'; class ParseEngineRegistry { private static _supportedLanguagesIds: string[]; private static _registry: ParseEngine[] = [ new CssParseEngine() ]; public static get supportedLanguagesIds(): string[] { if (!ParseEngineRegistry._supportedLanguagesIds) { ParseEngineRegistry._supportedLanguagesIds = ParseEngineRegistry._registry.map(parseEngine => parseEngine.languageId); } return ParseEngineRegistry._supportedLanguagesIds; } public static getParseEngine(languageId: string): ParseEngine { let foundParseEngine = ParseEngineRegistry._registry.find(value => value.languageId === languageId); if (!foundParseEngine) { throw `Could not find a parse engine for the provided language id ("${languageId}").`; } return foundParseEngine; } } export default ParseEngineRegistry;
Simplify some logic in the parse engine registry
Simplify some logic in the parse engine registry
TypeScript
mit
zignd/HTML-CSS-Class-Completion
--- +++ @@ -9,20 +9,14 @@ public static get supportedLanguagesIds(): string[] { if (!ParseEngineRegistry._supportedLanguagesIds) { - ParseEngineRegistry._supportedLanguagesIds = ParseEngineRegistry._registry.reduce<string[]>( - (previousValue: string[], currentValue: ParseEngine, currentIndex: number, array: ParseEngine[]) => { - previousValue.push(currentValue.languageId) - return previousValue; - }, []); + ParseEngineRegistry._supportedLanguagesIds = ParseEngineRegistry._registry.map(parseEngine => parseEngine.languageId); } return ParseEngineRegistry._supportedLanguagesIds; } public static getParseEngine(languageId: string): ParseEngine { - let foundParseEngine: ParseEngine = ParseEngineRegistry._registry.find((value: ParseEngine, index: number, obj: ParseEngine[]) => { - return value.languageId === languageId; - }); + let foundParseEngine = ParseEngineRegistry._registry.find(value => value.languageId === languageId); if (!foundParseEngine) { throw `Could not find a parse engine for the provided language id ("${languageId}").`;
1de0d2caa25176932f521ae6de091a199027e44b
packages/@glimmer/blueprint/files/src/main.ts
packages/@glimmer/blueprint/files/src/main.ts
import Application from '@glimmer/application'; import Resolver, { BasicModuleRegistry } from '@glimmer/resolver'; import moduleMap from '../config/module-map'; import resolverConfiguration from '../config/resolver-configuration'; export default class App extends Application { constructor() { let moduleRegistry = new BasicModuleRegistry(moduleMap); let resolver = new Resolver(resolverConfiguration, moduleRegistry); super({ resolver, rootName: resolverConfiguration.app.rootName }); } }
import Application, { AsyncRenderer, DOMBuilder, RuntimeCompilerLoader } from '@glimmer/application'; import Resolver, { BasicModuleRegistry } from '@glimmer/resolver'; import moduleMap from '../config/module-map'; import resolverConfiguration from '../config/resolver-configuration'; export default class App extends Application { constructor() { let moduleRegistry = new BasicModuleRegistry(moduleMap); let resolver = new Resolver(resolverConfiguration, moduleRegistry); const element = document.body; super({ builder: new DOMBuilder({ element, nextSibling: null }), loader: new RuntimeCompilerLoader(resolver), renderer: new AsyncRenderer(), rootName: resolverConfiguration.app.rootName, resolver }); } }
Update blueprint ot use builder/loader/renderer API
Update blueprint ot use builder/loader/renderer API
TypeScript
mit
glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js
--- +++ @@ -1,4 +1,4 @@ -import Application from '@glimmer/application'; +import Application, { AsyncRenderer, DOMBuilder, RuntimeCompilerLoader } from '@glimmer/application'; import Resolver, { BasicModuleRegistry } from '@glimmer/resolver'; import moduleMap from '../config/module-map'; import resolverConfiguration from '../config/resolver-configuration'; @@ -7,10 +7,14 @@ constructor() { let moduleRegistry = new BasicModuleRegistry(moduleMap); let resolver = new Resolver(resolverConfiguration, moduleRegistry); + const element = document.body; super({ - resolver, - rootName: resolverConfiguration.app.rootName + builder: new DOMBuilder({ element, nextSibling: null }), + loader: new RuntimeCompilerLoader(resolver), + renderer: new AsyncRenderer(), + rootName: resolverConfiguration.app.rootName, + resolver }); } }
4fb40859d652285be613f9689f54a4fb4ff7fd8b
functions/amazon.ts
functions/amazon.ts
import * as apac from "apac"; import * as functions from "firebase-functions"; const amazonClient = new apac.OperationHelper({ assocId: functions.config().aws.tag, awsId: functions.config().aws.id, awsSecret: functions.config().aws.secret, endPoint: "webservices.amazon.co.jp", }); export async function books(): Promise<any[]> { const { result: { ItemSearchResponse: { Items: { Item } } } } = await amazonClient.execute("ItemSearch", { BrowseNode: "466298", ResponseGroup: "Images,ItemAttributes", SearchIndex: "Books", }); return Item.map(({ DetailPageURL, SmallImage, ItemAttributes: { Title } }) => ({ imageUri: SmallImage.URL, pageUri: DetailPageURL, title: Title, })); }
import * as apac from "apac"; import * as functions from "firebase-functions"; const amazonClient = new apac.OperationHelper({ assocId: functions.config().aws.tag, awsId: functions.config().aws.id, awsSecret: functions.config().aws.secret, endPoint: "webservices.amazon.co.jp", }); export async function books(): Promise<any[]> { const { result: { ItemSearchResponse: { Items: { Item } } } } = await amazonClient.execute("ItemSearch", { BrowseNode: "466298", ResponseGroup: "Images,ItemAttributes", SearchIndex: "Books", }); return Item.map(({ ASIN, DetailPageURL, SmallImage, ItemAttributes: { Author, Publisher, Title } }) => ({ asin: ASIN, author: Author, imageUri: SmallImage.URL, pageUri: DetailPageURL, publisher: Publisher, title: Title, })); }
Send ASIN, author, and publisher properties
Send ASIN, author, and publisher properties
TypeScript
mit
raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d
--- +++ @@ -16,9 +16,16 @@ SearchIndex: "Books", }); - return Item.map(({ DetailPageURL, SmallImage, ItemAttributes: { Title } }) => ({ - imageUri: SmallImage.URL, - pageUri: DetailPageURL, - title: Title, - })); + return Item.map(({ + ASIN, + DetailPageURL, + SmallImage, + ItemAttributes: { Author, Publisher, Title } }) => ({ + asin: ASIN, + author: Author, + imageUri: SmallImage.URL, + pageUri: DetailPageURL, + publisher: Publisher, + title: Title, + })); }
33505c07e6fc2f2b682ce485a817908a526aa38a
src/postgres/edge-record.ts
src/postgres/edge-record.ts
import { FactRecord, FactReference } from '../storage'; export type EdgeRecord = { predecessor_hash: string, predecessor_type: string, successor_hash: string, successor_type: string, role: string }; function makeEdgeRecord(predecessor: FactReference, successor: FactRecord, role: string): EdgeRecord { return { predecessor_hash: predecessor.hash, predecessor_type: predecessor.type, successor_hash: successor.hash, successor_type: successor.type, role }; } export function makeEdgeRecords(fact: FactRecord): EdgeRecord[] { let records: EdgeRecord[] = []; for (const role in fact.predecessors) { const predecessor = fact.predecessors[role]; if (Array.isArray(predecessor)) { records = records.concat(predecessor.map(p => makeEdgeRecord(p, fact, role))); } else { records.push(makeEdgeRecord(predecessor, fact, role)); } } return records; }
import { FactRecord, FactReference } from '../storage'; export type EdgeRecord = { predecessor_hash: string, predecessor_type: string, successor_hash: string, successor_type: string, role: string }; function makeEdgeRecord(predecessor: FactReference, successor: FactRecord, role: string): EdgeRecord { if (!predecessor.hash || !predecessor.type || !successor.hash || !successor.type) { throw new Error('Attempting to save edge with null hash or type.'); } return { predecessor_hash: predecessor.hash, predecessor_type: predecessor.type, successor_hash: successor.hash, successor_type: successor.type, role }; } export function makeEdgeRecords(fact: FactRecord): EdgeRecord[] { let records: EdgeRecord[] = []; for (const role in fact.predecessors) { const predecessor = fact.predecessors[role]; if (Array.isArray(predecessor)) { records = records.concat(predecessor.map(p => makeEdgeRecord(p, fact, role))); } else { records.push(makeEdgeRecord(predecessor, fact, role)); } } return records; }
Throw on edge record, too.
Throw on edge record, too.
TypeScript
mit
michaellperry/jinaga,michaellperry/jinaga
--- +++ @@ -9,6 +9,9 @@ }; function makeEdgeRecord(predecessor: FactReference, successor: FactRecord, role: string): EdgeRecord { + if (!predecessor.hash || !predecessor.type || !successor.hash || !successor.type) { + throw new Error('Attempting to save edge with null hash or type.'); + } return { predecessor_hash: predecessor.hash, predecessor_type: predecessor.type,
90a602140dac91f187fc48b3b1e1b872674a146d
index.d.ts
index.d.ts
import { ChartitGraphProps } from './index.d'; import * as React from 'react'; import { IChartOptions, IResponsiveOptionTuple, ILineChartOptions, IBarChartOptions, IPieChartOptions, } from 'chartist'; export interface ChartitGraphProps { type: string; data: object; className?: string; options?: IChartOptions; style?: React.CSSProperties; } export interface ChartitGraphLineProps extends ChartitGraphProps { type: 'Line'; options?: ILineChartOptions; responseOptions?: Array<IResponsiveOptionTuple<ILineChartOptions>>; } export interface ChartitGraphPieProps extends ChartitGraphProps { type: 'Pie'; options?: IPieChartOptions; responseOptions?: Array<IResponsiveOptionTuple<IPieChartOptions>>; } export interface ChartitGraphBarProps extends ChartitGraphProps { type: 'Bar'; options: IBarChartOptions; responseOptions?: Array<IResponsiveOptionTuple<IBarChartOptions>>; } export default class ChartistGraph extends React.Component<ChartitGraphProps> {}
import * as React from 'react'; import { IChartOptions, IResponsiveOptionTuple, ILineChartOptions, IBarChartOptions, IPieChartOptions, } from 'chartist'; export interface ChartitGraphProps { type: string; data: object; className?: string; options?: IChartOptions; style?: React.CSSProperties; } export interface ChartitGraphLineProps extends ChartitGraphProps { type: 'Line'; options?: ILineChartOptions; responseOptions?: Array<IResponsiveOptionTuple<ILineChartOptions>>; } export interface ChartitGraphPieProps extends ChartitGraphProps { type: 'Pie'; options?: IPieChartOptions; responseOptions?: Array<IResponsiveOptionTuple<IPieChartOptions>>; } export interface ChartitGraphBarProps extends ChartitGraphProps { type: 'Bar'; options: IBarChartOptions; responseOptions?: Array<IResponsiveOptionTuple<IBarChartOptions>>; } export default class ChartistGraph extends React.Component<ChartitGraphProps> {}
Remove recursive self-import of ChartitGraphProps
Remove recursive self-import of ChartitGraphProps
TypeScript
mit
fraserxu/react-chartist,fraserxu/react-chartist
--- +++ @@ -1,4 +1,3 @@ -import { ChartitGraphProps } from './index.d'; import * as React from 'react'; import { IChartOptions,
4a392641880f6fc0c4e44cf3e83490ef0445f373
ts/util/getStoryBackground.ts
ts/util/getStoryBackground.ts
// Copyright 2022 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import type { AttachmentType, TextAttachmentType } from '../types/Attachment'; const COLOR_BLACK_ALPHA_90 = 'rgba(0, 0, 0, 0.9)'; export const COLOR_BLACK_INT = 4278190080; export const COLOR_WHITE_INT = 4294704123; export function getHexFromNumber(color: number): string { return `#${color.toString(16).slice(2)}`; } export function getBackgroundColor({ color, gradient, }: Pick<TextAttachmentType, 'color' | 'gradient'>): string { if (gradient) { return `linear-gradient(${gradient.angle}deg, ${getHexFromNumber( gradient.startColor || COLOR_WHITE_INT )}, ${getHexFromNumber(gradient.endColor || COLOR_WHITE_INT)}) border-box`; } return getHexFromNumber(color || COLOR_WHITE_INT); } export function getStoryBackground(attachment?: AttachmentType): string { if (!attachment) { return COLOR_BLACK_ALPHA_90; } if (attachment.textAttachment) { return getBackgroundColor(attachment.textAttachment); } if (attachment.url) { return `url("${attachment.url}")`; } return COLOR_BLACK_ALPHA_90; }
// Copyright 2022 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import type { AttachmentType, TextAttachmentType } from '../types/Attachment'; const COLOR_BLACK_ALPHA_90 = 'rgba(0, 0, 0, 0.9)'; export const COLOR_BLACK_INT = 4278190080; export const COLOR_WHITE_INT = 4294704123; export function getHexFromNumber(color: number): string { return `#${color.toString(16).slice(2)}`; } export function getBackgroundColor({ color, gradient, }: Pick<TextAttachmentType, 'color' | 'gradient'>): string { if (gradient) { return `linear-gradient(${gradient.angle}deg, ${getHexFromNumber( gradient.startColor || COLOR_WHITE_INT )}, ${getHexFromNumber(gradient.endColor || COLOR_WHITE_INT)}) border-box`; } return getHexFromNumber(color || COLOR_WHITE_INT); } export function getStoryBackground(attachment?: AttachmentType): string { if (!attachment) { return COLOR_BLACK_ALPHA_90; } if (attachment.textAttachment) { return getBackgroundColor(attachment.textAttachment); } if (attachment.screenshot && attachment.screenshot.url) { return `url("${attachment.screenshot.url}")`; } if (attachment.url) { return `url("${attachment.url}")`; } return COLOR_BLACK_ALPHA_90; }
Use video screenshot as background blur in story viewer
Use video screenshot as background blur in story viewer
TypeScript
agpl-3.0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
--- +++ @@ -33,6 +33,10 @@ return getBackgroundColor(attachment.textAttachment); } + if (attachment.screenshot && attachment.screenshot.url) { + return `url("${attachment.screenshot.url}")`; + } + if (attachment.url) { return `url("${attachment.url}")`; }
1e31e51ca4d76ed46e82724dc2d6e1b9273ac771
server.ts
server.ts
require("source-map-support").install(); import * as dbInit from "./db"; Object.keys(dbInit); // initializes all database models import logger from "./server/api/logger"; // Required to setup logger import WebServer from "./server/WebServer"; import { connect } from "./server/api/db"; /** * Sets the webserver up and starts it. Called once on app start. */ export default async function main(): Promise<void> { if (process.env.ETA_ENVIRONMENT !== "docker-compose") { console.warn("You should run this server with docker-compose: `docker-compose up`"); } process.on("uncaughtException", (err: Error) => { console.log("An uncaught error occurred: " + err.message); console.log(err.stack); }); let server: WebServer; process.on("SIGINT", async () => { // gracefully close server on CTRL+C if (!server) { return; } logger.trace("Stopping Eta..."); try { await server.close(); } catch (err) { logger.error(err); } finally { process.exit(); } }); server = new WebServer(); if (!await server.init()) { server.close(); return; } server.start(); } if (!module.parent) { main().then(() => { }) .catch(err => console.error(err)); }
require("source-map-support").install(); import * as dbInit from "./db"; Object.keys(dbInit); // initializes all database models import logger from "./server/api/logger"; // Required to setup logger import WebServer from "./server/WebServer"; import { connect } from "./server/api/db"; /** * Sets the webserver up and starts it. Called once on app start. */ export default async function main(): Promise<void> { if (process.env.ETA_ENVIRONMENT !== "docker-compose") { console.warn("You should run this server with docker-compose: `docker-compose up`"); } process.on("uncaughtException", (err: Error) => { console.error("An uncaught error occurred: " + err.message); console.log(err.stack); }); let server: WebServer; process.on("SIGINT", async () => { // gracefully close server on CTRL+C if (!server) { return; } logger.trace("Stopping Eta..."); try { await server.close(); } catch (err) { logger.error(err); } finally { process.exit(); } }); server = new WebServer(); if (!await server.init()) { server.close(); return; } server.start(); } if (!module.parent) { main().then(() => { }) .catch(err => console.error(err)); }
Use console.error instead of console.log
Use console.error instead of console.log
TypeScript
mit
crossroads-education/eta,crossroads-education/eta
--- +++ @@ -13,7 +13,7 @@ console.warn("You should run this server with docker-compose: `docker-compose up`"); } process.on("uncaughtException", (err: Error) => { - console.log("An uncaught error occurred: " + err.message); + console.error("An uncaught error occurred: " + err.message); console.log(err.stack); }); let server: WebServer;
e8147198073fc98a1a4828d8d55930f8153d75da
src/index.tsx
src/index.tsx
import * as MarkdownUtil from "./util/MarkdownUtil" import * as commands from "./commands"; import { ReactMde, ReactMdeProps } from "./components"; import { IconProviderProps, SvgIcon, MdeFontAwesomeIcon } from "./icons"; import { L18n } from "./types/L18n"; export { ReactMdeProps, MarkdownUtil, L18n, SvgIcon, MdeFontAwesomeIcon, IconProviderProps, commands }; export default ReactMde;
import * as MarkdownUtil from "./util/MarkdownUtil" import * as commands from "./commands"; import { ReactMde, ReactMdeProps } from "./components"; import { IconProviderProps, SvgIcon, MdeFontAwesomeIcon } from "./icons"; import { L18n } from "./types/L18n"; import { TextState, TextApi } from "./types/CommandOptions"; import { Command } from "./types/Command"; export { ReactMdeProps, MarkdownUtil, L18n, SvgIcon, MdeFontAwesomeIcon, IconProviderProps, commands, TextState, TextApi, Command }; export default ReactMde;
Add exports to be able to create custom commands
Add exports to be able to create custom commands
TypeScript
mit
andrerpena/react-mde,andrerpena/react-mde,andrerpena/react-mde
--- +++ @@ -3,6 +3,8 @@ import { ReactMde, ReactMdeProps } from "./components"; import { IconProviderProps, SvgIcon, MdeFontAwesomeIcon } from "./icons"; import { L18n } from "./types/L18n"; +import { TextState, TextApi } from "./types/CommandOptions"; +import { Command } from "./types/Command"; export { ReactMdeProps, @@ -11,7 +13,10 @@ SvgIcon, MdeFontAwesomeIcon, IconProviderProps, - commands + commands, + TextState, + TextApi, + Command }; export default ReactMde;
40a86731851ad3f5cbccf4b85ecc150f966e4861
saleor/static/dashboard-next/components/Navigator.tsx
saleor/static/dashboard-next/components/Navigator.tsx
import * as invariant from "invariant"; import * as PropTypes from "prop-types"; import * as React from "react"; interface NavigatorProps { children: (( navigate: (url: string, replace?: boolean, preserveQs?: boolean) => any ) => React.ReactElement<any>); } const Navigator: React.StatelessComponent<NavigatorProps> = ( { children }, { router } ) => { invariant(router, "You should not use <Navigator> outside a <Router>"); const { history, route: { location: { search } } } = router; const navigate = (url, replace = false, preserveQs = false) => { const targetUrl = preserveQs ? url + search : url; replace ? history.replace(targetUrl) : history.push(targetUrl); window.scrollTo({ top: 0, behavior: "smooth" }); }; return children(navigate); }; Navigator.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ push: PropTypes.func.isRequired, replace: PropTypes.func.isRequired }).isRequired }) }; Navigator.displayName = "Navigator"; interface NavigatorLinkProps { replace?: boolean; to: string; children: ((navigate: () => any) => React.ReactElement<any>); } export const NavigatorLink: React.StatelessComponent<NavigatorLinkProps> = ({ children, replace, to }) => ( <Navigator>{navigate => children(() => navigate(to, replace))}</Navigator> ); NavigatorLink.displayName = "NavigatorLink"; export default Navigator;
import * as React from "react"; import { RouteComponentProps, withRouter } from "react-router"; interface NavigatorProps { children: ( navigate: (url: string, replace?: boolean, preserveQs?: boolean) => any ) => React.ReactElement<any>; } const Navigator = withRouter<NavigatorProps & RouteComponentProps<any>>( ({ children, location, history }) => { const { search } = location; const navigate = (url, replace = false, preserveQs = false) => { const targetUrl = preserveQs ? url + search : url; replace ? history.replace(targetUrl) : history.push(targetUrl); window.scrollTo({ top: 0, behavior: "smooth" }); }; return children(navigate); } ); Navigator.displayName = "Navigator"; interface NavigatorLinkProps { replace?: boolean; to: string; children: (navigate: () => any) => React.ReactElement<any>; } export const NavigatorLink: React.StatelessComponent<NavigatorLinkProps> = ({ children, replace, to }) => ( <Navigator>{navigate => children(() => navigate(to, replace))}</Navigator> ); NavigatorLink.displayName = "NavigatorLink"; export default Navigator;
Drop context and replace it with HOC
Drop context and replace it with HOC
TypeScript
bsd-3-clause
UITools/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,mociepka/saleor
--- +++ @@ -1,46 +1,30 @@ -import * as invariant from "invariant"; -import * as PropTypes from "prop-types"; import * as React from "react"; +import { RouteComponentProps, withRouter } from "react-router"; interface NavigatorProps { - children: (( + children: ( navigate: (url: string, replace?: boolean, preserveQs?: boolean) => any - ) => React.ReactElement<any>); + ) => React.ReactElement<any>; } -const Navigator: React.StatelessComponent<NavigatorProps> = ( - { children }, - { router } -) => { - invariant(router, "You should not use <Navigator> outside a <Router>"); - const { - history, - route: { - location: { search } - } - } = router; - const navigate = (url, replace = false, preserveQs = false) => { - const targetUrl = preserveQs ? url + search : url; - replace ? history.replace(targetUrl) : history.push(targetUrl); - window.scrollTo({ top: 0, behavior: "smooth" }); - }; +const Navigator = withRouter<NavigatorProps & RouteComponentProps<any>>( + ({ children, location, history }) => { + const { search } = location; + const navigate = (url, replace = false, preserveQs = false) => { + const targetUrl = preserveQs ? url + search : url; + replace ? history.replace(targetUrl) : history.push(targetUrl); + window.scrollTo({ top: 0, behavior: "smooth" }); + }; - return children(navigate); -}; -Navigator.contextTypes = { - router: PropTypes.shape({ - history: PropTypes.shape({ - push: PropTypes.func.isRequired, - replace: PropTypes.func.isRequired - }).isRequired - }) -}; + return children(navigate); + } +); Navigator.displayName = "Navigator"; interface NavigatorLinkProps { replace?: boolean; to: string; - children: ((navigate: () => any) => React.ReactElement<any>); + children: (navigate: () => any) => React.ReactElement<any>; } export const NavigatorLink: React.StatelessComponent<NavigatorLinkProps> = ({
15a3ea55841bb7079a0744e04bae72ed68dc2327
main.ts
main.ts
/* * Copyright (c) 2015 ARATA Mizuki * This software is released under the MIT license. * See LICENSE.txt. */ /// <reference path="ts/ComplexIntegralView.ts"/> window.addEventListener("DOMContentLoaded", () => { let canvas = <HTMLCanvasElement>document.getElementById("plane"); let view = new ComplexIntegralView(canvas); window.addEventListener("load", () => { view.adjustSize(); view.refresh(); }, false); let functionRadioButtons: HTMLInputElement[] = Array.prototype.filter.call(document.getElementsByName("function"), (e: HTMLElement) => e.tagName === "input" && e.getAttribute("type") === "radio"); functionRadioButtons.forEach(b => { let functionName = b.value; let func = WellknownFunctions[functionName]; if (!func) { console.error("function " + functionName + " not found"); } else { if (b.checked) { view.function = func; } b.addEventListener("change", () => { if (b.checked) { view.function = func; } }, false); } }); let keyCommandButtons: HTMLAnchorElement[] = Array.prototype.filter.call(document.getElementsByClassName("key-command"), (a: HTMLElement) => (a.tagName === "a" && a.accessKey)); keyCommandButtons.forEach(a => { a.addEventListener("click", event => { view.keyCommand(a.accessKey); }, false); }); }, false);
/* * Copyright (c) 2015 ARATA Mizuki * This software is released under the MIT license. * See LICENSE.txt. */ /// <reference path="ts/ComplexIntegralView.ts"/> var theView: ComplexIntegralView | undefined; window.addEventListener("DOMContentLoaded", () => { let canvas = <HTMLCanvasElement>document.getElementById("plane"); let view = new ComplexIntegralView(canvas); window.addEventListener("load", () => { view.adjustSize(); view.refresh(); }, false); theView = view; let functionRadioButtons: HTMLInputElement[] = Array.prototype.filter.call(document.getElementsByName("function"), (e: HTMLElement) => e.tagName === "input" && e.getAttribute("type") === "radio"); functionRadioButtons.forEach(b => { let functionName = b.value; let func = WellknownFunctions[functionName]; if (!func) { console.error("function " + functionName + " not found"); } else { if (b.checked) { view.function = func; } b.addEventListener("change", () => { if (b.checked) { view.function = func; } }, false); } }); let keyCommandButtons: HTMLAnchorElement[] = Array.prototype.filter.call(document.getElementsByClassName("key-command"), (a: HTMLElement) => (a.tagName === "a" && a.accessKey)); keyCommandButtons.forEach(a => { a.addEventListener("click", event => { view.keyCommand(a.accessKey); }, false); }); }, false);
Make the view object accessible from the browser console with `theView` variable
Make the view object accessible from the browser console with `theView` variable
TypeScript
mit
minoki/singularity
--- +++ @@ -6,6 +6,7 @@ /// <reference path="ts/ComplexIntegralView.ts"/> +var theView: ComplexIntegralView | undefined; window.addEventListener("DOMContentLoaded", () => { let canvas = <HTMLCanvasElement>document.getElementById("plane"); let view = new ComplexIntegralView(canvas); @@ -13,6 +14,7 @@ view.adjustSize(); view.refresh(); }, false); + theView = view; let functionRadioButtons: HTMLInputElement[] = Array.prototype.filter.call(document.getElementsByName("function"), (e: HTMLElement) => e.tagName === "input" && e.getAttribute("type") === "radio"); functionRadioButtons.forEach(b => { let functionName = b.value;
18df0b5624a50d936e1a0fa4f5f8cdd4dc9cab01
src/selectors/SelectorInventories.tsx
src/selectors/SelectorInventories.tsx
import { createSelector } from 'reselect'; import { filter, mapKeys, mapValues, lowerCase } from 'lodash'; const getProducts = (state: RXState) => state.products; const getInventories = (state: RXState) => state.inventories; const getSearchTerm = (state: RXState) => lowerCase(state.searchTerm); export const filteredInventories = createSelector( [getProducts, getInventories, getSearchTerm], (products, inventories, searchTerm) => { inventories = mapValues(inventories, (inventory) => ({ ...inventory, product: products[inventory.productId], })); if ( !searchTerm || searchTerm === '' ) { return inventories; } return mapKeys( filter(inventories, (inventory) => ( lowerCase(inventory.id).includes(searchTerm) || lowerCase(inventory.product && inventory.product.name).includes(searchTerm) )), 'id' ); } );
import { createSelector } from 'reselect'; import { filter, mapKeys, mapValues, reduce, lowerCase } from 'lodash'; const getProducts = (state: RXState) => state.products; const getInventories = (state: RXState) => state.inventories; const getOrderItems = (state: RXState) => state.orderItems; const getSearchTerm = (state: RXState) => lowerCase(state.searchTerm); export const filteredInventories = createSelector( [getProducts, getInventories, getOrderItems, getSearchTerm], (products, inventories, orderItems, searchTerm) => { inventories = mapValues(inventories, (inventory) => ({ ...inventory, product: products[inventory.productId], reserved: reduce( orderItems, (sum, orderItem) => { const quantity = orderItem.productId === inventory.productId ? orderItem.quantity : 0; return sum + quantity; }, 0, ), })); if ( !searchTerm || searchTerm === '' ) { return inventories; } return mapKeys( filter(inventories, (inventory) => ( lowerCase(inventory.id).includes(searchTerm) || lowerCase(inventory.product && inventory.product.name).includes(searchTerm) )), 'id' ); } );
Fix reserved quantity in inventories
Fix reserved quantity in inventories
TypeScript
mit
luchillo17/porcelain-factory,luchillo17/porcelain-factory
--- +++ @@ -1,16 +1,26 @@ import { createSelector } from 'reselect'; -import { filter, mapKeys, mapValues, lowerCase } from 'lodash'; +import { filter, mapKeys, mapValues, reduce, lowerCase } from 'lodash'; const getProducts = (state: RXState) => state.products; const getInventories = (state: RXState) => state.inventories; +const getOrderItems = (state: RXState) => state.orderItems; const getSearchTerm = (state: RXState) => lowerCase(state.searchTerm); export const filteredInventories = createSelector( - [getProducts, getInventories, getSearchTerm], - (products, inventories, searchTerm) => { + [getProducts, getInventories, getOrderItems, getSearchTerm], + (products, inventories, orderItems, searchTerm) => { inventories = mapValues(inventories, (inventory) => ({ ...inventory, product: products[inventory.productId], + reserved: reduce( + orderItems, + (sum, orderItem) => { + const quantity = orderItem.productId === inventory.productId ? + orderItem.quantity : 0; + return sum + quantity; + }, + 0, + ), })); if (
ba17b144e7ea1eb64010a3b5de1cd8b6b914f057
src/util/notifications.ts
src/util/notifications.ts
import { browser, Notifications } from 'webextension-polyfill-ts' import * as noop from 'lodash/fp/noop' export const DEF_ICON_URL = '/img/worldbrain-logo-narrow.png' export const DEF_TYPE = 'basic' const onClickListeners = new Map<string, Function>() browser.notifications.onClicked.addListener(id => { browser.notifications.clear(id) const listener = onClickListeners.get(id) listener(id) onClickListeners.delete(id) // Manually clean up ref }) async function createNotification( notifOptions: Notifications.CreateNotificationOptions, onClick = noop as Function, ) { const id = await browser.notifications.create({ type: DEF_TYPE, iconUrl: DEF_ICON_URL, ...notifOptions, }) onClickListeners.set(id, onClick) } export default createNotification
import { browser, Notifications } from 'webextension-polyfill-ts' import * as noop from 'lodash/fp/noop' export const DEF_ICON_URL = '/img/worldbrain-logo-narrow.png' export const DEF_TYPE = 'basic' // Chrome allows some extra notif opts that the standard web ext API doesn't support export interface NotifOpts extends Notifications.CreateNotificationOptions { [chromeKeys: string]: any } const onClickListeners = new Map<string, Function>() browser.notifications.onClicked.addListener(id => { browser.notifications.clear(id) const listener = onClickListeners.get(id) listener(id) onClickListeners.delete(id) // Manually clean up ref }) /** * Firefox supports only a subset of notif options. If you pass unknowns, it throws Errors. * So filter them down if browser is FF, else nah. */ function filterOpts({ type, iconUrl, title, message, ...rest }: NotifOpts): NotifOpts { const opts = { type, iconUrl, title, message } return browser.runtime.getBrowserInfo != null ? opts : { ...opts, ...rest } } async function createNotification( notifOptions: NotifOpts, onClick = noop as Function, ) { const id = await browser.notifications.create(filterOpts({ type: DEF_TYPE, iconUrl: DEF_ICON_URL, ...notifOptions, })) onClickListeners.set(id, onClick) } export default createNotification
Set up notif module to filter out unknown opts on FF
Set up notif module to filter out unknown opts on FF - FF only supports a small subset of web ext API notif options - filter others out if FF, as it will throw Errors on unexpected options... annoying
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -3,6 +3,11 @@ export const DEF_ICON_URL = '/img/worldbrain-logo-narrow.png' export const DEF_TYPE = 'basic' + +// Chrome allows some extra notif opts that the standard web ext API doesn't support +export interface NotifOpts extends Notifications.CreateNotificationOptions { + [chromeKeys: string]: any +} const onClickListeners = new Map<string, Function>() @@ -14,15 +19,26 @@ onClickListeners.delete(id) // Manually clean up ref }) +/** + * Firefox supports only a subset of notif options. If you pass unknowns, it throws Errors. + * So filter them down if browser is FF, else nah. + */ +function filterOpts({ type, iconUrl, title, message, ...rest }: NotifOpts): NotifOpts { + const opts = { type, iconUrl, title, message } + return browser.runtime.getBrowserInfo != null + ? opts + : { ...opts, ...rest } +} + async function createNotification( - notifOptions: Notifications.CreateNotificationOptions, + notifOptions: NotifOpts, onClick = noop as Function, ) { - const id = await browser.notifications.create({ + const id = await browser.notifications.create(filterOpts({ type: DEF_TYPE, iconUrl: DEF_ICON_URL, ...notifOptions, - }) + })) onClickListeners.set(id, onClick) }
785e88200dcae6eb1ed7bc3eb07e8353fd1ccca1
src/ediHighlightProvider.ts
src/ediHighlightProvider.ts
import { DocumentHighlightProvider, DocumentHighlight, MarkedString, TextDocument, CancellationToken, Position, Range } from 'vscode'; import { EdiController } from './ediController'; import { Parser } from './parser'; import { Constants } from './constants' import { Document } from './document' export class EdiHighlightProvider implements DocumentHighlightProvider { private ediController: EdiController; private parser: Parser; constructor(ediController: EdiController) { this.ediController = ediController; this.parser = new Parser(); } public async provideDocumentHighlights(document: TextDocument, position: Position, token: CancellationToken): Promise<DocumentHighlight[]> { let text = document.getText(); let doc = Document.create(text); let segments = this.parser.parseSegments(text); let realPosition = doc.positionToIndex(position.line, position.character); let selectedSegment = segments.find(x => realPosition >= x.startIndex && realPosition <= x.endIndex); let startLine = doc.indexToPosition(selectedSegment.startIndex); let endLine = doc.indexToPosition(selectedSegment.endIndex); return [new DocumentHighlight(new Range(new Position(startLine.line, startLine.character), new Position(endLine.line, endLine.character)))]; } } class LineIndex { public length: number; public line: number; public startIndex: number; constructor(length: number, line: number, startIndex: number) { this.length = length; this.line = line; this.startIndex = startIndex; } }
import { DocumentHighlightProvider, DocumentHighlight, MarkedString, TextDocument, CancellationToken, Position, Range, DocumentHighlightKind } from 'vscode'; import { EdiController } from './ediController'; import { Parser } from './parser'; import { Constants } from './constants' import { Document } from './document' export class EdiHighlightProvider implements DocumentHighlightProvider { private ediController: EdiController; private parser: Parser; constructor(ediController: EdiController) { this.ediController = ediController; this.parser = new Parser(); } public async provideDocumentHighlights(document: TextDocument, position: Position, token: CancellationToken): Promise<DocumentHighlight[]> { let text = document.getText(); let doc = Document.create(text); let segments = this.parser.parseSegments(text); let realPosition = doc.positionToIndex(position.line, position.character); let selectedSegment = segments.find(x => realPosition >= x.startIndex && realPosition <= x.endIndex); let startLine = doc.indexToPosition(selectedSegment.startIndex); let endLine = doc.indexToPosition(selectedSegment.endIndex); return [new DocumentHighlight(new Range(new Position(startLine.line, startLine.character), new Position(endLine.line, endLine.character)), DocumentHighlightKind.Read)]; } } class LineIndex { public length: number; public line: number; public startIndex: number; constructor(length: number, line: number, startIndex: number) { this.length = length; this.line = line; this.startIndex = startIndex; } }
Use the read color for highlights.
Use the read color for highlights.
TypeScript
mit
Silvenga/vscode-edi-x12-support,Silvenga/vscode-edi-x12-support
--- +++ @@ -1,4 +1,4 @@ -import { DocumentHighlightProvider, DocumentHighlight, MarkedString, TextDocument, CancellationToken, Position, Range } from 'vscode'; +import { DocumentHighlightProvider, DocumentHighlight, MarkedString, TextDocument, CancellationToken, Position, Range, DocumentHighlightKind } from 'vscode'; import { EdiController } from './ediController'; import { Parser } from './parser'; import { Constants } from './constants' @@ -26,7 +26,7 @@ let startLine = doc.indexToPosition(selectedSegment.startIndex); let endLine = doc.indexToPosition(selectedSegment.endIndex); - return [new DocumentHighlight(new Range(new Position(startLine.line, startLine.character), new Position(endLine.line, endLine.character)))]; + return [new DocumentHighlight(new Range(new Position(startLine.line, startLine.character), new Position(endLine.line, endLine.character)), DocumentHighlightKind.Read)]; } }
67517dd28cbf001dc1bf61ffe9c75b892aedfc75
src/lib/typography/index.ts
src/lib/typography/index.ts
import { NgModule } from '@angular/core'; import { AdjustMarginDirective, Display1Directive, Display2Directive, Display3Directive, Display4Directive, HeadlineDirective, TitleDirective, Subheading1Directive, Subheading2Directive, Body1Directive, Body2Directive, CaptionDirective } from './typography.directive'; const TYPOGRAPHY_DIRECTIVES = [ AdjustMarginDirective, Display1Directive, Display2Directive, Display3Directive, Display4Directive, HeadlineDirective, TitleDirective, Subheading1Directive, Subheading2Directive, Body1Directive, Body2Directive, CaptionDirective ]; @NgModule({ exports: [TYPOGRAPHY_DIRECTIVES], declarations: [TYPOGRAPHY_DIRECTIVES], }) export class TypographyModule { }
import { NgModule } from '@angular/core'; import { Typography, AdjustMarginDirective, Display1Directive, Display2Directive, Display3Directive, Display4Directive, HeadlineDirective, TitleDirective, Subheading1Directive, Subheading2Directive, Body1Directive, Body2Directive, CaptionDirective } from './typography.directive'; const TYPOGRAPHY_DIRECTIVES = [ Typography, AdjustMarginDirective, Display1Directive, Display2Directive, Display3Directive, Display4Directive, HeadlineDirective, TitleDirective, Subheading1Directive, Subheading2Directive, Body1Directive, Body2Directive, CaptionDirective ]; @NgModule({ exports: [TYPOGRAPHY_DIRECTIVES], declarations: [TYPOGRAPHY_DIRECTIVES], }) export class TypographyModule { }
Fix missing module import of
fix(typography): Fix missing module import of [typography]
TypeScript
mit
trimox/angular-mdc-web,trimox/angular-mdc-web
--- +++ @@ -1,37 +1,39 @@ import { NgModule } from '@angular/core'; import { - AdjustMarginDirective, - Display1Directive, - Display2Directive, - Display3Directive, - Display4Directive, - HeadlineDirective, - TitleDirective, - Subheading1Directive, - Subheading2Directive, - Body1Directive, - Body2Directive, - CaptionDirective + Typography, + AdjustMarginDirective, + Display1Directive, + Display2Directive, + Display3Directive, + Display4Directive, + HeadlineDirective, + TitleDirective, + Subheading1Directive, + Subheading2Directive, + Body1Directive, + Body2Directive, + CaptionDirective } from './typography.directive'; const TYPOGRAPHY_DIRECTIVES = [ - AdjustMarginDirective, - Display1Directive, - Display2Directive, - Display3Directive, - Display4Directive, - HeadlineDirective, - TitleDirective, - Subheading1Directive, - Subheading2Directive, - Body1Directive, - Body2Directive, - CaptionDirective + Typography, + AdjustMarginDirective, + Display1Directive, + Display2Directive, + Display3Directive, + Display4Directive, + HeadlineDirective, + TitleDirective, + Subheading1Directive, + Subheading2Directive, + Body1Directive, + Body2Directive, + CaptionDirective ]; @NgModule({ - exports: [TYPOGRAPHY_DIRECTIVES], - declarations: [TYPOGRAPHY_DIRECTIVES], + exports: [TYPOGRAPHY_DIRECTIVES], + declarations: [TYPOGRAPHY_DIRECTIVES], }) export class TypographyModule { }
323d6eeb52545e8f7e515b4f66e20fe93c46f990
src/index.ts
src/index.ts
export { default as default } from './ketting'; export { default as Ketting } from './ketting'; export { default as Resource } from './resource';
import BaseKetting from './ketting'; import Resource from './resource'; class Ketting extends BaseKetting { static Resource = Resource; } module.exports = Ketting;
Fix the default export for browser distros and nodejs
Fix the default export for browser distros and nodejs
TypeScript
mit
evert/restl,evert/ketting,evert/ketting
--- +++ @@ -1,3 +1,10 @@ -export { default as default } from './ketting'; -export { default as Ketting } from './ketting'; -export { default as Resource } from './resource'; +import BaseKetting from './ketting'; +import Resource from './resource'; + +class Ketting extends BaseKetting { + + static Resource = Resource; + +} + +module.exports = Ketting;
9615f74447881f8d9be317c3da3e08c0ee764e97
test/server/countryMappingSpec.ts
test/server/countryMappingSpec.ts
/* * Copyright (c) 2014-2022 Bjoern Kimminich & the OWASP Juice Shop contributors. * SPDX-License-Identifier: MIT */ import sinon = require('sinon') const chai = require('chai') const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) describe('countryMapping', () => { const countryMapping = require('../../routes/countryMapping') let req: any let res: any beforeEach(() => { req = {} res = { send: sinon.spy(), status: sinon.stub().returns({ send: sinon.spy() }) } }) it('should return configured country mappings', () => { countryMapping({ get: sinon.stub().withArgs('ctf.countryMapping').returns('TEST') })(req, res) expect(res.send).to.have.been.calledWith('TEST') }) it('should return server error when configuration has no country mappings', () => { countryMapping({ get: sinon.stub().withArgs('ctf.countryMapping').returns(null) })(req, res) expect(res.status).to.have.been.calledWith(500) }) it('should return server error for default configuration', () => { countryMapping()(req, res) expect(res.status).to.have.been.calledWith(500) }) })
/* * Copyright (c) 2014-2022 Bjoern Kimminich & the OWASP Juice Shop contributors. * SPDX-License-Identifier: MIT */ import sinon = require('sinon') const config = require('config') const chai = require('chai') const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) describe('countryMapping', () => { const countryMapping = require('../../routes/countryMapping') let req: any let res: any beforeEach(() => { req = {} res = { send: sinon.spy(), status: sinon.stub().returns({ send: sinon.spy() }) } }) it('should return configured country mappings', () => { countryMapping({ get: sinon.stub().withArgs('ctf.countryMapping').returns('TEST') })(req, res) expect(res.send).to.have.been.calledWith('TEST') }) it('should return server error when configuration has no country mappings', () => { countryMapping({ get: sinon.stub().withArgs('ctf.countryMapping').returns(null) })(req, res) expect(res.status).to.have.been.calledWith(500) }) it('should return ' + (config.get('ctf.countryMapping') ? 'no ' : '') + 'server error for active configuration from config/' + process.env.NODE_ENV + '.yml', () => { countryMapping()(req, res) if (config.get('ctf.countryMapping')) { expect(res.send).to.have.been.calledWith(config.get('ctf.countryMapping')) } else { expect(res.status).to.have.been.calledWith(500) } }) })
Fix country mapping test for FBCTF configuration
Fix country mapping test for FBCTF configuration
TypeScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -4,6 +4,7 @@ */ import sinon = require('sinon') +const config = require('config') const chai = require('chai') const sinonChai = require('sinon-chai') const expect = chai.expect @@ -31,9 +32,13 @@ expect(res.status).to.have.been.calledWith(500) }) - it('should return server error for default configuration', () => { + it('should return ' + (config.get('ctf.countryMapping') ? 'no ' : '') + 'server error for active configuration from config/' + process.env.NODE_ENV + '.yml', () => { countryMapping()(req, res) - expect(res.status).to.have.been.calledWith(500) + if (config.get('ctf.countryMapping')) { + expect(res.send).to.have.been.calledWith(config.get('ctf.countryMapping')) + } else { + expect(res.status).to.have.been.calledWith(500) + } }) })
8c987e4ad20767681ca7c018cee53cb821af6d55
source/WebApp/ts/state/handlers/defaults.ts
source/WebApp/ts/state/handlers/defaults.ts
import { languages, LanguageName } from '../../helpers/languages'; import { targets, TargetName } from '../../helpers/targets'; import help from '../../helpers/help'; import asLookup from '../../helpers/as-lookup'; const code = asLookup({ [languages.csharp]: 'using System;\r\npublic class C {\r\n public void M() {\r\n }\r\n}', [languages.vb]: 'Imports System\r\nPublic Class C\r\n Public Sub M()\r\n End Sub\r\nEnd Class', [languages.fsharp]: 'open System\r\ntype C() =\r\n member _.M() = ()', [`${languages.csharp}.run`]: `using System;\r\n${help.run.csharp}\r\npublic static class Program {\r\n public static void Main() {\r\n Console.WriteLine("🌄");\r\n }\r\n}`, [`${languages.vb}.run`]: 'Imports System\r\nPublic Module Program\r\n Public Sub Main()\r\n Console.WriteLine("🌄")\r\n End Sub\r\nEnd Module', [`${languages.fsharp}.run`]: 'printfn "🌄"' } as const); export default { getOptions: () => ({ language: languages.csharp, target: languages.csharp, release: false }), getCode: (language: LanguageName|undefined, target: TargetName|string|undefined) => code[ (target === targets.run ? language + '.run' : language) as string ] ?? '' };
import { languages, LanguageName } from '../../helpers/languages'; import { targets, TargetName } from '../../helpers/targets'; import help from '../../helpers/help'; import asLookup from '../../helpers/as-lookup'; const code = asLookup({ [languages.csharp]: 'using System;\r\npublic class C {\r\n public void M() {\r\n }\r\n}', [languages.vb]: 'Imports System\r\nPublic Class C\r\n Public Sub M()\r\n End Sub\r\nEnd Class', [languages.fsharp]: 'open System\r\ntype C() =\r\n member _.M() = ()', [`${languages.csharp}.run`]: `${help.run.csharp}\r\nusing System;\r\n\r\nConsole.WriteLine("🌄");`, [`${languages.vb}.run`]: 'Imports System\r\nPublic Module Program\r\n Public Sub Main()\r\n Console.WriteLine("🌄")\r\n End Sub\r\nEnd Module', [`${languages.fsharp}.run`]: 'printfn "🌄"' } as const); export default { getOptions: () => ({ language: languages.csharp, target: languages.csharp, release: false }), getCode: (language: LanguageName|undefined, target: TargetName|string|undefined) => code[ (target === targets.run ? language + '.run' : language) as string ] ?? '' };
Simplify default code in Run mode
Simplify default code in Run mode
TypeScript
bsd-2-clause
ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab
--- +++ @@ -8,7 +8,7 @@ [languages.vb]: 'Imports System\r\nPublic Class C\r\n Public Sub M()\r\n End Sub\r\nEnd Class', [languages.fsharp]: 'open System\r\ntype C() =\r\n member _.M() = ()', - [`${languages.csharp}.run`]: `using System;\r\n${help.run.csharp}\r\npublic static class Program {\r\n public static void Main() {\r\n Console.WriteLine("🌄");\r\n }\r\n}`, + [`${languages.csharp}.run`]: `${help.run.csharp}\r\nusing System;\r\n\r\nConsole.WriteLine("🌄");`, [`${languages.vb}.run`]: 'Imports System\r\nPublic Module Program\r\n Public Sub Main()\r\n Console.WriteLine("🌄")\r\n End Sub\r\nEnd Module', [`${languages.fsharp}.run`]: 'printfn "🌄"' } as const);
2795b1cf5bf1bc3dc5cb4e97596fb28aa5c92099
src/components/atoms/ToolbarButtonGroup.tsx
src/components/atoms/ToolbarButtonGroup.tsx
import styled from '../../lib/styled' export default styled.div` border-radius: 2px; border: solid 1px ${({ theme }) => theme.colors.border}; & > button { margin: 0; border: 0; border-right: 1px solid ${({ theme }) => theme.colors.border}; border-radius: 0; &:last-child { border-right: 0; } } `
import styled from '../../lib/styled' export default styled.div` border-radius: 2px; border: solid 1px ${({ theme }) => theme.colors.border}; & > button { margin: 0; border: 0; border-right: 1px solid ${({ theme }) => theme.colors.border}; border-radius: 0; &:first-child { border-top-left-radius: 2px; border-bottom-left-radius: 2px; } &:last-child { border-right: 0; border-top-right-radius: 2px; border-bottom-right-radius: 2px; } } `
Fix toolbar button group border radius style
Fix toolbar button group border radius style
TypeScript
mit
Sarah-Seo/Inpad,Sarah-Seo/Inpad
--- +++ @@ -8,8 +8,14 @@ border: 0; border-right: 1px solid ${({ theme }) => theme.colors.border}; border-radius: 0; + &:first-child { + border-top-left-radius: 2px; + border-bottom-left-radius: 2px; + } &:last-child { border-right: 0; + border-top-right-radius: 2px; + border-bottom-right-radius: 2px; } } `
f3d1b46dcba63bf70900c9ca607bb1aabf0047dd
tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts
tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts
/// <reference path="fourslash.ts"/> ////class List<T> { //// constructor(public a: boolean, public b: T, c: number) { //// var local = 0; //// } ////} verify.navigationBar([ { "text": "<global>", "kind": "module", "childItems": [ { "text": "List", "kind": "class" } ] }, { "text": "List", "kind": "class", "childItems": [ { "text": "constructor", "kind": "constructor" }, { "text": "a", "kind": "property", "kindModifiers": "public" }, { "text": "b", "kind": "property", "kindModifiers": "public" } ], "indent": 1 } ]);
/// <reference path="fourslash.ts"/> ////class List<T> { //// constructor(public a: boolean, private b: T, readonly c: string, d: number) { //// var local = 0; //// } ////} verify.navigationBar([ { "text": "<global>", "kind": "module", "childItems": [ { "text": "List", "kind": "class" } ] }, { "text": "List", "kind": "class", "childItems": [ { "text": "constructor", "kind": "constructor" }, { "text": "a", "kind": "property", "kindModifiers": "public" }, { "text": "b", "kind": "property", "kindModifiers": "private" }, { "text": "c", "kind": "property" } ], "indent": 1 } ]);
Add tests for private and readonly parameter properties in navbar
Add tests for private and readonly parameter properties in navbar
TypeScript
apache-2.0
weswigham/TypeScript,minestarks/TypeScript,Eyas/TypeScript,plantain-00/TypeScript,kitsonk/TypeScript,vilic/TypeScript,nojvek/TypeScript,thr0w/Thr0wScript,thr0w/Thr0wScript,synaptek/TypeScript,jeremyepling/TypeScript,erikmcc/TypeScript,vilic/TypeScript,vilic/TypeScript,thr0w/Thr0wScript,DLehenbauer/TypeScript,synaptek/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,erikmcc/TypeScript,basarat/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,chuckjaz/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,TukekeSoft/TypeScript,basarat/TypeScript,microsoft/TypeScript,kpreisser/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,mihailik/TypeScript,jwbay/TypeScript,mihailik/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,jwbay/TypeScript,weswigham/TypeScript,kitsonk/TypeScript,TukekeSoft/TypeScript,Eyas/TypeScript,plantain-00/TypeScript,nojvek/TypeScript,DLehenbauer/TypeScript,erikmcc/TypeScript,kitsonk/TypeScript,jeremyepling/TypeScript,jwbay/TypeScript,TukekeSoft/TypeScript,donaldpipowitch/TypeScript,Microsoft/TypeScript,jwbay/TypeScript,alexeagle/TypeScript,basarat/TypeScript,Microsoft/TypeScript,basarat/TypeScript,Eyas/TypeScript,Eyas/TypeScript,chuckjaz/TypeScript,jeremyepling/TypeScript,chuckjaz/TypeScript,microsoft/TypeScript,thr0w/Thr0wScript,synaptek/TypeScript,alexeagle/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,chuckjaz/TypeScript,mihailik/TypeScript,RyanCavanaugh/TypeScript,DLehenbauer/TypeScript,vilic/TypeScript,plantain-00/TypeScript,mihailik/TypeScript,synaptek/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,Microsoft/TypeScript,DLehenbauer/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,plantain-00/TypeScript,erikmcc/TypeScript,nojvek/TypeScript
--- +++ @@ -1,7 +1,7 @@ /// <reference path="fourslash.ts"/> ////class List<T> { -//// constructor(public a: boolean, public b: T, c: number) { +//// constructor(public a: boolean, private b: T, readonly c: string, d: number) { //// var local = 0; //// } ////} @@ -33,7 +33,11 @@ { "text": "b", "kind": "property", - "kindModifiers": "public" + "kindModifiers": "private" + }, + { + "text": "c", + "kind": "property" } ], "indent": 1
143e2c714a5aadfec7f1cf1cdb7ec9edaddfd293
lib/msal-electron-proof-of-concept/src/AppConfig/PublicClientApplication.ts
lib/msal-electron-proof-of-concept/src/AppConfig/PublicClientApplication.ts
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { AuthenticationParameters } from './AuthenticationParameters'; import { AuthOptions } from './AuthOptions'; import { ClientApplicationBase } from './ClientApplicationBase'; import { ClientConfigurationError } from './Error/ClientConfigurationError'; import { strict as assert } from 'assert'; /** * PublicClientApplication class * * This class can be instantiated into objects that the developer * can use in order to acquire tokens. */ export class PublicClientApplication extends ClientApplicationBase { constructor(authOptions: AuthOptions) { super(authOptions); } /** * The acquireToken method uses the Authorization Code * Grant to retrieve an access token from the AAD authorization server, * which can be used to make authenticated calls to an resource server * such as MS Graph. */ public acquireToken(request: AuthenticationParameters): string { // Validate and filter scopes this.validateInputScopes(request.scopes); const scope = request.scopes.join(' ').toLowerCase(); return 'Access Token'; } private validateInputScopes(scopes: string[]): void { // Check that scopes are present assert(scopes, ClientConfigurationError.createScopesRequiredError(scopes)); // Check that scopes is an array if (!Array.isArray(scopes)) { throw ClientConfigurationError.createScopesNonArrayError(scopes); } // Check that scopes array is non-empty if (scopes.length < 1) { throw ClientConfigurationError.createEmptyScopesArrayError(scopes); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { AuthenticationParameters } from './AuthenticationParameters'; import { AuthOptions } from './AuthOptions'; import { ClientApplicationBase } from './ClientApplicationBase'; import { ClientConfigurationError } from './Error/ClientConfigurationError'; import { strict as assert } from 'assert'; /** * PublicClientApplication class * * This class can be instantiated into objects that the developer * can use in order to acquire tokens. */ export class PublicClientApplication extends ClientApplicationBase { constructor(authOptions: AuthOptions) { super(authOptions); } /** * The acquireToken method uses the Authorization Code * Grant to retrieve an access token from the AAD authorization server, * which can be used to make authenticated calls to an resource server * such as MS Graph. */ public acquireToken(request: AuthenticationParameters): string { // Validate and filter scopes this.validateInputScopes(request.scopes); return 'Access Token'; } private validateInputScopes(scopes: string[]): void { // Check that scopes are present assert(scopes, ClientConfigurationError.createScopesRequiredError(scopes)); // Check that scopes is an array if (!Array.isArray(scopes)) { throw ClientConfigurationError.createScopesNonArrayError(scopes); } // Check that scopes array is non-empty if (scopes.length < 1) { throw ClientConfigurationError.createEmptyScopesArrayError(scopes); } } }
Remove useless scope join in PublicCLientApplication for msal-electron
Remove useless scope join in PublicCLientApplication for msal-electron
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -27,7 +27,6 @@ public acquireToken(request: AuthenticationParameters): string { // Validate and filter scopes this.validateInputScopes(request.scopes); - const scope = request.scopes.join(' ').toLowerCase(); return 'Access Token'; }
f96a94199c2618203f8c11b255e82fc9e28f6d73
TameGame/Core/UninitializedField.ts
TameGame/Core/UninitializedField.ts
module TameGame { /** * Declares a lazily-initialized field on an object * * This can be used when a field is costly to initialize (in terms of performance or storage space) and is seldom used * or as a way to declare a field in an object prototype with a value that depends on how the object is used */ export function defineUnintializedField<TObjType, TFieldType>(obj: TObjType, fieldName: string, initialize: (obj: TObjType) => TFieldType) { // Relies on the standard JavaScript behaviour for 'this' (not captured by a closure, but referring to the calling object) function getFunction() { if (Object.isFrozen(this) || Object.isSealed(this)) { return initialize(this); } var newVal = initialize(this); Object.defineProperty(this, fieldName, { configurable: true, enumerable: true, writable: true, value: newVal }); return newVal; } var setting: boolean = false; function setFunction(val: TFieldType) { Object.defineProperty(this, fieldName, { configurable: true, enumerable: true, writable: true, value: val }); } Object.defineProperty(obj, fieldName, { configurable: true, enumerable: true, get: getFunction, set: setFunction }); } }
module TameGame { /** * Declares a lazily-initialized field on an object * * This can be used when a field is costly to initialize (in terms of performance or storage space) and is seldom used * or as a way to declare a field in an object prototype with a value that depends on how the object is used */ export function defineUnintializedField<TObjType, TFieldType>(obj: TObjType, fieldName: string, initialize: (obj: TObjType, defineProperty: (descriptor: PropertyDescriptor) => void) => TFieldType) { // Relies on the standard JavaScript behaviour for 'this' (not captured by a closure, but referring to the calling object) function getFunction() { var initialized = false; var newVal = initialize(this, (descriptor) => { Object.defineProperty(this, fieldName, descriptor); initialized = true; }); if (!initialized) { Object.defineProperty(this, fieldName, { configurable: true, enumerable: true, writable: true, value: newVal }); } return newVal; } var setting: boolean = false; function setFunction(val: TFieldType) { Object.defineProperty(this, fieldName, { configurable: true, enumerable: true, writable: true, value: val }); } Object.defineProperty(obj, fieldName, { configurable: true, enumerable: true, get: getFunction, set: setFunction }); } }
Add a way to define the uninitialized property via a defineProperty call
Add a way to define the uninitialized property via a defineProperty call
TypeScript
apache-2.0
TameGame/Engine,TameGame/Engine,TameGame/Engine
--- +++ @@ -5,15 +5,20 @@ * This can be used when a field is costly to initialize (in terms of performance or storage space) and is seldom used * or as a way to declare a field in an object prototype with a value that depends on how the object is used */ - export function defineUnintializedField<TObjType, TFieldType>(obj: TObjType, fieldName: string, initialize: (obj: TObjType) => TFieldType) { + export function defineUnintializedField<TObjType, TFieldType>(obj: TObjType, fieldName: string, initialize: (obj: TObjType, defineProperty: (descriptor: PropertyDescriptor) => void) => TFieldType) { // Relies on the standard JavaScript behaviour for 'this' (not captured by a closure, but referring to the calling object) function getFunction() { - if (Object.isFrozen(this) || Object.isSealed(this)) { - return initialize(this); + var initialized = false; + + var newVal = initialize(this, (descriptor) => { + Object.defineProperty(this, fieldName, descriptor); + initialized = true; + }); + + if (!initialized) { + Object.defineProperty(this, fieldName, { configurable: true, enumerable: true, writable: true, value: newVal }); } - var newVal = initialize(this); - Object.defineProperty(this, fieldName, { configurable: true, enumerable: true, writable: true, value: newVal }); return newVal; }
875e0e62fa91d85c28208f00e4dd2b820d446e2f
client/Library/SpellLibrary.ts
client/Library/SpellLibrary.ts
module ImprovedInitiative { export class SpellLibrary { Spells = ko.observableArray<SpellListing>([]); SpellsByNameRegex = ko.computed(() => { const allSpellNames = this.Spells().map(s => s.Name()); if (allSpellNames.length === 0) { return new RegExp('a^'); } return new RegExp(allSpellNames.join("|"), "gim"); }); constructor() { $.ajax("../spells/").done(this.addSpellListings); const customSpells = Store.List(Store.Spells); customSpells.forEach(id => { var spell = { ...Spell.Default(), ...Store.Load<Spell>(Store.Spells, id) }; this.Spells.push(new SpellListing(id, spell.Name, Spell.GetKeywords(spell), null, "localStorage", spell)); }); const appInsights: Client = window["appInsights"]; appInsights.trackEvent("CustomSpells", { Count: customSpells.length.toString() }); } private addSpellListings = (listings: { Id: string, Name: string, Keywords: string, Link: string }[]) => { listings.sort((c1, c2) => { return c1.Name.toLocaleLowerCase() > c2.Name.toLocaleLowerCase() ? 1 : -1; }); ko.utils.arrayPushAll<SpellListing>(this.Spells, listings.map(c => { return new SpellListing(c.Id, c.Name, c.Keywords, c.Link, "server"); })); } } }
module ImprovedInitiative { export class SpellLibrary { Spells = ko.observableArray<SpellListing>([]); SpellsByNameRegex = ko.computed(() => { const allSpellNames = this.Spells().map(s => s.Name()); if (allSpellNames.length === 0) { return new RegExp('a^'); } return new RegExp(`\\b(${allSpellNames.join("|")})\\b`, "gim"); }); constructor() { $.ajax("../spells/").done(this.addSpellListings); const customSpells = Store.List(Store.Spells); customSpells.forEach(id => { var spell = { ...Spell.Default(), ...Store.Load<Spell>(Store.Spells, id) }; this.Spells.push(new SpellListing(id, spell.Name, Spell.GetKeywords(spell), null, "localStorage", spell)); }); const appInsights: Client = window["appInsights"]; appInsights.trackEvent("CustomSpells", { Count: customSpells.length.toString() }); } private addSpellListings = (listings: { Id: string, Name: string, Keywords: string, Link: string }[]) => { listings.sort((c1, c2) => { return c1.Name.toLocaleLowerCase() > c2.Name.toLocaleLowerCase() ? 1 : -1; }); ko.utils.arrayPushAll<SpellListing>(this.Spells, listings.map(c => { return new SpellListing(c.Id, c.Name, c.Keywords, c.Link, "server"); })); } } }
Enforce word boundaries when finding spell names
Enforce word boundaries when finding spell names
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -6,7 +6,7 @@ if (allSpellNames.length === 0) { return new RegExp('a^'); } - return new RegExp(allSpellNames.join("|"), "gim"); + return new RegExp(`\\b(${allSpellNames.join("|")})\\b`, "gim"); }); constructor() {
762dcef3697b03ad0815e442c09c3b77672cbdde
visualization/app/codeCharta/state/store/fileSettings/markedPackages/markedPackages.reducer.ts
visualization/app/codeCharta/state/store/fileSettings/markedPackages/markedPackages.reducer.ts
import { MarkedPackagesAction, MarkedPackagesActions, setMarkedPackages } from "./markedPackages.actions" import { MarkedPackage } from "../../../../codeCharta.model" import { addItemToArray, removeItemFromArray } from "../../../../util/reduxHelper" const clone = require("rfdc")() export function markedPackages(state: MarkedPackage[] = setMarkedPackages().payload, action: MarkedPackagesAction): MarkedPackage[] { switch (action.type) { case MarkedPackagesActions.SET_MARKED_PACKAGES: return clone(action.payload) case MarkedPackagesActions.MARK_PACKAGE: return addItemToArray(state, action.payload) case MarkedPackagesActions.UNMARK_PACKAGE: return removeItemFromArray(state, action.payload) default: return state } }
import { MarkedPackagesAction, MarkedPackagesActions, setMarkedPackages } from "./markedPackages.actions" import { MarkedPackage } from "../../../../codeCharta.model" import { addItemToArray, removeItemFromArray } from "../../../../util/reduxHelper" export function markedPackages(state: MarkedPackage[] = setMarkedPackages().payload, action: MarkedPackagesAction): MarkedPackage[] { switch (action.type) { case MarkedPackagesActions.SET_MARKED_PACKAGES: return [...action.payload] case MarkedPackagesActions.MARK_PACKAGE: return addItemToArray(state, action.payload) case MarkedPackagesActions.UNMARK_PACKAGE: return removeItemFromArray(state, action.payload) default: return state } }
Refactor shallow copy instead of deep clone
Refactor shallow copy instead of deep clone
TypeScript
bsd-3-clause
MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta,MaibornWolff/codecharta
--- +++ @@ -1,12 +1,11 @@ import { MarkedPackagesAction, MarkedPackagesActions, setMarkedPackages } from "./markedPackages.actions" import { MarkedPackage } from "../../../../codeCharta.model" import { addItemToArray, removeItemFromArray } from "../../../../util/reduxHelper" -const clone = require("rfdc")() export function markedPackages(state: MarkedPackage[] = setMarkedPackages().payload, action: MarkedPackagesAction): MarkedPackage[] { switch (action.type) { case MarkedPackagesActions.SET_MARKED_PACKAGES: - return clone(action.payload) + return [...action.payload] case MarkedPackagesActions.MARK_PACKAGE: return addItemToArray(state, action.payload) case MarkedPackagesActions.UNMARK_PACKAGE:
9c454e51c49fb6b9116953ac714c51c619dced8b
test/test.ts
test/test.ts
import * as chai from 'chai'; chai.should(); describe('Array', () => { describe('#indexOf()', () => { it('should return -1 when the value is not present', () => { [1, 2, 3].indexOf(4).should.equal(-1); }); }); });
import {expect} from 'chai'; describe('Array', () => { describe('#indexOf()', () => { it('should return -1 when the value is not present', () => { expect([1, 2, 3].indexOf(4)).to.equal(-1); }); }); });
Use expect instead of should assertions
Use expect instead of should assertions
TypeScript
unlicense
rizadh/scheduler
--- +++ @@ -1,10 +1,9 @@ -import * as chai from 'chai'; -chai.should(); +import {expect} from 'chai'; describe('Array', () => { describe('#indexOf()', () => { it('should return -1 when the value is not present', () => { - [1, 2, 3].indexOf(4).should.equal(-1); + expect([1, 2, 3].indexOf(4)).to.equal(-1); }); }); });
9d14c5b680b07c206d3aa5356d68ae94ad1b8ad6
bmi-typescript/src/LabeledSlider.ts
bmi-typescript/src/LabeledSlider.ts
import xs, {Stream, MemoryStream} from 'xstream'; import {div, span, input, VNode} from '@cycle/dom'; import {DOMSource} from '@cycle/dom/xstream-typings.d.ts'; export interface LabeledSliderProps { label: string; unit: string; min: number; initial: number; max: number; } export type Sources = { DOM: DOMSource, props$: Stream<LabeledSliderProps>, } export type Sinks = { DOM: Stream<VNode>, value$: MemoryStream<number>, } function LabeledSlider(sources: Sources): Sinks { let props$: Stream<LabeledSliderProps> = sources.props$; let initialValue$ = props$.map(props => props.initial).take(1); let el$ = sources.DOM.select('.slider').elements(); let newValue$ = sources.DOM.select('.slider').events('input') .map(ev => parseInt((<HTMLInputElement> ev.target).value)); let value$ = xs.merge(initialValue$, newValue$).remember(); let vtree$ = xs.combine( (props, value) => div('.labeled-slider', [ span('.label', [ props.label + ' ' + value + props.unit ]), input('.slider', { attrs: {type: 'range', min: props.min, max: props.max, value: value} }) ]), props$, value$ ); return { DOM: vtree$, value$: value$, }; } export default LabeledSlider;
import xs, {Stream, MemoryStream} from 'xstream'; import {div, span, input, VNode} from '@cycle/dom'; import {DOMSource} from '@cycle/dom/xstream-typings'; export interface LabeledSliderProps { label: string; unit: string; min: number; initial: number; max: number; } export type Sources = { DOM: DOMSource, props$: Stream<LabeledSliderProps>, } export type Sinks = { DOM: Stream<VNode>, value$: MemoryStream<number>, } function LabeledSlider(sources: Sources): Sinks { let props$: Stream<LabeledSliderProps> = sources.props$; let initialValue$ = props$.map(props => props.initial).take(1); let el$ = sources.DOM.select('.slider').elements(); let newValue$ = sources.DOM.select('.slider').events('input') .map(ev => parseInt((<HTMLInputElement> ev.target).value)); let value$ = xs.merge(initialValue$, newValue$).remember(); let vtree$ = xs.combine( (props, value) => div('.labeled-slider', [ span('.label', [ props.label + ' ' + value + props.unit ]), input('.slider', { attrs: {type: 'range', min: props.min, max: props.max, value: value} }) ]), props$, value$ ); return { DOM: vtree$, value$: value$, }; } export default LabeledSlider;
Improve bmi-typescript example a bit
Improve bmi-typescript example a bit Use better import of xstream-typings in cycle/dom
TypeScript
mit
cyclejs/cycle-examples,mikekidder/cycle-examples,mikekidder/cycle-examples,cyclejs/cycle-examples,mikekidder/cycle-examples
--- +++ @@ -1,6 +1,6 @@ import xs, {Stream, MemoryStream} from 'xstream'; import {div, span, input, VNode} from '@cycle/dom'; -import {DOMSource} from '@cycle/dom/xstream-typings.d.ts'; +import {DOMSource} from '@cycle/dom/xstream-typings'; export interface LabeledSliderProps { label: string;
f507c227af574e57a774e2f87d115b02c8049986
src/dependument.ts
src/dependument.ts
/// <reference path="../typings/node/node.d.ts" /> import * as fs from 'fs'; export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } this.source = options.source; this.output = options.output; } writeOutput() { fs.writeFile(this.output, 'dependument test writeOutput', (err) => { if (err) throw err; console.log(`Output written to ${this.output}`); }); } }
/// <reference path="../typings/node/node.d.ts" /> import * as fs from 'fs'; export class Dependument { private source: string; private output: string; constructor(options: any) { if (!options) { throw new Error("No options provided"); } if (!options.source) { throw new Error("No source path specified in options"); } if (!options.output) { throw new Error("No output path specified in options"); } this.source = options.source; this.output = options.output; } writeOutput() { fs.writeFile(this.output, 'dependument test writeOutput', (err) => { if (err) throw err; console.log(`Output written to ${this.output}`); }); } }
Throw error if no options
Throw error if no options
TypeScript
unlicense
dependument/dependument,Jameskmonger/dependument,Jameskmonger/dependument,dependument/dependument
--- +++ @@ -7,6 +7,10 @@ private output: string; constructor(options: any) { + if (!options) { + throw new Error("No options provided"); + } + if (!options.source) { throw new Error("No source path specified in options"); }
645a38a83fa460c6e9afece739faa83aa2d16fbe
src/environment.ts
src/environment.ts
// made availabe by webpack plugins // Unused VARS in .env are NOT included in the bundle const ISPRODUCTION = process.env.NODE_ENV === 'production' export const API_HOST = ISPRODUCTION ? process.env.PRODUCTION_HOST : process.env.DEVELOPMENT_HOST
// made availabe by webpack plugins // Unused VARS in .env are NOT included in the bundle export const ISPRODUCTION = process.env.NODE_ENV === 'production' if (!(process.env.PRODUCTION_HOST && process.env.DEVELOPMENT_HOST)) { throw 'PRODUCTION_HOST and DEVELOPMENT_HOST must be defined in env' } export const API_HOST = process.env.API_HOST ? process.env.API_HOST as string : ISPRODUCTION ? process.env.PRODUCTION_HOST : process.env.DEVELOPMENT_HOST
Allow API_HOST to be defiend in client env
Allow API_HOST to be defiend in client env
TypeScript
mit
OpenDirective/brian,OpenDirective/brian,OpenDirective/brian
--- +++ @@ -1,7 +1,11 @@ // made availabe by webpack plugins // Unused VARS in .env are NOT included in the bundle -const ISPRODUCTION = process.env.NODE_ENV === 'production' +export const ISPRODUCTION = process.env.NODE_ENV === 'production' -export const API_HOST = ISPRODUCTION - ? process.env.PRODUCTION_HOST - : process.env.DEVELOPMENT_HOST +if (!(process.env.PRODUCTION_HOST && process.env.DEVELOPMENT_HOST)) { + throw 'PRODUCTION_HOST and DEVELOPMENT_HOST must be defined in env' +} + +export const API_HOST = process.env.API_HOST + ? process.env.API_HOST as string + : ISPRODUCTION ? process.env.PRODUCTION_HOST : process.env.DEVELOPMENT_HOST
7e7d404bca97f7bb91b6ea13fa8f0fb131bbf4ea
src/interfaces/ISelectorFilter.ts
src/interfaces/ISelectorFilter.ts
export interface ISelectorFilter { selector: string|RegExp; replacement: any; } export interface ISelectorFilterRaw { selector: string; replacement: any; }
export interface ISelectorFilter { selector: string|RegExp; replacement: any; } export interface ISelectorFilterRaw extends ISelectorFilter { selector: string; }
Use extend for describing the raw selector filter interface
Use extend for describing the raw selector filter interface
TypeScript
mit
maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer
--- +++ @@ -3,7 +3,6 @@ replacement: any; } -export interface ISelectorFilterRaw { +export interface ISelectorFilterRaw extends ISelectorFilter { selector: string; - replacement: any; }
00c8904127774f5baa89fcfc4e63f5ef605dec18
src/app.ts
src/app.ts
import App from './core/App'; import readConfig from './util/readConfig'; // Start up application (async function () { const config = await readConfig(); const app = new App(config); await app.start(); }());
import App from './core/App'; import readConfig from './util/readConfig'; // Start up application (async function main(): Promise<void> { const config = await readConfig(); const app = new App(config); await app.start(); }());
Fix eslint errors of main()
Fix eslint errors of main()
TypeScript
agpl-3.0
takashiro/karuta-server,takashiro/karuta-server,takashiro/karuta-server
--- +++ @@ -2,7 +2,7 @@ import readConfig from './util/readConfig'; // Start up application -(async function () { +(async function main(): Promise<void> { const config = await readConfig(); const app = new App(config); await app.start();
9435149c3da8fc52e9fd7214b7843983990a7279
app/core/settings/username-provider.ts
app/core/settings/username-provider.ts
/** * @author Daniel de */ export abstract class UsernameProvider { abstract getUsername(): string; }
/** * @author Daniel de Oliveira */ export abstract class UsernameProvider { abstract getUsername(): string; }
Fix incomplete author name in comment
Fix incomplete author name in comment
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -1,5 +1,5 @@ /** - * @author Daniel de + * @author Daniel de Oliveira */ export abstract class UsernameProvider {
c75812a017c6010ea526e587c9afa5c57b1272ad
lib/driver/NeoTypes.ts
lib/driver/NeoTypes.ts
import neo4j from "neo4j-driver"; export const Neo4jNode = neo4j.types.Node; export const Neo4jRelationship = neo4j.types.Relationship; import {Node, Relationship} from "neo4j-driver/types/v1/graph-types"; export function isNode(node: any): node is Node { return (node && node.labels) } export function isRelationship(rel: any): rel is Relationship { return (rel && rel.type) }
import neo4j from "neo4j-driver"; import {Node, Relationship} from "neo4j-driver/types/v1/graph-types"; const Neo4jNode = neo4j.types.Node; const Neo4jRelationship = neo4j.types.Relationship; export function isNode(node: any): node is Node { return node instanceof Neo4jNode; } export function isRelationship(rel: any): rel is Relationship { return rel instanceof Neo4jRelationship; }
Refactor type guards for Node and Relationships classes
Refactor type guards for Node and Relationships classes
TypeScript
mit
robak86/neography
--- +++ @@ -1,17 +1,13 @@ - - import neo4j from "neo4j-driver"; - -export const Neo4jNode = neo4j.types.Node; -export const Neo4jRelationship = neo4j.types.Relationship; - - import {Node, Relationship} from "neo4j-driver/types/v1/graph-types"; +const Neo4jNode = neo4j.types.Node; +const Neo4jRelationship = neo4j.types.Relationship; + export function isNode(node: any): node is Node { - return (node && node.labels) + return node instanceof Neo4jNode; } export function isRelationship(rel: any): rel is Relationship { - return (rel && rel.type) + return rel instanceof Neo4jRelationship; }
f28e643f333ddc877e03249154ca8b9be28a832e
src/main.ts
src/main.ts
import Vue from 'vue'; import App from './App.vue'; import './registerServiceWorker'; import router from './router'; import store from './store'; import vuetify from './plugins/vuetify'; import './plugins/codemirror'; // Style import 'roboto-fontface/css/roboto/roboto-fontface.css'; import '@mdi/font/css/materialdesignicons.css'; // Composition API import VueCompositionAPI from '@vue/composition-api'; Vue.use(VueCompositionAPI); // Toast notification import VueToast from 'vue-toast-notification'; // import 'vue-toast-notification/dist/theme-default.css'; import 'vue-toast-notification/dist/theme-sugar.css'; Vue.use(VueToast); // Production Vue.config.productionTip = false; // Load the data from public/config.json for the global config and mount the app. fetch(process.env.BASE_URL + 'config.json') .then(response => response.json()) .then(appConfig => (Vue.prototype.$appConfig = appConfig)) .finally(() => { new Vue({ router, store, vuetify, render: h => h(App), }).$mount('#app'); });
import Vue from 'vue'; import App from './App.vue'; import './registerServiceWorker'; import combineURLs from 'axios/lib/helpers/combineURLs'; import router from './router'; import store from './store'; import vuetify from './plugins/vuetify'; import './plugins/codemirror'; // Style import 'roboto-fontface/css/roboto/roboto-fontface.css'; import '@mdi/font/css/materialdesignicons.css'; // Composition API import VueCompositionAPI from '@vue/composition-api'; Vue.use(VueCompositionAPI); // Toast notification import VueToast from 'vue-toast-notification'; // import 'vue-toast-notification/dist/theme-default.css'; import 'vue-toast-notification/dist/theme-sugar.css'; Vue.use(VueToast); // Production Vue.config.productionTip = false; const mountApp = () => { new Vue({ router, store, vuetify, render: h => h(App), }).$mount('#app'); }; if (process.env.IS_ELECTRON) { Vue.prototype.$appConfig = { insiteAccess: { url: 'http://localhost:8080' }, nestSimulator: { url: 'http://localhost:5000' }, }; mountApp(); } else { // Load the data from public/config.json for the global config and mount the app. fetch(combineURLs(process.env.BASE_URL, 'config.json')) .then(response => response.json()) .then(appConfig => (Vue.prototype.$appConfig = appConfig)) .finally(mountApp); }
Use specific config for electron
Use specific config for electron
TypeScript
mit
babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop
--- +++ @@ -1,6 +1,7 @@ import Vue from 'vue'; import App from './App.vue'; import './registerServiceWorker'; +import combineURLs from 'axios/lib/helpers/combineURLs'; import router from './router'; import store from './store'; @@ -24,15 +25,25 @@ // Production Vue.config.productionTip = false; -// Load the data from public/config.json for the global config and mount the app. -fetch(process.env.BASE_URL + 'config.json') - .then(response => response.json()) - .then(appConfig => (Vue.prototype.$appConfig = appConfig)) - .finally(() => { - new Vue({ - router, - store, - vuetify, - render: h => h(App), - }).$mount('#app'); - }); +const mountApp = () => { + new Vue({ + router, + store, + vuetify, + render: h => h(App), + }).$mount('#app'); +}; + +if (process.env.IS_ELECTRON) { + Vue.prototype.$appConfig = { + insiteAccess: { url: 'http://localhost:8080' }, + nestSimulator: { url: 'http://localhost:5000' }, + }; + mountApp(); +} else { + // Load the data from public/config.json for the global config and mount the app. + fetch(combineURLs(process.env.BASE_URL, 'config.json')) + .then(response => response.json()) + .then(appConfig => (Vue.prototype.$appConfig = appConfig)) + .finally(mountApp); +}
be25e47b71c41c884c6bc2f32933b3b793be498a
ui/src/documents.ts
ui/src/documents.ts
type Query = { q: string, size?: number, from?: number, skipTypes?: string[] }; export const get = async (id: string): Promise<any> => { const response = await fetch(`/documents/${id}`); if (response.ok) return await response.json(); else throw(await response.json()); }; export const search = async (query: Query): Promise<any> => { let uri = `/documents/?q=${getQueryString(query)}`; if (query.size) uri += `&size=${query.size}`; if (query.from) uri += `&from=${query.from}`; const response = await fetch(uri); return await response.json(); }; const getQueryString = (query: Query) => `${query.q} ${query.skipTypes ? query.skipTypes.map(type => `-resource.type:${type}`).join(' ') : '' }`;
type Query = { q: string, size?: number, from?: number, skipTypes?: string[] }; export const get = async (id: string): Promise<any> => { const response = await fetch(`/documents/${id}`); if (response.ok) return await response.json(); else throw(await response.json()); }; export const search = async (query: Query): Promise<any> => { let uri = `/documents/?q=${getQueryString(query)}`; if (query.size) uri += `&size=${query.size}`; if (query.from) uri += `&from=${query.from}`; const response = await fetch(uri); return (await response.json()).hits; }; const getQueryString = (query: Query) => `${query.q} ${query.skipTypes ? query.skipTypes.map(type => `-resource.type:${type}`).join(' ') : '' }`;
Use hits property of search response in frontend
Use hits property of search response in frontend
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -20,7 +20,7 @@ if (query.from) uri += `&from=${query.from}`; const response = await fetch(uri); - return await response.json(); + return (await response.json()).hits; }; const getQueryString = (query: Query) =>
cf21303edea9abd919ecdab84698c6ab8513b1c2
classnames/index.d.ts
classnames/index.d.ts
// Type definitions for classnames // Project: https://github.com/JedWatson/classnames // Definitions by: Dave Keen <http://www.keendevelopment.ch>, Adi Dahiya <https://github.com/adidahiya>, Jason Killian <https://github.com/JKillian> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null; interface ClassDictionary { [id: string]: boolean | undefined | null; } interface ClassArray extends Array<ClassValue> { } interface ClassNamesFn { (...classes: ClassValue[]): string; } declare var classNames: ClassNamesFn; declare module "classnames" { export = classNames }
// Type definitions for classnames // Project: https://github.com/JedWatson/classnames // Definitions by: Dave Keen <http://www.keendevelopment.ch>, Adi Dahiya <https://github.com/adidahiya>, Jason Killian <https://github.com/JKillian> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false; interface ClassDictionary { [id: string]: boolean | undefined | null; } interface ClassArray extends Array<ClassValue> { } interface ClassNamesFn { (...classes: ClassValue[]): string; } declare var classNames: ClassNamesFn; declare module "classnames" { export = classNames }
Allow false as input value.
Allow false as input value.
TypeScript
mit
johan-gorter/DefinitelyTyped,minodisk/DefinitelyTyped,jimthedev/DefinitelyTyped,shlomiassaf/DefinitelyTyped,AgentME/DefinitelyTyped,YousefED/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,alexdresko/DefinitelyTyped,borisyankov/DefinitelyTyped,scriby/DefinitelyTyped,sledorze/DefinitelyTyped,mcliment/DefinitelyTyped,sledorze/DefinitelyTyped,chrootsu/DefinitelyTyped,benishouga/DefinitelyTyped,one-pieces/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,aciccarello/DefinitelyTyped,benishouga/DefinitelyTyped,QuatroCode/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,aciccarello/DefinitelyTyped,amir-arad/DefinitelyTyped,pocesar/DefinitelyTyped,rolandzwaga/DefinitelyTyped,zuzusik/DefinitelyTyped,nycdotnet/DefinitelyTyped,isman-usoh/DefinitelyTyped,arusakov/DefinitelyTyped,martinduparc/DefinitelyTyped,psnider/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,jimthedev/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,martinduparc/DefinitelyTyped,dsebastien/DefinitelyTyped,smrq/DefinitelyTyped,zuzusik/DefinitelyTyped,abbasmhd/DefinitelyTyped,psnider/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,schmuli/DefinitelyTyped,scriby/DefinitelyTyped,pocesar/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,johan-gorter/DefinitelyTyped,smrq/DefinitelyTyped,mcrawshaw/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,subash-a/DefinitelyTyped,georgemarshall/DefinitelyTyped,alexdresko/DefinitelyTyped,hellopao/DefinitelyTyped,psnider/DefinitelyTyped,aciccarello/DefinitelyTyped,alvarorahul/DefinitelyTyped,mcrawshaw/DefinitelyTyped,benishouga/DefinitelyTyped,QuatroCode/DefinitelyTyped,subash-a/DefinitelyTyped,pocesar/DefinitelyTyped,ashwinr/DefinitelyTyped,abbasmhd/DefinitelyTyped,isman-usoh/DefinitelyTyped,use-strict/DefinitelyTyped,use-strict/DefinitelyTyped,YousefED/DefinitelyTyped,progre/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,shlomiassaf/DefinitelyTyped,hellopao/DefinitelyTyped,nycdotnet/DefinitelyTyped,schmuli/DefinitelyTyped,jimthedev/DefinitelyTyped,minodisk/DefinitelyTyped,markogresak/DefinitelyTyped,chrismbarr/DefinitelyTyped,micurs/DefinitelyTyped,chrismbarr/DefinitelyTyped,benliddicott/DefinitelyTyped,ashwinr/DefinitelyTyped,AgentME/DefinitelyTyped,alvarorahul/DefinitelyTyped,schmuli/DefinitelyTyped,martinduparc/DefinitelyTyped,chrootsu/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,magny/DefinitelyTyped,progre/DefinitelyTyped,hellopao/DefinitelyTyped,magny/DefinitelyTyped,rolandzwaga/DefinitelyTyped
--- +++ @@ -3,7 +3,7 @@ // Definitions by: Dave Keen <http://www.keendevelopment.ch>, Adi Dahiya <https://github.com/adidahiya>, Jason Killian <https://github.com/JKillian> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null; +declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false; interface ClassDictionary { [id: string]: boolean | undefined | null;
a7c6c437ecaa6384c701201ad481f3ee33f66697
src/model/Deck.ts
src/model/Deck.ts
import { computed } from 'mobx' import { Card } from './Card' import { CardValue } from './CardValue' import { Settings } from './Settings' import { Suit } from './Suit' export class Deck { private constructor() { const cards: Array<Card> = [] for (const suit of [Suit.Clubs, Suit.Diamonds, Suit.Hearts, Suit.Spades]) { if (Suit.hasOwnProperty(suit)) { for (let value = Settings.instance.maxCardValue; value >= 1; value--) { const nextCard = value === Settings.instance.maxCardValue ? undefined : cards[cards.length - 1] cards.push(new Card(suit, value as CardValue, nextCard)) } } } this.cards = cards } private static _instance: Deck public static get instance(): Deck { if (this._instance === undefined) { this._instance = new Deck() } return this._instance } public readonly cards: ReadonlyArray<Card> @computed public get theFourAces(): ReadonlyArray<Card> { const theFourAces = this.cards.filter(card => card.value === 1) return theFourAces } }
import { computed } from 'mobx' import { Card } from './Card' import { CardValue } from './CardValue' import { Settings } from './Settings' import { Suit } from './Suit' export class Deck { private constructor() { } private static _instance: Deck public static get instance(): Deck { if (this._instance === undefined) { this._instance = new Deck() } return this._instance } @computed public get cards(): ReadonlyArray<Card> { const cards: Array<Card> = [] for (const suit of [Suit.Clubs, Suit.Diamonds, Suit.Hearts, Suit.Spades]) { if (Suit.hasOwnProperty(suit)) { for (let value = Settings.instance.maxCardValue; value >= 1; value--) { const nextCard = value === Settings.instance.maxCardValue ? undefined : cards[cards.length - 1] cards.push(new Card(suit, value as CardValue, nextCard)) } } } return cards } @computed public get theFourAces(): ReadonlyArray<Card> { const theFourAces = this.cards.filter(card => card.value === 1) return theFourAces } }
Make cards a computed value
Make cards a computed value
TypeScript
mit
janaagaard75/desert-walk,janaagaard75/desert-walk
--- +++ @@ -7,6 +7,20 @@ export class Deck { private constructor() { + } + + private static _instance: Deck + + public static get instance(): Deck { + if (this._instance === undefined) { + this._instance = new Deck() + } + + return this._instance + } + + @computed + public get cards(): ReadonlyArray<Card> { const cards: Array<Card> = [] for (const suit of [Suit.Clubs, Suit.Diamonds, Suit.Hearts, Suit.Spades]) { if (Suit.hasOwnProperty(suit)) { @@ -20,20 +34,8 @@ } } - this.cards = cards + return cards } - - private static _instance: Deck - - public static get instance(): Deck { - if (this._instance === undefined) { - this._instance = new Deck() - } - - return this._instance - } - - public readonly cards: ReadonlyArray<Card> @computed public get theFourAces(): ReadonlyArray<Card> {
e8ba1a83c5217eaa6aecdd0f04a2eff0b112187f
src/app/annotator.component.ts
src/app/annotator.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AppUtilService } from './app-util.service'; @Component({ selector: 'annotator', templateUrl: './annotator.component.html', styleUrls: ['./annotator.component.css'], }) export class AnnotatorComponent { constructor( public router: Router, public appService: AppUtilService, ) { } actionBack(): void { //this.appService.data.selected=null this.router.navigate(['./selector']); } getClip(): any { return null; } getClipName(): string { return ""; } getAudioData(): any { return null; } }
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AppUtilService } from './app-util.service'; @Component({ selector: 'annotator', templateUrl: './annotator.component.html', styleUrls: ['./annotator.component.css'], }) export class AnnotatorComponent { constructor( public router: Router, public appService: AppUtilService, ) { } actionBack(): void { this.router.navigate(['./dataview']); } getClip(): any { return null; } getClipName(): string { return ""; } getAudioData(): any { return null; } }
Set the proper back button URL
Set the proper back button URL
TypeScript
bsd-3-clause
Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber
--- +++ @@ -16,8 +16,7 @@ ) { } actionBack(): void { - //this.appService.data.selected=null - this.router.navigate(['./selector']); + this.router.navigate(['./dataview']); } getClip(): any {
77d442f3108767f9657645f8a9a4e63960595fb7
src/app/loadout/loadout.module.ts
src/app/loadout/loadout.module.ts
import { module } from 'angular'; import { LoadoutDrawerComponent } from './loadout-drawer.component'; import { LoadoutPopupComponent } from './loadout-popup.component'; import { react2angular } from 'react2angular'; import RandomLoadoutButton from './random/RandomLoadoutButton'; export default module('loadoutModule', []) .component('dimLoadoutPopup', LoadoutPopupComponent) .component('loadoutDrawer', LoadoutDrawerComponent) .component('randomLoadout', react2angular(RandomLoadoutButton, ['destinyVersion'])) .name;
import { module } from 'angular'; import { LoadoutDrawerComponent } from './loadout-drawer.component'; import { LoadoutPopupComponent } from './loadout-popup.component'; export default module('loadoutModule', []) .component('dimLoadoutPopup', LoadoutPopupComponent) .component('loadoutDrawer', LoadoutDrawerComponent) .name;
Remove random loadout from angular
Remove random loadout from angular
TypeScript
mit
bhollis/DIM,DestinyItemManager/DIM,chrisfried/DIM,DestinyItemManager/DIM,chrisfried/DIM,bhollis/DIM,delphiactual/DIM,chrisfried/DIM,delphiactual/DIM,DestinyItemManager/DIM,chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,bhollis/DIM,delphiactual/DIM,delphiactual/DIM
--- +++ @@ -2,11 +2,8 @@ import { LoadoutDrawerComponent } from './loadout-drawer.component'; import { LoadoutPopupComponent } from './loadout-popup.component'; -import { react2angular } from 'react2angular'; -import RandomLoadoutButton from './random/RandomLoadoutButton'; export default module('loadoutModule', []) .component('dimLoadoutPopup', LoadoutPopupComponent) .component('loadoutDrawer', LoadoutDrawerComponent) - .component('randomLoadout', react2angular(RandomLoadoutButton, ['destinyVersion'])) .name;
fe5fdb0c77986a6a80aacbc29ba5f20c1213f144
packages/expo-local-authentication/src/__tests__/LocalAuthentication-test.ios.ts
packages/expo-local-authentication/src/__tests__/LocalAuthentication-test.ios.ts
import ExpoLocalAuthentication from '../ExpoLocalAuthentication'; import * as LocalAuthentication from '../LocalAuthentication'; beforeEach(() => { ExpoLocalAuthentication.authenticateAsync.mockReset(); ExpoLocalAuthentication.authenticateAsync.mockReturnValue({ success: true }); }); it(`uses promptMessage and fallbackLabel on iOS`, async () => { const options = { promptMessage: 'Authentication is required', fallbackLabel: 'Use passcode', }; await LocalAuthentication.authenticateAsync(options); expect(ExpoLocalAuthentication.authenticateAsync).toHaveBeenLastCalledWith(options); }); it(`throws when an invalid message is used on iOS`, async () => { expect( LocalAuthentication.authenticateAsync({ promptMessage: undefined as any }) ).rejects.toThrow(); expect(LocalAuthentication.authenticateAsync({ promptMessage: '' })).rejects.toThrow(); expect(LocalAuthentication.authenticateAsync({ promptMessage: {} as any })).rejects.toThrow(); expect(LocalAuthentication.authenticateAsync({ promptMessage: 123 as any })).rejects.toThrow(); });
import ExpoLocalAuthentication from '../ExpoLocalAuthentication'; import * as LocalAuthentication from '../LocalAuthentication'; beforeEach(() => { ExpoLocalAuthentication.authenticateAsync.mockReset(); ExpoLocalAuthentication.authenticateAsync.mockImplementation(async () => ({ success: true })); }); it(`uses promptMessage and fallbackLabel on iOS`, async () => { const options = { promptMessage: 'Authentication is required', fallbackLabel: 'Use passcode', }; await LocalAuthentication.authenticateAsync(options); expect(ExpoLocalAuthentication.authenticateAsync).toHaveBeenLastCalledWith(options); }); it(`throws when an invalid message is used on iOS`, async () => { expect( LocalAuthentication.authenticateAsync({ promptMessage: undefined as any }) ).rejects.toThrow(); expect(LocalAuthentication.authenticateAsync({ promptMessage: '' })).rejects.toThrow(); expect(LocalAuthentication.authenticateAsync({ promptMessage: {} as any })).rejects.toThrow(); expect(LocalAuthentication.authenticateAsync({ promptMessage: 123 as any })).rejects.toThrow(); });
Use a mock async function for iOS tests as well
[local-auth] Use a mock async function for iOS tests as well The Android tests use `mockImplementation(async () => ({ success: true }));` and this does the same for iOS now.
TypeScript
bsd-3-clause
exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent
--- +++ @@ -3,7 +3,7 @@ beforeEach(() => { ExpoLocalAuthentication.authenticateAsync.mockReset(); - ExpoLocalAuthentication.authenticateAsync.mockReturnValue({ success: true }); + ExpoLocalAuthentication.authenticateAsync.mockImplementation(async () => ({ success: true })); }); it(`uses promptMessage and fallbackLabel on iOS`, async () => {
d47d0c777b0bd5bec43f292a4ecee82d3ea973ae
src/ts/content/chat/ParseHighlight.tsx
src/ts/content/chat/ParseHighlight.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import * as events from '../../core/events'; function fromText(text: string, keygen: () => number) : JSX.Element[] { //events.fire('chat-play-sound-highlight'); return [<span key={keygen()} className={'chat-room-highlight'}>{text}</span>]; } function createRegExp(highlight: string[]) : RegExp { let regex: string; highlight.forEach((h: string) => { if (!regex) { regex = '\\b' + h + '\\b'; } else { regex += '|\\b' + h + '\\b'; } }); return new RegExp(regex, 'g'); } export default { fromText, createRegExp }
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import * as events from '../../core/events'; function fromText(text: string, keygen: () => number) : JSX.Element[] { //events.fire('chat-play-sound-highlight'); return [<span key={keygen()} className={'chat-room-highlight'}>{text}</span>]; } function createRegExp(highlight: string[]) : RegExp { let regex: string; highlight.forEach((h: string) => { if (!regex) { regex = '(?:^|\\s)@?' + h + ':?(?:$|\\s)'; } else { regex += '|(?:^|\\s)@?' + h + ':?(?:$|\\s)'; } }); return new RegExp(regex, 'g'); } export default { fromText, createRegExp }
Allow @name and name: to work for highlighting.
Allow @name and name: to work for highlighting.
TypeScript
mpl-2.0
stanley85/cu-patcher-ui,stanley85/cu-patcher-ui,jamkoo/cu-patcher-ui,jamkoo/cu-patcher-ui
--- +++ @@ -16,9 +16,9 @@ let regex: string; highlight.forEach((h: string) => { if (!regex) { - regex = '\\b' + h + '\\b'; + regex = '(?:^|\\s)@?' + h + ':?(?:$|\\s)'; } else { - regex += '|\\b' + h + '\\b'; + regex += '|(?:^|\\s)@?' + h + ':?(?:$|\\s)'; } }); return new RegExp(regex, 'g');
d3d86555f0397445d2200d00732ee95861b59522
packages/@uppy/react/src/DashboardModal.d.ts
packages/@uppy/react/src/DashboardModal.d.ts
import { DashboardProps } from './Dashboard'; export interface DashboardModalProps extends DashboardProps { target: string | HTMLElement; open?: boolean; onRequestClose?: VoidFunction; closeModalOnClickOutside?: boolean; disablePageScrollWhenModalOpen?: boolean; } /** * React Component that renders a Dashboard for an Uppy instance in a Modal * dialog. Visibility of the Modal is toggled using the `open` prop. */ declare const DashboardModal: React.ComponentType<DashboardModalProps>; export default DashboardModal;
import { DashboardProps } from './Dashboard'; export interface DashboardModalProps extends DashboardProps { target?: string | HTMLElement; open?: boolean; onRequestClose?: VoidFunction; closeModalOnClickOutside?: boolean; disablePageScrollWhenModalOpen?: boolean; } /** * React Component that renders a Dashboard for an Uppy instance in a Modal * dialog. Visibility of the Modal is toggled using the `open` prop. */ declare const DashboardModal: React.ComponentType<DashboardModalProps>; export default DashboardModal;
Make "target" prop optional in Typescript.
Make "target" prop optional in Typescript.
TypeScript
mit
transloadit/uppy,transloadit/uppy,transloadit/uppy,transloadit/uppy
--- +++ @@ -1,7 +1,7 @@ import { DashboardProps } from './Dashboard'; export interface DashboardModalProps extends DashboardProps { - target: string | HTMLElement; + target?: string | HTMLElement; open?: boolean; onRequestClose?: VoidFunction; closeModalOnClickOutside?: boolean;
ba3453ef8390848d60e7a7ae1a08b673ae9a14d4
src/handlers/Store.ts
src/handlers/Store.ts
import {Frame, ResponseContext, ResponseModel} from "../definitions/Handler"; import {Attributes, RequestContext} from "../definitions/SkillContext"; import * as Frames from "../definitions/FrameDirectory"; import {Items} from "../definitions/Inventory"; let entry = (attr: Attributes, ctx: RequestContext) => { let model = new ResponseModel(); model.speech = "You can purchase: " + attr.Upgrades.map(itemId => { let item = Items.All[itemId]; return item.id; }).join(", ") + ". What would you like to purchase?"; model.reprompt = "What would you like to purchase?"; return new ResponseContext(model); }; let actionMap = { "LaunchRequest": (attr: Attributes) => { return Frames["Start"]; }, "PurchaseUpgradeIntent": (attr: Attributes) => { return Frames["Purchase"]; }, "EatCookieIntent": (attr: Attributes) => { return Frames["Eat"]; }, }; let unhandled = () => { return Frames["Start"]; }; new Frame("Store", entry, unhandled, actionMap);
import {Frame, ResponseContext, ResponseModel} from "../definitions/Handler"; import {Attributes, RequestContext} from "../definitions/SkillContext"; import * as Frames from "../definitions/FrameDirectory"; import {Items} from "../definitions/Inventory"; import {Humanize} from "../resources/humanize"; import {getNextUpgradeCost} from "../resources/store"; let entry = (attr: Attributes, ctx: RequestContext) => { let model = new ResponseModel(); attr.NextUpgrade = getNextUpgradeCost(attr.Inventory); if (attr.Upgrades.length > 0) { model.speech = "You can purchase: " + attr.Upgrades.map(itemId => { let item = Items.All[itemId]; return item.id; }).join(", ") + ". What would you like to purchase?"; model.reprompt = "What would you like to purchase?"; } else { if (attr.NextUpgrade.greaterThan(0)) { model.speech = "There are no items available for purchase right now. The next upgrade is available at " + Humanize(attr.NextUpgrade, 4) + " cookies."; } else { model.speech = "There are no items available for purchase right now. Bake more cookies!"; } model.reprompt = "You need more cookies."; } return new ResponseContext(model); }; let actionMap = { "LaunchRequest": (attr: Attributes) => { return Frames["Start"]; }, "PurchaseUpgradeIntent": (attr: Attributes) => { return Frames["Purchase"]; }, "EatCookieIntent": (attr: Attributes) => { return Frames["Eat"]; }, "CookieIntent": (attr: Attributes) => { return Frames["Cookie"]; } }; let unhandled = () => { return Frames["Start"]; }; new Frame("Store", entry, unhandled, actionMap);
Fix handling of dialog around available upgrades and next upgrade availability.
Fix handling of dialog around available upgrades and next upgrade availability.
TypeScript
agpl-3.0
deegles/cookietime,deegles/cookietime
--- +++ @@ -3,18 +3,32 @@ import * as Frames from "../definitions/FrameDirectory"; import {Items} from "../definitions/Inventory"; +import {Humanize} from "../resources/humanize"; +import {getNextUpgradeCost} from "../resources/store"; let entry = (attr: Attributes, ctx: RequestContext) => { let model = new ResponseModel(); + attr.NextUpgrade = getNextUpgradeCost(attr.Inventory); - model.speech = "You can purchase: " + attr.Upgrades.map(itemId => { - let item = Items.All[itemId]; + if (attr.Upgrades.length > 0) { + model.speech = "You can purchase: " + attr.Upgrades.map(itemId => { + let item = Items.All[itemId]; - return item.id; - }).join(", ") + ". What would you like to purchase?"; + return item.id; + }).join(", ") + ". What would you like to purchase?"; - model.reprompt = "What would you like to purchase?"; + model.reprompt = "What would you like to purchase?"; + } else { + if (attr.NextUpgrade.greaterThan(0)) { + model.speech = "There are no items available for purchase right now. The next upgrade is available at " + Humanize(attr.NextUpgrade, 4) + " cookies."; + } else { + model.speech = "There are no items available for purchase right now. Bake more cookies!"; + + } + + model.reprompt = "You need more cookies."; + } return new ResponseContext(model); }; @@ -29,6 +43,9 @@ "EatCookieIntent": (attr: Attributes) => { return Frames["Eat"]; }, + "CookieIntent": (attr: Attributes) => { + return Frames["Cookie"]; + } }; let unhandled = () => {
1e6a7092cdd755a5c5b1c8b8ca39336cb408279a
src/protocol.ts
src/protocol.ts
'use strict'; import { RequestType, NotificationType, TextDocumentIdentifier} from 'vscode-languageclient'; export interface StatusReport { message: string; type: string; } export namespace StatusNotification { export const type: NotificationType<StatusReport> = { get method() { return 'language/status'; } }; } export namespace ClassFileContentsRequest { export const type: RequestType<TextDocumentIdentifier, string, void> = { get method() { return 'java/ClassFileContents'; }}; }
'use strict'; import { RequestType, NotificationType, TextDocumentIdentifier} from 'vscode-languageclient'; export interface StatusReport { message: string; type: string; } export namespace StatusNotification { export const type: NotificationType<StatusReport> = { get method() { return 'language/status'; } }; } export namespace ClassFileContentsRequest { export const type: RequestType<TextDocumentIdentifier, string, void> = { get method() { return 'java/classFileContents'; }}; }
Rename java.ClassFileContents request to java.classFileContents
Rename java.ClassFileContents request to java.classFileContents This is a consequence of https://github.com/gorkem/java-language-server/issues/111 Signed-off-by: Fred Bricon <[email protected]>
TypeScript
epl-1.0
gorkem/vscode-java,gorkem/vscode-java
--- +++ @@ -12,5 +12,5 @@ } export namespace ClassFileContentsRequest { - export const type: RequestType<TextDocumentIdentifier, string, void> = { get method() { return 'java/ClassFileContents'; }}; + export const type: RequestType<TextDocumentIdentifier, string, void> = { get method() { return 'java/classFileContents'; }}; }
8a12396ffa7cfab08dbb2078c9b3c54ca83cf55f
src/code/test/index.ts
src/code/test/index.ts
import * as path from 'path'; import * as Mocha from 'mocha'; import * as glob from 'glob'; export function run(): Promise<void> { // Create the mocha test const mocha = new Mocha({ ui: 'tdd' }); mocha.useColors(true); const testsRoot = path.resolve(__dirname, '..'); return new Promise((c, e) => { glob('**/**.test.js', { cwd: testsRoot }, (err, files) => { if (err) { return e(err); } // Add files to the test suite files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); try { // Run the mocha test mocha.run(failures => { if (failures > 0) { e(new Error(`${failures} tests failed.`)); } else { c(); } }); } catch (err) { e(err); } }); }); }
import * as path from 'path'; import * as Mocha from 'mocha'; import * as glob from 'glob'; export function run(): Promise<void> { // Create the mocha test const mocha = new Mocha({ ui: 'tdd', color: true, }); const testsRoot = path.resolve(__dirname, '..'); return new Promise((c, e) => { glob('**/**.test.js', { cwd: testsRoot }, (err, files) => { if (err) { return e(err); } // Add files to the test suite files.forEach(f => mocha.addFile(path.resolve(testsRoot, f))); try { // Run the mocha test mocha.run(failures => { if (failures > 0) { e(new Error(`${failures} tests failed.`)); } else { c(); } }); } catch (err) { e(err); } }); }); }
Stop using the deprecated useColor method
Stop using the deprecated useColor method
TypeScript
mit
yasuyuky/transient-emacs,yasuyuky/transient-emacs
--- +++ @@ -5,9 +5,9 @@ export function run(): Promise<void> { // Create the mocha test const mocha = new Mocha({ - ui: 'tdd' + ui: 'tdd', + color: true, }); - mocha.useColors(true); const testsRoot = path.resolve(__dirname, '..');
c466ca682ea5ceba5ebd13e1db45c611f10387d5
src/build.ts
src/build.ts
const fs = require("fs") const builddocs = require("builddocs") const mkdirp = require('mkdirp'); const path = require('path') import {ModuleContents} from "./types" import {TypeInfos, baseTypes, mergeTypeInfos} from "./env" import {exportedTypeInfos} from "./exports" import moduleDef from "./genmodule"; function mkdirpIfNotExists(dir: string) { if (!fs.existsSync(dir)) { mkdirp.sync(dir) console.log("created '" + dir + "'") } } export default function ( modules: { name: string, srcFiles: string, outFile: string }[], typeInfos: TypeInfos ) { let moduleContents: { [name: string]: ModuleContents } = Object.create(null) for (let module of modules) { const mod = builddocs.read({ files: module.srcFiles }) typeInfos = mergeTypeInfos(exportedTypeInfos(module.name, mod), typeInfos) moduleContents[module.name] = mod } for (let module of modules) { const mod = moduleContents[module.name] let sb = moduleDef(mod, module.name, typeInfos); mkdirpIfNotExists(path.dirname(module.outFile)) fs.writeFileSync(module.outFile, sb.toString()); } }
const fs = require("fs") const builddocs = require("builddocs") const mkdirp = require('mkdirp'); const path = require('path') import {ModuleContents} from "./types" import {TypeInfos, baseTypes, mergeTypeInfos} from "./env" import {exportedTypeInfos} from "./exports" import moduleDef from "./genmodule"; function mkdirpIfNotExists(dir: string) { if (!fs.existsSync(dir)) { mkdirp.sync(dir) console.log("created '" + dir + "'") } } export default function ( modules: { name: string, srcFiles: string, outFile: string, header?: string }[], typeInfos: TypeInfos ) { let moduleContents: { [name: string]: ModuleContents } = Object.create(null) for (let module of modules) { const mod = builddocs.read({ files: module.srcFiles }) typeInfos = mergeTypeInfos(exportedTypeInfos(module.name, mod), typeInfos) moduleContents[module.name] = mod } for (let module of modules) { const mod = moduleContents[module.name] let sb = moduleDef(mod, module.name, typeInfos); mkdirpIfNotExists(path.dirname(module.outFile)) fs.writeFileSync(module.outFile, (module.header || '') + sb.toString()); } }
Add option for outputting header
Add option for outputting header
TypeScript
mit
davidka/buildtypedefs
--- +++ @@ -16,7 +16,7 @@ } export default function ( - modules: { name: string, srcFiles: string, outFile: string }[], + modules: { name: string, srcFiles: string, outFile: string, header?: string }[], typeInfos: TypeInfos ) { @@ -32,7 +32,7 @@ const mod = moduleContents[module.name] let sb = moduleDef(mod, module.name, typeInfos); mkdirpIfNotExists(path.dirname(module.outFile)) - fs.writeFileSync(module.outFile, sb.toString()); + fs.writeFileSync(module.outFile, (module.header || '') + sb.toString()); } }
d23702709ddfc66b14a0986866bac4832d183cdd
app/src/ui/updates/update-available.tsx
app/src/ui/updates/update-available.tsx
import * as React from 'react' import { LinkButton } from '../lib/link-button' import { Dispatcher } from '../../lib/dispatcher' import { updateStore } from '../lib/update-store' import { Octicon, OcticonSymbol } from '../octicons' interface IUpdateAvailableProps { readonly dispatcher: Dispatcher } /** * A component which tells the user an update is available and gives them the * option of moving into the future or being a luddite. */ export class UpdateAvailable extends React.Component<IUpdateAvailableProps, void> { public render() { return ( <div id='update-available' onSubmit={this.updateNow} > <Octicon symbol={OcticonSymbol.desktopDownload} /> <span> An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>. </span> <a className='close' onClick={this.dismiss}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } private updateNow = () => { updateStore.quitAndInstallUpdate() } private dismiss = () => { this.props.dispatcher.closePopup() } }
import * as React from 'react' import { LinkButton } from '../lib/link-button' import { updateStore } from '../lib/update-store' import { Octicon, OcticonSymbol } from '../octicons' interface IUpdateAvailableProps { readonly onDismissed: () => void } /** * A component which tells the user an update is available and gives them the * option of moving into the future or being a luddite. */ export class UpdateAvailable extends React.Component<IUpdateAvailableProps, void> { public render() { return ( <div id='update-available' onSubmit={this.updateNow} > <Octicon symbol={OcticonSymbol.desktopDownload} /> <span> An updated version of GitHub Desktop is avalble and will be installed at the next launch. See what's new or <LinkButton onClick={this.updateNow}>restart now </LinkButton>. </span> <a className='close' onClick={this.dismiss}> <Octicon symbol={OcticonSymbol.x} /> </a> </div> ) } private updateNow = () => { updateStore.quitAndInstallUpdate() } private dismiss = () => { this.props.onDismissed() } }
Modify function to use function passed from props
Modify function to use function passed from props
TypeScript
mit
say25/desktop,say25/desktop,hjobrien/desktop,gengjiawen/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,hjobrien/desktop,BugTesterTest/desktops,gengjiawen/desktop,j-f1/forked-desktop,j-f1/forked-desktop,BugTesterTest/desktops,say25/desktop,hjobrien/desktop,hjobrien/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,BugTesterTest/desktops,BugTesterTest/desktops,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,gengjiawen/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,gengjiawen/desktop,kactus-io/kactus,desktop/desktop
--- +++ @@ -1,11 +1,10 @@ import * as React from 'react' import { LinkButton } from '../lib/link-button' -import { Dispatcher } from '../../lib/dispatcher' import { updateStore } from '../lib/update-store' import { Octicon, OcticonSymbol } from '../octicons' interface IUpdateAvailableProps { - readonly dispatcher: Dispatcher + readonly onDismissed: () => void } /** @@ -39,6 +38,6 @@ } private dismiss = () => { - this.props.dispatcher.closePopup() + this.props.onDismissed() } }
3090cec6dca4d809bd1e7788976b5c048c3858d5
src/index.ts
src/index.ts
import {app, BrowserWindow} from "electron"; let win; function createWindow() { win = new BrowserWindow({ width: 800, height: 600 }); win.loadURL(`file://${__dirname}/app/view/index.html`); // win.webContents.openDevTools(); win.on("closed", () => { win = null; }); } app.on("ready", createWindow); app.on("window-all-closed", () => { process.platform !== "darwin" && app.quit(); // Code like if you were in Satan's church }); app.on("activate", () => { win === null && createWindow(); // Code like if you were in Satan's church });
import {app, BrowserWindow} from "electron"; let win; function createWindow() { win = new BrowserWindow({ width: 800, height: 600 }); win.loadURL(`file://${__dirname}/app/view/index.html`); win.on("closed", () => { win = null; }); } app.on("ready", createWindow); app.on("window-all-closed", () => { process.platform !== "darwin" && app.quit(); // Code like if you were in Satan's church }); app.on("activate", () => { win === null && createWindow(); // Code like if you were in Satan's church });
Remove the dev tools opening by default
Remove the dev tools opening by default
TypeScript
mit
Xstoudi/alduin,Xstoudi/alduin,Xstoudi/alduin
--- +++ @@ -6,8 +6,6 @@ win = new BrowserWindow({ width: 800, height: 600 }); win.loadURL(`file://${__dirname}/app/view/index.html`); - - // win.webContents.openDevTools(); win.on("closed", () => { win = null;
ab8ce82b51316b6b3ce8293aa7faa3d19fef0c39
src/middlewear/loadTests.ts
src/middlewear/loadTests.ts
import path from "path"; import Setup from "../types/Setup"; import callWith from "../utils/callWith"; import TestFunction from "../types/TestFunction"; export default function loadTests(setup: Setup) { const { testFilePaths, tests } = setup; testFilePaths.forEach(testFilePath => { const beforeEachs = []; (global as any).beforeEach = fn => beforeEachs.push(fn); const afterEachs = []; (global as any).afterEach = fn => afterEachs.push(fn); function test(description: string, fn: TestFunction) { const wrapped: TestFunction = (components: any) => { beforeEachs.map(callWith()); fn(components); afterEachs.map(callWith()); }; tests.push({ testFilePath, description, fn: wrapped, runState: "run" }); } (global as any).test = test; test.skip = (description: string, fn: TestFunction) => { const wrapped: TestFunction = (components: any) => { beforeEachs.map(callWith()); fn(components); afterEachs.map(callWith()); }; tests.push({ testFilePath, description, fn: wrapped, runState: "skip" }); }; require(path.join(process.cwd(), testFilePath)); }); }
import path from "path"; import Setup from "../types/Setup"; import callWith from "../utils/callWith"; import TestFunction from "../types/TestFunction"; export default function loadTests(setup: Setup) { const { testFilePaths, tests } = setup; testFilePaths.forEach(testFilePath => { const beforeEachs = []; (global as any).beforeEach = fn => beforeEachs.push(fn); const afterEachs = []; (global as any).afterEach = fn => afterEachs.push(fn); function test(description: string, fn: TestFunction) { const wrapped: TestFunction = (components: any) => { beforeEachs.map(callWith()); fn(components); afterEachs.map(callWith()); }; tests.push({ testFilePath, description, fn: wrapped, runState: "run" }); } (global as any).test = test; test.skip = (description: string, fn: TestFunction) => { const wrapped: TestFunction = (components: any) => { beforeEachs.map(callWith()); fn(components); afterEachs.map(callWith()); }; tests.push({ testFilePath, description, fn: wrapped, runState: "skip" }); }; require(path.join(process.cwd(), testFilePath)); delete (global as any).beforeEach; delete (global as any).afterEach; delete (global as any).test; }); }
Clean up global functions after each test
Clean up global functions after each test
TypeScript
mit
testingrequired/tf,testingrequired/tf
--- +++ @@ -36,5 +36,9 @@ }; require(path.join(process.cwd(), testFilePath)); + + delete (global as any).beforeEach; + delete (global as any).afterEach; + delete (global as any).test; }); }
caad207806241674d44b0e513c784c4cd6859046
packages/truffle-decoder/lib/interface/index.ts
packages/truffle-decoder/lib/interface/index.ts
import { AstDefinition } from "truffle-decode-utils"; import { DataPointer } from "../types/pointer"; import { EvmInfo } from "../types/evm"; import decode from "../decode"; import TruffleDecoder from "./contract-decoder"; import { ContractObject } from "truffle-contract-schema/spec"; import { Provider } from "web3/providers"; import { DecoderRequest } from "../types/request"; export { getStorageAllocations, storageSize } from "../allocate/storage"; export { getCalldataAllocations } from "../allocate/calldata"; export { getMemoryAllocations } from "../allocate/memory"; export { readStack } from "../read/stack"; export { slotAddress } from "../read/storage"; export function forContract(contract: ContractObject, relevantContracts: ContractObject[], provider: Provider, address?: string): TruffleDecoder { return new TruffleDecoder(contract, relevantContracts, provider, address); } export function* forEvmState(definition: AstDefinition, pointer: DataPointer, info: EvmInfo): IterableIterator<any | DecoderRequest> { return yield* decode(definition, pointer, info); }
import { AstDefinition, Values } from "truffle-decode-utils"; import { DataPointer } from "../types/pointer"; import { EvmInfo } from "../types/evm"; import decode from "../decode"; import TruffleDecoder from "./contract-decoder"; import { ContractObject } from "truffle-contract-schema/spec"; import { Provider } from "web3/providers"; import { DecoderRequest, GeneratorJunk } from "../types/request"; export { getStorageAllocations, storageSize } from "../allocate/storage"; export { getCalldataAllocations } from "../allocate/calldata"; export { getMemoryAllocations } from "../allocate/memory"; export { readStack } from "../read/stack"; export { slotAddress } from "../read/storage"; export function forContract(contract: ContractObject, relevantContracts: ContractObject[], provider: Provider, address?: string): TruffleDecoder { return new TruffleDecoder(contract, relevantContracts, provider, address); } export function* forEvmState(definition: AstDefinition, pointer: DataPointer, info: EvmInfo): IterableIterator<Values.Value | DecoderRequest | GeneratorJunk> { return yield* decode(definition, pointer, info); }
Fix return type of forEvmState
Fix return type of forEvmState
TypeScript
mit
ConsenSys/truffle
--- +++ @@ -1,11 +1,11 @@ -import { AstDefinition } from "truffle-decode-utils"; +import { AstDefinition, Values } from "truffle-decode-utils"; import { DataPointer } from "../types/pointer"; import { EvmInfo } from "../types/evm"; import decode from "../decode"; import TruffleDecoder from "./contract-decoder"; import { ContractObject } from "truffle-contract-schema/spec"; import { Provider } from "web3/providers"; -import { DecoderRequest } from "../types/request"; +import { DecoderRequest, GeneratorJunk } from "../types/request"; export { getStorageAllocations, storageSize } from "../allocate/storage"; export { getCalldataAllocations } from "../allocate/calldata"; @@ -17,6 +17,6 @@ return new TruffleDecoder(contract, relevantContracts, provider, address); } -export function* forEvmState(definition: AstDefinition, pointer: DataPointer, info: EvmInfo): IterableIterator<any | DecoderRequest> { +export function* forEvmState(definition: AstDefinition, pointer: DataPointer, info: EvmInfo): IterableIterator<Values.Value | DecoderRequest | GeneratorJunk> { return yield* decode(definition, pointer, info); }
1767b36d140d7bbb44bd678c9bbe1afbd41d22d6
src/types.ts
src/types.ts
import BN = require('bn.js') export type RLPInput = Buffer | string | number | Uint8Array | BN | RLPObject | RLPArray | null export interface RLPArray extends Array<RLPInput> {} interface RLPObject { [x: string]: RLPInput } export interface RLPDecoded { data: Buffer | Buffer[] remainder: Buffer }
import BN = require('bn.js') export type RLPInput = Buffer | string | number | Uint8Array | BN | RLPObject | RLPArray | null export interface RLPArray extends Array<RLPInput> {} export interface RLPObject { [x: string]: RLPInput } export interface RLPDecoded { data: Buffer | Buffer[] remainder: Buffer }
Add missing export of RLPObject
Add missing export of RLPObject
TypeScript
mpl-2.0
ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm
--- +++ @@ -3,7 +3,8 @@ export type RLPInput = Buffer | string | number | Uint8Array | BN | RLPObject | RLPArray | null export interface RLPArray extends Array<RLPInput> {} -interface RLPObject { + +export interface RLPObject { [x: string]: RLPInput }
73c561ddc6d5eaba6e5e878a469152198e879b31
packages/core/src/model.ts
packages/core/src/model.ts
import { ActionObject, AssignAction, Assigner, PropertyAssigner, assign } from '.'; import { EventObject } from './types'; export interface ContextModel<TC, TE extends EventObject> { context: TC; actions: { [key: string]: ActionObject<TC, TE>; }; assign: <TEventType extends TE['type'] = TE['type']>( assigner: | Assigner<TC, TE & { type: TEventType }> | PropertyAssigner<TC, TE & { type: TEventType }>, eventType?: TEventType ) => AssignAction<TC, TE & { type: TEventType }>; } export function createModel<TContext, TEvent extends EventObject>( initialState: TContext ): ContextModel<TContext, TEvent> { const model: ContextModel<TContext, TEvent> = { context: initialState, actions: {}, assign }; return model; } export function assertEvent<TE extends EventObject, TType extends TE['type']>( event: TE, type: TType ): event is TE & { type: TType } { return event.type === type; }
import { assign } from './actions'; import type { ActionObject, AssignAction, Assigner, PropertyAssigner, ExtractEvent, EventObject } from './types'; export interface ContextModel<TContext, TEvent extends EventObject> { initialContext: TContext; actions: { [key: string]: ActionObject<TContext, TEvent>; }; assign: <TEventType extends TEvent['type'] = TEvent['type']>( assigner: | Assigner<TContext, ExtractEvent<TEvent, TEventType>> | PropertyAssigner<TContext, ExtractEvent<TEvent, TEventType>>, eventType?: TEventType ) => AssignAction<TContext, ExtractEvent<TEvent, TEventType>>; } export function createModel<TContext, TEvent extends EventObject>( initialContext: TContext ): ContextModel<TContext, TEvent> { const model: ContextModel<TContext, TEvent> = { initialContext, actions: {}, assign }; return model; } export function assertEvent< TEvent extends EventObject, TEventType extends TEvent['type'] >(event: TEvent, type: TEventType): event is TEvent & { type: TEventType } { return event.type === type; }
Rename context -> initialContext, use ExtractEvent
Rename context -> initialContext, use ExtractEvent
TypeScript
mit
davidkpiano/xstate,davidkpiano/xstate,davidkpiano/xstate
--- +++ @@ -1,30 +1,31 @@ -import { +import { assign } from './actions'; +import type { ActionObject, AssignAction, Assigner, PropertyAssigner, - assign -} from '.'; -import { EventObject } from './types'; + ExtractEvent, + EventObject +} from './types'; -export interface ContextModel<TC, TE extends EventObject> { - context: TC; +export interface ContextModel<TContext, TEvent extends EventObject> { + initialContext: TContext; actions: { - [key: string]: ActionObject<TC, TE>; + [key: string]: ActionObject<TContext, TEvent>; }; - assign: <TEventType extends TE['type'] = TE['type']>( + assign: <TEventType extends TEvent['type'] = TEvent['type']>( assigner: - | Assigner<TC, TE & { type: TEventType }> - | PropertyAssigner<TC, TE & { type: TEventType }>, + | Assigner<TContext, ExtractEvent<TEvent, TEventType>> + | PropertyAssigner<TContext, ExtractEvent<TEvent, TEventType>>, eventType?: TEventType - ) => AssignAction<TC, TE & { type: TEventType }>; + ) => AssignAction<TContext, ExtractEvent<TEvent, TEventType>>; } export function createModel<TContext, TEvent extends EventObject>( - initialState: TContext + initialContext: TContext ): ContextModel<TContext, TEvent> { const model: ContextModel<TContext, TEvent> = { - context: initialState, + initialContext, actions: {}, assign }; @@ -32,9 +33,9 @@ return model; } -export function assertEvent<TE extends EventObject, TType extends TE['type']>( - event: TE, - type: TType -): event is TE & { type: TType } { +export function assertEvent< + TEvent extends EventObject, + TEventType extends TEvent['type'] +>(event: TEvent, type: TEventType): event is TEvent & { type: TEventType } { return event.type === type; }
e952d63f505b75bacf5b1f26ac629a5ce487c2f4
src/app/car-list/car-list.component.ts
src/app/car-list/car-list.component.ts
import { Component, OnInit } from '@angular/core'; import { AngularFire, FirebaseListObservable} from 'angularfire2' import {Observable} from 'rxjs' import "rxjs/add/operator/filter"; import 'rxjs/add/operator/map' import { Car } from '../Car' @Component({ selector: 'app-car-list', templateUrl: './car-list.component.html', styleUrls: ['./car-list.component.css'] }) export class CarListComponent implements OnInit { // items: Observable<Car>; items: FirebaseListObservable<any> constructor(af: AngularFire){ this.items = af.database.list('cars'); } // constructor(af: AngularFire) { // this.items = af.database.list('cars').map( items =>{ // return items.filter(item => (<Car>item).name ==='Test car 2'); // }); // } ngOnInit() { } }
import { Component, OnInit } from '@angular/core'; import { AngularFire, FirebaseListObservable} from 'angularfire2' import {Observable} from 'rxjs' import "rxjs/add/operator/filter"; import 'rxjs/add/operator/map' import { Car } from '../Car' @Component({ selector: 'app-car-list', templateUrl: './car-list.component.html', styleUrls: ['./car-list.component.css'] }) export class CarListComponent implements OnInit { // items: Observable<Car>; items: FirebaseListObservable<any> constructor(af: AngularFire){ af.auth.subscribe(authData => { console.log(authData); let uid = authData.uid; this.items = af.database.list('cars', { query: { orderByChild: 'owner', equalTo: uid // currentUser.uid } }); });//this.items = af.database.list('cars'); } // constructor(af: AngularFire) { // this.items = af.database.list('cars').map( items =>{ // return items.filter(item => (<Car>item).name ==='Test car 2'); // }); // } ngOnInit() { } }
Load only cars for logged in user.
Load only cars for logged in user.
TypeScript
mit
troygerber/ng-pinewood-derby,troygerber/ng-pinewood-derby,troygerber/ng-pinewood-derby
--- +++ @@ -16,7 +16,17 @@ items: FirebaseListObservable<any> constructor(af: AngularFire){ - this.items = af.database.list('cars'); + + af.auth.subscribe(authData => { + console.log(authData); + let uid = authData.uid; + this.items = af.database.list('cars', { + query: { + orderByChild: 'owner', + equalTo: uid // currentUser.uid + } + }); +});//this.items = af.database.list('cars'); } // constructor(af: AngularFire) { // this.items = af.database.list('cars').map( items =>{
6be9a1da44b18834f4e4ccdddaf5697b11309630
src/lib/JsonDBConfig.ts
src/lib/JsonDBConfig.ts
export interface JsonDBConfig { filename: string, saveOnPush: boolean, humanReadable: boolean, separator: string } export class Config implements JsonDBConfig { filename: string humanReadable: boolean saveOnPush: boolean separator: string constructor(filename: string, saveOnPush: boolean = true, humanReadable: boolean = false, separator: string = '/') { this.filename = filename if (!filename.endsWith(".json")) { this.filename += ".json" } this.humanReadable = humanReadable this.saveOnPush = saveOnPush this.separator = separator } }
import * as path from "path"; export interface JsonDBConfig { filename: string, saveOnPush: boolean, humanReadable: boolean, separator: string } export class Config implements JsonDBConfig { filename: string humanReadable: boolean saveOnPush: boolean separator: string constructor(filename: string, saveOnPush: boolean = true, humanReadable: boolean = false, separator: string = '/') { this.filename = filename if (path.extname(filename) === '') this.filename += '.json' this.humanReadable = humanReadable this.saveOnPush = saveOnPush this.separator = separator } }
Support non json file extensions
feat(filename): Support non json file extensions
TypeScript
mit
Belphemur/node-json-db,Belphemur/node-json-db
--- +++ @@ -1,3 +1,5 @@ +import * as path from "path"; + export interface JsonDBConfig { filename: string, saveOnPush: boolean, @@ -15,9 +17,8 @@ constructor(filename: string, saveOnPush: boolean = true, humanReadable: boolean = false, separator: string = '/') { this.filename = filename - if (!filename.endsWith(".json")) { - this.filename += ".json" - } + if (path.extname(filename) === '') + this.filename += '.json' this.humanReadable = humanReadable this.saveOnPush = saveOnPush
63e7492b62dcebf4681479148caa39b90fc8b85a
lib/tsx/TsxParser.ts
lib/tsx/TsxParser.ts
type FunctionalComponent = (props: Props) => JSX.Element; type TsxElement = string | FunctionalComponent; export interface Props { [key: string]: string; } const parseNode = (element: string, children: string[]) => { let elementString = `<${element}>`; children.forEach((child) => { elementString += child; }); elementString += `</${element}>`; return elementString; }; const tsxParser = (element: TsxElement, properties: Props = {}, ...children: string[]) => { if (typeof element === 'function') { return element(properties); } return parseNode(element, children); }; export const textAddSpaces = (text?: string): string => `&nbsp${text}&nbsp`; export default tsxParser;
type FunctionalComponent = (props: Partial<Props>) => JSX.Element; type TsxElement = string | FunctionalComponent; export interface Props { [key: string]: string | []; } interface PropertRewrites { [key: string]: string; } const propertyRewrites: PropertRewrites = { httpEquiv: 'http-equiv', className: 'class', }; interface VoidElements { [key: string]: string; } const voidElements: VoidElements = { meta: 'meta', link: 'link', br: 'br', }; const parseNode = (element: string, properties: Partial<Props>, children: string[]) => { let elementString = `<${element} `; Object.keys(properties).forEach((property) => { elementString += `${propertyRewrites[property] || property}="${properties[property]}" `; }); elementString += voidElements[element] ? '/>' : '>'; children.forEach((child) => { elementString += child; }); if (!voidElements[element]) { elementString += `</${element}>`; } return elementString; }; const tsxParser = (element: TsxElement, properties: Partial<Props> = {}, ...children: string[]) => { if (typeof element === 'function') { return element(properties); } return parseNode(element, properties || {}, children); }; export const textAddSpaces = (text?: string): string => `&nbsp${text}&nbsp`; export default tsxParser;
Add support for renaming properties and short closing void elements.
Add support for renaming properties and short closing void elements.
TypeScript
mit
birkett/a-birkett.co.uk
--- +++ @@ -1,28 +1,55 @@ -type FunctionalComponent = (props: Props) => JSX.Element; +type FunctionalComponent = (props: Partial<Props>) => JSX.Element; type TsxElement = string | FunctionalComponent; export interface Props { + [key: string]: string | []; +} + +interface PropertRewrites { [key: string]: string; } -const parseNode = (element: string, children: string[]) => { - let elementString = `<${element}>`; +const propertyRewrites: PropertRewrites = { + httpEquiv: 'http-equiv', + className: 'class', +}; + +interface VoidElements { + [key: string]: string; +} + +const voidElements: VoidElements = { + meta: 'meta', + link: 'link', + br: 'br', +}; + +const parseNode = (element: string, properties: Partial<Props>, children: string[]) => { + let elementString = `<${element} `; + + Object.keys(properties).forEach((property) => { + elementString += `${propertyRewrites[property] || property}="${properties[property]}" `; + }); + + elementString += voidElements[element] ? '/>' : '>'; children.forEach((child) => { elementString += child; }); - elementString += `</${element}>`; + if (!voidElements[element]) { + elementString += `</${element}>`; + } return elementString; }; -const tsxParser = (element: TsxElement, properties: Props = {}, ...children: string[]) => { +const tsxParser = (element: TsxElement, properties: Partial<Props> = {}, ...children: string[]) => { if (typeof element === 'function') { return element(properties); } - return parseNode(element, children); + return parseNode(element, properties || {}, children); }; export const textAddSpaces = (text?: string): string => `&nbsp${text}&nbsp`;
25f6778e819fa2e60ba3ae206b8c4b4352352539
src/rename.ts
src/rename.ts
import * as vscode from 'vscode'; import { Index } from './index'; export class RenameProvider implements vscode.RenameProvider { constructor(private index: Index) { } provideRenameEdits(document: vscode.TextDocument, position: vscode.Position, newName: string): vscode.WorkspaceEdit { let section = this.index.query(document.uri, { name_position: position })[0]; if (!section) { return null; } let references = this.index.queryReferences("ALL_FILES", { target: section }); if (references.length === 0) { return null; } let edit = new vscode.WorkspaceEdit; edit.replace(document.uri, section.nameLocation.range, newName); const newId = section.id(newName); references.forEach((reference) => { if (!reference.nameRange) { // references in .tf edit.replace(reference.location.uri, reference.location.range, newId); } else { // references in .tfvars edit.replace(reference.location.uri, reference.nameRange, newName); } }); return edit; } }
import * as vscode from 'vscode'; import { Index } from './index'; import { IndexLocator } from './index/index-locator'; export class RenameProvider implements vscode.RenameProvider { constructor(private indexLocator: IndexLocator) { } provideRenameEdits(document: vscode.TextDocument, position: vscode.Position, newName: string): vscode.WorkspaceEdit { let index = this.indexLocator.getIndexForDoc(document); let section = index.query(document.uri, { name_position: position })[0]; if (!section) { return null; } let references = index.queryReferences("ALL_FILES", { target: section }); if (references.length === 0) { return null; } let edit = new vscode.WorkspaceEdit; edit.replace(document.uri, section.nameLocation.range, newName); const newId = section.id(newName); references.forEach((reference) => { if (!reference.nameRange) { // references in .tf edit.replace(reference.location.uri, reference.location.range, newId); } else { // references in .tfvars edit.replace(reference.location.uri, reference.nameRange, newName); } }); return edit; } }
Use IndexLocator instead of Index
RenameProvider: Use IndexLocator instead of Index
TypeScript
mpl-2.0
hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform
--- +++ @@ -1,16 +1,18 @@ import * as vscode from 'vscode'; import { Index } from './index'; +import { IndexLocator } from './index/index-locator'; export class RenameProvider implements vscode.RenameProvider { - constructor(private index: Index) { } + constructor(private indexLocator: IndexLocator) { } provideRenameEdits(document: vscode.TextDocument, position: vscode.Position, newName: string): vscode.WorkspaceEdit { - let section = this.index.query(document.uri, { name_position: position })[0]; + let index = this.indexLocator.getIndexForDoc(document); + let section = index.query(document.uri, { name_position: position })[0]; if (!section) { return null; } - let references = this.index.queryReferences("ALL_FILES", { target: section }); + let references = index.queryReferences("ALL_FILES", { target: section }); if (references.length === 0) { return null; }
acbaf638569004d16bc246dc79f37bbe22c0fbf9
src/in-page-ui/keyboard-shortcuts/constants.ts
src/in-page-ui/keyboard-shortcuts/constants.ts
export const KEYBOARDSHORTCUTS_STORAGE_NAME = 'memex-keyboardshortcuts' export const KEYBOARDSHORTCUTS_DEFAULT_STATE = { shortcutsEnabled: true, linkShortcut: 'shift+l', openDashboard: checkOperatingSystem() + '+d', toggleSidebarShortcut: checkOperatingSystem() + '+q', toggleHighlightsShortcut: checkOperatingSystem() + '+r', createAnnotationShortcut: checkOperatingSystem() + '+w', createHighlightShortcut: checkOperatingSystem() + '+a', createBookmarkShortcut: checkOperatingSystem() + '+s', addTagShortcut: checkOperatingSystem() + '+x', addToCollectionShortcut: checkOperatingSystem() + '+c', addCommentShortcut: checkOperatingSystem() + '+e', linkShortcutEnabled: false, toggleSidebarShortcutEnabled: true, toggleHighlightsShortcutEnabled: true, createAnnotationShortcutEnabled: true, createBookmarkShortcutEnabled: true, createHighlightShortcutEnabled: true, addTagShortcutEnabled: true, addToCollectionShortcutEnabled: true, addCommentShortcutEnabled: true, } function checkOperatingSystem() { let OperatingSystem = navigator.platform if (OperatingSystem.startsWith('Linux')) { return 'alt' } if (OperatingSystem.startsWith('Mac')) { return 'option' } if (OperatingSystem.startsWith('Win')) { return 'alt' } }
export const KEYBOARDSHORTCUTS_STORAGE_NAME = 'memex-keyboardshortcuts' export const KEYBOARDSHORTCUTS_DEFAULT_STATE = { shortcutsEnabled: true, linkShortcut: 'shift+l', openDashboardShortcut: checkOperatingSystem() + '+f', toggleSidebarShortcut: checkOperatingSystem() + '+q', toggleHighlightsShortcut: checkOperatingSystem() + '+r', createAnnotationShortcut: checkOperatingSystem() + '+w', createHighlightShortcut: checkOperatingSystem() + '+a', createBookmarkShortcut: checkOperatingSystem() + '+s', addTagShortcut: checkOperatingSystem() + '+x', addToCollectionShortcut: checkOperatingSystem() + '+c', addCommentShortcut: checkOperatingSystem() + '+e', linkShortcutEnabled: false, toggleSidebarShortcutEnabled: true, toggleHighlightsShortcutEnabled: true, createAnnotationShortcutEnabled: true, createBookmarkShortcutEnabled: true, createHighlightShortcutEnabled: true, addTagShortcutEnabled: true, addToCollectionShortcutEnabled: true, addCommentShortcutEnabled: true, openDashboardShortcutEnabled: true, } function checkOperatingSystem() { let OperatingSystem = navigator.platform if (OperatingSystem.startsWith('Linux')) { return 'alt' } if (OperatingSystem.startsWith('Mac')) { return 'option' } if (OperatingSystem.startsWith('Win')) { return 'alt' } }
Fix new dashboard shortcut not being registered and enabled by default
Fix new dashboard shortcut not being registered and enabled by default
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -3,7 +3,7 @@ export const KEYBOARDSHORTCUTS_DEFAULT_STATE = { shortcutsEnabled: true, linkShortcut: 'shift+l', - openDashboard: checkOperatingSystem() + '+d', + openDashboardShortcut: checkOperatingSystem() + '+f', toggleSidebarShortcut: checkOperatingSystem() + '+q', toggleHighlightsShortcut: checkOperatingSystem() + '+r', createAnnotationShortcut: checkOperatingSystem() + '+w', @@ -21,6 +21,7 @@ addTagShortcutEnabled: true, addToCollectionShortcutEnabled: true, addCommentShortcutEnabled: true, + openDashboardShortcutEnabled: true, } function checkOperatingSystem() {
7b7b7d39113955be602ae71adf72478c9c1ad276
frontend/src/components/navbar/index.tsx
frontend/src/components/navbar/index.tsx
import React from 'react'; import { Menu } from 'react-feather'; import { Box } from '../box'; import { Logo } from '../logo'; export class Navbar extends React.Component<{}, {}> { render() { return ( <Box p={3} flexDirection="row" display="flex" alignItems="center"> <Box p={2}> <Menu /> </Box> <Logo /> </Box> ); } }
import React from 'react'; import { Menu } from 'react-feather'; import { Box } from '../box'; import { Logo } from '../logo'; import { ButtonLink } from '../button'; export class Navbar extends React.Component<{}, {}> { render() { return ( <Box p={3} flexDirection="row" display="flex" alignItems="center"> <Box p={2}> <Menu /> </Box> <Logo /> <ButtonLink href="/" style={{ marginLeft: 'auto' }} > Tickets </ButtonLink> </Box> ); } }
Add tickets link to navbar
Add tickets link to navbar
TypeScript
mit
patrick91/pycon,patrick91/pycon
--- +++ @@ -3,6 +3,7 @@ import { Menu } from 'react-feather'; import { Box } from '../box'; import { Logo } from '../logo'; +import { ButtonLink } from '../button'; export class Navbar extends React.Component<{}, {}> { render() { @@ -13,6 +14,15 @@ </Box> <Logo /> + + <ButtonLink + href="/" + style={{ + marginLeft: 'auto' + }} + > + Tickets + </ButtonLink> </Box> ); }
cfb96d932b73572084175cc96eb251178f7fdd63
src/app/app.filter.pipe.ts
src/app/app.filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterSearch implements PipeTransform { transform(items: any[], search: string) { const contains = new RegExp(search, 'i'); return (items as any[]).filter(item => contains.test(item.path)); } }
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterSearch implements PipeTransform { transform(items: any[], search: string) { const contains = new RegExp(search, 'i'); return (items).filter(item => contains.test(item.path)); } }
Revert "fix matching search with menuitems"
Revert "fix matching search with menuitems" This reverts commit 593c66d4b600f7dba88c3380fc337f5f9e516b6b.
TypeScript
mit
qgrid/ng2,qgrid/ng2,azkurban/ng2,qgrid/ng2,azkurban/ng2,azkurban/ng2
--- +++ @@ -7,6 +7,6 @@ export class FilterSearch implements PipeTransform { transform(items: any[], search: string) { const contains = new RegExp(search, 'i'); - return (items as any[]).filter(item => contains.test(item.path)); + return (items).filter(item => contains.test(item.path)); } }
9cafb277ec84bb74bc367d2efbd7c7bfde5340a2
src/entities/index.ts
src/entities/index.ts
export * from './reducer' export * from './types' import * as actions from './actions' export { actions } import * as components from './components' export { components }
export * from './datasources' export * from './reducer' export * from './types' export * from './utils' import * as actions from './actions' export { actions } import * as components from './components' export { components }
Add exports to entities module
Add exports to entities module
TypeScript
mit
Mytrill/hypract,Mytrill/hypract
--- +++ @@ -1,5 +1,7 @@ +export * from './datasources' export * from './reducer' export * from './types' +export * from './utils' import * as actions from './actions' export { actions }
5ded205104500b4791511003f1ccdf40114ff34c
platforms/platform-alexa/src/AlexaHandles.ts
platforms/platform-alexa/src/AlexaHandles.ts
import { PermissionStatus } from './interfaces'; import { HandleOptions, Jovo } from '@jovotech/framework'; import { AlexaRequest } from './AlexaRequest'; export type PermissionType = 'timers' | 'reminders'; export class AlexaHandles { static onPermission(status: PermissionStatus, type?: PermissionType): HandleOptions { return { types: ['Connections.Response'], platforms: ['alexa'], if: (jovo: Jovo) => (jovo.$request as AlexaRequest).request?.name === 'AskFor' && (jovo.$request as AlexaRequest).request?.payload?.status === status && (type ? (jovo.$request as AlexaRequest).request?.payload?.permissionScope === `alexa::alerts:${type}:skill:readwrite` : true), }; } }
import { PermissionStatus } from './interfaces'; import { HandleOptions, Jovo } from '@jovotech/framework'; import { AlexaRequest } from './AlexaRequest'; export type PermissionType = 'timers' | 'reminders'; export class AlexaHandles { static onPermission(status: PermissionStatus, type?: PermissionType): HandleOptions { return { global: true, types: ['Connections.Response'], platforms: ['alexa'], if: (jovo: Jovo) => (jovo.$request as AlexaRequest).request?.name === 'AskFor' && (jovo.$request as AlexaRequest).request?.payload?.status === status && (type ? (jovo.$request as AlexaRequest).request?.payload?.permissionScope === `alexa::alerts:${type}:skill:readwrite` : true), }; } }
Add global property to permission handle object
:recycle: Add global property to permission handle object
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -7,6 +7,7 @@ export class AlexaHandles { static onPermission(status: PermissionStatus, type?: PermissionType): HandleOptions { return { + global: true, types: ['Connections.Response'], platforms: ['alexa'], if: (jovo: Jovo) =>
25d5632cbf45c0c69412fb24da302f370a65b9a4
src/theme/helpers/getMarkdownFromHtml.ts
src/theme/helpers/getMarkdownFromHtml.ts
const TurndownService = require('turndown'); const turndownService = new TurndownService(); /** * Coverts html to markdown. We need this in comment blocks that have been processed by the 'Marked' plugin. * @param options */ export function getMarkdownFromHtml(options: any) { return turndownService.turndown(options.fn(this)); }
const TurndownService = require('turndown'); const turndownService = new TurndownService(); /** * Coverts html to markdown. We need this in comment blocks that have been processed by the 'Marked' plugin. * @param options */ export function getMarkdownFromHtml(options: any) { return turndownService.turndown(options.fn(this), { codeBlockStyle: 'fenced' }); }
Make turndown default to using fenced code blocks
Make turndown default to using fenced code blocks
TypeScript
mit
tgreyuk/typedoc-plugin-markdown,tgreyuk/typedoc-plugin-markdown
--- +++ @@ -6,5 +6,7 @@ * @param options */ export function getMarkdownFromHtml(options: any) { - return turndownService.turndown(options.fn(this)); + return turndownService.turndown(options.fn(this), { + codeBlockStyle: 'fenced' + }); }
005eaebe99a62a5780f16b1651e2c331acb8584c
ui/src/app/about/user/user.component.ts
ui/src/app/about/user/user.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SecurityService } from 'src/app/security/service/security.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html' }) export class UserComponent implements OnInit { loggedinUser$ = this.securityService.loggedinUser(); constructor( private securityService: SecurityService, private router: Router ) { } ngOnInit(): void { } logout(): void { this.securityService.logout().subscribe(security => { this.router.navigate(['/']); }); } }
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SecurityService } from '../../security/service/security.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html' }) export class UserComponent implements OnInit { loggedinUser$ = this.securityService.loggedinUser(); constructor( private securityService: SecurityService, private router: Router ) { } ngOnInit(): void { } logout(): void { this.securityService.logout().subscribe(security => { this.router.navigate(['/']); }); } }
Update import absolute to relative
Update import absolute to relative
TypeScript
apache-2.0
spring-cloud/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui
--- +++ @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; -import { SecurityService } from 'src/app/security/service/security.service'; +import { SecurityService } from '../../security/service/security.service'; @Component({ selector: 'app-user',
9893d19085223e06d631e59170c721fff7d6b52a
src/constants.ts
src/constants.ts
import * as path from 'path'; export const DEFAULT_APP_NAME = 'APP'; // Update both DEFAULT_ELECTRON_VERSION and DEFAULT_CHROME_VERSION together, // and update app / package.json / devDeps / electron to value of DEFAULT_ELECTRON_VERSION export const DEFAULT_ELECTRON_VERSION = '12.0.11'; export const DEFAULT_CHROME_VERSION = '89.0.4389.128'; // Update each of these periodically // https://product-details.mozilla.org/1.0/firefox_versions.json export const DEFAULT_FIREFOX_VERSION = '89.0'; // https://en.wikipedia.org/wiki/Safari_version_history export const DEFAULT_SAFARI_VERSION = { majorVersion: 14, version: '14.0.3', webkitVersion: '610.4.3.1.7', }; export const ELECTRON_MAJOR_VERSION = parseInt( DEFAULT_ELECTRON_VERSION.split('.')[0], 10, ); export const PLACEHOLDER_APP_DIR = path.join(__dirname, './../', 'app');
import * as path from 'path'; export const DEFAULT_APP_NAME = 'APP'; // Update both DEFAULT_ELECTRON_VERSION and DEFAULT_CHROME_VERSION together, // and update app / package.json / devDeps / electron to value of DEFAULT_ELECTRON_VERSION export const DEFAULT_ELECTRON_VERSION = '12.0.12'; export const DEFAULT_CHROME_VERSION = '89.0.4389.128'; // Update each of these periodically // https://product-details.mozilla.org/1.0/firefox_versions.json export const DEFAULT_FIREFOX_VERSION = '89.0'; // https://en.wikipedia.org/wiki/Safari_version_history export const DEFAULT_SAFARI_VERSION = { majorVersion: 14, version: '14.0.3', webkitVersion: '610.4.3.1.7', }; export const ELECTRON_MAJOR_VERSION = parseInt( DEFAULT_ELECTRON_VERSION.split('.')[0], 10, ); export const PLACEHOLDER_APP_DIR = path.join(__dirname, './../', 'app');
Bump default Electron to 12.0.12
Bump default Electron to 12.0.12
TypeScript
bsd-2-clause
jiahaog/Nativefier,jiahaog/Nativefier,jiahaog/Nativefier
--- +++ @@ -4,7 +4,7 @@ // Update both DEFAULT_ELECTRON_VERSION and DEFAULT_CHROME_VERSION together, // and update app / package.json / devDeps / electron to value of DEFAULT_ELECTRON_VERSION -export const DEFAULT_ELECTRON_VERSION = '12.0.11'; +export const DEFAULT_ELECTRON_VERSION = '12.0.12'; export const DEFAULT_CHROME_VERSION = '89.0.4389.128'; // Update each of these periodically
cd7d860529f39542106f0d7427cce08c7abe502d
SorasNerdDen/Scripts/addServiceWorker.ts
SorasNerdDen/Scripts/addServiceWorker.ts
((w, d, n, l) => { "use strict"; if ('serviceWorker' in n) { // Register a service worker hosted at the root of the // site using the default scope. n.serviceWorker.register('/serviceWorker.js', { scope: "./" }).then(function (registration) { console.log('Service worker registration succeeded:', registration); }).catch(function (error) { console.log('Service worker registration failed:', error); }); n.serviceWorker.addEventListener("message", recieveMessage); } const updateMessage = d.getElementById('update'); function recieveMessage(messageEvent: MessageEvent) { if (messageEvent.data && messageEvent.data.type === "refresh") { const url = messageEvent.data.url as string; if (url === l.href || url === l.pathname || url === l.pathname.substring(1)) { updateMessage.removeAttribute('hidden'); } } } updateMessage.getElementsByTagName('a')[0].addEventListener('click', () => { l.reload(); }) })(window, document, navigator, location);
((w, d, n, l) => { "use strict"; if ('serviceWorker' in n) { // Register a service worker hosted at the root of the // site using the default scope. n.serviceWorker.register('/serviceWorker.js', { scope: "./" }).then(function (registration) { console.log('Service worker registration succeeded:', registration); }).catch(function (error) { console.log('Service worker registration failed:', error); }); n.serviceWorker.addEventListener("message", recieveMessage); } const updateMessage = d.getElementById('update'); function recieveMessage(messageEvent: MessageEvent) { if (messageEvent.data && messageEvent.data.type === "refresh") { const url = messageEvent.data.url as string; if (url === l.href || url === l.pathname || url === l.pathname.substring(1)) { updateMessage.removeAttribute('hidden'); } } } updateMessage.getElementsByTagName('a')[0].addEventListener('click', () => { l.reload(); }); const cs = d.currentScript; if (cs) { cs.parentNode.removeChild(cs); } })(window, document, navigator, location);
Remove 'add service worker' script element after it has run so that the first visit to the site looks identical to all other visits.
Remove 'add service worker' script element after it has run so that the first visit to the site looks identical to all other visits.
TypeScript
mit
Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den,Sora2455/Sora-s-Nerd-Den
--- +++ @@ -24,5 +24,7 @@ } updateMessage.getElementsByTagName('a')[0].addEventListener('click', () => { l.reload(); - }) + }); + const cs = d.currentScript; + if (cs) { cs.parentNode.removeChild(cs); } })(window, document, navigator, location);
9e61640883208929723ca71b0850228183ea6fff
src/app/app.routes.ts
src/app/app.routes.ts
import { Routes } from '@angular/router'; import { NoContentComponent } from './no-content'; import {ProjectComponent} from "./cardsView/project/project.component"; import {RootComponent} from "./cardsView/root/root.component"; export const ROUTES: Routes = [ { path: '', component: RootComponent }, { path: 'project/:key', component: ProjectComponent}, { path: '**', component: NoContentComponent } ];
import { Routes } from '@angular/router'; import { NoContentComponent } from './no-content'; import {ProjectComponent} from "./cardsView/project/project.component"; import {RootComponent} from "./cardsView/root/root.component"; export const ROUTES: Routes = [ { path: '', component: RootComponent }, { path: 'project/:key', component: ProjectComponent}, { path: '**', redirectTo: '' } ];
Add redirection from '**' to '' (root).
Add redirection from '**' to '' (root).
TypeScript
mit
JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend
--- +++ @@ -7,5 +7,5 @@ export const ROUTES: Routes = [ { path: '', component: RootComponent }, { path: 'project/:key', component: ProjectComponent}, - { path: '**', component: NoContentComponent } + { path: '**', redirectTo: '' } ];
a26a0a02efd60a83c8f325942a3778daccf8beb0
types/sqs-consumer/sqs-consumer-tests.ts
types/sqs-consumer/sqs-consumer-tests.ts
import Consumer = require("sqs-consumer"); import { SQS } from "aws-sdk"; const app = Consumer.create({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage(message, done) { // do some work with `message` done(); } }); const app2 = Consumer.create({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage(message, done) { done(); }, region: "us-west-1", batchSize: 15, visibilityTimeout: 50, waitTimeSeconds: 50 }); // Test message handler. const handleMessage = (message: SQS.Message, done: Consumer.ConsumerDone) => { done(); }; const app3 = Consumer.create({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage }); const app4 = new Consumer({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage }); app.on('error', (err: any) => { console.log(err.message); }); app.start();
import Consumer = require("sqs-consumer"); import { SQS } from "aws-sdk"; const app = Consumer.create({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage(message, done) { // do some work with `message` done(); } }); const app2 = Consumer.create({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage(message, done) { done(); }, region: "us-west-1", batchSize: 15, visibilityTimeout: 50, waitTimeSeconds: 50, terminateVisibilityTimeout: true }); // Test message handler. const handleMessage = (message: SQS.Message, done: Consumer.ConsumerDone) => { done(); }; const app3 = Consumer.create({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage }); const app4 = new Consumer({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage }); app.on('error', (err: any) => { console.log(err.message); }); app.start();
Add terminateVisibilityTimeout to a test
Add terminateVisibilityTimeout to a test
TypeScript
mit
AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,mcliment/DefinitelyTyped,chrootsu/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,one-pieces/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrootsu/DefinitelyTyped,borisyankov/DefinitelyTyped,arusakov/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,arusakov/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped
--- +++ @@ -17,7 +17,8 @@ region: "us-west-1", batchSize: 15, visibilityTimeout: 50, - waitTimeSeconds: 50 + waitTimeSeconds: 50, + terminateVisibilityTimeout: true }); // Test message handler.
668f3f1bd9e9ed578ab58da02b7276950f9a4b4b
src/mobile/lib/model/MstGoal.ts
src/mobile/lib/model/MstGoal.ts
import {MstSvt} from "../../../model/master/Master"; import {MstSkillContainer, MstSvtSkillContainer, MstCombineSkillContainer} from "../../../model/impl/MstContainer"; export interface MstGoal { appVer: string; svtRawData: Array<MstSvt>; svtSkillData: MstSvtSkillContainer; skillCombineData: MstCombineSkillContainer; skillData: MstSkillContainer; current: Goal; goals: Array<Goal>; compareSourceId: string; // UUID of one Goal compareTargetId: string; // UUID of one Goal } export interface Goal { id: string; // UUID name: string; servants: Array<GoalSvt>; } export interface GoalSvt { svtId: number; skills: Array<GoalSvtSkill>; } export interface GoalSvtSkill { skillId: number; level: number; } export const defaultCurrentGoal = { // Goal id: "current", name: "当前进度", servants: [], } as Goal; export const defaultMstGoal = { // MstGoal appVer: undefined, current: undefined, goals: [defaultCurrentGoal], compareSourceId: "current", compareTargetId: "current", } as MstGoal;
import {MstSvt} from "../../../model/master/Master"; import {MstSkillContainer, MstSvtSkillContainer, MstCombineSkillContainer} from "../../../model/impl/MstContainer"; export interface MstGoal { appVer: string; svtRawData: Array<MstSvt>; svtSkillData: MstSvtSkillContainer; skillCombineData: MstCombineSkillContainer; skillData: MstSkillContainer; current: Goal; goals: Array<Goal>; compareSourceId: string; // UUID of one Goal compareTargetId: string; // UUID of one Goal } export interface Goal { id: string; // UUID name: string; servants: Array<GoalSvt>; } export interface GoalSvt { svtId: number; limit: number; // 灵基再临状态,0 - 4 skills: Array<GoalSvtSkill>; } export interface GoalSvtSkill { skillId: number; level: number; } export const defaultCurrentGoal = { // Goal id: "current", name: "当前进度", servants: [], } as Goal; export const defaultMstGoal = { // MstGoal appVer: undefined, current: undefined, goals: [defaultCurrentGoal], compareSourceId: "current", compareTargetId: "current", } as MstGoal;
Add servant limit attribute in state.
Add servant limit attribute in state.
TypeScript
mit
agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook,agreatfool/fgo-handbook
--- +++ @@ -21,6 +21,7 @@ export interface GoalSvt { svtId: number; + limit: number; // 灵基再临状态,0 - 4 skills: Array<GoalSvtSkill>; }
5afeb9bcc985b4ad565f0f3775ede9c3d7f87689
sdks/node-ts/src/apache_beam/core.ts
sdks/node-ts/src/apache_beam/core.ts
class PValue { constructor() { } apply(transform: PTransform): PValue { return transform.expand(this); } map(callable): PValue { return this.apply(new ParDo(callable)); } } class Pipeline extends PValue { } class PCollection extends PValue { } class PTransform { expand(input: PValue): PValue { throw new Error('Method expand has not been implemented.'); } } class ParDo extends PTransform { private doFn; constructor(callableOrDoFn) { super() this.doFn = callableOrDoFn; } } class DoFn { }
class PValue { constructor() { } apply(transform: PTransform): PValue { return transform.expand(this); } map(callable: any): PValue { return this.apply(new ParDo(callable)); } } class Pipeline extends PValue { } class PCollection extends PValue { } class PTransform { expand(input: PValue): PValue { throw new Error('Method expand has not been implemented.'); } } class ParDo extends PTransform { private doFn; constructor(callableOrDoFn: any) { super() this.doFn = callableOrDoFn; } } class DoFn { }
Fix complile errors with explicit any for callables.
Fix complile errors with explicit any for callables.
TypeScript
apache-2.0
lukecwik/incubator-beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,lukecwik/incubator-beam,apache/beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,apache/beam,apache/beam,chamikaramj/beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,chamikaramj/beam,apache/beam,chamikaramj/beam
--- +++ @@ -6,7 +6,7 @@ return transform.expand(this); } - map(callable): PValue { + map(callable: any): PValue { return this.apply(new ParDo(callable)); } @@ -28,12 +28,12 @@ class ParDo extends PTransform { private doFn; - constructor(callableOrDoFn) { + constructor(callableOrDoFn: any) { super() this.doFn = callableOrDoFn; } } class DoFn { - + }
475d899555686122c9e19acf2060b2739c6f97c6
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> <span className="icon stop" /> {message} </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 stop" /> <div className="alert-message">{message}</div> </div> ) export default DeprecationWarning
Apply alert styles to deprecation warning
Apply alert styles to deprecation warning
TypeScript
mit
influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,li-ang/influxdb,influxdata/influxdb
--- +++ @@ -5,8 +5,9 @@ } const DeprecationWarning: SFC<Props> = ({message}) => ( - <div> - <span className="icon stop" /> {message} + <div className="alert alert-primary"> + <span className="icon stop" /> + <div className="alert-message">{message}</div> </div> )