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
900a086dea0f4b508b42b9d3e30c46f59bbff174
react-renderer/index.d.ts
react-renderer/index.d.ts
import { Canvas, Packets, ILayer } from "src/module"; import { Protocol, IRendererEvents, ConnectionStatus, IEditorEvents } from "src/protocol"; declare module "mathjax"; export { Canvas, Packets, Protocol, ConnectionStatus, IEditorEvents, IRendererEvents, ILayer };
import { Canvas, Packets, ILayer } from "src/module"; import { Protocol, IRendererEvents, ConnectionStatus, IEditorEvents } from "src/Protocol"; declare module "mathjax"; export { Canvas, Packets, Protocol, ConnectionStatus, IEditorEvents, IRendererEvents, ILayer };
Change path to Protocol.tsx to uppercase
Change path to Protocol.tsx to uppercase
TypeScript
mit
penrose/penrose,penrose/penrose,penrose/penrose,penrose/penrose
--- +++ @@ -4,7 +4,7 @@ IRendererEvents, ConnectionStatus, IEditorEvents -} from "src/protocol"; +} from "src/Protocol"; declare module "mathjax";
1709af0bc53bd962466dd2025672b95f2e9399cc
packages/api/core/src/util/electron-version.ts
packages/api/core/src/util/electron-version.ts
import debug from 'debug'; const d = debug('electron-forge:electron-version'); const electronPackageNames = [ 'electron-prebuilt-compile', 'electron-prebuilt', 'electron-nightly', 'electron', ]; function findElectronDep(dep: string): boolean { return electronPackageNames.includes(dep); } export function getElectronVersion(packageJSON: any) { if (!packageJSON.devDependencies) { throw new Error('package.json for app does not have any devDependencies'.red); } const packageName = electronPackageNames.find(pkg => packageJSON.devDependencies[pkg]); if (packageName === undefined) { throw new Error('Could not find any Electron packages in devDependencies'); } return packageJSON.devDependencies[packageName]; } export function updateElectronDependency(packageJSON: any, dev: string[], exact: string[]): [string[], string[]] { if (Object.keys(packageJSON.devDependencies).find(findElectronDep)) { exact = exact.filter(dep => dep !== 'electron'); } else { const electronKey = Object.keys(packageJSON.dependencies).find(findElectronDep); if (electronKey) { exact = exact.filter(dep => dep !== 'electron'); d(`Moving ${electronKey} from dependencies to devDependencies`); dev.push(`${electronKey}@${packageJSON.dependencies[electronKey]}`); delete packageJSON.dependencies[electronKey]; } } return [dev, exact]; }
import debug from 'debug'; const d = debug('electron-forge:electron-version'); const electronPackageNames = [ 'electron-prebuilt-compile', 'electron-prebuilt', 'electron-nightly', 'electron', ]; function findElectronDep(dep: string): boolean { return electronPackageNames.includes(dep); } export function getElectronVersion(packageJSON: any) { if (!packageJSON.devDependencies) { throw new Error('package.json for app does not have any devDependencies'.red); } const packageName = electronPackageNames.find(pkg => packageJSON.devDependencies[pkg]); if (packageName === undefined) { throw new Error('Could not find any Electron packages in devDependencies'); } return packageJSON.devDependencies[packageName]; } export function updateElectronDependency(packageJSON: any, dev: string[], exact: string[]): [string[], string[]] { const alteredDev = ([] as string[]).concat(dev); let alteredExact = ([] as string[]).concat(exact); if (Object.keys(packageJSON.devDependencies).find(findElectronDep)) { alteredExact = alteredExact.filter(dep => dep !== 'electron'); } else { const electronKey = Object.keys(packageJSON.dependencies).find(findElectronDep); if (electronKey) { alteredExact = alteredExact.filter(dep => dep !== 'electron'); d(`Moving ${electronKey} from dependencies to devDependencies`); alteredDev.push(`${electronKey}@${packageJSON.dependencies[electronKey]}`); delete packageJSON.dependencies[electronKey]; } } return [alteredDev, alteredExact]; }
Make copies of the dep lists instead of altering in-place
Make copies of the dep lists instead of altering in-place
TypeScript
mit
electron-userland/electron-forge,electron-userland/electron-forge,electron-userland/electron-forge,electron-userland/electron-forge
--- +++ @@ -25,17 +25,19 @@ } export function updateElectronDependency(packageJSON: any, dev: string[], exact: string[]): [string[], string[]] { + const alteredDev = ([] as string[]).concat(dev); + let alteredExact = ([] as string[]).concat(exact); if (Object.keys(packageJSON.devDependencies).find(findElectronDep)) { - exact = exact.filter(dep => dep !== 'electron'); + alteredExact = alteredExact.filter(dep => dep !== 'electron'); } else { const electronKey = Object.keys(packageJSON.dependencies).find(findElectronDep); if (electronKey) { - exact = exact.filter(dep => dep !== 'electron'); + alteredExact = alteredExact.filter(dep => dep !== 'electron'); d(`Moving ${electronKey} from dependencies to devDependencies`); - dev.push(`${electronKey}@${packageJSON.dependencies[electronKey]}`); + alteredDev.push(`${electronKey}@${packageJSON.dependencies[electronKey]}`); delete packageJSON.dependencies[electronKey]; } } - return [dev, exact]; + return [alteredDev, alteredExact]; }
0faa1ca0954b4c5250c06143ba49815134a61b46
src/client/app/shared/models/filter-criteria.model.ts
src/client/app/shared/models/filter-criteria.model.ts
import { Params } from '@angular/router'; import { cloneDeep, pick } from 'lodash'; import { DateRangeType } from './date-range-type.model'; export class FilterCriteria { fromDate: string; //iso toDate: string; //iso ascending: boolean = true; rangeSelection: DateRangeType = DateRangeType.CURRENT_SEASON; playerIds: number[] = []; factionIds: number[] = []; agendaIds: number[] = []; deckIds: number[] = []; static serialise(criteria: FilterCriteria): any { return cloneDeep(criteria); } static deserialise(routeParams: Params): FilterCriteria { const criteria = new FilterCriteria(); Object.assign(criteria, pick(routeParams, [ 'fromDate', 'toDate', ])); // params are strings if (routeParams['rangeSelection']) { criteria.rangeSelection = +routeParams['rangeSelection']; } criteria.ascending = routeParams['ascending'] === 'true'; const arrayParamKeys = [ 'playerIds', 'factionIds', 'agendaIds', 'deckIds', ]; return arrayParamKeys.reduce((memo: any, key: string) => { memo[key] = extractNumberArray(routeParams[key]); return memo; }, criteria); function extractNumberArray(param: string): number[] { return param ? param.split(',').map((id) => +id) : []; } } }
import { Params } from '@angular/router'; import { cloneDeep, pick } from 'lodash'; import { DateRangeType } from './date-range-type.model'; export class FilterCriteria { fromDate: string; //iso toDate: string; //iso ascending: boolean = true; rangeSelection: DateRangeType = DateRangeType.CURRENT_SEASON; playerIds: number[] = []; factionIds: number[] = []; agendaIds: number[] = []; deckIds: number[] = []; static serialise(criteria: FilterCriteria): any { return cloneDeep(criteria); } static deserialise(routeParams: Params, sourceCriteria?: FilterCriteria): FilterCriteria { const criteria = sourceCriteria || new FilterCriteria(); Object.assign(criteria, pick(routeParams, [ 'fromDate', 'toDate', ])); // params are strings if (routeParams['rangeSelection']) { criteria.rangeSelection = +routeParams['rangeSelection']; } if (routeParams['ascending']) { criteria.ascending = routeParams['ascending'] === 'true'; } const arrayParamKeys = [ 'playerIds', 'factionIds', 'agendaIds', 'deckIds', ]; return arrayParamKeys.reduce((memo: any, key: string) => { if (routeParams[key]) { memo[key] = extractNumberArray(routeParams[key]); } return memo; }, criteria); function extractNumberArray(param: string): number[] { return param ? param.split(',').map((id) => +id) : []; } } }
Allow filtercriteria deserialise to take an optional source parameter, to stop defaults overriding initial values passed by components
Allow filtercriteria deserialise to take an optional source parameter, to stop defaults overriding initial values passed by components (cherry picked from commit 88fcfe23378e5211687d2570830db2ff9dc0f7fd)
TypeScript
mit
davewragg/agot-spa,davewragg/agot-spa,davewragg/agot-spa
--- +++ @@ -16,8 +16,8 @@ return cloneDeep(criteria); } - static deserialise(routeParams: Params): FilterCriteria { - const criteria = new FilterCriteria(); + static deserialise(routeParams: Params, sourceCriteria?: FilterCriteria): FilterCriteria { + const criteria = sourceCriteria || new FilterCriteria(); Object.assign(criteria, pick(routeParams, [ 'fromDate', 'toDate', ])); @@ -25,7 +25,9 @@ if (routeParams['rangeSelection']) { criteria.rangeSelection = +routeParams['rangeSelection']; } - criteria.ascending = routeParams['ascending'] === 'true'; + if (routeParams['ascending']) { + criteria.ascending = routeParams['ascending'] === 'true'; + } const arrayParamKeys = [ 'playerIds', @@ -34,7 +36,9 @@ 'deckIds', ]; return arrayParamKeys.reduce((memo: any, key: string) => { - memo[key] = extractNumberArray(routeParams[key]); + if (routeParams[key]) { + memo[key] = extractNumberArray(routeParams[key]); + } return memo; }, criteria);
3c7d782b133699e0c57689ce4f98712ada228619
src/main/components/composable/Layer/index.tsx
src/main/components/composable/Layer/index.tsx
import * as React from 'react' import * as PropTypes from 'prop-types' import { RenderingTarget, } from '../../../../main' export type Props = { target: RenderingTarget, } export default class Layer extends React.Component<Props, {}> { static contextTypes = { target: PropTypes.func.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, } static propTypes = { target: PropTypes.func, } render() { const { width, height } = this.context const target = this.props.target || this.context.target return ( <div style={{ width, height, position: 'absolute', top: '0px', left: '0px', }} > {target({ width, height, data: {} })} </div> ) } }
import * as React from 'react' import * as PropTypes from 'prop-types' import { RenderingTarget, } from '../../../../main' export type Props = { target?: RenderingTarget, } export default class Layer extends React.Component<Props, {}> { static contextTypes = { target: PropTypes.func.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, } static propTypes = { target: PropTypes.func, } render() { const { width, height } = this.context const target = this.props.target || this.context.target return ( <div style={{ width, height, position: 'absolute', top: '0px', left: '0px', }} > {target({ width, height, data: {} })} </div> ) } }
Make target optional on Layer
Make target optional on Layer
TypeScript
mit
CJ-Johnson/Bullseye,CJ-Johnson/Bullseye
--- +++ @@ -6,7 +6,7 @@ } from '../../../../main' export type Props = { - target: RenderingTarget, + target?: RenderingTarget, } export default class Layer extends React.Component<Props, {}> {
cd18489f005e4eeed52699fcc772b5d0b94b180b
templates/Angular2Spa/ClientApp/boot-client.ts
templates/Angular2Spa/ClientApp/boot-client.ts
import 'angular2-universal-polyfills/browser'; import { enableProdMode } from '@angular/core'; import { platformUniversalDynamic } from 'angular2-universal'; import { AppModule } from './app/app.module'; // Include styles in the bundle import 'bootstrap'; import './styles/site.css'; // Enable either Hot Module Reloading or production mode const hotModuleReplacement = module['hot']; if (hotModuleReplacement) { hotModuleReplacement.accept(); hotModuleReplacement.dispose(() => { platform.destroy(); }); } else { enableProdMode(); } // Boot the application const platform = platformUniversalDynamic(); document.addEventListener('DOMContentLoaded', () => { platform.bootstrapModule(AppModule); });
import 'angular2-universal-polyfills/browser'; import { enableProdMode } from '@angular/core'; import { platformUniversalDynamic } from 'angular2-universal'; import { AppModule } from './app/app.module'; // Include styles in the bundle import 'bootstrap'; import './styles/site.css'; // Enable either Hot Module Reloading or production mode const hotModuleReplacement = module['hot']; if (hotModuleReplacement) { hotModuleReplacement.accept(); hotModuleReplacement.dispose(() => { platform.destroy(); }); } else { enableProdMode(); } // Boot the application, either now or when the DOM content is loaded const platform = platformUniversalDynamic(); const bootApplication = () => { platform.bootstrapModule(AppModule); }; if (document.readyState === 'complete') { bootApplication(); } else { document.addEventListener('DOMContentLoaded', bootApplication); }
Fix HMR again following previous change
Fix HMR again following previous change
TypeScript
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
--- +++ @@ -16,8 +16,11 @@ enableProdMode(); } -// Boot the application +// Boot the application, either now or when the DOM content is loaded const platform = platformUniversalDynamic(); -document.addEventListener('DOMContentLoaded', () => { - platform.bootstrapModule(AppModule); -}); +const bootApplication = () => { platform.bootstrapModule(AppModule); }; +if (document.readyState === 'complete') { + bootApplication(); +} else { + document.addEventListener('DOMContentLoaded', bootApplication); +}
6eb078e045983cf1f5d5a1d9f71cca06b541de5b
src/frameListener.ts
src/frameListener.ts
if (window.self !== window.top) { window.addEventListener('message', (e) => { if (e.data === '_tcfdt_subdoc_std') { browser.runtime.sendMessage({request: 'stdFg'}); (window as any).tcfdtFrameFixed = true; } e.stopPropagation(); }, true); }
const requestStdColors = (e: MessageEvent) => { if (e.data === '_tcfdt_subdoc_std') { browser.runtime.sendMessage({request: 'stdFg'}); (window as any).tcfdtFrameFixed = true; } e.stopPropagation(); // No need to listen to more messages if we have fixed ourselves window.removeEventListener('message', requestStdColors, {capture: true}); }; if (window.self !== window.top) { window.addEventListener('message', requestStdColors, {capture: true}); }
Stop listening to frame fix events once one has already been received
Stop listening to frame fix events once one has already been received
TypeScript
mit
DmitriK/darkContrast,DmitriK/darkContrast,DmitriK/darkContrast
--- +++ @@ -1,9 +1,13 @@ +const requestStdColors = (e: MessageEvent) => { + if (e.data === '_tcfdt_subdoc_std') { + browser.runtime.sendMessage({request: 'stdFg'}); + (window as any).tcfdtFrameFixed = true; + } + e.stopPropagation(); + // No need to listen to more messages if we have fixed ourselves + window.removeEventListener('message', requestStdColors, {capture: true}); +}; + if (window.self !== window.top) { - window.addEventListener('message', (e) => { - if (e.data === '_tcfdt_subdoc_std') { - browser.runtime.sendMessage({request: 'stdFg'}); - (window as any).tcfdtFrameFixed = true; - } - e.stopPropagation(); - }, true); + window.addEventListener('message', requestStdColors, {capture: true}); }
dabbab507a56a7642688af51af8183171fda1f7f
app/src/lib/tip.ts
app/src/lib/tip.ts
import { TipState, Tip } from '../models/tip' export function getTipSha(tip: Tip) { if (tip.kind === TipState.Valid) { return tip.branch.tip.sha } if (tip.kind === TipState.Detached) { return tip.currentSha } return '(unknown)' }
import { TipState, Tip } from '../models/tip' export function getTipSha(tip: Tip) { if (tip.kind === TipState.Valid) { return tip.branch.tip.sha } if (tip.kind === TipState.Detached) { return tip.currentSha } return '(unknown)' }
Revert "Okay, let's try a linting error that doesn't fail the build"
Revert "Okay, let's try a linting error that doesn't fail the build" This reverts commit 4d19e2e7e1e5c4ac617ccbec8ed1e5cc576855ae.
TypeScript
mit
j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,shiftkey/desktop,say25/desktop,say25/desktop,kactus-io/kactus
--- +++ @@ -1,6 +1,6 @@ import { TipState, Tip } from '../models/tip' -export function getTipSha(tip: Tip) { +export function getTipSha(tip: Tip) { if (tip.kind === TipState.Valid) { return tip.branch.tip.sha }
2eadf4f82fe442c5f01c855dd66df7eaac698297
src/ts/mobilev3playerapi.ts
src/ts/mobilev3playerapi.ts
import { PlayerAPI, PlayerEvent, PlayerEventBase, PlayerEventCallback } from 'bitmovin-player'; import { WrappedPlayer } from './uimanager'; export enum MobileV3PlayerEvent { SourceError = 'sourceerror', PlayerError = 'playererror', PlaylistTransition = 'playlisttransition', } export interface MobileV3PlayerErrorEvent extends PlayerEventBase { name: 'onPlayerError'; code: number; message: string; } export interface MobileV3SourceErrorEvent extends PlayerEventBase { name: 'onSourceError'; code: number; message: string; } export type MobileV3PlayerEventType = PlayerEvent | MobileV3PlayerEvent; export interface MobileV3PlayerAPI extends PlayerAPI { on(eventType: MobileV3PlayerEventType, callback: PlayerEventCallback): void; exports: PlayerAPI['exports'] & { PlayerEvent: MobileV3PlayerEventType }; } export function isMobileV3PlayerAPI(player: WrappedPlayer | PlayerAPI | MobileV3PlayerAPI): player is MobileV3PlayerAPI { let everyKeyExists = true; for (const key in MobileV3PlayerEvent) { if (MobileV3PlayerEvent.hasOwnProperty(key) && !player.exports.PlayerEvent.hasOwnProperty(key)) { everyKeyExists = false; } } return everyKeyExists; }
import { PlayerAPI, PlayerEvent, PlayerEventBase, PlayerEventCallback } from 'bitmovin-player'; import { WrappedPlayer } from './uimanager'; export enum MobileV3PlayerEvent { SourceError = 'sourceerror', PlayerError = 'playererror', PlaylistTransition = 'playlisttransition', } export interface MobileV3PlayerErrorEvent extends PlayerEventBase { name: 'onPlayerError'; code: number; message: string; } export interface MobileV3SourceErrorEvent extends PlayerEventBase { name: 'onSourceError'; code: number; message: string; } export type MobileV3PlayerEventType = PlayerEvent | MobileV3PlayerEvent; export interface MobileV3PlayerAPI extends PlayerAPI { on(eventType: MobileV3PlayerEventType, callback: PlayerEventCallback): void; exports: PlayerAPI['exports'] & { PlayerEvent: MobileV3PlayerEventType }; } export function isMobileV3PlayerAPI(player: WrappedPlayer | PlayerAPI | MobileV3PlayerAPI): player is MobileV3PlayerAPI { for (const key in MobileV3PlayerEvent) { if (MobileV3PlayerEvent.hasOwnProperty(key) && !player.exports.PlayerEvent.hasOwnProperty(key)) { return false; } } return true; }
Return from isMobileV3PlayerAPI instead of using const
Return from isMobileV3PlayerAPI instead of using const
TypeScript
mit
bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui
--- +++ @@ -27,13 +27,11 @@ } export function isMobileV3PlayerAPI(player: WrappedPlayer | PlayerAPI | MobileV3PlayerAPI): player is MobileV3PlayerAPI { - let everyKeyExists = true; - for (const key in MobileV3PlayerEvent) { if (MobileV3PlayerEvent.hasOwnProperty(key) && !player.exports.PlayerEvent.hasOwnProperty(key)) { - everyKeyExists = false; + return false; } } - return everyKeyExists; + return true; }
6b8c3f28a2c372908c530a354b2d04006ecc8eb7
src/reducers/quotes.ts
src/reducers/quotes.ts
import { reducerWithInitialState } from 'typescript-fsa-reducers'; import { dicitActions } from '../actions'; import { Quote } from '../states/QuoteState'; export interface DicitState { quote: Quote; } const initialState: DicitState = { quote: { sentence: '', author: '' } }; export const quotesReducer = reducerWithInitialState(initialState) .case(dicitActions.init, (state) => { return Object.assign({}, state, { initialState }); }) .case(dicitActions.fetchQuote, (state) => { const currQuote = { sentence: 'The sinews of war are not gold, but good soldiers.', author: 'Niccoló Machiavelli' }; return Object.assign({}, state, { currQuote }); });
import { reducerWithInitialState } from 'typescript-fsa-reducers'; import { dicitActions } from '../actions'; import { Quote } from '../states/QuoteState'; export interface DicitState { quote: Quote; } const fetchNewQuote = (): Quote => { let remainedQuotes = []; if ('remainedQuotes' in localStorage) { remainedQuotes = JSON.parse(localStorage.getItem('remainedQuotes')); } if (remainedQuotes.length === 0) { const wholeQuotes = require('./../../data/quotes.json'); remainedQuotes = wholeQuotes.quotes; } const index = Math.floor(Math.random() * remainedQuotes.length); remainedQuotes.splice(index, 1); localStorage.setItem('remainedQuotes', JSON.stringify(remainedQuotes)); return remainedQuotes[index]; }; const initialState: DicitState = { quote: fetchNewQuote() }; export const quotesReducer = reducerWithInitialState(initialState) .case(dicitActions.init, (state) => { return Object.assign({}, state, { initialState }); }) .case(dicitActions.fetchQuote, (state) => { return Object.assign({}, state, { initialState }); });
Add an action to fetch dynamically
Add an action to fetch dynamically
TypeScript
mit
saiidalhalawi/dicit,saiidalhalawi/dicit,saiidalhalawi/dicit
--- +++ @@ -7,13 +7,30 @@ quote: Quote; } -const initialState: DicitState = { quote: { sentence: '', author: '' } }; +const fetchNewQuote = (): Quote => { + let remainedQuotes = []; + if ('remainedQuotes' in localStorage) { + remainedQuotes = JSON.parse(localStorage.getItem('remainedQuotes')); + } + + if (remainedQuotes.length === 0) { + const wholeQuotes = require('./../../data/quotes.json'); + remainedQuotes = wholeQuotes.quotes; + } + + const index = Math.floor(Math.random() * remainedQuotes.length); + remainedQuotes.splice(index, 1); + localStorage.setItem('remainedQuotes', JSON.stringify(remainedQuotes)); + + return remainedQuotes[index]; +}; + +const initialState: DicitState = { quote: fetchNewQuote() }; export const quotesReducer = reducerWithInitialState(initialState) .case(dicitActions.init, (state) => { return Object.assign({}, state, { initialState }); }) .case(dicitActions.fetchQuote, (state) => { - const currQuote = { sentence: 'The sinews of war are not gold, but good soldiers.', author: 'Niccoló Machiavelli' }; - return Object.assign({}, state, { currQuote }); + return Object.assign({}, state, { initialState }); });
53cd29bd4019fde67a9a28fb416b18f3717f2a5f
libs/screeps-webpack-sources.ts
libs/screeps-webpack-sources.ts
import * as path from "path"; import * as webpack from "webpack"; // disable tslint rule, because we don't have types for these files /* tslint:disable:no-var-requires */ const ConcatSource = require("webpack-sources").ConcatSource; // Tiny tiny helper plugin that prepends "module.exports = " to all `.map` assets export class ScreepsSourceMapToJson implements webpack.Plugin { // constructor(_options: any) { // // we don't use options // } public apply(compiler: webpack.Compiler) { compiler.plugin("emit", (compilation, cb) => { for (const filename in compilation.assets) { // matches any files ending in ".map" or ".map.js" if (path.basename(filename, ".js").match(/\.map/)) { compilation.assets[filename] = new ConcatSource("module.exports = ", compilation.assets[filename]); } } cb(); }); } }
import * as path from 'path' import * as webpack from 'webpack' // disable tslint rule, because we don't have types for these files /* tslint:disable:no-var-requires */ const ConcatSource = require('webpack-sources').ConcatSource // Tiny tiny helper plugin that prepends "module.exports = " to all `.map` assets export class ScreepsSourceMapToJson implements webpack.Plugin { // constructor(_options: any) { // // we don't use options // } public apply(compiler: webpack.Compiler) { compiler.plugin('emit', (compilation, cb) => { for (const filename in compilation.assets) { // matches any files ending in ".map" or ".map.js" if (path.basename(filename, '.js').match(/\.map/)) { compilation.assets[filename] = new ConcatSource('module.exports = ', compilation.assets[filename]) } } cb() }) } }
Update to match tslint settings
Update to match tslint settings
TypeScript
unlicense
tinnvec/aints,tinnvec/aints
--- +++ @@ -1,9 +1,9 @@ -import * as path from "path"; -import * as webpack from "webpack"; +import * as path from 'path' +import * as webpack from 'webpack' // disable tslint rule, because we don't have types for these files /* tslint:disable:no-var-requires */ -const ConcatSource = require("webpack-sources").ConcatSource; +const ConcatSource = require('webpack-sources').ConcatSource // Tiny tiny helper plugin that prepends "module.exports = " to all `.map` assets export class ScreepsSourceMapToJson implements webpack.Plugin { @@ -12,14 +12,14 @@ // } public apply(compiler: webpack.Compiler) { - compiler.plugin("emit", (compilation, cb) => { + compiler.plugin('emit', (compilation, cb) => { for (const filename in compilation.assets) { // matches any files ending in ".map" or ".map.js" - if (path.basename(filename, ".js").match(/\.map/)) { - compilation.assets[filename] = new ConcatSource("module.exports = ", compilation.assets[filename]); + if (path.basename(filename, '.js').match(/\.map/)) { + compilation.assets[filename] = new ConcatSource('module.exports = ', compilation.assets[filename]) } } - cb(); - }); + cb() + }) } }
d8519b2963e5616c7762f985914d799044ca0ab0
src/utils/backup.ts
src/utils/backup.ts
import * as localforage from 'localforage'; export const persistedStateToJsonString = async () => { try { const localForageKeys: string[] = await localforage.keys(); const stringArray = await Promise.all( localForageKeys.map( async key => `"${key}":` + (await localforage.getItem(key)) ) ); return '{' + stringArray.join(',') + '}'; } catch (e) { throw new Error('Failed to read user settings.'); } }; export const generateBackupBlob = (stateString: string): Blob => new Blob([stateString], { type: 'text/plain' }); export const generateFileName = (): string => `mturk-engine-backup-${new Date().toLocaleDateString()}.bak`; export const readUploadedFileAsText = async (settingsFile: File) => { const BackupFileReader = new FileReader(); BackupFileReader.onerror = err => { BackupFileReader.abort(); }; return new Promise((resolve, reject) => { BackupFileReader.onload = () => { resolve(BackupFileReader.result); }; BackupFileReader.readAsText(settingsFile); }); }; export const createTemporaryDownloadLink = (blob: Blob): HTMLAnchorElement => { const userSettingsBackup = window.URL.createObjectURL(blob); const temporaryAnchor = document.createElement('a'); temporaryAnchor.href = userSettingsBackup; temporaryAnchor.download = generateFileName(); return temporaryAnchor; };
import * as localforage from 'localforage'; export const persistedStateToJsonString = async () => { try { const localForageKeys: string[] = await localforage.keys(); const stringArray = await Promise.all( localForageKeys.map( async key => `"${key}":` + (await localforage.getItem(key)) ) ); return '{' + stringArray.join(',') + '}'; } catch (e) { throw new Error('Failed to read user settings.'); } }; export const generateBackupBlob = (stateString: string): Blob => new Blob([stateString], { type: 'text/plain' }); export const generateFileName = (): string => `mturk-engine-backup-${new Date().toLocaleDateString()}.bak`; export const readUploadedFileAsText = async (settingsFile: File) => { const BackupFileReader = new FileReader(); /** * FileReader.readAsText is asynchronous but does not use Promises. We wrap it * in a Promise here so we can await it elsewhere without blocking the main thread. */ return new Promise((resolve, reject) => { BackupFileReader.onerror = () => { reject('Failed to parse file.'); }; BackupFileReader.onload = () => { resolve(BackupFileReader.result); }; BackupFileReader.readAsText(settingsFile); }); }; export const createTemporaryDownloadLink = (blob: Blob): HTMLAnchorElement => { const userSettingsBackup = window.URL.createObjectURL(blob); const temporaryAnchor = document.createElement('a'); temporaryAnchor.href = userSettingsBackup; temporaryAnchor.download = generateFileName(); return temporaryAnchor; };
Add rejection condition to readUploadedFileAsText promise.
Add rejection condition to readUploadedFileAsText promise.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -25,11 +25,16 @@ export const readUploadedFileAsText = async (settingsFile: File) => { const BackupFileReader = new FileReader(); - BackupFileReader.onerror = err => { - BackupFileReader.abort(); - }; + /** + * FileReader.readAsText is asynchronous but does not use Promises. We wrap it + * in a Promise here so we can await it elsewhere without blocking the main thread. + */ return new Promise((resolve, reject) => { + BackupFileReader.onerror = () => { + reject('Failed to parse file.'); + }; + BackupFileReader.onload = () => { resolve(BackupFileReader.result); };
4aae02a7460b6c49025b4683bbc511f7f29bc1f1
helpers/session.ts
helpers/session.ts
import * as cookie from "cookie"; import * as http from "http"; import * as orm from "typeorm"; import * as redis from "redis"; import * as eta from "../eta"; import Application from "../server/Application"; export default class HelperSession { public static getFromRequest(req: http.IncomingMessage, redis: redis.RedisClient): Promise<{[key: string]: any}> { let sid: string; try { sid = cookie.parse(<any>req.headers.cookie)["connect.sid"]; } catch (err) { return undefined; } if (!sid) return undefined; sid = sid.split(".")[0].substring(2); return new Promise((resolve, reject) => redis.get("sess:" + sid, (err: Error, value: string) => { if (err) return reject(err); try { return resolve(JSON.parse(value)); } catch (err) { return reject(err); } }) ); } public static async promise(session: Express.Session, methodName: "save" | "regenerate" | "destroy"): Promise<void> { return new Promise<void>((resolve, reject) => { session[methodName].bind(session)((err: Error) => { if (err) reject(err); else resolve(); }); }); } }
import * as cookie from "cookie"; import * as http from "http"; import * as orm from "typeorm"; import * as redis from "redis"; import * as eta from "../eta"; export default class HelperSession { public static getFromRequest(req: http.IncomingMessage, redis: redis.RedisClient): Promise<{[key: string]: any}> { let sid: string; try { sid = cookie.parse(<any>req.headers.cookie)["connect.sid"]; } catch (err) { return undefined; } if (!sid) return undefined; sid = sid.split(".")[0].substring(2); return new Promise((resolve, reject) => redis.get("sess:" + sid, (err: Error, value: string) => { if (err) return reject(err); try { return resolve(JSON.parse(value)); } catch (err) { return reject(err); } }) ); } public static async promise(session: Express.Session, methodName: "save" | "regenerate" | "destroy"): Promise<void> { return new Promise<void>((resolve, reject) => { session[methodName].bind(session)((err: Error) => { if (err) reject(err); else resolve(); }); }); } }
Remove unnecessary import from HelperSession
Remove unnecessary import from HelperSession
TypeScript
mit
crossroads-education/eta,crossroads-education/eta
--- +++ @@ -3,7 +3,6 @@ import * as orm from "typeorm"; import * as redis from "redis"; import * as eta from "../eta"; -import Application from "../server/Application"; export default class HelperSession { public static getFromRequest(req: http.IncomingMessage, redis: redis.RedisClient): Promise<{[key: string]: any}> {
0d413bd7372143b40dd463e8856b950b2f2e5af9
types/react-big-calendar/lib/addons/dragAndDrop.d.ts
types/react-big-calendar/lib/addons/dragAndDrop.d.ts
import BigCalendar, { BigCalendarProps, Event, stringOrDate } from '../../index'; import React = require('react'); interface withDragAndDropProps<TEvent> { onEventDrop?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void; onEventResize?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void; resizable?: boolean; } declare class DragAndDropCalendar<TEvent extends Event = Event, TResource extends object = object> extends React.Component<BigCalendarProps<TEvent, TResource> & withDragAndDropProps<TEvent>> {} declare function withDragAndDrop(calendar: typeof BigCalendar): typeof DragAndDropCalendar; export = withDragAndDrop;
import BigCalendar, { BigCalendarProps, Event, stringOrDate } from '../../index'; import React from 'react'; interface withDragAndDropProps<TEvent> { onEventDrop?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void; onEventResize?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void; resizable?: boolean; } declare class DragAndDropCalendar<TEvent extends Event = Event, TResource extends object = object> extends React.Component<BigCalendarProps<TEvent, TResource> & withDragAndDropProps<TEvent>> {} declare function withDragAndDrop(calendar: typeof BigCalendar): typeof DragAndDropCalendar; export = withDragAndDrop;
Use ES import to see if it works
Use ES import to see if it works
TypeScript
mit
georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped
--- +++ @@ -1,5 +1,5 @@ import BigCalendar, { BigCalendarProps, Event, stringOrDate } from '../../index'; -import React = require('react'); +import React from 'react'; interface withDragAndDropProps<TEvent> { onEventDrop?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void;
4e75ff21cdb979d063e0f48ef341af4ca62de07e
frontend/src/ts/abalone/player.ts
frontend/src/ts/abalone/player.ts
module Abalone { export enum Player {White, Black} export function next(p: Player) { return (p === Player.White) ? Player.Black : Player.White; } export function player2str(p: Player): string { return p === Player.White ? "White" : "Black" } export function str2player(s: String): Player { switch (s) { case "White": return Player.White; case "Black": return Player.Black; default: return null; } } }
module Abalone { export enum Player {White, Black} export function next(p: Player) { return (p === Player.White) ? Player.Black : Player.White; } export function player2str(p: Player): string { return p === Player.White ? "white" : "black" } export function str2player(s: String): Player { switch (s) { case "white": return Player.White; case "black": return Player.Black; default: return null; } } }
Standardize around lowercase "white" and "black"
Standardize around lowercase "white" and "black"
TypeScript
mit
danmane/abalone,danmane/abalone,danmane/abalone,danmane/abalone,danmane/abalone,danmane/abalone
--- +++ @@ -5,13 +5,13 @@ } export function player2str(p: Player): string { - return p === Player.White ? "White" : "Black" + return p === Player.White ? "white" : "black" } export function str2player(s: String): Player { switch (s) { - case "White": + case "white": return Player.White; - case "Black": + case "black": return Player.Black; default: return null;
d5b891d71c74a8941830aa1f767926989ee1bba8
src/keyPathify.ts
src/keyPathify.ts
const _ = require('underscore'); require('underscore-keypath'); const seedrandom = require('seedrandom'); import { State } from './state' var seed: string|number|undefined; var rng = seedrandom(); export default function keyPathify(input: string|any, state: any, checkIfDefined = false) { // Coerce stringly-numbers into numbers if (input == parseInt(input)) { return parseInt(input) } // TODO: I'm not sure I like this solution. if (state.rngSeed && state.rngSeed !== seed) { seed = state.rngSeed rng = seedrandom(seed) } // TODO: I'm not sure I like this object solution. // If I keep it, though, add a TS interface if (_.isObject(input)) { if(input.randInt && _.isArray(input.randInt)) { const lower = input.randInt[0]; const upper = input.randInt[1]; return Math.floor(rng() * (upper - lower)) + lower; } else { return input; } } else if (!_.isString(input)) { return input; } const result = _(state).valueForKeyPath(input) if (checkIfDefined && _.isUndefined(result)) { return input; } return result; }
const _ = require('underscore'); require('underscore-keypath'); const seedrandom = require('seedrandom'); import { State } from './state' var seed: string|number|undefined; var rng = seedrandom(); export default function keyPathify(input: string|any, state: any, checkIfDefined = false) { // TODO: I'm not sure I like this solution. if (state.rngSeed && state.rngSeed !== seed) { seed = state.rngSeed rng = seedrandom(seed) } // TODO: I'm not sure I like this object solution. // If I keep it, though, add a TS interface if (_.isObject(input)) { if(input.randInt && _.isArray(input.randInt)) { const lower = input.randInt[0]; const upper = input.randInt[1]; return Math.floor(rng() * (upper - lower)) + lower; } else { return input; } } else if (!_.isString(input)) { return input; } const result = _(state).valueForKeyPath(input) if (checkIfDefined && _.isUndefined(result)) { return input; } return result; }
Remove string/number parsing hack (now handled by the language parser)
Remove string/number parsing hack (now handled by the language parser)
TypeScript
mit
lazerwalker/storyboard,lazerwalker/storyboard,lazerwalker/storyboard
--- +++ @@ -8,11 +8,6 @@ var rng = seedrandom(); export default function keyPathify(input: string|any, state: any, checkIfDefined = false) { - // Coerce stringly-numbers into numbers - if (input == parseInt(input)) { - return parseInt(input) - } - // TODO: I'm not sure I like this solution. if (state.rngSeed && state.rngSeed !== seed) { seed = state.rngSeed
f5d3521d36919a7428f33e616d0b583c0cf8008c
src/app/app.module.ts
src/app/app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { routing, appRoutingProviders } from './app.routing'; import { Ng2BootstrapModule, ButtonsModule } from 'ng2-bootstrap/ng2-bootstrap'; import { NG2_WEBSTORAGE } from 'ng2-webstorage'; import { AppComponent } from './app.component'; import { ShowsComponent } from './shows/shows.component'; import { SeatsComponent } from './seats/seats.component'; @NgModule({ imports: [ BrowserModule, FormsModule, routing, Ng2BootstrapModule, ButtonsModule ], declarations: [ AppComponent, ShowsComponent, SeatsComponent ], providers: [ appRoutingProviders, NG2_WEBSTORAGE ], bootstrap: [AppComponent] }) export class AppModule { }
import { NgModule } from '@angular/core'; import { LocationStrategy, HashLocationStrategy } from '@angular/common'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { routing, appRoutingProviders } from './app.routing'; import { Ng2BootstrapModule, ButtonsModule } from 'ng2-bootstrap/ng2-bootstrap'; import { NG2_WEBSTORAGE } from 'ng2-webstorage'; import { AppComponent } from './app.component'; import { ShowsComponent } from './shows/shows.component'; import { SeatsComponent } from './seats/seats.component'; @NgModule({ imports: [ BrowserModule, FormsModule, routing, Ng2BootstrapModule, ButtonsModule ], declarations: [ AppComponent, ShowsComponent, SeatsComponent ], providers: [ appRoutingProviders, NG2_WEBSTORAGE, { provide: LocationStrategy, useClass: HashLocationStrategy } ], bootstrap: [AppComponent] }) export class AppModule { }
Use hash-based locationstrategy to allow refreshes
Use hash-based locationstrategy to allow refreshes
TypeScript
mit
XiTickets/Frontend,XiTickets/Frontend
--- +++ @@ -1,4 +1,5 @@ import { NgModule } from '@angular/core'; +import { LocationStrategy, HashLocationStrategy } from '@angular/common'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; @@ -26,7 +27,8 @@ ], providers: [ appRoutingProviders, - NG2_WEBSTORAGE + NG2_WEBSTORAGE, + { provide: LocationStrategy, useClass: HashLocationStrategy } ], bootstrap: [AppComponent] })
ebd4955b038ae6a4fa235ec49206948ebd0d9a26
src/app/app.module.ts
src/app/app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { FooterComponent } from '../components/footer/footer.component'; import { HeaderComponent } from '../components/header/header.component'; @NgModule({ imports: [ BrowserModule, HttpModule, FormsModule ], declarations: [ AppComponent, FooterComponent, HeaderComponent ], bootstrap: [ AppComponent, FooterComponent, HeaderComponent ] }) export class AppModule { }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { MaterializeModule } from 'angular2-materialize'; import { AppComponent } from './app.component'; import { FooterComponent } from '../components/footer/footer.component'; import { HeaderComponent } from '../components/header/header.component'; @NgModule({ imports: [ BrowserModule, HttpModule, FormsModule, MaterializeModule ], declarations: [ AppComponent, FooterComponent, HeaderComponent ], bootstrap: [ AppComponent, FooterComponent, HeaderComponent ] }) export class AppModule { }
Add library for MaterializeCSS integration
Add library for MaterializeCSS integration
TypeScript
mit
ivanna-ostrovets/language-and-literature-admin,ivanna-ostrovets/language-and-literature-admin,ivanna-ostrovets/language-and-literature-admin
--- +++ @@ -2,6 +2,8 @@ import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; + +import { MaterializeModule } from 'angular2-materialize'; import { AppComponent } from './app.component'; @@ -12,7 +14,8 @@ imports: [ BrowserModule, HttpModule, - FormsModule + FormsModule, + MaterializeModule ], declarations: [ AppComponent,
f2eda6950a6dacf3615a198954ebdba411780a47
src/app/optimizer/optimizer.component.ts
src/app/optimizer/optimizer.component.ts
import {Component, OnInit} from '@angular/core'; import {HTTP_PROVIDERS} from '@angular/http'; import {OptimizerDataService} from './optimizer-data.service'; import {InputComponent} from './input/input.component'; import {BarchartComponent} from './barchart/barchart.component'; import {ResultsTableComponent} from './results-table/results-table.component'; @Component({ moduleId: module.id, selector: 'optimizer', templateUrl: 'optimizer.component.html', styleUrls: ['optimizer.component.css'], directives: [InputComponent, BarchartComponent, ResultsTableComponent], providers: [OptimizerDataService, HTTP_PROVIDERS] }) export class OptimizerComponent { this.optimalAllocs = {AAPL: 0.0, GOOG: 0.5489549524820141, FB: 0.4510450475179859}; this.sharpeRatio = 0.5730332517669126; history = Object[] = []; data; constructor(private optimizerDataService: OptimizerDataService) { optimizerDataService.optimalAllocs$.subscribe( optimalAllocs ) } // ngOnInit() { // this.optimizerDataService.optimizePortfolio(); // } // getOptimizationData() { // this.data = this.optimizerDataService.optimizePortfolio(this.data); // } }
import {Component, OnInit} from '@angular/core'; import {HTTP_PROVIDERS} from '@angular/http'; import {OptimizerDataService} from './optimizer-data.service'; import {InputComponent} from './input/input.component'; import {BarchartComponent} from './barchart/barchart.component'; import {ResultsTableComponent} from './results-table/results-table.component'; @Component({ moduleId: module.id, selector: 'optimizer', templateUrl: 'optimizer.component.html', styleUrls: ['optimizer.component.css'], directives: [InputComponent, BarchartComponent, ResultsTableComponent], providers: [OptimizerDataService, HTTP_PROVIDERS] }) export class OptimizerComponent { optimalAllocs = {AAPL: 0.0, GOOG: 0.5489549524820141, FB: 0.4510450475179859}; sharpeRatio = 0.5730332517669126; history: Object[] = []; data; constructor(private optimizerDataService: OptimizerDataService) { optimizerDataService.optimalAllocs$.subscribe(); } // ngOnInit() { // this.optimizerDataService.optimizePortfolio(); // } // getOptimizationData() { // this.data = this.optimizerDataService.optimizePortfolio(this.data); // } }
Fix variable scoping and subscription to data service.
Fix variable scoping and subscription to data service.
TypeScript
mit
coshx/portfolio_optimizer,coshx/portfolio_optimizer,coshx/portfolio_optimizer,coshx/portfolio_optimizer
--- +++ @@ -15,17 +15,15 @@ providers: [OptimizerDataService, HTTP_PROVIDERS] }) export class OptimizerComponent { - this.optimalAllocs = {AAPL: 0.0, - GOOG: 0.5489549524820141, - FB: 0.4510450475179859}; - this.sharpeRatio = 0.5730332517669126; - history = Object[] = []; + optimalAllocs = {AAPL: 0.0, + GOOG: 0.5489549524820141, + FB: 0.4510450475179859}; + sharpeRatio = 0.5730332517669126; + history: Object[] = []; data; constructor(private optimizerDataService: OptimizerDataService) { - optimizerDataService.optimalAllocs$.subscribe( - optimalAllocs - ) + optimizerDataService.optimalAllocs$.subscribe(); } // ngOnInit() {
210f576c951bdaa6a6014631286d0c0074430f49
src/app/public/ts/pagenotfound.component.ts
src/app/public/ts/pagenotfound.component.ts
import { Component } from '@angular/core'; @Component({ templateUrl: '../html/pagenotfound.component.html' }) export class PageNotFound {}
import { Component } from '@angular/core'; import { Router } from '@angular/router' import { Socket } from '../../../services/socketio.service'; @Component({ templateUrl: '../html/pagenotfound.component.html' }) export class PageNotFound { constructor(private router: Router, private socket: Socket) { } ngOnInit() { if(this.router.url != '/404-test') { this.socket.emit('404', this.router.url); } } }
Send 404 to the server for stats
Send 404 to the server for stats
TypeScript
agpl-3.0
V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War
--- +++ @@ -1,7 +1,20 @@ import { Component } from '@angular/core'; +import { Router } from '@angular/router' +import { Socket } from '../../../services/socketio.service'; @Component({ templateUrl: '../html/pagenotfound.component.html' }) -export class PageNotFound {} +export class PageNotFound { + + constructor(private router: Router, private socket: Socket) { + + } + + ngOnInit() { + if(this.router.url != '/404-test') { + this.socket.emit('404', this.router.url); + } + } +}
eb74e49155dcd55b2203b7a5f03cd6a4ccf03294
src/CK.Glouton.Web/app/src/app/common/logs/models/log.model.ts
src/CK.Glouton.Web/app/src/app/common/logs/models/log.model.ts
export enum LogType { OpenGroup, Line, CloseGroup } export interface ILogViewModel { logType: LogType; logTime: string; text: string; tags: string; sourceFileName: string; lineNumber: string; exception: IExceptionViewModel; logLevel:string; monitorId: string; groupDepth: string; previousEntryType: string; previousLogTime: string; appName: string; conclusion: string; } export interface IInnerExceptionViewModel { stackTrace: string; message: string; fileName: string; } export interface IExceptionViewModel { innerException: IInnerExceptionViewModel; aggregatedExceptions: IExceptionViewModel[]; message: string; stackTrace: string; }
export enum LogType { OpenGroup, Line, CloseGroup } export interface ILogViewModel { logType: LogType; logTime: string; text: string; tags: string; sourceFileName: string; lineNumber: string; exception: IExceptionViewModel; logLevel:string; monitorId: string; groupDepth: number; previousEntryType: string; previousLogTime: string; appName: string; conclusion: string; } export interface IInnerExceptionViewModel { stackTrace: string; message: string; fileName: string; } export interface IExceptionViewModel { innerException: IInnerExceptionViewModel; aggregatedExceptions: IExceptionViewModel[]; message: string; stackTrace: string; }
Update groupDepth to number in ILogViewModel.
Update groupDepth to number in ILogViewModel.
TypeScript
mit
ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton
--- +++ @@ -14,7 +14,7 @@ exception: IExceptionViewModel; logLevel:string; monitorId: string; - groupDepth: string; + groupDepth: number; previousEntryType: string; previousLogTime: string; appName: string;
4edb58841c53e454302174aaf4f5d7eedeca2390
src/services/vuestic-ui/global-config.ts
src/services/vuestic-ui/global-config.ts
import VaIcon from './components/va-icon' import VaToast from './components/va-toast' import VaButton from './components/va-button' import iconsConfig from './icons-config/icons-config' import { COLOR_THEMES } from './themes' export default { components: { VaIcon, VaToast, VaButton, }, colors: COLOR_THEMES[0].colors, icons: iconsConfig }
import VaIcon from './components/va-icon' import VaToast from './components/va-toast' import VaButton from './components/va-button' import iconsConfig from './icons-config/icons-config' import { COLOR_THEMES } from './themes' export default { components: { VaIcon, VaToast, VaButton, ...COLOR_THEMES[0].components }, colors: COLOR_THEMES[0].colors, icons: iconsConfig }
Set Navbar and Sidebar color from theme before render.
Set Navbar and Sidebar color from theme before render.
TypeScript
mit
epicmaxco/vuestic-admin,epicmaxco/vuestic-admin,epicmaxco/vuestic-admin,epicmaxco/vuestic-admin
--- +++ @@ -9,6 +9,7 @@ VaIcon, VaToast, VaButton, + ...COLOR_THEMES[0].components }, colors: COLOR_THEMES[0].colors, icons: iconsConfig
bc8303b43a8948a02b387dfb0218466ae8ddc62a
core/lib/router-manager.ts
core/lib/router-manager.ts
import { router } from '@vue-storefront/core/app' import VueRouter, { RouteConfig } from 'vue-router' const RouterManager = { _registeredRoutes: new Array<RouteConfig>(), addRoutes: function (routes: RouteConfig[], routerInstance: VueRouter = router): void { this._registeredRoutes.push(...routes) router.addRoutes(routes) }, findByName: function (name: string): RouteConfig { return this._registeredRoutes.find(r => r.name === name) }, findByPath: function (fullPath: string): RouteConfig { return this._registeredRoutes.find(r => r.fullPath === fullPath) } } export { RouterManager }
import { router } from '@vue-storefront/core/app' import VueRouter, { RouteConfig } from 'vue-router' const RouterManager = { _registeredRoutes: new Array<RouteConfig>(), addRoutes: function (routes: RouteConfig[], routerInstance: VueRouter = router): void { const uniqueRoutes = routes.filter( (route) => this._registeredRoutes.findIndex( (registeredRoute) => registeredRoute.name === route.name && registeredRoute.path === route.path ) === -1 ) this._registeredRoutes.push(...uniqueRoutes) router.addRoutes(uniqueRoutes) }, findByName: function (name: string): RouteConfig { return this._registeredRoutes.find(r => r.name === name) }, findByPath: function (fullPath: string): RouteConfig { return this._registeredRoutes.find(r => r.fullPath === fullPath) } } export { RouterManager }
Fix same routes being registered multiple times
Fix same routes being registered multiple times
TypeScript
mit
pkarw/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront
--- +++ @@ -4,8 +4,13 @@ const RouterManager = { _registeredRoutes: new Array<RouteConfig>(), addRoutes: function (routes: RouteConfig[], routerInstance: VueRouter = router): void { - this._registeredRoutes.push(...routes) - router.addRoutes(routes) + const uniqueRoutes = routes.filter( + (route) => this._registeredRoutes.findIndex( + (registeredRoute) => registeredRoute.name === route.name && registeredRoute.path === route.path + ) === -1 + ) + this._registeredRoutes.push(...uniqueRoutes) + router.addRoutes(uniqueRoutes) }, findByName: function (name: string): RouteConfig { return this._registeredRoutes.find(r => r.name === name)
fdd58d8e96beea4bd8005159e77f28cb79bad06b
src/plugins/autocompletion_providers/Cd.ts
src/plugins/autocompletion_providers/Cd.ts
import {expandHistoricalDirectory} from "../../shell/Command"; import {styles, Suggestion, directoriesSuggestionsProvider} from "./Common"; import * as _ from "lodash"; import {PluginManager} from "../../PluginManager"; PluginManager.registerAutocompletionProvider("cd", async(context) => { let suggestions: Suggestion[] = []; /** * Historical directories. */ if (context.argument.value.startsWith("-")) { const historicalDirectoryAliases = _.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalPresentDirectoriesStack.size) .map(alias => new Suggestion().withValue(alias).withDescription(expandHistoricalDirectory(alias, context.historicalPresentDirectoriesStack)).withStyle(styles.directory)); suggestions.push(...historicalDirectoryAliases); } suggestions.push(...await directoriesSuggestionsProvider(context)); if (context.argument.value.length > 0) { const cdpathDirectories = _.flatten(await Promise.all(context.environment.cdpath .filter(directory => directory !== context.environment.pwd) .map(async(directory) => (await directoriesSuggestionsProvider(context, directory)).map(suggestion => suggestion.withDescription(`In ${directory}`))))); suggestions.push(...cdpathDirectories); } return suggestions; });
import {expandHistoricalDirectory} from "../../shell/Command"; import {styles, Suggestion, directoriesSuggestionsProvider} from "./Common"; import * as _ from "lodash"; import {PluginManager} from "../../PluginManager"; PluginManager.registerAutocompletionProvider("cd", async(context) => { let suggestions: Suggestion[] = []; /** * Historical directories. */ if (context.argument.value.startsWith("-")) { const historicalDirectoryAliases = ["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"] .slice(0, context.historicalPresentDirectoriesStack.size) .map(alias => new Suggestion().withValue(alias).withDescription(expandHistoricalDirectory(alias, context.historicalPresentDirectoriesStack)).withStyle(styles.directory)); suggestions.push(...historicalDirectoryAliases); } suggestions.push(...await directoriesSuggestionsProvider(context)); if (context.argument.value.length > 0) { const cdpathDirectories = _.flatten(await Promise.all(context.environment.cdpath .filter(directory => directory !== context.environment.pwd) .map(async(directory) => (await directoriesSuggestionsProvider(context, directory)).map(suggestion => suggestion.withDescription(`In ${directory}`))))); suggestions.push(...cdpathDirectories); } return suggestions; });
Use slice instead of take.
Use slice instead of take.
TypeScript
mit
black-screen/black-screen,vshatskyi/black-screen,drew-gross/black-screen,black-screen/black-screen,drew-gross/black-screen,vshatskyi/black-screen,shockone/black-screen,railsware/upterm,j-allard/black-screen,vshatskyi/black-screen,vshatskyi/black-screen,black-screen/black-screen,j-allard/black-screen,drew-gross/black-screen,railsware/upterm,shockone/black-screen,drew-gross/black-screen,j-allard/black-screen
--- +++ @@ -10,7 +10,8 @@ * Historical directories. */ if (context.argument.value.startsWith("-")) { - const historicalDirectoryAliases = _.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalPresentDirectoriesStack.size) + const historicalDirectoryAliases = ["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"] + .slice(0, context.historicalPresentDirectoriesStack.size) .map(alias => new Suggestion().withValue(alias).withDescription(expandHistoricalDirectory(alias, context.historicalPresentDirectoriesStack)).withStyle(styles.directory)); suggestions.push(...historicalDirectoryAliases);
b074e0eff35ac8b1b34efa902681aa19ba2b8629
js/components/DropTarget.tsx
js/components/DropTarget.tsx
import React from "react"; interface Coord { x: number; y: number; } interface Props extends React.HTMLAttributes<HTMLDivElement> { handleDrop(e: React.DragEvent<HTMLDivElement>, coord: Coord): void; } export default class DropTarget extends React.Component<Props> { supress(e: React.DragEvent<HTMLDivElement>) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = "link"; e.dataTransfer.effectAllowed = "link"; } handleDrop = (e: React.DragEvent<HTMLDivElement>) => { this.supress(e); const { target } = e; if (!(target instanceof Element)) { return; } const { left: x, top: y } = target.getBoundingClientRect(); this.props.handleDrop(e, { x, y }); }; render() { const { // eslint-disable-next-line no-shadow, no-unused-vars handleDrop, ...passThroughProps } = this.props; return ( <div {...passThroughProps} onDragStart={this.supress} onDragEnter={this.supress} onDragOver={this.supress} onDrop={this.handleDrop} /> ); } }
import React from "react"; interface Coord { x: number; y: number; } interface Props extends React.HTMLAttributes<HTMLDivElement> { handleDrop(e: React.DragEvent<HTMLDivElement>, coord: Coord): void; } export default class DropTarget extends React.Component<Props> { supress(e: React.DragEvent<HTMLDivElement>) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = "link"; e.dataTransfer.effectAllowed = "link"; } handleDrop = (e: React.DragEvent<HTMLDivElement>) => { this.supress(e); // TODO: We could probably move this coordinate logic into the playlist. // I think that's the only place it gets used. const { currentTarget } = e; if (!(currentTarget instanceof Element)) { return; } const { left: x, top: y } = currentTarget.getBoundingClientRect(); this.props.handleDrop(e, { x, y }); }; render() { const { // eslint-disable-next-line no-shadow, no-unused-vars handleDrop, ...passThroughProps } = this.props; return ( <div {...passThroughProps} onDragStart={this.supress} onDragEnter={this.supress} onDragOver={this.supress} onDrop={this.handleDrop} /> ); } }
Fix how we calculate the position of trackes dropped into the playlist
Fix how we calculate the position of trackes dropped into the playlist Fixes #688
TypeScript
mit
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
--- +++ @@ -19,12 +19,14 @@ handleDrop = (e: React.DragEvent<HTMLDivElement>) => { this.supress(e); - const { target } = e; - if (!(target instanceof Element)) { + // TODO: We could probably move this coordinate logic into the playlist. + // I think that's the only place it gets used. + const { currentTarget } = e; + if (!(currentTarget instanceof Element)) { return; } - const { left: x, top: y } = target.getBoundingClientRect(); + const { left: x, top: y } = currentTarget.getBoundingClientRect(); this.props.handleDrop(e, { x, y }); };
99f92ae44ebf0d70ceaedd596f1b7746fde2a8db
tools/node_tools/node_modules_licenses/utils.ts
tools/node_tools/node_modules_licenses/utils.ts
/** * @license * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as fs from "fs"; export function fail(message: string): never { console.error(message); process.exit(1); } export function readMultilineParamFile(path: string): string[] { return fs.readFileSync(path, {encoding: 'utf-8'}).split(/\r?\n/).filter(f => f.length > 0); }
/** * @license * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as fs from "fs"; export function fail(message: string): never { console.error(message); process.exit(1); } // Bazel params may be surrounded with quotes function removeSurrondedQuotes(str: string): string { return str.startsWith("'") && str.endsWith("'") ? str.slice(1, -1) : str; } export function readMultilineParamFile(path: string): string[] { return fs.readFileSync(path, {encoding: 'utf-8'}) .split(/\r?\n/) .filter(f => f.length > 0) .map(removeSurrondedQuotes); }
Fix infinity loop when bazel passes an argument with surrounded quotes
Fix infinity loop when bazel passes an argument with surrounded quotes Change-Id: I35a96f20a05c3042165081efb4fb1dd6a369e0a5
TypeScript
apache-2.0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
--- +++ @@ -22,6 +22,15 @@ process.exit(1); } +// Bazel params may be surrounded with quotes +function removeSurrondedQuotes(str: string): string { + return str.startsWith("'") && str.endsWith("'") ? + str.slice(1, -1) : str; +} + export function readMultilineParamFile(path: string): string[] { - return fs.readFileSync(path, {encoding: 'utf-8'}).split(/\r?\n/).filter(f => f.length > 0); + return fs.readFileSync(path, {encoding: 'utf-8'}) + .split(/\r?\n/) + .filter(f => f.length > 0) + .map(removeSurrondedQuotes); }
36adda016fb05ca2f5a456b506b951df803d7fe4
src/selfupdater.ts
src/selfupdater.ts
import fs from './fs'; import { Controller, Events } from './controller'; import { ControllerWrapper } from './controller-wrapper'; import { Manifest } from './data'; export abstract class SelfUpdater { static async attach(manifestFile: string): Promise<SelfUpdaterInstance> { const manifestStr = await fs.readFile(manifestFile, 'utf8'); const manifest: Manifest = JSON.parse(manifestStr); if (!manifest.runningInfo) { throw new Error(`Manifest doesn't have a running info, cannot connect to self updater`); } const controller = new Controller(manifest.runningInfo.port, { process: manifest.runningInfo.pid, keepConnected: true, }); controller.connect(); return new SelfUpdaterInstance(controller); } } export type SelfUpdaterEvents = Events; export class SelfUpdaterInstance extends ControllerWrapper<SelfUpdaterEvents> { constructor(controller: Controller) { super(controller); } async checkForUpdates(options?: { authToken?: string; metadata?: string }) { options = options || {}; const result = await this.controller.sendCheckForUpdates( '', '', options.authToken, options.metadata ); return result; } async updateBegin() { const result = await this.controller.sendUpdateBegin(); return result; } async updateApply() { const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2)); return result; } }
import fs from './fs'; import { Controller, Events } from './controller'; import { ControllerWrapper } from './controller-wrapper'; import { Manifest } from './data'; export abstract class SelfUpdater { static async attach(manifestFile: string): Promise<SelfUpdaterInstance> { const manifestStr = await fs.readFile(manifestFile, 'utf8'); const manifest: Manifest = JSON.parse(manifestStr); if (!manifest.runningInfo) { throw new Error(`Manifest doesn't have a running info, cannot connect to self updater`); } const controller = new Controller(manifest.runningInfo.port, { process: manifest.runningInfo.pid, keepConnected: true, }); controller.connect(); return new SelfUpdaterInstance(controller); } } export type SelfUpdaterEvents = Events; export class SelfUpdaterInstance extends ControllerWrapper<SelfUpdaterEvents> { constructor(controller: Controller) { super(controller); } async checkForUpdates(options?: { authToken?: string; metadata?: string }) { options = options || {}; const result = await this.controller.sendCheckForUpdates( '', '', options.authToken, options.metadata ); return result.success; } async updateBegin() { const result = await this.controller.sendUpdateBegin(); return result.success; } async updateApply() { const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2)); return result.success; } }
Revert "Return the actual results from the self updater"
Revert "Return the actual results from the self updater" This reverts commit a35351453d050d945f9b205bcfeb99a59c62ac07.
TypeScript
mit
gamejolt/client-voodoo,gamejolt/client-voodoo
--- +++ @@ -37,16 +37,16 @@ options.authToken, options.metadata ); - return result; + return result.success; } async updateBegin() { const result = await this.controller.sendUpdateBegin(); - return result; + return result.success; } async updateApply() { const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2)); - return result; + return result.success; } }
758c77896f335848fb609a907033f13bf2431b67
functions/src/add-item.ts
functions/src/add-item.ts
import { Request, Response } from "express"; import * as admin from "firebase-admin"; import * as msgpack from "msgpack-lite"; import nanoid = require("nanoid"); import { parse } from "url"; import { convertUrlIntoArticle } from "./article"; import { httpsFunction } from "./utils"; import { convertUrlIntoVideo } from "./video"; class File { private file; constructor(path: string) { this.file = admin.storage().bucket().file(path); } public read = async () => await msgpack.decode((await this.file.download())[0]); public write = async (content: any) => await this.file.save(msgpack.encode(content)); } export default httpsFunction( async ({ query: { url } }: Request, response: Response, userId: string) => { const isVideo = parse(url).hostname === "www.youtube.com"; const item = await (isVideo ? convertUrlIntoVideo : convertUrlIntoArticle)(url); console.log("Item:", item); const file = new File(`/users/${userId}/${isVideo ? "videos" : "articles"}/todo`); let items = []; try { items = await file.read(); } catch (error) { if (error.code === 404) { console.log(error); } else { throw error; } } await file.write([{ id: nanoid(), ...item }, ...items]); response.sendStatus(200); }, { noCache: true });
import { Request, Response } from "express"; import * as admin from "firebase-admin"; import * as msgpack from "msgpack-lite"; import nanoid = require("nanoid"); import { parse } from "url"; import { convertUrlIntoArticle } from "./article"; import { httpsFunction } from "./utils"; import { convertUrlIntoVideo } from "./video"; class File { private file; constructor(path: string) { this.file = admin.storage().bucket().file(path); } public read = async () => await msgpack.decode((await this.file.download())[0]); public write = async (content: any) => await this.file.save(msgpack.encode(content)); } export default httpsFunction( async ({ query: { url } }: Request, response: Response, userId: string) => { const isVideo = parse(url).hostname === "www.youtube.com"; const item = await (isVideo ? convertUrlIntoVideo : convertUrlIntoArticle)(url); console.log("Item:", item); const file = new File(`/users/${userId}/${isVideo ? "videos" : "articles"}/todo`); let items = []; try { items = await file.read(); } catch (error) { if (error.code === 404) { console.log(error); } else { throw error; } } await file.write([{ id: nanoid(), ...item }, ...items]); response.send(item); }, { noCache: true });
Return added items from addItem function
Return added items from addItem function
TypeScript
mit
raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d
--- +++ @@ -43,5 +43,5 @@ await file.write([{ id: nanoid(), ...item }, ...items]); - response.sendStatus(200); + response.send(item); }, { noCache: true });
62210337b3d036875c06bab66c36f745f86c2085
MvcNG/Views/ngApp/myapp/services/NameSvc.ts
MvcNG/Views/ngApp/myapp/services/NameSvc.ts
namespace MyApp.Services { export interface IData { value: string; } export class NameSvc { static $inject = ["$q", "WAIT"]; constructor(private $q: angular.IQService, private wait: number) { this.wait = wait || 1000; } private _newValue(value: string): IData { return {value}; } getName(): angular.IPromise<IData> { var p = this.$q.defer<IData>() setTimeout(() => p.resolve( this._newValue("Pippo") ), this.wait); return p.promise; } } }
namespace MyApp.Services { export interface IData { value: string; } export class NameSvc { static $inject = ["$q", "WAIT", "NAME"]; constructor(private $q: angular.IQService, private wait: number, private name:string) { this.wait = wait || 1000; } private _newValue(value: string): IData { return {value}; } getName(): angular.IPromise<IData> { var p = this.$q.defer<IData>() setTimeout(() => p.resolve( this._newValue(this.name) ), this.wait); return p.promise; } } }
Add inject of NAME from angular.constant <-- dynInject
Add inject of NAME from angular.constant <-- dynInject
TypeScript
mit
dmorosinotto/MVC_NG_TS,dmorosinotto/MVC_NG_TS
--- +++ @@ -4,8 +4,8 @@ } export class NameSvc { - static $inject = ["$q", "WAIT"]; - constructor(private $q: angular.IQService, private wait: number) { + static $inject = ["$q", "WAIT", "NAME"]; + constructor(private $q: angular.IQService, private wait: number, private name:string) { this.wait = wait || 1000; } @@ -15,7 +15,7 @@ getName(): angular.IPromise<IData> { var p = this.$q.defer<IData>() - setTimeout(() => p.resolve( this._newValue("Pippo") ), this.wait); + setTimeout(() => p.resolve( this._newValue(this.name) ), this.wait); return p.promise; } }
b440c2f32f12978bf9ec8a94822aff487579460f
app/src/ui/preferences/advanced.tsx
app/src/ui/preferences/advanced.tsx
import * as React from 'react' import { DialogContent } from '../dialog' import { Checkbox, CheckboxValue } from '../lib/checkbox' import { LinkButton } from '../lib/link-button' interface IAdvancedPreferencesProps { readonly isOptedOut: boolean, readonly confirmRepoRemoval: boolean, readonly onOptOutSet: (checked: boolean) => void readonly onConfirmRepoRemovalSet: (checked: boolean) => void } interface IAdvancedPreferencesState { readonly reportingOptOut: boolean } const SamplesURL = 'https://desktop.github.com/samples/' export class Advanced extends React.Component<IAdvancedPreferencesProps, IAdvancedPreferencesState> { public constructor(props: IAdvancedPreferencesProps) { super(props) this.state = { reportingOptOut: this.props.isOptedOut, } } private onChange = (event: React.FormEvent<HTMLInputElement>) => { const value = !event.currentTarget.checked this.setState({ reportingOptOut: value }) this.props.onOptOutSet(value) } public render() { return ( <DialogContent> <div> Would you like to help us improve GitHub Desktop by periodically submitting <LinkButton uri={SamplesURL}>anonymous usage data</LinkButton>? </div> <br /> <Checkbox label='Yes, submit anonymized usage data' value={this.state.reportingOptOut ? CheckboxValue.Off : CheckboxValue.On} onChange={this.onChange} /> </DialogContent> ) } }
import * as React from 'react' import { DialogContent } from '../dialog' import { Checkbox, CheckboxValue } from '../lib/checkbox' import { LinkButton } from '../lib/link-button' interface IAdvancedPreferencesProps { readonly isOptedOut: boolean, readonly confirmRepoRemoval: boolean, readonly onOptOutSet: (checked: boolean) => void readonly onConfirmRepoRemovalSet: (checked: boolean) => void } interface IAdvancedPreferencesState { readonly reportingOptOut: boolean readonly confirmRepoRemoval: boolean } const SamplesURL = 'https://desktop.github.com/samples/' export class Advanced extends React.Component<IAdvancedPreferencesProps, IAdvancedPreferencesState> { public constructor(props: IAdvancedPreferencesProps) { super(props) this.state = { reportingOptOut: this.props.isOptedOut, confirmRepoRemoval: this.props.confirmRepoRemoval, } } private onChange = (event: React.FormEvent<HTMLInputElement>) => { const value = !event.currentTarget.checked this.setState({ reportingOptOut: value }) this.props.onOptOutSet(value) } public render() { return ( <DialogContent> <div> Would you like to help us improve GitHub Desktop by periodically submitting <LinkButton uri={SamplesURL}>anonymous usage data</LinkButton>? </div> <br /> <Checkbox label='Yes, submit anonymized usage data' value={this.state.reportingOptOut ? CheckboxValue.Off : CheckboxValue.On} onChange={this.onChange} /> </DialogContent> ) } }
Add state for repo removal
Add state for repo removal
TypeScript
mit
kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,desktop/desktop,desktop/desktop,desktop/desktop,hjobrien/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,BugTesterTest/desktops,artivilla/desktop,say25/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,gengjiawen/desktop,shiftkey/desktop,artivilla/desktop,hjobrien/desktop,gengjiawen/desktop,say25/desktop,artivilla/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,BugTesterTest/desktops,BugTesterTest/desktops,say25/desktop,j-f1/forked-desktop,BugTesterTest/desktops,hjobrien/desktop,shiftkey/desktop,hjobrien/desktop,j-f1/forked-desktop
--- +++ @@ -12,6 +12,7 @@ interface IAdvancedPreferencesState { readonly reportingOptOut: boolean + readonly confirmRepoRemoval: boolean } const SamplesURL = 'https://desktop.github.com/samples/' @@ -22,6 +23,7 @@ this.state = { reportingOptOut: this.props.isOptedOut, + confirmRepoRemoval: this.props.confirmRepoRemoval, } }
382d091f82b70ce3a0236ff0ee12ccb8e8887b67
app/types/ItemTypes.ts
app/types/ItemTypes.ts
/// <reference path="../References.d.ts"/> export const LOADING = Symbol('item.loading'); export const LOAD = Symbol('item.load'); export const CREATE = Symbol('item.create'); export const REMOVE = Symbol('item.remove'); export const UPDATE = Symbol('item.update'); export interface Item { id: string; content: string; } export type Items = {[key: string]: Item} export interface ItemDispatch { type: Symbol; data: { id: string; content: string; items: Item[]; }; }
/// <reference path="../References.d.ts"/> export const LOADING = Symbol('item.loading'); export const LOAD = Symbol('item.load'); export const CREATE = Symbol('item.create'); export const REMOVE = Symbol('item.remove'); export const UPDATE = Symbol('item.update'); export interface Item { id: string; content: string; } export type Items = {[key: string]: Item} export interface ItemDispatch { type: Symbol; data?: { id: string; content: string; items: Item[]; }; }
Fix type in item types
Fix type in item types
TypeScript
mit
zachhuff386/react-boilerplate,zachhuff386/react-boilerplate
--- +++ @@ -14,7 +14,7 @@ export interface ItemDispatch { type: Symbol; - data: { + data?: { id: string; content: string; items: Item[];
fb6091893fb2b902528351d7084adfb4cd7f4eb4
lib/download-db.ts
lib/download-db.ts
import path from 'path'; import { downloadFolder } from './constants'; import { setDbLocation } from './db/maxmind/db-helper'; import { downloadDB } from './file-fetch-extract'; const main = async (): Promise<void> => { const downloadFileLocation = path.join(__dirname, downloadFolder); await setDbLocation(downloadFileLocation); await downloadDB(downloadFileLocation); }; main();
import path from 'path'; import { downloadFolder } from './constants'; import { setDbLocation } from './db/maxmind/db-helper'; import { downloadDB } from './file-fetch-extract'; const main = async (): Promise<void> => { const { MAXMIND_LICENSE_KEY } = process.env; if (!MAXMIND_LICENSE_KEY) { console.error('You need to export MAXMIND_LICENSE_KEY'); process.exit(); } const downloadFileLocation = path.join(__dirname, downloadFolder); await setDbLocation(downloadFileLocation); await downloadDB(downloadFileLocation); }; main();
Add early error message if MAXMIND_LICENSE_KEY is missing for DB download
Add early error message if MAXMIND_LICENSE_KEY is missing for DB download
TypeScript
mit
guyellis/ipapi,guyellis/ipapi,guyellis/ipapi
--- +++ @@ -4,6 +4,12 @@ import { downloadDB } from './file-fetch-extract'; const main = async (): Promise<void> => { + const { MAXMIND_LICENSE_KEY } = process.env; + if (!MAXMIND_LICENSE_KEY) { + console.error('You need to export MAXMIND_LICENSE_KEY'); + process.exit(); + } + const downloadFileLocation = path.join(__dirname, downloadFolder); await setDbLocation(downloadFileLocation); await downloadDB(downloadFileLocation);
7d7104e8efcf4d04b01e48a59773f4802caa1785
src/ts/environment.ts
src/ts/environment.ts
import {PreDestroy, Bean, Qualifier, Autowired, PostConstruct, Optional, Context} from "./context/context"; const themes = [ 'fresh', 'dark', 'blue', 'bootstrap', 'material-next', 'material']; const themeCLass = new RegExp(`ag-(${themes.join('|')})`); @Bean('environment') export class Environment { @Autowired('eGridDiv') private eGridDiv: HTMLElement; public getTheme(): string { return this.eGridDiv.className.match(themeCLass)[0]; } }
import {PreDestroy, Bean, Qualifier, Autowired, PostConstruct, Optional, Context} from "./context/context"; const themes = [ 'fresh', 'dark', 'blue', 'bootstrap', 'material-next', 'material']; const themeCLass = new RegExp(`ag-(${themes.join('|')})`); @Bean('environment') export class Environment { @Autowired('eGridDiv') private eGridDiv: HTMLElement; public getTheme(): string { const themeMatch: RegExpMatchArray = this.eGridDiv.className.match(themeCLass); if (themeMatch) { return themeMatch[0]; } else { return ''; } } }
Fix case when no theme is matched
Fix case when no theme is matched
TypeScript
mit
ceolter/ag-grid,seanlandsman/ag-grid,seanlandsman/ag-grid,ceolter/angular-grid,killyosaur/ag-grid,killyosaur/ag-grid,seanlandsman/ag-grid,ceolter/ag-grid,ceolter/angular-grid,killyosaur/ag-grid
--- +++ @@ -8,6 +8,11 @@ @Autowired('eGridDiv') private eGridDiv: HTMLElement; public getTheme(): string { - return this.eGridDiv.className.match(themeCLass)[0]; + const themeMatch: RegExpMatchArray = this.eGridDiv.className.match(themeCLass); + if (themeMatch) { + return themeMatch[0]; + } else { + return ''; + } } }
b66b5dc97be7c63c60d4a1e78120976d5fec1166
lib/src/Flex/utils.ts
lib/src/Flex/utils.ts
export interface Props { [key: string]: any; } export function exclude(props: Props): Props { const result = { ...props }; delete result.inline; delete result.alignContent; delete result.alignItems; delete result.alignSelf; delete result.justifyContent; delete result.basis; delete result.flexBasis; delete result.grow; delete result.shrink; delete result.row; delete result.column; delete result.reverse; delete result.wrap; delete result.order; delete result.hfill; delete result.vfill; delete result.fill; delete result.component; delete result.tagName; return result; }
export interface Props { [key: string]: any; } export function exclude(props: Props): Props { const result = { ...props }; delete result.inline; delete result.alignContent; delete result.alignItems; delete result.alignSelf; delete result.justifyContent; delete result.basis; delete result.flexBasis; delete result.grow; delete result.shrink; delete result.row; delete result.column; delete result.reverse; delete result.wrap; delete result.order; delete result.hfill; delete result.vfill; delete result.fill; delete result.component; delete result.tagName; delete result.center; return result; }
Exclude center prop from output
Exclude center prop from output
TypeScript
mit
vlazh/reflexy,vlazh/reflexy
--- +++ @@ -24,6 +24,7 @@ delete result.fill; delete result.component; delete result.tagName; + delete result.center; return result; }
3d54d68e8febab4a24d3ebfd125450b187466ff2
src/util.ts
src/util.ts
'use strict'; export function formatPath(contractPath: string) { return contractPath.replace(/\\/g, '/'); }
'use strict'; export function formatPath(contractPath: string) { return contractPath.replace(/\\/g, '/'); }
Remove response time bottleneck fix
Remove response time bottleneck fix
TypeScript
mit
juanfranblanco/vscode-solidity
--- +++ @@ -1,5 +1,5 @@ 'use strict'; export function formatPath(contractPath: string) { - return contractPath.replace(/\\/g, '/'); + return contractPath.replace(/\\/g, '/'); }
d18e10a7904d1156b351b2cc33c9d5a2713445f9
resources/assets/lib/beatmapsets-show/beatmapset-menu.tsx
resources/assets/lib/beatmapsets-show/beatmapset-menu.tsx
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import BeatmapsetJson from 'interfaces/beatmapset-json'; import { PopupMenuPersistent } from 'popup-menu-persistent'; import * as React from 'react'; import { ReportReportable } from 'report-reportable'; interface Props { beatmapset: BeatmapsetJson; } export default function BeatmapsetMenu(props: Props) { return ( <PopupMenuPersistent> {() => ( <ReportReportable className='simple-menu__item' icon reportableId={props.beatmapset.id.toString()} reportableType='beatmapset' user={{username: props.beatmapset.creator}} /> )} </PopupMenuPersistent> ); }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import BeatmapsetJson from 'interfaces/beatmapset-json'; import { PopupMenu } from 'popup-menu'; import * as React from 'react'; import { ReportReportable } from 'report-reportable'; interface Props { beatmapset: BeatmapsetJson; } export default function BeatmapsetMenu(props: Props) { return ( <PopupMenu> {() => ( <ReportReportable className='simple-menu__item' icon reportableId={props.beatmapset.id.toString()} reportableType='beatmapset' user={{username: props.beatmapset.creator}} /> )} </PopupMenu> ); }
Update another one which doesn't have contexts
Update another one which doesn't have contexts
TypeScript
agpl-3.0
notbakaneko/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,notbakaneko/osu-web,ppy/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,nanaya/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web
--- +++ @@ -2,7 +2,7 @@ // See the LICENCE file in the repository root for full licence text. import BeatmapsetJson from 'interfaces/beatmapset-json'; -import { PopupMenuPersistent } from 'popup-menu-persistent'; +import { PopupMenu } from 'popup-menu'; import * as React from 'react'; import { ReportReportable } from 'report-reportable'; @@ -12,7 +12,7 @@ export default function BeatmapsetMenu(props: Props) { return ( - <PopupMenuPersistent> + <PopupMenu> {() => ( <ReportReportable className='simple-menu__item' @@ -22,6 +22,6 @@ user={{username: props.beatmapset.creator}} /> )} - </PopupMenuPersistent> + </PopupMenu> ); }
a23a6224a359b047886addb4ff7f3a5b7b356b1b
packages/rev-api/src/examples/01_registering_an_api.ts
packages/rev-api/src/examples/01_registering_an_api.ts
import * as rev from 'rev-models'; import * as api from '../index'; // EXAMPLE: // import * as rev from 'rev-models' export class Person { @rev.TextField({label: 'First Name'}) first_name: string; @rev.TextField({label: 'Last Name'}) last_name: string; @rev.IntegerField({label: 'Age', required: false }) age: number; @rev.EmailField({label: 'Email'}) email: string; @rev.BooleanField({label: 'Registered for Newsletter?'}) newsletter: boolean; @rev.BooleanField({label: 'Date Registered'}) date_registered: Date; } rev.register(Person); api.register(Person, { operations: ['read'], methods: [ { name: 'unsubscribe', args: ['email'], handler: async (context, email) => { console.log('Unsubscribe requested for', email); return 'Unsubscribed'; } } ] });
import * as rev from 'rev-models'; import * as api from '../index'; // EXAMPLE: // import * as rev from 'rev-models'; // import * as api from 'rev-api'; export class Person { @rev.TextField({label: 'First Name'}) first_name: string; @rev.TextField({label: 'Last Name'}) last_name: string; @rev.IntegerField({label: 'Age', required: false }) age: number; @rev.EmailField({label: 'Email'}) email: string; @rev.BooleanField({label: 'Registered for Newsletter?'}) newsletter: boolean; @rev.BooleanField({label: 'Date Registered'}) date_registered: Date; } rev.register(Person); api.register(Person, { operations: ['read'], methods: [ { name: 'unsubscribe', args: ['email'], handler: async (context, email) => { console.log('Unsubscribe requested for', email); return 'Unsubscribed'; } }, { name: 'randomMember', args: [ new rev.fields.TextField('name'), new rev.fields.IntegerField('minAge', {minValue: 16}) ], handler: async (context, name) => { console.log('Getting a random member named', name); return { first_name: 'Bob', age: 21 }; } } ] });
Add further api method example using field object args
Add further api method example using field object args
TypeScript
mit
RevFramework/rev-framework,RevFramework/rev-framework
--- +++ @@ -3,7 +3,8 @@ import * as api from '../index'; // EXAMPLE: -// import * as rev from 'rev-models' +// import * as rev from 'rev-models'; +// import * as api from 'rev-api'; export class Person { @@ -33,6 +34,20 @@ console.log('Unsubscribe requested for', email); return 'Unsubscribed'; } + }, + { + name: 'randomMember', + args: [ + new rev.fields.TextField('name'), + new rev.fields.IntegerField('minAge', {minValue: 16}) + ], + handler: async (context, name) => { + console.log('Getting a random member named', name); + return { + first_name: 'Bob', + age: 21 + }; + } } ] });
80765df64ae4f3430ce05de695593f8274a13e25
packages/utils/src/interaction/useKeyboardDetection.ts
packages/utils/src/interaction/useKeyboardDetection.ts
import { useEffect } from "react"; import useToggle from "../useToggle"; /** * A small hook for checking if the app is currently being interacted with * by a keyboard. * * @return true if the app is in keyboard mode * @private */ export default function useKeyboardDetection(): boolean { const [enabled, enable, disable] = useToggle(false); useEffect(() => { if (enabled) { return; } window.addEventListener("keydown", enable, true); return () => { window.removeEventListener("keydown", enable, true); }; }, [enabled, enable]); useEffect(() => { if (!enabled) { return; } window.addEventListener("wheel", disable, true); window.addEventListener("mousedown", disable, true); window.addEventListener("touchstart", disable, true); return () => { window.removeEventListener("wheel", disable, true); window.removeEventListener("mousedown", disable, true); window.removeEventListener("touchstart", disable, true); }; }, [enabled, disable]); return enabled; }
import { useEffect } from "react"; import useToggle from "../useToggle"; /** * A small hook for checking if the app is currently being interacted with * by a keyboard. * * @return true if the app is in keyboard mode * @private */ export default function useKeyboardDetection(): boolean { const [enabled, enable, disable] = useToggle(false); useEffect(() => { if (enabled) { return; } window.addEventListener("keydown", enable, true); return () => { window.removeEventListener("keydown", enable, true); }; }, [enabled, enable]); useEffect(() => { if (!enabled) { return; } window.addEventListener("mousedown", disable, true); window.addEventListener("touchstart", disable, true); return () => { window.removeEventListener("mousedown", disable, true); window.removeEventListener("touchstart", disable, true); }; }, [enabled, disable]); return enabled; }
Revert "Fixed interaction mode for shift+mousewheel"
Revert "Fixed interaction mode for shift+mousewheel" This reverts commit a57ce970ce26de7474c987a2d2482d3bc01e406e. This doesn't seem like good behavior after playing with it a bit more. It would work much better if the shift key was being pressed while the wheel event was triggered instead, but I don't think it's worth the extra event listeners/work right now to implement.
TypeScript
mit
mlaursen/react-md,mlaursen/react-md,mlaursen/react-md
--- +++ @@ -29,12 +29,10 @@ return; } - window.addEventListener("wheel", disable, true); window.addEventListener("mousedown", disable, true); window.addEventListener("touchstart", disable, true); return () => { - window.removeEventListener("wheel", disable, true); window.removeEventListener("mousedown", disable, true); window.removeEventListener("touchstart", disable, true); };
d7c2e1be8be9f2fc66607ccf76d71941998f9add
src/question_radiogroup.ts
src/question_radiogroup.ts
import { Serializer } from "./jsonobject"; import { QuestionFactory } from "./questionfactory"; import { QuestionCheckboxBase } from "./question_baseselect"; import { surveyLocalization } from "./surveyStrings"; /** * A Model for a radiogroup question. */ export class QuestionRadiogroupModel extends QuestionCheckboxBase { constructor(public name: string) { super(name); } public getType(): string { return "radiogroup"; } protected getFirstInputElementId(): string { return this.inputId + "_0"; } /** * Show "clear button" flag. */ public get showClearButton(): boolean { return this.getPropertyValue("showClearButton", false); } public set showClearButton(val: boolean) { this.setPropertyValue("showClearButton", val); } public get canShowClearButton(): boolean { return this.showClearButton && !this.isReadOnly; } public get clearButtonCaption() { return surveyLocalization.getString("clearCaption"); } supportGoNextPageAutomatic() { return true; } } Serializer.addClass( "radiogroup", [{ name: "showClearButton:boolean", default: false }], function() { return new QuestionRadiogroupModel(""); }, "checkboxbase" ); QuestionFactory.Instance.registerQuestion("radiogroup", name => { var q = new QuestionRadiogroupModel(name); q.choices = QuestionFactory.DefaultChoices; return q; });
import { Serializer } from "./jsonobject"; import { QuestionFactory } from "./questionfactory"; import { QuestionCheckboxBase } from "./question_baseselect"; import { surveyLocalization } from "./surveyStrings"; import { ItemValue } from "./itemvalue"; /** * A Model for a radiogroup question. */ export class QuestionRadiogroupModel extends QuestionCheckboxBase { constructor(public name: string) { super(name); } public getType(): string { return "radiogroup"; } protected getFirstInputElementId(): string { return this.inputId + "_0"; } public get selectedItem(): ItemValue { if (this.isEmpty()) return null; return ItemValue.getItemByValue(this.visibleChoices, this.value); } /** * Show "clear button" flag. */ public get showClearButton(): boolean { return this.getPropertyValue("showClearButton", false); } public set showClearButton(val: boolean) { this.setPropertyValue("showClearButton", val); } public get canShowClearButton(): boolean { return this.showClearButton && !this.isReadOnly; } public get clearButtonCaption() { return surveyLocalization.getString("clearCaption"); } supportGoNextPageAutomatic() { return true; } } Serializer.addClass( "radiogroup", [{ name: "showClearButton:boolean", default: false }], function() { return new QuestionRadiogroupModel(""); }, "checkboxbase" ); QuestionFactory.Instance.registerQuestion("radiogroup", name => { var q = new QuestionRadiogroupModel(name); q.choices = QuestionFactory.DefaultChoices; return q; });
Add selectedItem property into radiogroup question
Add selectedItem property into radiogroup question
TypeScript
mit
andrewtelnov/surveyjs,surveyjs/surveyjs,surveyjs/surveyjs,andrewtelnov/surveyjs,andrewtelnov/surveyjs,surveyjs/surveyjs,surveyjs/surveyjs
--- +++ @@ -2,6 +2,7 @@ import { QuestionFactory } from "./questionfactory"; import { QuestionCheckboxBase } from "./question_baseselect"; import { surveyLocalization } from "./surveyStrings"; +import { ItemValue } from "./itemvalue"; /** * A Model for a radiogroup question. @@ -15,6 +16,10 @@ } protected getFirstInputElementId(): string { return this.inputId + "_0"; + } + public get selectedItem(): ItemValue { + if (this.isEmpty()) return null; + return ItemValue.getItemByValue(this.visibleChoices, this.value); } /** * Show "clear button" flag.
c276930cc3a40dde0cb3fae6f0c78ac5c6f3230f
polygerrit-ui/app/services/flags/flags.ts
polygerrit-ui/app/services/flags/flags.ts
/** * @license * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export interface FlagsService { isEnabled(experimentId: string): boolean; enabledExperiments: string[]; } /** * @desc Experiment ids used in Gerrit. */ export enum KnownExperimentId { // Note that this flag is not supposed to be used by Gerrit itself, but can // be used by plugins. The new Checks UI will show up, if a plugin registers // with the new Checks plugin API. CI_REBOOT_CHECKS = 'UiFeature__ci_reboot_checks', NEW_CHANGE_SUMMARY_UI = 'UiFeature__new_change_summary_ui', PORTING_COMMENTS = 'UiFeature__porting_comments', }
/** * @license * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export interface FlagsService { isEnabled(experimentId: string): boolean; enabledExperiments: string[]; } /** * @desc Experiment ids used in Gerrit. */ export enum KnownExperimentId { // Note that this flag is not supposed to be used by Gerrit itself, but can // be used by plugins. The new Checks UI will show up, if a plugin registers // with the new Checks plugin API. CI_REBOOT_CHECKS = 'UiFeature__ci_reboot_checks', NEW_CHANGE_SUMMARY_UI = 'UiFeature__new_change_summary_ui', PORTING_COMMENTS = 'UiFeature__porting_comments', NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui', }
Add experiment ID for new image diff UI
Add experiment ID for new image diff UI Change-Id: Ieeb7b586912d0f375dbb6db9326ad38951c2368c
TypeScript
apache-2.0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
--- +++ @@ -30,4 +30,5 @@ CI_REBOOT_CHECKS = 'UiFeature__ci_reboot_checks', NEW_CHANGE_SUMMARY_UI = 'UiFeature__new_change_summary_ui', PORTING_COMMENTS = 'UiFeature__porting_comments', + NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui', }
0f2668550c47ed2c06d28aee341786e5d6eec681
Assignment_2/src/frontend/components/MonitoringItem.tsx
Assignment_2/src/frontend/components/MonitoringItem.tsx
import * as React from 'react'; import { WeatherLocationData } from '../../model/WeatherLocationData'; interface MonitoringItemProps { weatherData: WeatherLocationData; } class MonitoringItem extends React.Component<MonitoringItemProps, void> { public render(): JSX.Element { let temperatureDataToRender: string = 'N/A'; if (this.props.weatherData.temperatureData) { // Don't render ℃ with N/A. if (this.props.weatherData.temperatureData.temperature !== 'N/A') { temperatureDataToRender = this.props.weatherData.temperatureData.temperature + ' ℃'; } } let rainfallDataToRender: string = 'N/A'; if (this.props.weatherData.rainfallData) { if (this.props.weatherData.rainfallData.rainfall !== 'N/A') { rainfallDataToRender = this.props.weatherData.rainfallData.rainfall + ' mm'; } } return ( <section className="pad-item-list"> <h1 className="txt-body-2">{this.props.weatherData.location}</h1> { this.props.weatherData.rainfallData ? <h2 className="txt-body-1">{rainfallDataToRender}</h2> : null } { this.props.weatherData.temperatureData ? <h2 className="txt-body-1">{temperatureDataToRender}</h2> : null } </section> ); } } export {MonitoringItem}; export default MonitoringItem;
import * as React from 'react'; import { WeatherLocationData } from '../../model/WeatherLocationData'; interface MonitoringItemProps { weatherData: WeatherLocationData; } class MonitoringItem extends React.Component<MonitoringItemProps, void> { public render(): JSX.Element { let temperatureDataToRender: string = 'N/A'; if (this.props.weatherData.temperatureData) { // Don't render ℃ with N/A. if (this.props.weatherData.temperatureData.temperature !== 'N/A') { temperatureDataToRender = this.props.weatherData.temperatureData.temperature + ' ℃'; } } let rainfallDataToRender: string = 'N/A'; if (this.props.weatherData.rainfallData) { if (this.props.weatherData.rainfallData.rainfall !== 'N/A') { rainfallDataToRender = this.props.weatherData.rainfallData.rainfall + ' mm'; } } return ( <section className="pad-item-list"> <h1 className="txt-body-2">{this.props.weatherData.location}</h1> { this.props.weatherData.rainfallData ? <h2 className="txt-body-1">Rainfall: {rainfallDataToRender}</h2> : null } { this.props.weatherData.temperatureData ? <h2 className="txt-body-1">Temperature: {temperatureDataToRender}</h2> : null } </section> ); } } export {MonitoringItem}; export default MonitoringItem;
Add names for data displayed
Add names for data displayed
TypeScript
mit
PatrickShaw/weather-app,PatrickShaw/weather-app,PatrickShaw/weather-app
--- +++ @@ -28,12 +28,12 @@ <h1 className="txt-body-2">{this.props.weatherData.location}</h1> { this.props.weatherData.rainfallData ? - <h2 className="txt-body-1">{rainfallDataToRender}</h2> : + <h2 className="txt-body-1">Rainfall: {rainfallDataToRender}</h2> : null } { this.props.weatherData.temperatureData ? - <h2 className="txt-body-1">{temperatureDataToRender}</h2> : + <h2 className="txt-body-1">Temperature: {temperatureDataToRender}</h2> : null } </section>
8557031a2533107cecf44b64678fcc1a4ff69d24
src/components/Provider/index.tsx
src/components/Provider/index.tsx
import { Grommet } from 'grommet'; import merge from 'lodash/merge'; import * as React from 'react'; import styled from 'styled-components'; import { DefaultProps, Theme } from '../../common-types'; import defaultTheme from '../../theme'; import { px } from '../../utils'; import { BreakpointProvider } from './BreakpointProvider'; const Base = styled(Grommet)` font-family: ${props => props.theme.font}; font-size: ${props => px(props.theme.fontSizes[1])}; h1, h2, h3, h4, h5, h6, button { font-family: ${props => props.theme.titleFont}; } `; const Provider = ({ theme, ...props }: ThemedProvider) => { const providerTheme = merge(defaultTheme, theme); return ( <BreakpointProvider breakpoints={providerTheme.breakpoints}> <Base theme={providerTheme} {...props} /> </BreakpointProvider> ); }; export interface ThemedProvider extends DefaultProps { theme?: Theme; } export default Provider;
import { Grommet } from 'grommet'; import merge from 'lodash/merge'; import * as React from 'react'; import styled from 'styled-components'; import { DefaultProps, Theme } from '../../common-types'; import defaultTheme from '../../theme'; import { px } from '../../utils'; import { BreakpointProvider } from './BreakpointProvider'; const Base = styled(Grommet)` font-family: ${props => props.theme.font}; font-size: ${props => px(props.theme.fontSizes[1])}; h1, h2, h3, h4, h5, h6, button { font-family: ${props => props.theme.titleFont}; } `; const Provider = ({ theme, ...props }: ThemedProvider) => { const providerTheme = merge(defaultTheme, theme); return ( <BreakpointProvider breakpoints={providerTheme.breakpoints}> <Base theme={providerTheme} {...props} /> </BreakpointProvider> ); }; export interface ThemedProvider extends DefaultProps { theme?: Partial<Theme>; } export default Provider;
Fix the theme prop typings
Provider: Fix the theme prop typings Since we do `merge`, we do not require all theme props to be provided. Change-type: patch Signed-off-by: Thodoris Greasidis <5791bdc4541e79bd43d586e3c3eff1e39c16665f@balena.io>
TypeScript
mit
resin-io-modules/resin-components,resin-io-modules/resin-components,resin-io-modules/resin-components
--- +++ @@ -32,7 +32,7 @@ }; export interface ThemedProvider extends DefaultProps { - theme?: Theme; + theme?: Partial<Theme>; } export default Provider;
c738588ae69ec069ee9af0cc5c9f0a9e374d61c4
pages/posts/index.tsx
pages/posts/index.tsx
import { NextPage } from "next" import Page from "../../layouts/main" import postPreviewsLoader from "../../data/loaders/PostPreviewsLoader" import EntryPreviews from "../../components/EntryPreviews" import Head from "next/head" import BlogPostPreview from "../../models/BlogPostPreview" interface Props { posts: BlogPostPreview[] } const PostPage: NextPage<Props> = props => { const { posts } = props return ( <Page> <Head> <title>Blog Posts</title> <meta name="description" content="Blog posts by Joseph Duffy" /> </Head> <EntryPreviews entries={posts} pageCount={1} paginationHREF="/posts/[slug]" currentPage={1} /> </Page> ) } interface StaticProps { props: Props } export async function getStaticProps(): Promise<StaticProps> { const posts = await postPreviewsLoader.getPostsPreviews() return { props: { posts, }, } } export default PostPage
import { NextPage } from "next" import Page from "../../layouts/main" import postPreviewsLoader from "../../data/loaders/PostPreviewsLoader" import EntryPreviews from "../../components/EntryPreviews" import Head from "next/head" import BlogPostPreview from "../../models/BlogPostPreview" import { compareDesc } from "date-fns" interface Props { posts: BlogPostPreview[] } const PostPage: NextPage<Props> = props => { const { posts } = props return ( <Page> <Head> <title>Blog Posts</title> <meta name="description" content="Blog posts by Joseph Duffy" /> </Head> <EntryPreviews entries={posts} pageCount={1} paginationHREF="/posts/[slug]" currentPage={1} /> </Page> ) } interface StaticProps { props: Props } export async function getStaticProps(): Promise<StaticProps> { const posts = await postPreviewsLoader.getPostsPreviews() posts.sort((postA, postB) => { return compareDesc(new Date(postA.date), new Date(postB.date)) }) return { props: { posts, }, } } export default PostPage
Fix /posts/ not being in date order
Fix /posts/ not being in date order
TypeScript
mit
JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk
--- +++ @@ -4,6 +4,7 @@ import EntryPreviews from "../../components/EntryPreviews" import Head from "next/head" import BlogPostPreview from "../../models/BlogPostPreview" +import { compareDesc } from "date-fns" interface Props { posts: BlogPostPreview[] @@ -33,6 +34,9 @@ export async function getStaticProps(): Promise<StaticProps> { const posts = await postPreviewsLoader.getPostsPreviews() + posts.sort((postA, postB) => { + return compareDesc(new Date(postA.date), new Date(postB.date)) + }) return { props: {
e08f80ee747dfa22fefe2c5c76408e0f2d43e920
src/file-upload/file-like-object.class.ts
src/file-upload/file-like-object.class.ts
function isElement(node:any):boolean { return !!(node && (node.nodeName || node.prop && node.attr && node.find)); } export class FileLikeObject { public lastModifiedDate:any; public size:any; public type:string; public name:string; public constructor(fileOrInput:any) { let isInput = isElement(fileOrInput); let fakePathOrObject = isInput ? fileOrInput.value : fileOrInput; let postfix = typeof fakePathOrObject === 'string' ? 'FakePath' : 'Object'; let method = '_createFrom' + postfix; (this as any)[method](fakePathOrObject); } public _createFromFakePath(path:string):void { this.lastModifiedDate = void 0; this.size = void 0; this.type = 'like/' + path.slice(path.lastIndexOf('.') + 1).toLowerCase(); this.name = path.slice(path.lastIndexOf('/') + path.lastIndexOf('\\') + 2); } public _createFromObject(object:{size:number, type:string, name:string}):void { // this.lastModifiedDate = copy(object.lastModifiedDate); this.size = object.size; this.type = object.type; this.name = object.name; } }
function isElement(node:any):boolean { return !!(node && (node.nodeName || node.prop && node.attr && node.find)); } export class FileLikeObject { public lastModifiedDate:any; public size:any; public type:string; public name:string; public rawFile:string; public constructor(fileOrInput:any) { this.rawFile = fileOrInput; let isInput = isElement(fileOrInput); let fakePathOrObject = isInput ? fileOrInput.value : fileOrInput; let postfix = typeof fakePathOrObject === 'string' ? 'FakePath' : 'Object'; let method = '_createFrom' + postfix; (this as any)[method](fakePathOrObject); } public _createFromFakePath(path:string):void { this.lastModifiedDate = void 0; this.size = void 0; this.type = 'like/' + path.slice(path.lastIndexOf('.') + 1).toLowerCase(); this.name = path.slice(path.lastIndexOf('/') + path.lastIndexOf('\\') + 2); } public _createFromObject(object:{size:number, type:string, name:string}):void { // this.lastModifiedDate = copy(object.lastModifiedDate); this.size = object.size; this.type = object.type; this.name = object.name; } }
Add rawFile in the file like object
Add rawFile in the file like object
TypeScript
mit
valor-software/ng2-file-upload,valor-software/ng2-file-upload,valor-software/ng2-file-upload
--- +++ @@ -7,8 +7,10 @@ public size:any; public type:string; public name:string; + public rawFile:string; public constructor(fileOrInput:any) { + this.rawFile = fileOrInput; let isInput = isElement(fileOrInput); let fakePathOrObject = isInput ? fileOrInput.value : fileOrInput; let postfix = typeof fakePathOrObject === 'string' ? 'FakePath' : 'Object';
e6958ac8fddb3f6433e2157a27534fec3f5dd308
app/CakeInput.tsx
app/CakeInput.tsx
import * as React from "react"; interface CakeInputState { value: string; } class CakeInput extends React.Component<any, CakeInputState> { constructor(props: React.Props<any>) { super(props); // Required because of the ES6 class syntax decifiency this.onSubmit = this.onSubmit.bind(this); this.state = { value: "" }; } refs: { [string: string]: any; cakeName: any; } onSubmit(e: Event) { e.preventDefault(); const newCake = { name: this.refs.cakeName.value, description: "", date: new Date() }; // Propagate to external handler this.props.onSubmit(newCake); // State didn't for some reason propagate correctly to the input's default value, // so clearing the input field directly for now this.refs.cakeName.value = ""; } render() { return ( <form onSubmit={this.onSubmit}> <h3>New cake</h3> <input ref="cakeName" type="text" placeholder="Cake name" /> <button type="submit">Add</button> </form> ); } } export default CakeInput;
import * as React from "react"; interface CakeInputState { value: string; } class CakeInput extends React.Component<any, CakeInputState> { constructor(props: React.Props<any>) { super(props); // Rebindings required because of the ES6 class syntax decifiency this.onSubmit = this.onSubmit.bind(this); this.updateState = this.updateState.bind(this); this.state = { value: "" }; } refs: { [string: string]: any; cakeName: any; } onSubmit(e: Event) { e.preventDefault(); const newCake = { name: this.refs.cakeName.value, description: "", date: new Date() }; // Propagate to external handler this.props.onSubmit(newCake); // Equally valid for this use case, but less React-kosher would have been simply to this.refs.cakeName.value = ""; this.setState({ value: "" }); } updateState(e: Event) { const newValue = this.refs.cakeName.value; this.setState({ value: newValue }); } render() { return ( <form onSubmit={this.onSubmit}> <h3>New cake</h3> <input ref="cakeName" type="text" onChange={this.updateState} value={this.state.value} placeholder="Cake name" /> <button type="submit">Add</button> </form> ); } } export default CakeInput;
Clear input field on submit somewhat properly, via state and not manually
Clear input field on submit somewhat properly, via state and not manually
TypeScript
mit
mieky/we-love-cake,mieky/we-love-cake
--- +++ @@ -8,8 +8,9 @@ constructor(props: React.Props<any>) { super(props); - // Required because of the ES6 class syntax decifiency + // Rebindings required because of the ES6 class syntax decifiency this.onSubmit = this.onSubmit.bind(this); + this.updateState = this.updateState.bind(this); this.state = { value: "" }; } @@ -30,16 +31,20 @@ // Propagate to external handler this.props.onSubmit(newCake); - // State didn't for some reason propagate correctly to the input's default value, - // so clearing the input field directly for now - this.refs.cakeName.value = ""; + // Equally valid for this use case, but less React-kosher would have been simply to this.refs.cakeName.value = ""; + this.setState({ value: "" }); + } + + updateState(e: Event) { + const newValue = this.refs.cakeName.value; + this.setState({ value: newValue }); } render() { return ( <form onSubmit={this.onSubmit}> <h3>New cake</h3> - <input ref="cakeName" type="text" placeholder="Cake name" /> + <input ref="cakeName" type="text" onChange={this.updateState} value={this.state.value} placeholder="Cake name" /> <button type="submit">Add</button> </form> );
642afe3746496a4195f5d9cb7a666f1b135c2ba2
app/scripts/index.tsx
app/scripts/index.tsx
import 'core-js/stable'; import 'regenerator-runtime/runtime'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './redux/store'; import App from './components/App'; import 'purecss/build/pure-min.css'; // Static assets import '../.htaccess'; import '../humans.txt'; import '../robots.txt'; // Favicon/manifest assets import '../manifest/manifest.json'; import '../manifest/browserconfig.xml'; import '../manifest/favicon.ico'; import '../manifest/favicon-16x16.png'; import '../manifest/favicon-32x32.png'; import '../manifest/android-chrome-192x192.png'; import '../manifest/android-chrome-512x512.png'; import '../manifest/apple-touch-icon.png'; import '../manifest/mstile-150x150.png'; import '../manifest/safari-pinned-tab.svg'; // Render app ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); // @ts-ignore if (module.hot) { // @ts-ignore module.hot.accept(); }
import 'core-js/stable'; import 'regenerator-runtime/runtime'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import 'purecss/build/pure-min.css'; import store from './redux/store'; import App from './components/App'; // Static assets import '../.htaccess'; import '../humans.txt'; import '../robots.txt'; // Favicon/manifest assets import '../manifest/manifest.json'; import '../manifest/browserconfig.xml'; import '../manifest/favicon.ico'; import '../manifest/favicon-16x16.png'; import '../manifest/favicon-32x32.png'; import '../manifest/android-chrome-192x192.png'; import '../manifest/android-chrome-512x512.png'; import '../manifest/apple-touch-icon.png'; import '../manifest/mstile-150x150.png'; import '../manifest/safari-pinned-tab.svg'; // Render app ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); // @ts-ignore if (module.hot) { // @ts-ignore module.hot.accept(); }
Correct import order for pure css
Correct import order for pure css
TypeScript
mit
benct/tomlin-web,benct/tomlin-web
--- +++ @@ -5,10 +5,10 @@ import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; +import 'purecss/build/pure-min.css'; + import store from './redux/store'; import App from './components/App'; - -import 'purecss/build/pure-min.css'; // Static assets import '../.htaccess';
8bf6b3aa897329ba5bca358d2a79e77a1fe76c3b
src/parser/ui/BoringItemValueText.tsx
src/parser/ui/BoringItemValueText.tsx
/** * A simple component that shows the spell value in the most plain way possible. * Use this only as the very last resort. */ import { ItemIcon } from 'interface'; import { ItemLink } from 'interface'; import { Item } from 'parser/core/Events'; import * as React from 'react'; type Props = { item: Item; children: React.ReactNode; className?: string; }; const BoringItemValueText = ({ item, children, className }: Props) => ( <div className={`pad boring-text ${className || ''}`}> <label> <ItemIcon id={item.id} /> <ItemLink id={item.id} icon={false} /> </label> <div className="value">{children}</div> </div> ); export default BoringItemValueText;
/** * A simple component that shows the spell value in the most plain way possible. * Use this only as the very last resort. */ import { ItemLink } from 'interface'; import { Item } from 'parser/core/Events'; import * as React from 'react'; type Props = { item: Item; children: React.ReactNode; className?: string; }; const BoringItemValueText = ({ item, children, className }: Props) => ( <div className={`pad boring-text ${className || ''}`}> <label> <ItemLink id={item.id} quality={item.quality} details={item} /> </label> <div className="value">{children}</div> </div> ); export default BoringItemValueText;
Make itemvalue text link to correct itemlevel.
Make itemvalue text link to correct itemlevel.
TypeScript
agpl-3.0
WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,sMteX/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer
--- +++ @@ -3,7 +3,6 @@ * Use this only as the very last resort. */ -import { ItemIcon } from 'interface'; import { ItemLink } from 'interface'; import { Item } from 'parser/core/Events'; import * as React from 'react'; @@ -17,7 +16,7 @@ const BoringItemValueText = ({ item, children, className }: Props) => ( <div className={`pad boring-text ${className || ''}`}> <label> - <ItemIcon id={item.id} /> <ItemLink id={item.id} icon={false} /> + <ItemLink id={item.id} quality={item.quality} details={item} /> </label> <div className="value">{children}</div> </div>
64277658afb940bc0f35ca6c988228493e8f2c1b
utilitydelta-frontend/e2e/app.e2e-spec.ts
utilitydelta-frontend/e2e/app.e2e-spec.ts
import { UtilitydeltaFrontendPage } from './app.po'; describe('utilitydelta-frontend App', () => { let page: UtilitydeltaFrontendPage; beforeEach(() => { page = new UtilitydeltaFrontendPage(); }); it('should display message saying app works', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('app works!'); }); });
import { UtilitydeltaFrontendPage } from './app.po'; describe('utilitydelta-frontend App', () => { let page: UtilitydeltaFrontendPage; beforeEach(() => { page = new UtilitydeltaFrontendPage(); }); it('should display message saying UtilityDelta Frontend Hello World', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('UtilityDelta Frontend Hello World!'); }); });
Fix end to end tests
Fix end to end tests
TypeScript
mit
utilitydelta/spa-angular2-dotnet-auth,utilitydelta/spa-angular2-dotnet-auth,utilitydelta/spa-angular2-dotnet-auth,utilitydelta/spa-angular2-dotnet-auth
--- +++ @@ -7,8 +7,8 @@ page = new UtilitydeltaFrontendPage(); }); - it('should display message saying app works', () => { + it('should display message saying UtilityDelta Frontend Hello World', () => { page.navigateTo(); - expect(page.getParagraphText()).toEqual('app works!'); + expect(page.getParagraphText()).toEqual('UtilityDelta Frontend Hello World!'); }); });
f4ee705a9ebe45f81c744bee39e5d812c0bc864c
packages/sush-plugin-trim-id/src/index.ts
packages/sush-plugin-trim-id/src/index.ts
import { SUSHInfo } from 'sush'; export interface TrimIdParams { head?: number; tail?: number; } /** * `SUSHPluginTrimId` trims head or tail from ID. */ function SUSHPluginTrimId ( { head, tail }: TrimIdParams = { head: 0, tail: 0 } ) { return ({ id, stock }: SUSHInfo) => { const newId = (!tail) ? id.slice(head) : id.slice(head, -1 * tail); return { id: newId, stock } as SUSHInfo; }; }; export default SUSHPluginTrimId;
import { SUSHInfo } from 'sush'; export interface TrimIdParams { head?: number; tail?: number; } /** * `SUSHPluginTrimId` trims head or tail from ID. */ function SUSHPluginTrimId ( { head = 0, tail = 0 }: TrimIdParams = {} ) { return ({ id, stock }: SUSHInfo) => { const newId = (!tail) ? id.slice(head) : id.slice(head, -1 * tail); return { id: newId, stock } as SUSHInfo; }; }; export default SUSHPluginTrimId;
Change default params for plugin
fix: Change default params for plugin affects: sush-plugin-trim-id
TypeScript
mit
3846masa/SUSH,3846masa/SUSH
--- +++ @@ -9,7 +9,7 @@ * `SUSHPluginTrimId` trims head or tail from ID. */ function SUSHPluginTrimId ( - { head, tail }: TrimIdParams = { head: 0, tail: 0 } + { head = 0, tail = 0 }: TrimIdParams = {} ) { return ({ id, stock }: SUSHInfo) => { const newId = (!tail) ? id.slice(head) : id.slice(head, -1 * tail);
d92fca6a018f094a7156dcb447c8ad624d67f30d
src/DataTableColumn.tsx
src/DataTableColumn.tsx
import * as React from 'react' import { Component } from 'react' export interface ColumnDef { /** * Header label for this column. */ header: any /** * Function to read value from the source data. */ field: (rowData: any) => any } export class Column extends Component<ColumnDef, any> { static __DataTableColumn__ = true render() { if ('development' === ENV) { throw new Error('<TableColumn /> should never be rendered!') } return null } } export function mapColumnDef(child: any) { if (!child.type.__DataTableColumn__) { throw new Error('DataTable: children should be <Column />') } const def: ColumnDef = { header: child.props.header, field: child.props.field } return def }
import * as React from 'react' import { Component } from 'react' export interface ColumnDef { /** * Header label for this column. */ header: any /** * Function to read value from the source data. */ field: (rowData: any) => any } export class Column extends Component<ColumnDef, any> { static __DataTableColumn__ = true render() { if ('development' === process.env.NODE_ENV) { throw new Error('<TableColumn /> should never be rendered!') } return null } } export function mapColumnDef(child: any) { if (!child.type.__DataTableColumn__) { throw new Error('DataTable: children should be <Column />') } const def: ColumnDef = { header: child.props.header, field: child.props.field } return def }
Update dev environment variable name
Update dev environment variable name
TypeScript
mit
zhenwenc/rc-box,zhenwenc/rc-box,zhenwenc/rc-box
--- +++ @@ -17,7 +17,7 @@ static __DataTableColumn__ = true render() { - if ('development' === ENV) { + if ('development' === process.env.NODE_ENV) { throw new Error('<TableColumn /> should never be rendered!') } return null
3ffec3d225355e86ab9f684af9706387da1f1439
new-client/src/hooks/currentDate.ts
new-client/src/hooks/currentDate.ts
import { useCallback, useEffect, useState } from 'react'; import dayjs, { Dayjs } from 'dayjs'; // Plus one to make sure rounding doesn't interfere const msToMidnight = () => dayjs().add(1, 'day').startOf('date').diff(dayjs()) + 1; export function useCurrentDate(): Dayjs { const [currentDate, setCurrentDate] = useState(dayjs()); const updateDate = useCallback(() => { const currentDate = dayjs(); const msToNextDay = msToMidnight(); setCurrentDate(currentDate); setTimeout(updateDate, msToNextDay); }, []); useEffect(updateDate, [updateDate]); return currentDate; }
import { useCallback, useEffect, useState } from 'react'; import dayjs, { Dayjs } from 'dayjs'; // Plus one to make sure rounding doesn't interfere const msToMidnight = () => dayjs().add(1, 'day').startOf('date').diff(dayjs()) + 1; export function useCurrentDate(): Dayjs { const [currentDate, setCurrentDate] = useState(dayjs()); const updateDate = useCallback((): ReturnType<typeof setTimeout> => { const currentDate = dayjs(); const msToNextDay = msToMidnight(); setCurrentDate(currentDate); return setTimeout(updateDate, msToNextDay); }, []); useEffect(() => { const timer = updateDate(); return () => clearTimeout(timer); }, [updateDate]); return currentDate; }
Add cleanup to updateDate hook
Add cleanup to updateDate hook
TypeScript
apache-2.0
ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas
--- +++ @@ -7,15 +7,18 @@ export function useCurrentDate(): Dayjs { const [currentDate, setCurrentDate] = useState(dayjs()); - const updateDate = useCallback(() => { + const updateDate = useCallback((): ReturnType<typeof setTimeout> => { const currentDate = dayjs(); const msToNextDay = msToMidnight(); setCurrentDate(currentDate); - setTimeout(updateDate, msToNextDay); + return setTimeout(updateDate, msToNextDay); }, []); - useEffect(updateDate, [updateDate]); + useEffect(() => { + const timer = updateDate(); + return () => clearTimeout(timer); + }, [updateDate]); return currentDate; }
b56265c5d866c1b0bd9c54b7d2e79c52afbe0665
src/dockerDefinition.ts
src/dockerDefinition.ts
/* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; import { TextDocument, Position, Location } from 'vscode-languageserver'; import { DockerfileParser } from './parser/dockerfileParser'; export class DockerDefinition { public computeDefinition(document: TextDocument, position: Position): Location | null { let parser = new DockerfileParser(); let dockerfile = parser.parse(document); for (let instruction of dockerfile.getFROMs()) { let range = instruction.getBuildStageRange(); if (range && range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) { return Location.create(document.uri, range); } } let source = undefined; for (let instruction of dockerfile.getCOPYs()) { let range = instruction.getFromValueRange(); if (range && range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) { source = instruction.getFromValue(); break; } } if (source) { for (let instruction of dockerfile.getFROMs()) { if (instruction.getBuildStage() === source) { let range = instruction.getBuildStageRange(); return Location.create(document.uri, range); } } } return null; } }
/* -------------------------------------------------------------------------------------------- * Copyright (c) Remy Suen. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; import { TextDocument, Position, Location } from 'vscode-languageserver'; import { DockerfileParser } from './parser/dockerfileParser'; export class DockerDefinition { public computeDefinition(document: TextDocument, position: Position): Location | null { let parser = new DockerfileParser(); let dockerfile = parser.parse(document); let source = undefined; for (let instruction of dockerfile.getCOPYs()) { let range = instruction.getFromValueRange(); if (range && range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) { source = instruction.getFromValue(); break; } } for (let instruction of dockerfile.getFROMs()) { let range = instruction.getBuildStageRange(); if (range && ((range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) || (instruction.getBuildStage() === source))) { return Location.create(document.uri, range); } } return null; } }
Reorder the code so FROMs are iterated over only once
Reorder the code so FROMs are iterated over only once Signed-off-by: Remy Suen <553f7e7fc51e9ff47ae89d5a0ebd06651241b998@gmail.com>
TypeScript
mit
rcjsuen/dockerfile-language-server-nodejs,rcjsuen/dockerfile-language-server-nodejs
--- +++ @@ -12,13 +12,6 @@ public computeDefinition(document: TextDocument, position: Position): Location | null { let parser = new DockerfileParser(); let dockerfile = parser.parse(document); - for (let instruction of dockerfile.getFROMs()) { - let range = instruction.getBuildStageRange(); - if (range && range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) { - return Location.create(document.uri, range); - } - } - let source = undefined; for (let instruction of dockerfile.getCOPYs()) { let range = instruction.getFromValueRange(); @@ -28,12 +21,11 @@ } } - if (source) { - for (let instruction of dockerfile.getFROMs()) { - if (instruction.getBuildStage() === source) { - let range = instruction.getBuildStageRange(); - return Location.create(document.uri, range); - } + for (let instruction of dockerfile.getFROMs()) { + let range = instruction.getBuildStageRange(); + if (range && + ((range.start.line === position.line && range.start.character <= position.character && position.character <= range.end.character) || (instruction.getBuildStage() === source))) { + return Location.create(document.uri, range); } }
1f10ca68e6388c71c834e662eacf185e2484adbb
src/Button/Button.tsx
src/Button/Button.tsx
import * as React from "react"; import * as PropTypes from "prop-types"; import { BaseButton } from "./BaseButton"; import { ButtonDefaultProps, ButtonProps, ButtonPropTypes } from "./ButtonProps"; export class Button extends BaseButton { public static readonly propTypes = ButtonPropTypes; public static readonly defaultProps = ButtonDefaultProps; public props: ButtonProps; public render(): JSX.Element { const { action, activeClassName, ...HTMLProps } = this.props; const childProps = { ...this.childProps, ...HTMLProps, ...{ className: this.className } }; return ( <button {...childProps}> {this.props.children} </button> ); } protected handleClick = () => this.context.onChange(this.props.action); protected get className(): string { const additionalClassName = this.context.value === this.props.action ? ` ${this.props.activeClassName}` : ""; return `${this.props.className}${additionalClassName}`; } }
import * as React from "react"; import * as PropTypes from "prop-types"; import { BaseButton } from "./BaseButton"; import { ButtonDefaultProps, ButtonProps, ButtonPropTypes } from "./ButtonProps"; export class Button extends BaseButton { public static readonly propTypes = ButtonPropTypes; public static readonly defaultProps = ButtonDefaultProps; public props: ButtonProps; public render(): JSX.Element { const { action, activeClassName, ...HTMLProps } = this.props; const childProps = { ...this.childProps, ...HTMLProps, ...{ className: this.className } }; return ( <button {...childProps}> {this.props.children} </button> ); } protected handleClick = (event: React.MouseEvent<HTMLButtonElement>): void => { this.props.onClick && this.props.onClick(event); if (!event.defaultPrevented) { this.context.onChange(this.props.action); } }; protected get className(): string { const additionalClassName = this.context.value === this.props.action ? ` ${this.props.activeClassName}` : ""; return `${this.props.className}${additionalClassName}`; } }
Add missing prop callback on click
Add missing prop callback on click
TypeScript
mit
Horat1us/react-context-form,Horat1us/react-context-form
--- +++ @@ -28,7 +28,13 @@ ); } - protected handleClick = () => this.context.onChange(this.props.action); + protected handleClick = (event: React.MouseEvent<HTMLButtonElement>): void => { + this.props.onClick && this.props.onClick(event); + + if (!event.defaultPrevented) { + this.context.onChange(this.props.action); + } + }; protected get className(): string { const additionalClassName = this.context.value === this.props.action ? ` ${this.props.activeClassName}` : "";
e42e6c7b8347687b9582acd20adc5dc9f787696e
packages/scripts/src/helpers/worker-farm/index.ts
packages/scripts/src/helpers/worker-farm/index.ts
import createWorkerFarm = require('worker-farm'); type WorkerType = ( moduleName: string, methodName: string, args: any[], callback: (err: any, result?: any) => void, ) => void; const workers: WorkerType = createWorkerFarm( // we have some really long running tasks, so lets have // each worker only handle one at a time {maxConcurrentCallsPerWorker: 1}, require.resolve('./worker'), ); export function end() { createWorkerFarm.end(workers as any); } export default function getModule<T, Key extends keyof T>( moduleName: string, methods: ReadonlyArray<Key>, module: () => Promise<T>, ): {[key in Key]: T[key]} { const result: any = {}; methods.forEach(method => { result[method] = (...args: any[]) => { return new Promise((resolve, reject) => { workers(moduleName, method, args, (err, res) => { if (err) reject(err); else resolve(res); }); }); }; }); return result; }
import createWorkerFarm = require('worker-farm'); type WorkerType = ( moduleName: string, methodName: string, args: any[], callback: (err: any, result?: any) => void, ) => void; const workers: WorkerType = createWorkerFarm( // we have some really long running tasks, so lets have // each worker only handle one at a time {maxConcurrentCallsPerWorker: 1}, require.resolve('./worker'), ); export function end() { createWorkerFarm.end(workers as any); } export default function getModule<T, Key extends keyof T>( moduleName: string, methods: ReadonlyArray<Key>, module: () => Promise<T>, ): {[key in Key]: T[key]} { const result: any = {}; methods.forEach(method => { result[method] = (...args: any[]) => { return new Promise((resolve, reject) => { workers(moduleName, method as string, args, (err, res) => { if (err) reject(err); else resolve(res); }); }); }; }); return result; }
Fix type error in worker-farm
Fix type error in worker-farm
TypeScript
mit
mopedjs/moped,mopedjs/moped,mopedjs/moped
--- +++ @@ -25,7 +25,7 @@ methods.forEach(method => { result[method] = (...args: any[]) => { return new Promise((resolve, reject) => { - workers(moduleName, method, args, (err, res) => { + workers(moduleName, method as string, args, (err, res) => { if (err) reject(err); else resolve(res); });
74f68a7c22ebd11a7ed45b971a28a45ab7b121f6
src/marketplace-checklist/AnswerGroup.tsx
src/marketplace-checklist/AnswerGroup.tsx
import * as React from 'react'; import * as ToggleButton from 'react-bootstrap/lib/ToggleButton'; import * as ToggleButtonGroup from 'react-bootstrap/lib/ToggleButtonGroup'; import { translate } from '@waldur/i18n'; export const AnswerGroup = ({ answers, question, setAnswers }) => ( <ToggleButtonGroup value={{true: 'true', false: 'false', null: 'null'}[answers[question.uuid]]} onChange={value => setAnswers({ ...answers, [question.uuid]: {true: true, false: false, null: null}[value], })} type="radio" name={`checklist-${question.uuid}`} defaultValue="null"> <ToggleButton value="true"> {translate('Yes')} </ToggleButton> <ToggleButton value="false"> {translate('No')} </ToggleButton> <ToggleButton value="null"> {translate('N/A')} </ToggleButton> </ToggleButtonGroup> );
import * as React from 'react'; import * as ToggleButton from 'react-bootstrap/lib/ToggleButton'; import * as ToggleButtonGroup from 'react-bootstrap/lib/ToggleButtonGroup'; import { translate } from '@waldur/i18n'; export const AnswerGroup = ({ answers, question, setAnswers }) => ( <ToggleButtonGroup value={{true: 'true', false: 'false', null: 'null'}[answers[question.uuid]]} onChange={value => setAnswers({ ...answers, [question.uuid]: {true: true, false: false, null: null}[value], })} type="radio" name={`checklist-${question.uuid}`} defaultValue="null"> <ToggleButton value="true"> {translate('Yes')} </ToggleButton> <ToggleButton value="false"> {translate('No')} </ToggleButton> <ToggleButton value="null"> {translate('?')} </ToggleButton> </ToggleButtonGroup> );
Change undefined answer from N/A to ?
Change undefined answer from N/A to ?
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -21,7 +21,7 @@ {translate('No')} </ToggleButton> <ToggleButton value="null"> - {translate('N/A')} + {translate('?')} </ToggleButton> </ToggleButtonGroup> );
856f2325f305466b57cd1504fda8f7e125675888
lib/components/ArticleTeaser.tsx
lib/components/ArticleTeaser.tsx
import React from "react"; import Link from "next/link"; const ArticleTeaser = ({ title, slug, date, abstract, variant = "default", }) => { const Headline = (props) => { if (variant === "small") { return <h3 {...props} />; } return <h2 {...props} />; }; return ( <article className="posts__post"> <header className={`posts__post__header${ variant === "small" ? " posts__post__header--small" : "" }`} > <Headline itemProp="title"> <Link href={`/blog/${slug}`}> <a>{title}</a> </Link> </Headline> <time className="posts__date">Published on {date}</time> </header> <div dangerouslySetInnerHTML={{ __html: abstract }} /> <div className="posts__post__readmore clearfix"> <Link href={`/blog/${slug}`}> <a className="button">Read more</a> </Link> </div> </article> ); }; export default ArticleTeaser;
import React from "react"; import Link from "next/link"; const ArticleTeaser = ({ title, slug, date, abstract, variant = "default", }) => { const Headline = (props) => { if (variant === "small") { return <h3 {...props} />; } return <h2 {...props} />; }; return ( <article className="posts__post"> <header className={`posts__post__header${ variant === "small" ? " posts__post__header--small" : "" }`} > <Headline itemProp="title"> <Link href={`/blog/${slug}`}> <a>{title}</a> </Link> </Headline> <time className="posts__date">Published on {date}</time> </header> <div dangerouslySetInnerHTML={{ __html: abstract }} /> <div className="posts__post__readmore clearfix"> <Link href={`/blog/${slug}`}> <a className="button">Read this Article</a> </Link> </div> </article> ); }; export default ArticleTeaser;
Update text for "read more"
Update text for "read more"
TypeScript
mit
drublic/vc,drublic/vc,drublic/vc
--- +++ @@ -36,7 +36,7 @@ <div className="posts__post__readmore clearfix"> <Link href={`/blog/${slug}`}> - <a className="button">Read more</a> + <a className="button">Read this Article</a> </Link> </div> </article>
0266091e4bd20475df5d335479c249f20ef24cc6
src/shared/pub/api.ts
src/shared/pub/api.ts
import { WebClient } from "../fetch"; export class PubApi { constructor(private readonly webClient: WebClient) { } public async getPackage(packageID: string): Promise<PubPackage> { return this.get<PubPackage>(`packages/${packageID}`); } private async get<T>(url: string): Promise<T> { const headers = { Accept: "application/vnd.pub.v2+json", }; return JSON.parse(await this.webClient.fetch(`https://pub.dev/api/${url}`, headers)) as T; } } interface PubPackage { name: string; latest: PubPackageVersion; versions: PubPackageVersion[]; } interface PubPackageVersion { archive_url: string; version: string; pubspec: { version: string; name: string; author: string; description: string; homepage: string; }; }
import { WebClient } from "../fetch"; export class PubApi { private readonly pubHost: string; constructor(private readonly webClient: WebClient) { this.pubHost = process.env.PUB_HOSTED_URL || "https://pub.dev"; } public async getPackage(packageID: string): Promise<PubPackage> { return this.get<PubPackage>(`packages/${packageID}`); } private async get<T>(url: string): Promise<T> { const headers = { Accept: "application/vnd.pub.v2+json", }; return JSON.parse(await this.webClient.fetch(`${this.pubHost}/api/${url}`, headers)) as T; } } interface PubPackage { name: string; latest: PubPackageVersion; versions: PubPackageVersion[]; } interface PubPackageVersion { archive_url: string; version: string; pubspec: { version: string; name: string; author: string; description: string; homepage: string; }; }
Use PUB_HOSTED_URL when doing version checks
Use PUB_HOSTED_URL when doing version checks Fixes #2503.
TypeScript
mit
Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code
--- +++ @@ -1,7 +1,9 @@ import { WebClient } from "../fetch"; export class PubApi { + private readonly pubHost: string; constructor(private readonly webClient: WebClient) { + this.pubHost = process.env.PUB_HOSTED_URL || "https://pub.dev"; } public async getPackage(packageID: string): Promise<PubPackage> { @@ -12,7 +14,7 @@ const headers = { Accept: "application/vnd.pub.v2+json", }; - return JSON.parse(await this.webClient.fetch(`https://pub.dev/api/${url}`, headers)) as T; + return JSON.parse(await this.webClient.fetch(`${this.pubHost}/api/${url}`, headers)) as T; } }
21334d9eb3648b85cf9bf36f5e502a394e6cf957
helpers/string.ts
helpers/string.ts
export default class HelperString { public static toCamelCase(str: string): string { return str[0].toLowerCase() + str.substring(1); } }
export default class HelperString { public static toCamelCase(str: string): string { if (str.length < 2) { return !!str ? str.toLowerCase() : str; } return str[0].toLowerCase() + str.substring(1); } }
Fix a bug in HelperString.toCamelCase()
Fix a bug in HelperString.toCamelCase()
TypeScript
mit
crossroads-education/eta,crossroads-education/eta
--- +++ @@ -1,5 +1,8 @@ export default class HelperString { public static toCamelCase(str: string): string { + if (str.length < 2) { + return !!str ? str.toLowerCase() : str; + } return str[0].toLowerCase() + str.substring(1); } }
bbde568559ecb1ae9e85c5161bd1517633922af8
src/app/modal/modal.component.ts
src/app/modal/modal.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { @Output() opened = new EventEmitter<any>(); @Output() closed = new EventEmitter<any>(); private show: boolean = false; private html: HTMLElement = document.getElementsByTagName('html')[0]; constructor() { } ngOnInit() { } open() { this.show = true; this.opened.emit(null); this.preventBgScrolling(); } close() { this.show = false; this.closed.emit(null); this.preventBgScrolling(); } private preventBgScrolling() { this.html.style.overflow = this.show ? 'hidden' : ''; } }
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; interface ModalConfig extends Object { title?: string; id?: string; } const defaultConfig = <ModalConfig> {}; let id = 0; @Component({ selector: 'app-modal', templateUrl: './modal.component.html', styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { @Input() options: ModalConfig; @Output() opened = new EventEmitter<any>(); @Output() closed = new EventEmitter<any>(); private show: boolean = false; private id: string; private titleId: string; private contentId: string; private html: HTMLElement = document.getElementsByTagName('html')[0]; constructor() {} ngOnInit() { this.options = Object.assign({}, defaultConfig, this.options); this.id = this.options.id || `modal-${id++}`; this.titleId = `${this.id}-title`; this.contentId = `${this.id}-content`; } open() { this.show = true; this.opened.emit(null); this.preventBgScrolling(); } close() { this.show = false; this.closed.emit(null); this.preventBgScrolling(); } private preventBgScrolling() { this.html.style.overflow = this.show ? 'hidden' : ''; } }
Add options input and calc IDs 👌🏽
Add options input and calc IDs 👌🏽
TypeScript
mit
filoxo/an-angular-modal,filoxo/an-angular-modal,filoxo/an-angular-modal
--- +++ @@ -1,4 +1,13 @@ -import { Component, OnInit, Output, EventEmitter } from '@angular/core'; +import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; + +interface ModalConfig extends Object { + title?: string; + id?: string; +} + +const defaultConfig = <ModalConfig> {}; + +let id = 0; @Component({ selector: 'app-modal', @@ -6,15 +15,22 @@ styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit { - + @Input() options: ModalConfig; @Output() opened = new EventEmitter<any>(); @Output() closed = new EventEmitter<any>(); private show: boolean = false; + private id: string; + private titleId: string; + private contentId: string; private html: HTMLElement = document.getElementsByTagName('html')[0]; - constructor() { } + constructor() {} ngOnInit() { + this.options = Object.assign({}, defaultConfig, this.options); + this.id = this.options.id || `modal-${id++}`; + this.titleId = `${this.id}-title`; + this.contentId = `${this.id}-content`; } open() {
5ef7f4b078edb14f6edfebdc8600d5a9868bc858
app/src/container/Items.tsx
app/src/container/Items.tsx
import * as React from "react"; import Article = require("react-icons/lib/fa/file-code-o"); import Book = require("react-icons/lib/go/book"); import Todo = require("react-icons/lib/md/playlist-add-check"); import { connect } from "react-redux"; import { Link, Redirect } from "react-router-dom"; import "./style/Items.css"; interface IProps { createItem: JSX.Element; currentItem: JSX.Element; list: JSX.Element; menu: JSX.Element; signedIn: boolean; } class Items extends React.Component<IProps> { public render() { const { createItem, currentItem, list, menu, signedIn } = this.props; if (!signedIn) { return <Redirect to="/sign-in" />; } return ( <div className="Items-container"> <div className="Items-menu-blank" /> <div className="Items-menu"> {menu} <div className="Items-menu-buttons"> <Link to="/tasks"><Todo /></Link> <Link to="/articles"><Article /></Link> </div> </div> <div className="Items-main"> {list} <div className="Items-side-bar"> {currentItem} {createItem} </div> </div> <div className="Items-blank" /> </div> ); } } export default connect(({ authState }) => authState)(Items);
import * as React from "react"; import Article = require("react-icons/lib/fa/file-code-o"); import Book = require("react-icons/lib/go/book"); import Todo = require("react-icons/lib/md/playlist-add-check"); import { connect } from "react-redux"; import { Link, Redirect } from "react-router-dom"; import "./style/Items.css"; interface IProps { createItem: JSX.Element; currentItem: JSX.Element; list: JSX.Element; menu: JSX.Element; signedIn: boolean; } class Items extends React.Component<IProps> { public render() { const { createItem, currentItem, list, menu, signedIn } = this.props; if (!signedIn) { return <Redirect to="/sign-in" />; } return ( <div className="Items-container"> <div className="Items-menu-blank" /> <div className="Items-menu"> {menu} <div className="Items-menu-buttons"> <Link to="/tasks"><Todo /></Link> <Link to="/articles"><Article /></Link> </div> </div> <div className="Items-main"> {list} <div className="Items-side-bar"> {currentItem || <div />} {createItem} </div> </div> <div className="Items-blank" /> </div> ); } } export default connect(({ authState }) => authState)(Items);
Fix position of create-item components when no item is present
Fix position of create-item components when no item is present
TypeScript
mit
raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d
--- +++ @@ -36,7 +36,7 @@ <div className="Items-main"> {list} <div className="Items-side-bar"> - {currentItem} + {currentItem || <div />} {createItem} </div> </div>
608ffe41e13896362f39953483a596209113b0bd
app/client/src/components/generator/form/inputs/Input.tsx
app/client/src/components/generator/form/inputs/Input.tsx
import { InputHTMLAttributes, memo, FC } from 'react' import { FieldPath, UseFormReturn } from 'react-hook-form' import styled from 'styled-components' import { colors } from '../../../../theme' import { FormValues } from '../../../../types/form' const StyledInput = styled.input` border: none; background: ${colors.input}; padding: 1rem; color: ${colors.white}; transition: all 0.2s ease; border-radius: 10px; font-size: 0.85rem; &:focus { outline: 0; border-color: ${colors.primary}; box-shadow: 0 0 4px 1px ${colors.primary}; } &::placeholder { color: ${colors.placeholder}; opacity: 0.5; } ` export interface InputProps extends InputHTMLAttributes<HTMLInputElement> { formContext: UseFormReturn<FormValues> name: FieldPath<FormValues> } export const Input: FC<InputProps> = memo( ({ formContext, name, ...inputProps }) => ( <StyledInput {...inputProps} {...formContext.register(name)} /> ), (prevProps, nextProps) => prevProps.formContext.formState.isDirty === nextProps.formContext.formState.isDirty )
import { InputHTMLAttributes, memo, FC } from 'react' import { FieldPath, UseFormReturn } from 'react-hook-form' import styled from 'styled-components' import { colors } from '../../../../theme' import { FormValues } from '../../../../types/form' const StyledInput = styled.input` border: none; background: ${colors.input}; padding: 1rem; color: ${colors.white}; transition: all 0.2s ease; border-radius: 10px; font-size: 0.85rem; &:focus { outline: 0; color: ${colors.primary}; border-color: ${colors.primary}; box-shadow: 0 0 4px 2px ${colors.primary}; } &::placeholder { color: ${colors.placeholder}; opacity: 0.5; } ` export interface InputProps extends InputHTMLAttributes<HTMLInputElement> { formContext: UseFormReturn<FormValues> name: FieldPath<FormValues> } export const Input: FC<InputProps> = memo( ({ formContext, name, ...inputProps }) => ( <StyledInput {...inputProps} {...formContext.register(name)} /> ), (prevProps, nextProps) => prevProps.formContext.formState.isDirty === nextProps.formContext.formState.isDirty )
Change input text and shadow styling
Change input text and shadow styling
TypeScript
mit
saadq/latexresu.me,saadq/latexresu.me
--- +++ @@ -15,8 +15,9 @@ &:focus { outline: 0; + color: ${colors.primary}; border-color: ${colors.primary}; - box-shadow: 0 0 4px 1px ${colors.primary}; + box-shadow: 0 0 4px 2px ${colors.primary}; } &::placeholder {
b096544f4dc5e98e2667e91182691feb0bdeddf4
hawtio-web/src/main/webapp/app/jmx/js/mbeans.ts
hawtio-web/src/main/webapp/app/jmx/js/mbeans.ts
module Jmx { export function MBeansController($scope, $location: ng.ILocationService, workspace: Workspace) { $scope.$on("$routeChangeSuccess", function (event, current, previous) { // lets do this asynchronously to avoid Error: $digest already in progress setTimeout(updateSelectionFromURL, 50); }); $scope.select = (node:DynaTreeNode) => { $scope.workspace.updateSelectionNode(node); $scope.$apply(); }; function updateSelectionFromURL() { updateTreeSelectionFromURL($location, $("#jmxtree")); } $scope.populateTree = () => { var treeElement = $("#jmxtree"); enableTree($scope, $location, workspace, treeElement, workspace.tree.children, true); setTimeout(updateSelectionFromURL, 50); } $scope.$on('jmxTreeUpdated', $scope.populateTree); $scope.populateTree(); } }
module Jmx { export function MBeansController($scope, $location: ng.ILocationService, workspace: Workspace) { $scope.$on("$routeChangeSuccess", function (event, current, previous) { // lets do this asynchronously to avoid Error: $digest already in progress setTimeout(updateSelectionFromURL, 50); }); $scope.select = (node:DynaTreeNode) => { $scope.workspace.updateSelectionNode(node); $scope.$apply(); }; function updateSelectionFromURL() { updateTreeSelectionFromURL($location, $("#jmxtree")); } $scope.populateTree = () => { var treeElement = $("#jmxtree"); $scope.tree = workspace.tree; enableTree($scope, $location, workspace, treeElement, $scope.tree.children, true); setTimeout(updateSelectionFromURL, 50); } $scope.$on('jmxTreeUpdated', $scope.populateTree); $scope.populateTree(); } }
Fix tree on integration tab, still need to sort a few things out post-refactor
Fix tree on integration tab, still need to sort a few things out post-refactor
TypeScript
apache-2.0
jfbreault/hawtio,samkeeleyong/hawtio,tadayosi/hawtio,andytaylor/hawtio,jfbreault/hawtio,mposolda/hawtio,Fatze/hawtio,mposolda/hawtio,jfbreault/hawtio,telefunken/hawtio,stalet/hawtio,fortyrunner/hawtio,uguy/hawtio,rajdavies/hawtio,telefunken/hawtio,mposolda/hawtio,andytaylor/hawtio,samkeeleyong/hawtio,stalet/hawtio,skarsaune/hawtio,fortyrunner/hawtio,tadayosi/hawtio,hawtio/hawtio,grgrzybek/hawtio,uguy/hawtio,Fatze/hawtio,fortyrunner/hawtio,voipme2/hawtio,skarsaune/hawtio,padmaragl/hawtio,uguy/hawtio,stalet/hawtio,fortyrunner/hawtio,rajdavies/hawtio,mposolda/hawtio,Fatze/hawtio,jfbreault/hawtio,grgrzybek/hawtio,voipme2/hawtio,tadayosi/hawtio,skarsaune/hawtio,telefunken/hawtio,padmaragl/hawtio,samkeeleyong/hawtio,skarsaune/hawtio,andytaylor/hawtio,rajdavies/hawtio,telefunken/hawtio,skarsaune/hawtio,hawtio/hawtio,grgrzybek/hawtio,grgrzybek/hawtio,rajdavies/hawtio,tadayosi/hawtio,samkeeleyong/hawtio,andytaylor/hawtio,hawtio/hawtio,uguy/hawtio,voipme2/hawtio,tadayosi/hawtio,padmaragl/hawtio,stalet/hawtio,uguy/hawtio,mposolda/hawtio,andytaylor/hawtio,Fatze/hawtio,Fatze/hawtio,padmaragl/hawtio,grgrzybek/hawtio,hawtio/hawtio,stalet/hawtio,rajdavies/hawtio,telefunken/hawtio,voipme2/hawtio,voipme2/hawtio,hawtio/hawtio,jfbreault/hawtio,padmaragl/hawtio,samkeeleyong/hawtio
--- +++ @@ -19,7 +19,8 @@ $scope.populateTree = () => { var treeElement = $("#jmxtree"); - enableTree($scope, $location, workspace, treeElement, workspace.tree.children, true); + $scope.tree = workspace.tree; + enableTree($scope, $location, workspace, treeElement, $scope.tree.children, true); setTimeout(updateSelectionFromURL, 50); }
0abf7d1f00d95547494dc1eba564aa27f91d9ac3
lib/utils.ts
lib/utils.ts
import { Response } from "request"; import { ApiResponse } from "./types"; export function resolveHttpError(response, message): Error | undefined { if (response.statusCode < 400) { return; } message = message ? message + " " : ""; message += "Status code " + response.statusCode + " (" + response.statusMessage + "). See the response property for details."; var error: Error & { rawResponse?: Response } = new Error(message); error.rawResponse = response; return error; } export function createCallback(action, cb): (err, response) => void { return function(err, response): void { err = err || resolveHttpError(response, "Error " + action + "."); if (err) { return cb(err); } cb(null, { data: response.body, response: response }); }; } export function createPromiseCallback<P>( action: string, resolve: (response: ApiResponse<P>) => void, reject: (err: {}) => void, transformPayload: (response: Response, payload: any) => P = (_, p) => p ): (err: Error, response: Response) => void { return function(err, response): void { err = err || resolveHttpError(response, "Error " + action + "."); if (err) { return reject(err); } resolve({ payload: transformPayload(response, response.body), rawResponse: response }); }; }
import { Response } from "request"; import { ApiResponse } from "./types"; export function resolveHttpError(response, message): Error | undefined { if (response.statusCode < 400) { return; } message = message ? message + " " : ""; message += "Status code " + response.statusCode + " (" + response.statusMessage + "). See the rawResponse property for details."; var error: Error & { rawResponse?: Response } = new Error(message); error.rawResponse = response; return error; } export function createCallback(action, cb): (err, response) => void { return function(err, response): void { err = err || resolveHttpError(response, "Error " + action + "."); if (err) { return cb(err); } cb(null, { data: response.body, response: response }); }; } export function createPromiseCallback<P>( action: string, resolve: (response: ApiResponse<P>) => void, reject: (err: {}) => void, transformPayload: (response: Response, payload: any) => P = (_, p) => p ): (err: Error, response: Response) => void { return function(err, response): void { err = err || resolveHttpError(response, "Error " + action + "."); if (err) { return reject(err); } resolve({ payload: transformPayload(response, response.body), rawResponse: response }); }; }
Update wording of http code errors to point at rawResponse
Update wording of http code errors to point at rawResponse
TypeScript
mit
itsananderson/kudu-api,itsananderson/kudu-api
--- +++ @@ -13,7 +13,7 @@ response.statusCode + " (" + response.statusMessage + - "). See the response property for details."; + "). See the rawResponse property for details."; var error: Error & { rawResponse?: Response } = new Error(message); error.rawResponse = response;
458960673148b70051315a4c0e73f9f22d749e2d
src/utilities/testing/itAsync.ts
src/utilities/testing/itAsync.ts
function wrap<TResult>( original: (...args: any[]) => TResult, ) { return ( message: string, callback: ( resolve: (result?: any) => void, reject: (reason?: any) => void, ) => any, timeout?: number, ) => original(message, function () { return new Promise( (resolve, reject) => callback.call(this, resolve, reject), ); }, timeout); } const wrappedIt = wrap(it); export function itAsync(...args: Parameters<typeof wrappedIt>) { return wrappedIt.apply(this, args); } export namespace itAsync { export const only = wrap(it.only); export const skip = wrap(it.skip); export const todo = wrap(it.todo); }
const itIsDefined = typeof it === "object"; function wrap<TResult>( original: ((...args: any[]) => TResult) | false, ) { return ( message: string, callback: ( resolve: (result?: any) => void, reject: (reason?: any) => void, ) => any, timeout?: number, ) => original && original(message, function () { return new Promise( (resolve, reject) => callback.call(this, resolve, reject), ); }, timeout); } const wrappedIt = wrap(itIsDefined && it); export function itAsync(...args: Parameters<typeof wrappedIt>) { return wrappedIt.apply(this, args); } export namespace itAsync { export const only = wrap(itIsDefined && it.only); export const skip = wrap(itIsDefined && it.skip); export const todo = wrap(itIsDefined && it.todo); }
Allow importing @apollo/client/testing when global.it undefined.
Allow importing @apollo/client/testing when global.it undefined. https://github.com/apollographql/apollo-client/pull/6576#issuecomment-664510739
TypeScript
mit
apollostack/apollo-client,apollographql/apollo-client,apollostack/apollo-client,apollostack/apollo-client,apollographql/apollo-client
--- +++ @@ -1,5 +1,7 @@ +const itIsDefined = typeof it === "object"; + function wrap<TResult>( - original: (...args: any[]) => TResult, + original: ((...args: any[]) => TResult) | false, ) { return ( message: string, @@ -8,20 +10,20 @@ reject: (reason?: any) => void, ) => any, timeout?: number, - ) => original(message, function () { + ) => original && original(message, function () { return new Promise( (resolve, reject) => callback.call(this, resolve, reject), ); }, timeout); } -const wrappedIt = wrap(it); +const wrappedIt = wrap(itIsDefined && it); export function itAsync(...args: Parameters<typeof wrappedIt>) { return wrappedIt.apply(this, args); } export namespace itAsync { - export const only = wrap(it.only); - export const skip = wrap(it.skip); - export const todo = wrap(it.todo); + export const only = wrap(itIsDefined && it.only); + export const skip = wrap(itIsDefined && it.skip); + export const todo = wrap(itIsDefined && it.todo); }
188740715a699c25651a74f3ce090aa130127680
src/commands.ts
src/commands.ts
import * as vscode from 'vscode'; const lodashSortBy = require('lodash.sortby'); export const COMMAND_LABELS = { '1toX': '1toX' }; export function runCommand (command: string) { const editor = vscode.window.activeTextEditor; const { document, selections } = editor; editor.edit(editBuilder => { if (command === '1toX') { let orderedSelections = lodashSortBy(selections, (selection: vscode.Selection) => selection.start.line); orderedSelections.forEach((location, index) => { let range = new vscode.Position(location.start.line, location.start.character); editBuilder.insert(range, String(index + 1)); }); } }); }
import * as vscode from 'vscode'; const lodashSortBy = require('lodash.sortby'); export const COMMAND_LABELS = { '1toX': '1toX' }; export function runCommand (command: string) { const editor = vscode.window.activeTextEditor; const { document, selections } = editor; editor.edit(editBuilder => { if (command === '1toX') { let orderedSelections = lodashSortBy(selections, (selection: vscode.Selection) => selection.start.line); orderedSelections.forEach((selection, index) => { let range = new vscode.Position(selection.start.line, selection.start.character); editBuilder.insert(range, String(index + 1)); editBuilder.delete(selection); }); } }); }
Delete any existing selected text when inserting text
Delete any existing selected text when inserting text
TypeScript
mit
jkjustjoshing/vscode-text-pastry
--- +++ @@ -13,9 +13,10 @@ editor.edit(editBuilder => { if (command === '1toX') { let orderedSelections = lodashSortBy(selections, (selection: vscode.Selection) => selection.start.line); - orderedSelections.forEach((location, index) => { - let range = new vscode.Position(location.start.line, location.start.character); + orderedSelections.forEach((selection, index) => { + let range = new vscode.Position(selection.start.line, selection.start.character); editBuilder.insert(range, String(index + 1)); + editBuilder.delete(selection); }); } });
3a92b9a07445fb536426447da7cc8289bf9f3e72
src/dev/stories/dashboard-refactor/header/sidebar-toggle.tsx
src/dev/stories/dashboard-refactor/header/sidebar-toggle.tsx
import React from 'react' import { storiesOf } from '@storybook/react' import SidebarToggle from 'src/dashboard-refactor/header/SidebarHeader/SidebarToggle/SidebarToggle' const stories = storiesOf('Dashboard Refactor|Header/Sidebar Toggle', module) export const sidebarToggleProps = { noHover: { sidebarLockedState: { toggleSidebarLockedState: function () {}, isSidebarLocked: false, }, hoverState: { onHoverEnter: function () {}, onHoverLeave: function () {}, isHovered: false, }, }, unlockedHover: { sidebarLockedState: { toggleSidebarLockedState: function () {}, isSidebarLocked: false, }, hoverState: { onHoverEnter: function () {}, onHoverLeave: function () {}, isHovered: true, }, }, lockedHover: { sidebarLockedState: { toggleSidebarLockedState: function () {}, isSidebarLocked: true, }, hoverState: { onHoverEnter: function () {}, onHoverLeave: function () {}, isHovered: true, }, }, } stories.add('No hover', () => <SidebarToggle {...sidebarToggleProps.noHover} />) stories.add('Unlocked hover', () => ( <SidebarToggle {...sidebarToggleProps.unlockedHover} /> )) stories.add('Locked hover', () => ( <SidebarToggle {...sidebarToggleProps.lockedHover} /> ))
import React from 'react' import { storiesOf } from '@storybook/react' import SidebarToggle, { SidebarToggleProps, } from 'src/dashboard-refactor/header/SidebarHeader/SidebarToggle/SidebarToggle' import { SidebarLockedState } from 'src/dashboard-refactor/lists-sidebar/types' import { HoverState } from 'src/dashboard-refactor/types' const stories = storiesOf('Dashboard Refactor|Header/Sidebar Toggle', module) const sidebarLockedState: SidebarLockedState = { isSidebarLocked: false, toggleSidebarLockedState: () => {}, } const hoverState: HoverState = { isHovered: false, onHoverEnter: () => {}, onHoverLeave: () => {}, } const template: SidebarToggleProps = { sidebarLockedState: sidebarLockedState, hoverState: hoverState, } export const sidebarToggleProps = { noHover: { ...template, }, unlockedHover: { ...template, hoverState: { ...hoverState, isHovered: true, }, }, lockedHover: { sidebarLockedState: { ...sidebarLockedState, isSidebarLocked: true, }, hoverState: { ...hoverState, isHovered: true, }, }, } stories.add('No hover', () => <SidebarToggle {...sidebarToggleProps.noHover} />) stories.add('Unlocked hover', () => ( <SidebarToggle {...sidebarToggleProps.unlockedHover} /> )) stories.add('Locked hover', () => ( <SidebarToggle {...sidebarToggleProps.lockedHover} /> ))
Refactor sidebar toggle story to run off template
Refactor sidebar toggle story to run off template
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -1,41 +1,48 @@ import React from 'react' import { storiesOf } from '@storybook/react' -import SidebarToggle from 'src/dashboard-refactor/header/SidebarHeader/SidebarToggle/SidebarToggle' +import SidebarToggle, { + SidebarToggleProps, +} from 'src/dashboard-refactor/header/SidebarHeader/SidebarToggle/SidebarToggle' +import { SidebarLockedState } from 'src/dashboard-refactor/lists-sidebar/types' +import { HoverState } from 'src/dashboard-refactor/types' const stories = storiesOf('Dashboard Refactor|Header/Sidebar Toggle', module) +const sidebarLockedState: SidebarLockedState = { + isSidebarLocked: false, + toggleSidebarLockedState: () => {}, +} + +const hoverState: HoverState = { + isHovered: false, + onHoverEnter: () => {}, + onHoverLeave: () => {}, +} + +const template: SidebarToggleProps = { + sidebarLockedState: sidebarLockedState, + hoverState: hoverState, +} + export const sidebarToggleProps = { noHover: { - sidebarLockedState: { - toggleSidebarLockedState: function () {}, - isSidebarLocked: false, - }, - hoverState: { - onHoverEnter: function () {}, - onHoverLeave: function () {}, - isHovered: false, - }, + ...template, }, unlockedHover: { - sidebarLockedState: { - toggleSidebarLockedState: function () {}, - isSidebarLocked: false, - }, + ...template, hoverState: { - onHoverEnter: function () {}, - onHoverLeave: function () {}, + ...hoverState, isHovered: true, }, }, lockedHover: { sidebarLockedState: { - toggleSidebarLockedState: function () {}, + ...sidebarLockedState, isSidebarLocked: true, }, hoverState: { - onHoverEnter: function () {}, - onHoverLeave: function () {}, + ...hoverState, isHovered: true, }, },
737abbfa822843e1a15e6bec8cb00d94fbab5041
src/constants/misc.ts
src/constants/misc.ts
import { DAYS_IN_WEEK } from './dates'; export const APPLICATION_TITLE = 'Mturk Engine'; export const MTURK_URL_ENCODING_FORMAT = 'RFC1738'; export const SQUARE_SIZE = 10; export const MONTH_LABEL_GUTTER_SIZE = 4; export const MONTH_LABEL_SIZE = SQUARE_SIZE + MONTH_LABEL_GUTTER_SIZE; export const HEATMAP_CSS_PREFIX = `react-calendar-heatmap-`; export const SQUARE_BORDER_RADIUS = 1; export const GUTTER_SIZE = 1; export const WEEKDAY_LABELS = ['', 'Mon', '', 'Wed', '', 'Fri', '']; export const WEEKDAY_LABEL_SIZE = 30; export const SQUARE_SIZE_WITH_GUTTER = SQUARE_SIZE + GUTTER_SIZE; export const WEEK_HEIGHT = DAYS_IN_WEEK * SQUARE_SIZE_WITH_GUTTER; export const DATABASE_RESULTS_PER_PAGE = 25; export const STATUS_DETAIL_RESULTS_PER_PAGE = 20; export const DEFAULT_WATCHER_FOLDER_ID = '___UNSORTED_WATCHER_FOLDER___'; export const DEFAULT_NEW_WATCHER_FOLDER_NAME = 'New Folder'; export const WATCHER_FOLDER_NAME_SUFFIX_CONNECTOR = '-'; export const RESOURCE_LIST_ITEM_CLASS = 'Polaris-ResourceList__Item Polaris-ResourceList__Item--focused';
import { DAYS_IN_WEEK } from './dates'; export const APPLICATION_TITLE = 'Mturk Engine'; export const MTURK_URL_ENCODING_FORMAT = 'RFC1738'; export const SQUARE_SIZE = 10; export const MONTH_LABEL_GUTTER_SIZE = 4; export const MONTH_LABEL_SIZE = SQUARE_SIZE + MONTH_LABEL_GUTTER_SIZE; export const HEATMAP_CSS_PREFIX = `react-calendar-heatmap-`; export const SQUARE_BORDER_RADIUS = 1; export const GUTTER_SIZE = 1; export const WEEKDAY_LABELS = ['', 'Mon', '', 'Wed', '', 'Fri', '']; export const WEEKDAY_LABEL_SIZE = 30; export const SQUARE_SIZE_WITH_GUTTER = SQUARE_SIZE + GUTTER_SIZE; export const WEEK_HEIGHT = DAYS_IN_WEEK * SQUARE_SIZE_WITH_GUTTER; export const DATABASE_RESULTS_PER_PAGE = 20; export const STATUS_DETAIL_RESULTS_PER_PAGE = 20; export const DEFAULT_WATCHER_FOLDER_ID = '___UNSORTED_WATCHER_FOLDER___'; export const DEFAULT_NEW_WATCHER_FOLDER_NAME = 'New Folder'; export const WATCHER_FOLDER_NAME_SUFFIX_CONNECTOR = '-'; export const RESOURCE_LIST_ITEM_CLASS = 'Polaris-ResourceList__Item Polaris-ResourceList__Item--focused';
Change DATABASE_RESULTS_PER_PAGE to 20 from 25.
Change DATABASE_RESULTS_PER_PAGE to 20 from 25.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -16,7 +16,7 @@ export const SQUARE_SIZE_WITH_GUTTER = SQUARE_SIZE + GUTTER_SIZE; export const WEEK_HEIGHT = DAYS_IN_WEEK * SQUARE_SIZE_WITH_GUTTER; -export const DATABASE_RESULTS_PER_PAGE = 25; +export const DATABASE_RESULTS_PER_PAGE = 20; export const STATUS_DETAIL_RESULTS_PER_PAGE = 20; export const DEFAULT_WATCHER_FOLDER_ID = '___UNSORTED_WATCHER_FOLDER___';
b0654c3018a0beb0c139aac98384f77a6e456aa6
src/Parsing/Outline/Patterns.ts
src/Parsing/Outline/Patterns.ts
const group = (pattern: string) => `(?:${pattern})` const optional = (pattern: string) => group(pattern) + '?' const all = (pattern: string) => group(pattern) + '*' const atLeast = (count: number, pattern: string) => group(pattern) + `{${count},}` const either = (...patterns: string[]) => group(patterns.join('|')) const WHITESPACE_CHAR = '[^\\S\\n]' const lineOf = (pattern: string) => '^' + pattern + all(WHITESPACE_CHAR) + '$' const streakOf = (char: string) => lineOf(atLeast(3, char)) const dottedStreakOf = (char: string) => lineOf(optional(' ') + atLeast(2, char + ' ') + char) const lineStartingWith = (pattern: string) => '^' + pattern const BLANK_LINE = new RegExp( lineOf('') ) const INDENT = either(' ', '\t') // We don't need to check for the start or end of the string, because if a line // contains a non-whitespace character anywhere in it, it's not blank. const NON_BLANK_LINE = /\S/ export { NON_BLANK_LINE, BLANK_LINE, WHITESPACE_CHAR, INDENT, optional, either, lineOf, streakOf, dottedStreakOf, lineStartingWith }
const group = (pattern: string) => `(?:${pattern})` const optional = (pattern: string) => group(pattern) + '?' const all = (pattern: string) => group(pattern) + '*' const atLeast = (count: number, pattern: string) => group(pattern) + `{${count},}` const either = (...patterns: string[]) => group(patterns.join('|')) const WHITESPACE_CHAR = '[^\\S\\n]' const lineOf = (pattern: string) => '^' + pattern + all(WHITESPACE_CHAR) + '$' const streakOf = (char: string) => lineOf(atLeast(3, char)) const dottedStreakOf = (char: string) => lineOf(optional(' ') + atLeast(2, char + ' ') + char) const lineStartingWith = (pattern: string) => '^' + pattern const BLANK_LINE = lineOf('') const INDENT = either(' ', '\t') // We don't need to check for the start or end of the string, because if a line // contains a non-whitespace character anywhere in it, it's not blank. const NON_BLANK_LINE = '\\S' export { NON_BLANK_LINE, BLANK_LINE, WHITESPACE_CHAR, INDENT, optional, either, lineOf, streakOf, dottedStreakOf, lineStartingWith }
Make pattern helper constants strings
[Broken] Make pattern helper constants strings
TypeScript
mit
start/up,start/up
--- +++ @@ -18,15 +18,13 @@ const lineStartingWith = (pattern: string) => '^' + pattern -const BLANK_LINE = new RegExp( - lineOf('') -) +const BLANK_LINE = lineOf('') const INDENT = either(' ', '\t') // We don't need to check for the start or end of the string, because if a line // contains a non-whitespace character anywhere in it, it's not blank. -const NON_BLANK_LINE = /\S/ +const NON_BLANK_LINE = '\\S' export { NON_BLANK_LINE,
53b41e90db2c6c4bda3ff36b5d7f850359b02b97
src/openstack/OpenStackPluginOptionsForm.tsx
src/openstack/OpenStackPluginOptionsForm.tsx
import * as React from 'react'; import { useSelector } from 'react-redux'; import { formValueSelector } from 'redux-form'; import { FormContainer, SelectField, NumberField } from '@waldur/form-react'; import { translate } from '@waldur/i18n'; import { FORM_ID } from '@waldur/marketplace/offerings/store/constants'; const pluginOptionsSelector = state => formValueSelector(FORM_ID)(state, 'plugin_options'); export const OpenStackPluginOptionsForm = ({ container }) => { const STORAGE_MODE_OPTIONS = React.useMemo( () => [ { label: translate('Fixed — use common storage quota'), value: 'fixed', }, { label: translate( 'Dynamic — use separate volume types for tracking pricing', ), value: 'dynamic', }, ], [], ); const pluginOptions = useSelector(pluginOptionsSelector); return ( <FormContainer {...container}> <SelectField name="storage_mode" label={translate('Storage mode')} options={STORAGE_MODE_OPTIONS} simpleValue={true} required={true} /> {pluginOptions.storage_mode == 'dynamic' && ( <NumberField name="snapshot_size_limit_gb" label={translate('Snapshot size limit')} unit="GB" description={translate( 'Additional space to apply to storage quota to be used by snapshots.', )} /> )} </FormContainer> ); };
import * as React from 'react'; import { useSelector } from 'react-redux'; import { formValueSelector } from 'redux-form'; import { FormContainer, SelectField, NumberField } from '@waldur/form-react'; import { translate } from '@waldur/i18n'; import { FORM_ID } from '@waldur/marketplace/offerings/store/constants'; const pluginOptionsSelector = state => formValueSelector(FORM_ID)(state, 'plugin_options'); export const OpenStackPluginOptionsForm = ({ container }) => { const STORAGE_MODE_OPTIONS = React.useMemo( () => [ { label: translate('Fixed — use common storage quota'), value: 'fixed', }, { label: translate( 'Dynamic — use separate volume types for tracking pricing', ), value: 'dynamic', }, ], [], ); const pluginOptions = useSelector(pluginOptionsSelector); return ( <FormContainer {...container}> <SelectField name="storage_mode" label={translate('Storage mode')} options={STORAGE_MODE_OPTIONS} simpleValue={true} required={true} /> {pluginOptions && pluginOptions.storage_mode == 'dynamic' && ( <NumberField name="snapshot_size_limit_gb" label={translate('Snapshot size limit')} unit="GB" description={translate( 'Additional space to apply to storage quota to be used by snapshots.', )} /> )} </FormContainer> ); };
Fix OpenStack offering provision form
Fix OpenStack offering provision form [WAL-2972]
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -37,7 +37,7 @@ simpleValue={true} required={true} /> - {pluginOptions.storage_mode == 'dynamic' && ( + {pluginOptions && pluginOptions.storage_mode == 'dynamic' && ( <NumberField name="snapshot_size_limit_gb" label={translate('Snapshot size limit')}
ec598768e6f50204f726a073c0d324a59bfcb1f5
kspRemoteTechPlanner/calculator/orbital.ts
kspRemoteTechPlanner/calculator/orbital.ts
/// <reference path="_references.ts" /> module Calculator.Orbital { 'use strict'; export function period(sma: number, stdGravParam: number): number { return 2 * Math.PI * Math.sqrt(Math.pow(sma, 3) / stdGravParam); } export function nightTime(radius: number, sma: number, stdGravParam: number): number { return Orbital.period(sma, stdGravParam) * Math.asin(radius / sma) / Math.PI; } export function hohmannStartDV(sma1: number, sma2: number, stdGravParam: number): number { return Math.sqrt(stdGravParam / sma1) * (Math.sqrt((2 * sma2) / (sma1 + sma2)) - 1); } export function hohmannFinishDV(sma1: number, sma2: number, stdGravParam: number): number { return Math.sqrt(stdGravParam / sma2) * (1 - Math.sqrt((2 * sma1) / (sma1 + sma2))); } export function slidePhaseAngle(slideDeg: number, periodLow: number, periodHigh: number): number { return slideDeg / (1 - periodLow / periodHigh); } }
/// <reference path="_references.ts" /> module Calculator.Orbital { 'use strict'; export function period(sma: number, stdGravParam: number): number { return 2 * Math.PI * Math.sqrt(Math.pow(sma, 3) / stdGravParam); } export function sma(stdGravParam: number, period: number): number { return Math.pow(Math.pow(period, 2) * stdGravParam / (4 * Math.pow(Math.PI, 2)), 1 / 3); } export function nightTime(radius: number, sma: number, stdGravParam: number): number { return Orbital.period(sma, stdGravParam) * Math.asin(radius / sma) / Math.PI; } export function hohmannStartDV(sma1: number, sma2: number, stdGravParam: number): number { return Math.sqrt(stdGravParam / sma1) * (Math.sqrt((2 * sma2) / (sma1 + sma2)) - 1); } export function hohmannFinishDV(sma1: number, sma2: number, stdGravParam: number): number { return Math.sqrt(stdGravParam / sma2) * (1 - Math.sqrt((2 * sma1) / (sma1 + sma2))); } export function slidePhaseAngle(slideDeg: number, periodLow: number, periodHigh: number): number { return slideDeg / (1 - periodLow / periodHigh); } }
Add inversion between sma and period.
Add inversion between sma and period.
TypeScript
mit
ryohpops/kspRemoteTechPlanner,ryohpops/kspRemoteTechPlanner,ryohpops/kspRemoteTechPlanner
--- +++ @@ -5,6 +5,10 @@ export function period(sma: number, stdGravParam: number): number { return 2 * Math.PI * Math.sqrt(Math.pow(sma, 3) / stdGravParam); + } + + export function sma(stdGravParam: number, period: number): number { + return Math.pow(Math.pow(period, 2) * stdGravParam / (4 * Math.pow(Math.PI, 2)), 1 / 3); } export function nightTime(radius: number, sma: number, stdGravParam: number): number {
533ca8d7168e37c205d79c6ee3fba2b661a4300b
packages/components/components/modal/Header.tsx
packages/components/components/modal/Header.tsx
import React from 'react'; import { c } from 'ttag'; import { classnames } from '../../helpers'; import Title from './Title'; import { Button } from '../button'; import Icon from '../icon/Icon'; interface Props extends Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>, 'children'> { modalTitleID: string; children: React.ReactNode; onClose?: () => void; displayTitle?: boolean; hasClose?: boolean; closeTextModal?: string; } const Header = ({ children, modalTitleID, className, closeTextModal, hasClose = true, displayTitle = true, onClose, ...rest }: Props) => { const closeText = !closeTextModal ? c('Action').t`Close modal` : closeTextModal; return ( <header className={classnames(['modal-header', !displayTitle && 'modal-header--no-title', className])} {...rest} > {hasClose ? ( <Button icon shape="ghost" size="small" className="modal-close" title={closeText} onClick={onClose}> <Icon className="modal-close-icon" name="close" alt={closeText} /> </Button> ) : null} {typeof children === 'string' ? ( <Title id={modalTitleID} className={!displayTitle ? 'sr-only' : undefined}> {children} </Title> ) : ( children )} </header> ); }; export default Header;
import React from 'react'; import { c } from 'ttag'; import { classnames } from '../../helpers'; import Title from './Title'; import { Button } from '../button'; import Icon from '../icon/Icon'; interface Props extends Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>, 'children'> { modalTitleID: string; children: React.ReactNode; onClose?: () => void; displayTitle?: boolean; hasClose?: boolean; closeTextModal?: string; } const Header = ({ children, modalTitleID, className, closeTextModal, hasClose = true, displayTitle = true, onClose, ...rest }: Props) => { const closeText = !closeTextModal ? c('Action').t`Close modal` : closeTextModal; return ( <header className={classnames(['modal-header', !displayTitle && 'modal-header--no-title', className])} {...rest} > {hasClose ? ( <Button icon shape="ghost" size="small" className="modal-close" title={closeText} onClick={onClose}> <Icon className="modal-close-icon" name="close" alt={closeText} /> </Button> ) : null} {typeof children === 'string' ? ( <Title id={modalTitleID} className={!displayTitle ? 'sr-only' : 'text-ellipsis'}> {children} </Title> ) : ( children )} </header> ); }; export default Header;
Fix names being too long in header modals
[MAILWEB-1927] Fix names being too long in header modals
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -36,7 +36,7 @@ </Button> ) : null} {typeof children === 'string' ? ( - <Title id={modalTitleID} className={!displayTitle ? 'sr-only' : undefined}> + <Title id={modalTitleID} className={!displayTitle ? 'sr-only' : 'text-ellipsis'}> {children} </Title> ) : (
fb5be32187cd40156b3cec56a070ee41c428be9b
web/webpack.config.ts
web/webpack.config.ts
import * as webpack from 'webpack'; import * as path from 'path'; import * as CopyWebpackPlugin from 'copy-webpack-plugin'; const OUTPUT_PATH = path.resolve(__dirname, 'dist'); const config: webpack.Configuration = { entry: './src/main.ts', output: { path: OUTPUT_PATH, filename: 'bundle.js' }, resolve: { extensions: ['.ts', '.tsx'] }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, use: ['ts-loader'] } ] }, plugins: [ new CopyWebpackPlugin([{ from: 'css/index.css', to: OUTPUT_PATH } ]) ] }; export default config;
import * as webpack from 'webpack'; import * as path from 'path'; import * as CopyWebpackPlugin from 'copy-webpack-plugin'; const OUTPUT_PATH = path.resolve(__dirname, 'dist'); const config: webpack.Configuration = { entry: './src/main.ts', output: { path: OUTPUT_PATH, filename: 'bundle.js' }, resolve: { extensions: ['.ts', '.tsx'] }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, use: ['ts-loader'] } ] }, plugins: [ new CopyWebpackPlugin([{ from: 'css/index.css', to: OUTPUT_PATH } ]), /** See https://github.com/webpack-contrib/uglifyjs-webpack-plugin/tree/v0.4.6 */ new webpack.optimize.UglifyJsPlugin() ] }; export default config;
Add uglification for web build
Add uglification for web build
TypeScript
mpl-2.0
gozer/voice-web,gozer/voice-web,kenrick95/voice-web,common-voice/common-voice,common-voice/common-voice,gozer/voice-web,gozer/voice-web,kenrick95/voice-web,kenrick95/voice-web,kenrick95/voice-web,kenrick95/voice-web,gozer/voice-web,common-voice/common-voice,common-voice/common-voice,gozer/voice-web,kenrick95/voice-web,gozer/voice-web
--- +++ @@ -27,7 +27,10 @@ new CopyWebpackPlugin([{ from: 'css/index.css', to: OUTPUT_PATH } - ]) + ]), + + /** See https://github.com/webpack-contrib/uglifyjs-webpack-plugin/tree/v0.4.6 */ + new webpack.optimize.UglifyJsPlugin() ] };
97663342c025187a919c963bbe5abaf0c54f6f79
src/app/common/services/http-authentication.interceptor.ts
src/app/common/services/http-authentication.interceptor.ts
import { Injectable, Injector, Inject } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs'; import { currentUser } from 'src/app/ajs-upgraded-providers'; import API_URL from 'src/app/config/constants/apiURL'; @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(@Inject(currentUser) private CurrentUser: any) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (request.url.startsWith(API_URL) && this.CurrentUser.authenticationToken) { request = request.clone({ setHeaders: { 'Auth-Token': `Bearer ${this.CurrentUser.authenticationToken}`, Username: `Bearer ${this.CurrentUser.username}`, }, }); } return next.handle(request); } }
import { Injectable, Injector, Inject } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs'; import { currentUser } from 'src/app/ajs-upgraded-providers'; import API_URL from 'src/app/config/constants/apiURL'; @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(@Inject(currentUser) private CurrentUser: any) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (request.url.startsWith(API_URL) && this.CurrentUser.authenticationToken) { request = request.clone({ setHeaders: { 'Auth-Token': `${this.CurrentUser.authenticationToken}`, Username: `${this.CurrentUser.profile.username}`, }, }); } return next.handle(request); } }
Remove Bearer from auth headers
FIX: Remove Bearer from auth headers
TypeScript
agpl-3.0
doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web
--- +++ @@ -11,8 +11,8 @@ if (request.url.startsWith(API_URL) && this.CurrentUser.authenticationToken) { request = request.clone({ setHeaders: { - 'Auth-Token': `Bearer ${this.CurrentUser.authenticationToken}`, - Username: `Bearer ${this.CurrentUser.username}`, + 'Auth-Token': `${this.CurrentUser.authenticationToken}`, + Username: `${this.CurrentUser.profile.username}`, }, }); }
f481d54fb3dfe7e00926ca0be287b89f34c5eef2
packages/controls/test/src/phosphor/currentselection_test.ts
packages/controls/test/src/phosphor/currentselection_test.ts
import { expect } from 'chai'; import { spy } from 'sinon'; import { Selection } from '../../../lib/phosphor/currentselection' describe('Selection with items', function() { let selection; let subscriber; // subscribe to signals from selection beforeEach(function() { selection = new Selection(['value-0', 'value-1']) selection.index = null; subscriber = spy() selection.selectionChanged.connect(subscriber); }); it('be unselected', function() { expect(selection.index).to.be.null; expect(selection.value).to.be.null; }) it('set an item', function() { selection.index = 1; expect(selection.index).to.equal(1); expect(selection.value).to.equal('value-1') }) it('dispatch a signal when setting an item', function() { selection.index = 1; expect(subscriber.calledOnce).to.be.true; const [_, message] = subscriber.getCall(0).args expect(message).to.deep.equal({ previousIndex: null, previousValue: null, currentIndex: 1, currentValue: 'value-1' }) }) });
import { expect } from 'chai'; import { spy } from 'sinon'; import { Selection } from '../../../lib/phosphor/currentselection' describe('Selection with items', function() { let selection; let subscriber; // subscribe to signals from selection beforeEach(function() { selection = new Selection(['value-0', 'value-1']) selection.index = null; subscriber = spy() selection.selectionChanged.connect(subscriber); }); it('be unselected', function() { expect(selection.index).to.be.null; expect(selection.value).to.be.null; }) it('set an item', function() { selection.index = 1; expect(selection.index).to.equal(1); expect(selection.value).to.equal('value-1') }) it('dispatch a signal when setting an item', function() { selection.index = 1; expect(subscriber.calledOnce).to.be.true; const [_, message] = subscriber.getCall(0).args expect(message).to.deep.equal({ previousIndex: null, previousValue: null, currentIndex: 1, currentValue: 'value-1' }) }) it('set a value', function() { selection.value = 'value-0'; expect(selection.value).to.equal('value-0'); expect(selection.index).to.equal(0) }) it('dispatch a signal when setting a value', function() { selection.value = 'value-0'; expect(subscriber.calledOnce).to.be.true; const [_, message] = subscriber.getCall(0).args expect(message).to.deep.equal({ previousIndex: null, previousValue: null, currentIndex: 0, currentValue: 'value-0' }) }) });
Test for setting by value
Test for setting by value
TypeScript
bsd-3-clause
SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets
--- +++ @@ -37,4 +37,22 @@ currentValue: 'value-1' }) }) + + it('set a value', function() { + selection.value = 'value-0'; + expect(selection.value).to.equal('value-0'); + expect(selection.index).to.equal(0) + }) + + it('dispatch a signal when setting a value', function() { + selection.value = 'value-0'; + expect(subscriber.calledOnce).to.be.true; + const [_, message] = subscriber.getCall(0).args + expect(message).to.deep.equal({ + previousIndex: null, + previousValue: null, + currentIndex: 0, + currentValue: 'value-0' + }) + }) });
caea49bad3943d82804e68d490f9319532d2e0c6
src/lib/Scenes/Home/__tests__/index-tests.tsx
src/lib/Scenes/Home/__tests__/index-tests.tsx
import { shallow } from "enzyme" import { Tab } from "lib/Components/TabBar" import React from "react" import Home from "../index" it("has the correct number of tabs", () => { const wrapper = shallow(<Home tracking={null} />) expect(wrapper.find(Tab)).toHaveLength(3) })
import { shallow } from "enzyme" import { Tab } from "lib/Components/TabBar" import React from "react" import Home from "../index" it("has the correct number of tabs", () => { const wrapper = shallow(<Home initialTab={0} isVisible={true} tracking={null} />) expect(wrapper.find(Tab)).toHaveLength(3) })
Update home props on index tests
[Tests] Update home props on index tests
TypeScript
mit
artsy/eigen,artsy/eigen,artsy/emission,artsy/emission,artsy/eigen,artsy/emission,artsy/emission,artsy/eigen,artsy/emission,artsy/emission,artsy/eigen,artsy/eigen,artsy/eigen,artsy/emission
--- +++ @@ -4,6 +4,6 @@ import Home from "../index" it("has the correct number of tabs", () => { - const wrapper = shallow(<Home tracking={null} />) + const wrapper = shallow(<Home initialTab={0} isVisible={true} tracking={null} />) expect(wrapper.find(Tab)).toHaveLength(3) })
9acd35f167b3249f3979f0ca9e0aa99d631f083c
src/viewer/OptionsParser.ts
src/viewer/OptionsParser.ts
import {IViewerOptions} from "../Viewer"; import {ParameterMapillaryError} from "../Error"; export class OptionsParser { public parseAndDefaultOptions(options: IViewerOptions): IViewerOptions { if (options === undefined || options == null) { options = {}; } if (options.ui == null) { options.ui = "cover"; } if (options.uiList == null) { options.uiList = ["none", "cover", "simple"]; } if (options.ui !== "none" && options.ui !== "cover" && options.ui !== "simple" && options.ui !== "gl") { throw new ParameterMapillaryError(); } return options; } } export default OptionsParser
import {IViewerOptions} from "../Viewer"; import {ParameterMapillaryError} from "../Error"; export class OptionsParser { public parseAndDefaultOptions(options: IViewerOptions): IViewerOptions { if (options === undefined || options == null) { options = {}; } if (options.ui == null) { options.ui = "cover"; } if (options.uiList == null) { options.uiList = ["none", "cover", "simple", "gl"]; } if (options.ui !== "none" && options.ui !== "cover" && options.ui !== "simple" && options.ui !== "gl") { throw new ParameterMapillaryError(); } return options; } } export default OptionsParser
Add GL to options parser default UI list.
Add GL to options parser default UI list.
TypeScript
mit
mapillary/mapillary-js,mapillary/mapillary-js
--- +++ @@ -12,7 +12,7 @@ } if (options.uiList == null) { - options.uiList = ["none", "cover", "simple"]; + options.uiList = ["none", "cover", "simple", "gl"]; }
08682308b195061788c2c53d23ce8b4dd89edd34
app/javascript/retrospring/features/moderation/privilege.ts
app/javascript/retrospring/features/moderation/privilege.ts
import Rails from '@rails/ujs'; import I18n from '../../../legacy/i18n'; import { showNotification, showErrorNotification } from 'utilities/notifications'; export function privilegeCheckHandler(event: Event): void { const checkbox = event.target as HTMLInputElement; checkbox.disabled = true; const privilegeType = checkbox.dataset.type; Rails.ajax({ url: '/ajax/mod/privilege', type: 'POST', data: new URLSearchParams({ user: checkbox.dataset.user, type: privilegeType, status: String(checkbox.checked) }).toString(), success: (data) => { if (data.success) { checkbox.checked = data.checked; } showNotification(data.message, data.success); }, error: (data, status, xhr) => { console.log(data, status, xhr); showErrorNotification(I18n.translate('frontend.error.message')); checkbox.checked = false; }, complete: () => { checkbox.disabled = false; } }); /* ($ document).on "click", "input[type=checkbox][name=check-your-privileges]", -> box = $(this) box.attr 'disabled', 'disabled' privType = box[0].dataset.type boxChecked = box[0].checked $.ajax url: '/ajax/mod/privilege' type: 'POST' data: user: box[0].dataset.user type: privType status: boxChecked success: (data, status, jqxhr) -> if data.success box[0].checked = if data.checked? then data.checked else !boxChecked showNotification data.message, data.success error: (jqxhr, status, error) -> box[0].checked = false console.log jqxhr, status, error showNotification translate('frontend.error.message'), false complete: (jqxhr, status) -> box.removeAttr "disabled" */ }
import Rails from '@rails/ujs'; import I18n from '../../../legacy/i18n'; import { showNotification, showErrorNotification } from 'utilities/notifications'; export function privilegeCheckHandler(event: Event): void { const checkbox = event.target as HTMLInputElement; checkbox.disabled = true; const privilegeType = checkbox.dataset.type; Rails.ajax({ url: '/ajax/mod/privilege', type: 'POST', data: new URLSearchParams({ user: checkbox.dataset.user, type: privilegeType, status: String(checkbox.checked) }).toString(), success: (data) => { if (data.success) { checkbox.checked = data.checked; } showNotification(data.message, data.success); }, error: (data, status, xhr) => { console.log(data, status, xhr); showErrorNotification(I18n.translate('frontend.error.message')); checkbox.checked = false; }, complete: () => { checkbox.disabled = false; } }); }
Apply review suggestion from @raccube
Apply review suggestion from @raccube Co-authored-by: Karina Kwiatek <a279f78642aaf231facf94ac593d2ad2fd791699@users.noreply.github.com>
TypeScript
agpl-3.0
Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring
--- +++ @@ -34,31 +34,4 @@ } }); - - /* - ($ document).on "click", "input[type=checkbox][name=check-your-privileges]", -> - box = $(this) - box.attr 'disabled', 'disabled' - - privType = box[0].dataset.type - boxChecked = box[0].checked - - $.ajax - url: '/ajax/mod/privilege' - type: 'POST' - data: - user: box[0].dataset.user - type: privType - status: boxChecked - success: (data, status, jqxhr) -> - if data.success - box[0].checked = if data.checked? then data.checked else !boxChecked - showNotification data.message, data.success - error: (jqxhr, status, error) -> - box[0].checked = false - console.log jqxhr, status, error - showNotification translate('frontend.error.message'), false - complete: (jqxhr, status) -> - box.removeAttr "disabled" - */ }
db2b2b08f88435bdc42ba2e4bfbc903cb1fcb896
test/maml/maml-html-spec.ts
test/maml/maml-html-spec.ts
import { Frame } from "../../src/frames/frame"; import { FrameString } from "../../src/frames/frame-string"; import { FrameExpr } from "../../src/frames/frame-expr"; import * as chai from "chai"; const expect = chai.expect; export class FrameHTML extends Frame { public static readonly BEGIN = ` <!DOCTYPE html> <html> <head> </head> <body> `; public static readonly END = ` </body> </html> `; public call(argument: FrameString) { return new FrameString(FrameHTML.BEGIN + argument.toStringData() + FrameHTML.END); } }; describe("FrameHTML", () => { const js_string = "Hello, HTML!"; const frame_string = new FrameString(js_string); const frame_html = new FrameHTML(); it("HTML-ifies string expressions when called", () => { const result = frame_html.call(frame_string); expect(result).to.be.an.instanceof(FrameString); expect(result.toString()).to.equal(`“${js_string}”`); }); });
import { Frame } from "../../src/frames/frame"; import { FrameString } from "../../src/frames/frame-string"; import { FrameExpr } from "../../src/frames/frame-expr"; import * as chai from "chai"; const expect = chai.expect; export class FrameHTML extends Frame { public static readonly BEGIN = ` <!DOCTYPE html> <html> <head> </head> <body> `; public static readonly END = ` </body> </html> `; public call(argument: FrameString) { return new FrameString(FrameHTML.BEGIN + argument.toStringData() + FrameHTML.END); } }; describe("FrameHTML", () => { const js_string = "Hello, HTML!"; const frame_string = new FrameString(js_string); const frame_html = new FrameHTML(); it("HTML-ifies string expressions when called", () => { const result = frame_html.call(frame_string); const result_string = result.toString(); expect(result).to.be.an.instanceof(FrameString); expect(result_string).to.include(js_string); expect(result_string).to.include('<!DOCTYPE html>'); expect(result_string).to.match(/<body>([\s\S]*)<\/body>/); }); });
Verify presence of HTML tags
Verify presence of HTML tags
TypeScript
mit
TheSwanFactory/maml,TheSwanFactory/maml,TheSwanFactory/hclang,TheSwanFactory/hclang
--- +++ @@ -24,7 +24,6 @@ } }; - describe("FrameHTML", () => { const js_string = "Hello, HTML!"; const frame_string = new FrameString(js_string); @@ -32,7 +31,10 @@ it("HTML-ifies string expressions when called", () => { const result = frame_html.call(frame_string); + const result_string = result.toString(); expect(result).to.be.an.instanceof(FrameString); - expect(result.toString()).to.equal(`“${js_string}”`); + expect(result_string).to.include(js_string); + expect(result_string).to.include('<!DOCTYPE html>'); + expect(result_string).to.match(/<body>([\s\S]*)<\/body>/); }); });
1d6f5aca0e7696c9c31f35d0b66e22a10c5d3b78
Presentation.Web/Tests/ItProject/Edit/projectEdit.e2e.spec.ts
Presentation.Web/Tests/ItProject/Edit/projectEdit.e2e.spec.ts
import mock = require('protractor-http-mock'); import Helper = require('../../helper'); import ItProjectEditPo = require('../../../app/components/it-project/it-project-edit.po'); describe('project edit view', () => { var browserHelper: Helper.BrowserHelper; var pageObject: ItProjectEditPo; beforeEach(() => { mock(['itproject', 'itprojectrole', 'itprojecttype', 'itprojectrights']); browserHelper = new Helper.BrowserHelper(browser); pageObject = new ItProjectEditPo(); pageObject.getPage(); browser.driver.manage().window().maximize(); }); it('should save when name looses focus', () => { // arrange pageObject.nameInput = 'SomeName'; // act pageObject.idElement.click(); // assert mock.requestsMade() .then((requests: Array<any>) => { var lastRequest = requests[requests.length - 1]; expect(lastRequest.method).toBe('PATCH'); expect(lastRequest.url).toMatch('api/itproject/1'); }); }); afterEach(() => { mock.teardown(); browserHelper.outputLog(); }); });
import mock = require('protractor-http-mock'); import Helper = require('../../helper'); import ItProjectEditPo = require('../../../app/components/it-project/it-project-edit.po'); describe('project edit view', () => { var browserHelper: Helper.BrowserHelper; var pageObject: ItProjectEditPo; beforeEach(() => { mock(['itproject', 'itprojectrole', 'itprojecttype', 'itprojectrights']); browserHelper = new Helper.BrowserHelper(browser); pageObject = new ItProjectEditPo(); pageObject.getPage(); browser.driver.manage().window().maximize(); }); afterEach(() => { mock.teardown(); browserHelper.outputLog(); }); });
Remove redundant e2e test. All tests are on e2e/project-edit branch.
Remove redundant e2e test. All tests are on e2e/project-edit branch.
TypeScript
mpl-2.0
miracle-as/kitos,miracle-as/kitos,miracle-as/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,miracle-as/kitos
--- +++ @@ -16,23 +16,6 @@ browser.driver.manage().window().maximize(); }); - it('should save when name looses focus', () => { - // arrange - pageObject.nameInput = 'SomeName'; - - // act - pageObject.idElement.click(); - - // assert - mock.requestsMade() - .then((requests: Array<any>) => { - var lastRequest = requests[requests.length - 1]; - - expect(lastRequest.method).toBe('PATCH'); - expect(lastRequest.url).toMatch('api/itproject/1'); - }); - }); - afterEach(() => { mock.teardown(); browserHelper.outputLog();
1894b03f4775f0d1b99510bd9af4afabb7a21c52
app/scripts/components/marketplace/details/FeatureSection.tsx
app/scripts/components/marketplace/details/FeatureSection.tsx
import * as React from 'react'; import { ListCell } from '@waldur/marketplace/common/ListCell'; import { Section, Product } from '@waldur/marketplace/types'; interface FeatureSectionProps { section: Section; product: Product; } const AttributeRow = ({ product, attribute }) => { let value = product.attributes[attribute.key]; if (attribute.type === 'list' && typeof value === 'object') { const options = attribute.options.reduce((map, item) => ({...map, [item.key]: item.title}), {}); value = value.map(item => options[item]); value = ListCell(value); } return ( <tr> <td className="col-md-3"> {attribute.title} </td> <td className="col-md-9"> {value} </td> </tr> ); }; export const FeatureSection = (props: FeatureSectionProps) => ( <> <tr className="gray-bg"> <th>{props.section.title}</th> <th/> </tr> {props.section.attributes .filter(attr => props.product.attributes.hasOwnProperty(attr.key)) .map((attr, index) => ( <AttributeRow key={index} product={props.product} attribute={attr}/> ))} </> );
import * as React from 'react'; import { ListCell } from '@waldur/marketplace/common/ListCell'; import { Section, Product } from '@waldur/marketplace/types'; interface FeatureSectionProps { section: Section; product: Product; } const getOptions = attribute => attribute.options.reduce((map, item) => ({...map, [item.key]: item.title}), {}); const AttributeRow = ({ product, attribute }) => { let value = product.attributes[attribute.key]; if (attribute.type === 'list' && typeof value === 'object') { const options = getOptions(attribute); value = value.map(item => options[item]); value = ListCell(value); } else if (attribute.type === 'choice') { const options = getOptions(attribute); value = options[value]; } return ( <tr> <td className="col-md-3"> {attribute.title} </td> <td className="col-md-9"> {value} </td> </tr> ); }; export const FeatureSection = (props: FeatureSectionProps) => ( <> <tr className="gray-bg"> <th>{props.section.title}</th> <th/> </tr> {props.section.attributes .filter(attr => props.product.attributes.hasOwnProperty(attr.key)) .map((attr, index) => ( <AttributeRow key={index} product={props.product} attribute={attr}/> ))} </> );
Add support for choice attribute in marketplace offering.
Add support for choice attribute in marketplace offering.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -8,12 +8,18 @@ product: Product; } +const getOptions = attribute => + attribute.options.reduce((map, item) => ({...map, [item.key]: item.title}), {}); + const AttributeRow = ({ product, attribute }) => { let value = product.attributes[attribute.key]; if (attribute.type === 'list' && typeof value === 'object') { - const options = attribute.options.reduce((map, item) => ({...map, [item.key]: item.title}), {}); + const options = getOptions(attribute); value = value.map(item => options[item]); value = ListCell(value); + } else if (attribute.type === 'choice') { + const options = getOptions(attribute); + value = options[value]; } return ( <tr>
edbeb90105f2ff43eaff3ef228bd89d34fdca828
clients/client-web-vue2/src/index.ts
clients/client-web-vue2/src/index.ts
import { Client, InitConfig } from '@jovotech/client-web'; import { PluginObject } from 'vue'; declare global { interface Window { JovoWebClientVue?: typeof import('.'); } } declare module 'vue/types/vue' { interface Vue { $client: Client; } } export interface JovoWebClientVueConfig { endpointUrl: string; config?: InitConfig; } export * from '@jovotech/client-web'; const plugin: PluginObject<JovoWebClientVueConfig> = { install: (vue, config) => { if (!config?.endpointUrl) { throw new Error( `At least the 'endpointUrl' option has to be set in order to use the JovoWebClientPlugin. `, ); } const client = new Client(config.endpointUrl, config.config); // make the client reactive vue.prototype.$client = vue.observable(client); }, }; export default plugin;
import { Client, InitConfig } from '@jovotech/client-web'; import { PluginObject } from 'vue'; declare global { interface Window { JovoWebClientVue?: typeof import('.'); } } declare module 'vue/types/vue' { interface Vue { $client: Client; } } export interface JovoWebClientVueConfig { endpointUrl: string; config?: InitConfig; } export type PluginConfig = JovoWebClientVueConfig | Client; export * from '@jovotech/client-web'; const plugin: PluginObject<PluginConfig> = { install: (vue, configOrClient) => { if (!(configOrClient instanceof Client)) { if (!configOrClient?.endpointUrl) { throw new Error( `At least the 'endpointUrl' option has to be set in order to use the JovoWebClientPlugin. `, ); } configOrClient = new Client(configOrClient.endpointUrl, configOrClient.config); } // make the client reactive vue.prototype.$client = vue.observable(configOrClient); }, }; export default plugin;
Allow directly passing a Client-instance to the vue2 plugin
:sparkles: Allow directly passing a Client-instance to the vue2 plugin
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -18,18 +18,22 @@ config?: InitConfig; } +export type PluginConfig = JovoWebClientVueConfig | Client; + export * from '@jovotech/client-web'; -const plugin: PluginObject<JovoWebClientVueConfig> = { - install: (vue, config) => { - if (!config?.endpointUrl) { - throw new Error( - `At least the 'endpointUrl' option has to be set in order to use the JovoWebClientPlugin. `, - ); +const plugin: PluginObject<PluginConfig> = { + install: (vue, configOrClient) => { + if (!(configOrClient instanceof Client)) { + if (!configOrClient?.endpointUrl) { + throw new Error( + `At least the 'endpointUrl' option has to be set in order to use the JovoWebClientPlugin. `, + ); + } + configOrClient = new Client(configOrClient.endpointUrl, configOrClient.config); } - const client = new Client(config.endpointUrl, config.config); // make the client reactive - vue.prototype.$client = vue.observable(client); + vue.prototype.$client = vue.observable(configOrClient); }, };
533ff171cf68484b297b3169a9596ed5ed0c8475
tests/legacy-cli/e2e/tests/misc/webpack-5.ts
tests/legacy-cli/e2e/tests/misc/webpack-5.ts
import { rimraf } from '../../utils/fs'; import { killAllProcesses, ng, silentYarn } from '../../utils/process'; import { ngServe, updateJsonFile } from '../../utils/project'; export default async function() { // Currently disabled as it breaks tslib 2.0.2 // Cannot destructure property '__extends' of '_tslib_js__WEBPACK_IMPORTED_MODULE_0___default(...)' as it is undefined. return; // Setup project for yarn usage await rimraf('node_modules'); await updateJsonFile('package.json', (json) => { json.resolutions = { webpack: '5.0.0-rc.3' }; }); await silentYarn(); await silentYarn('webdriver-update'); // Ensure webpack 5 is used const { stdout } = await silentYarn('list', '--pattern', 'webpack'); if (!/\swebpack@5/.test(stdout)) { throw new Error('Expected Webpack 5 to be installed.'); } if (/\swebpack@4/.test(stdout)) { throw new Error('Expected Webpack 4 to not be installed.'); } // Execute the CLI with Webpack 5 await ng('test', '--watch=false'); await ng('build'); await ng('build', '--prod'); await ng('e2e'); try { await ngServe(); } finally { killAllProcesses(); } }
import { rimraf } from '../../utils/fs'; import { killAllProcesses, ng, silentYarn } from '../../utils/process'; import { ngServe, updateJsonFile } from '../../utils/project'; export default async function() { // Setup project for yarn usage await rimraf('node_modules'); await updateJsonFile('package.json', (json) => { json.resolutions = { webpack: '5.0.0-rc.3' }; }); await silentYarn(); await silentYarn('webdriver-update'); // Ensure webpack 5 is used const { stdout } = await silentYarn('list', '--pattern', 'webpack'); if (!/\swebpack@5/.test(stdout)) { throw new Error('Expected Webpack 5 to be installed.'); } if (/\swebpack@4/.test(stdout)) { throw new Error('Expected Webpack 4 to not be installed.'); } // Execute the CLI with Webpack 5 await ng('test', '--watch=false'); await ng('build'); await ng('build', '--prod'); await ng('e2e'); try { await ngServe(); } finally { killAllProcesses(); } }
Revert "test(@angular/cli): disable webpack 5 e2e tests"
Revert "test(@angular/cli): disable webpack 5 e2e tests" This reverts commit ba830d56350920d95e6c0023c84da9e485cf7800.
TypeScript
mit
angular/angular-cli,geofffilippi/angular-cli,angular/angular-cli,geofffilippi/angular-cli,catull/angular-cli,Brocco/angular-cli,clydin/angular-cli,catull/angular-cli,Brocco/angular-cli,geofffilippi/angular-cli,catull/angular-cli,ocombe/angular-cli,angular/angular-cli,clydin/angular-cli,clydin/angular-cli,Brocco/angular-cli,ocombe/angular-cli,ocombe/angular-cli,Brocco/angular-cli,catull/angular-cli,Brocco/angular-cli,ocombe/angular-cli,clydin/angular-cli,geofffilippi/angular-cli,ocombe/angular-cli,angular/angular-cli
--- +++ @@ -3,10 +3,6 @@ import { ngServe, updateJsonFile } from '../../utils/project'; export default async function() { - // Currently disabled as it breaks tslib 2.0.2 - // Cannot destructure property '__extends' of '_tslib_js__WEBPACK_IMPORTED_MODULE_0___default(...)' as it is undefined. - return; - // Setup project for yarn usage await rimraf('node_modules'); await updateJsonFile('package.json', (json) => {
052699eba56b1f099f65ac686a41e866a2d088ed
src/app/directives/router-outlet.ts
src/app/directives/router-outlet.ts
import { ElementRef, DynamicComponentLoader, AttributeMetadata, Directive } from 'angular2/core'; import { Router, RouterOutlet } from 'angular2/router'; import { AuthApi } from '../services/auth-api/authentication'; @Directive({ selector: 'router-outlet' }) export class LoggedInRouterOutlet extends RouterOutlet { publicRoutes = [ '', 'about', 'Security/login', 'Security/register' ]; private parentRouter: Router; private userService: AuthApi; static get parameters() { return [[ElementRef], [DynamicComponentLoader], [Router], [new AttributeMetadata('name'), String], [AuthApi]]; } constructor(elementRef, componentLoader, parentRouter, name, userService) { super(elementRef, componentLoader, parentRouter, name); this.parentRouter = parentRouter; this.userService = userService; } activate(instruction) { if (this._canActivate(instruction.urlPath)) { return super.activate(instruction); } this.parentRouter.navigate(['Login']); } _canActivate(url) { return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn(); } }
import { ElementRef, DynamicComponentLoader, AttributeMetadata, Directive } from 'angular2/core'; import { Router, RouterOutlet } from 'angular2/router'; import { AuthApi } from '../services/auth-api/authentication'; @Directive({ selector: 'router-outlet' }) export class LoggedInRouterOutlet extends RouterOutlet { publicRoutes = [ '', 'about', 'Security/login', 'Security/register' ]; private parentRouter: Router; private userService: AuthApi; static get parameters() { return [[ElementRef], [DynamicComponentLoader], [Router], [new AttributeMetadata('name'), String], [AuthApi]]; } constructor(elementRef, componentLoader, parentRouter, name, userService) { super(elementRef, componentLoader, parentRouter, name); this.parentRouter = parentRouter; this.userService = userService; } activate(instruction) { if (this._canActivate(instruction.urlPath)) { return super.activate(instruction); } let link = ['Security', {task: 'login'}]; this.parentRouter.navigate(link); } _canActivate(url) { return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn(); } }
Modify to redirect to actual login route
Modify to redirect to actual login route
TypeScript
mit
bspride/ModernCookbook,bspride/ModernCookbook,bspride/ModernCookbook
--- +++ @@ -28,8 +28,8 @@ if (this._canActivate(instruction.urlPath)) { return super.activate(instruction); } - - this.parentRouter.navigate(['Login']); + let link = ['Security', {task: 'login'}]; + this.parentRouter.navigate(link); } _canActivate(url) {
13e96fced0341dfa2002c6de9a17ff241fa9cc81
packages/linter/src/rules/AmpImgUsesSrcSet.ts
packages/linter/src/rules/AmpImgUsesSrcSet.ts
import { Context } from "../index"; import { Rule } from "../rule"; const SVG_URL_PATTERN = /^[^?]+\.svg(\?.*)?$/i export class AmpImgUsesSrcSet extends Rule { async run(context: Context) { const $ = context.$; const incorrectImages = $("amp-img") .filter((_, e) => { const src = $(e).attr("src"); const layout = $(e).attr("layout"); const srcset = $(e).attr("srcset"); return ( !SVG_URL_PATTERN.exec(src) && layout && layout !== 'fixed' && layout != 'fixed-height' && !srcset ) }); if (incorrectImages.length > 0) { return this.warn( "Not all responsive <amp-img> define a srcset. Using AMP Optimizer might help." ); } return this.pass(); } meta() { return { url: "https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/amp-optimizer-guide/explainer/?format=websites#image-optimization", title: "Responsive <amp-img> uses srcset", info: "", }; } }
import { Context } from "../index"; import { Rule } from "../rule"; const SVG_URL_PATTERN = /^[^?]+\.svg(\?.*)?$/i const CHECKED_IMG_LAYOUTS = ["fill", "flex-item", "intrinsic", "responsive"]; export class AmpImgUsesSrcSet extends Rule { async run(context: Context) { const $ = context.$; const incorrectImages = $("amp-img") .filter((_, e) => { const src = $(e).attr("src"); const layout = $(e).attr("layout"); const srcset = $(e).attr("srcset"); return ( !SVG_URL_PATTERN.exec(src) && layout && CHECKED_IMG_LAYOUTS.includes(layout) && !srcset ) }); if (incorrectImages.length > 0) { return this.warn( "Not all <amp-img> with non-fixed layout define a srcset. Using AMP Optimizer might help." ); } return this.pass(); } meta() { return { url: "https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/amp-optimizer-guide/explainer/?format=websites#image-optimization", title: "<amp-img> with non-fixed layout uses srcset", info: "", }; } }
Change img srcset check messages and checked layouts
Change img srcset check messages and checked layouts
TypeScript
apache-2.0
ampproject/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox
--- +++ @@ -2,6 +2,8 @@ import { Rule } from "../rule"; const SVG_URL_PATTERN = /^[^?]+\.svg(\?.*)?$/i + +const CHECKED_IMG_LAYOUTS = ["fill", "flex-item", "intrinsic", "responsive"]; export class AmpImgUsesSrcSet extends Rule { async run(context: Context) { @@ -14,13 +16,13 @@ const srcset = $(e).attr("srcset"); return ( !SVG_URL_PATTERN.exec(src) - && layout && layout !== 'fixed' && layout != 'fixed-height' + && layout && CHECKED_IMG_LAYOUTS.includes(layout) && !srcset ) }); if (incorrectImages.length > 0) { return this.warn( - "Not all responsive <amp-img> define a srcset. Using AMP Optimizer might help." + "Not all <amp-img> with non-fixed layout define a srcset. Using AMP Optimizer might help." ); } return this.pass(); @@ -28,7 +30,7 @@ meta() { return { url: "https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/amp-optimizer-guide/explainer/?format=websites#image-optimization", - title: "Responsive <amp-img> uses srcset", + title: "<amp-img> with non-fixed layout uses srcset", info: "", }; }
b4abedc2bbc99e1997a83f9b6bdae1f3ea0135f6
server/tests/factory/NullLoggerFactoryTest.ts
server/tests/factory/NullLoggerFactoryTest.ts
import { assert, expect } from "chai"; import { only, skip, slow, suite, test, timeout } from "mocha-typescript"; import * as sinon from "sinon"; import NullLoggerFactory from "../../src/factory/NullLoggerFactory"; import NullLogger from "../../src/service/logger/NullLogger"; @suite("Null logger factory") class NullLoggerFactoryTest { @test("Should create NullLogger instance") public assertCreate() { // Arrange // ======= // Fake connection let connection = {}; // Create factory instance and configure let factory = new NullLoggerFactory(); factory.setConnection(connection); factory.setVerbose(false); // Act let logger = factory.create(); // Assert expect(logger).to.be.instanceof(NullLogger); } }
import { assert, expect } from "chai"; import { only, skip, slow, suite, test, timeout } from "mocha-typescript"; import * as sinon from "sinon"; import { IConnection } from "vscode-languageserver"; import NullLoggerFactory from "../../src/factory/NullLoggerFactory"; import NullLogger from "../../src/service/logger/NullLogger"; @suite("Null logger factory") class NullLoggerFactoryTest { @test("Should create NullLogger instance") public assertCreate() { // Arrange // ======= // Fake connection let connection = <IConnection> {}; // Create factory instance and configure let factory = new NullLoggerFactory(); factory.setConnection(connection); factory.setVerbose(false); // Act let logger = factory.create(); // Assert expect(logger).to.be.instanceof(NullLogger); } }
Fix unit tests after improved typing
Fix unit tests after improved typing
TypeScript
mit
sandhje/vscode-phpmd
--- +++ @@ -1,6 +1,7 @@ import { assert, expect } from "chai"; import { only, skip, slow, suite, test, timeout } from "mocha-typescript"; import * as sinon from "sinon"; +import { IConnection } from "vscode-languageserver"; import NullLoggerFactory from "../../src/factory/NullLoggerFactory"; import NullLogger from "../../src/service/logger/NullLogger"; @@ -12,7 +13,7 @@ // Arrange // ======= // Fake connection - let connection = {}; + let connection = <IConnection> {}; // Create factory instance and configure let factory = new NullLoggerFactory();
b379ecd03cf8faad81fc2b6e8beede28fa5fecc2
src/cronstrue-i18n.ts
src/cronstrue-i18n.ts
import { ExpressionDescriptor } from "./expressionDescriptor" import { allLocalesLoader } from "./i18n/allLocalesLoader" ExpressionDescriptor.initialize(new allLocalesLoader()); export = ExpressionDescriptor;
import { ExpressionDescriptor } from "./expressionDescriptor" import { allLocalesLoader } from "./i18n/allLocalesLoader" ExpressionDescriptor.initialize(new allLocalesLoader()); export default ExpressionDescriptor; let toString = ExpressionDescriptor.toString; export { toString };
Use named export for 'toString' for i18n version
Use named export for 'toString' for i18n version
TypeScript
mit
bradyholt/cRonstrue,bradyholt/cRonstrue
--- +++ @@ -2,5 +2,8 @@ import { allLocalesLoader } from "./i18n/allLocalesLoader" ExpressionDescriptor.initialize(new allLocalesLoader()); +export default ExpressionDescriptor; -export = ExpressionDescriptor; +let toString = ExpressionDescriptor.toString; +export { toString }; +
c52757bfd53829665ce54bf1d19961328c10bd0a
server/src/lib/utility.ts
server/src/lib/utility.ts
/** * Functions to be shared across mutiple modules. */ /** * Returns the file extension of some path. */ export function getFileExt(path: string): string { return path.substr(path.lastIndexOf('.') - path.length); } /** * Returns the first defined argument. Returns null if there are no defined * arguments. */ export function getFirstDefined(...options) { for (var i = 0; i < arguments.length; i++) { if (arguments[i] !== undefined) { return arguments[i]; } } return null; }
/** * Functions to be shared across mutiple modules. */ /** * Returns the file extension of some path. */ export function getFileExt(path: string): string { return path.substr(path.lastIndexOf('.') - path.length); } /** * Returns the first defined argument. Returns null if there are no defined * arguments. */ export function getFirstDefined(...options) { for (var i = 0; i < options.length; i++) { if (options[i] !== undefined) { return options[i]; } } return null; }
Use options variable instead of arguments in getFirstDefined
Use options variable instead of arguments in getFirstDefined
TypeScript
mpl-2.0
kenrick95/voice-web,kenrick95/voice-web,gozer/voice-web,gozer/voice-web,common-voice/common-voice,kenrick95/voice-web,kenrick95/voice-web,gozer/voice-web,gozer/voice-web,common-voice/common-voice,gozer/voice-web,kenrick95/voice-web,gozer/voice-web,gozer/voice-web,common-voice/common-voice,kenrick95/voice-web,common-voice/common-voice
--- +++ @@ -14,9 +14,9 @@ * arguments. */ export function getFirstDefined(...options) { - for (var i = 0; i < arguments.length; i++) { - if (arguments[i] !== undefined) { - return arguments[i]; + for (var i = 0; i < options.length; i++) { + if (options[i] !== undefined) { + return options[i]; } } return null;
67545a6c2f4ce1e3517504446e102f549a830292
packages/components/hooks/useIsMnemonicAvailable.ts
packages/components/hooks/useIsMnemonicAvailable.ts
import { getHasMigratedAddressKeys } from '@proton/shared/lib/keys'; import { FeatureCode } from '../containers/features'; import { useAddresses } from './useAddresses'; import useFeature from './useFeature'; const useIsMnemonicAvailable = (): boolean => { const mnemonicFeature = useFeature(FeatureCode.Mnemonic); const [addresses = []] = useAddresses(); const hasMigratedKeys = getHasMigratedAddressKeys(addresses); return mnemonicFeature.feature?.Value && hasMigratedKeys; }; export default useIsMnemonicAvailable;
import { getHasMigratedAddressKeys } from '@proton/shared/lib/keys'; import { FeatureCode } from '../containers/features'; import { useAddresses } from './useAddresses'; import useFeature from './useFeature'; import useUser from './useUser'; const useIsMnemonicAvailable = (): boolean => { const [user] = useUser(); const mnemonicFeature = useFeature(FeatureCode.Mnemonic); const [addresses = []] = useAddresses(); const hasMigratedKeys = getHasMigratedAddressKeys(addresses); const isNonPrivateUser = !user?.isPrivate; return mnemonicFeature.feature?.Value && hasMigratedKeys && !isNonPrivateUser; }; export default useIsMnemonicAvailable;
Make mnemonic unavailable for non private users
Make mnemonic unavailable for non private users
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -2,13 +2,17 @@ import { FeatureCode } from '../containers/features'; import { useAddresses } from './useAddresses'; import useFeature from './useFeature'; +import useUser from './useUser'; const useIsMnemonicAvailable = (): boolean => { + const [user] = useUser(); const mnemonicFeature = useFeature(FeatureCode.Mnemonic); const [addresses = []] = useAddresses(); const hasMigratedKeys = getHasMigratedAddressKeys(addresses); - return mnemonicFeature.feature?.Value && hasMigratedKeys; + const isNonPrivateUser = !user?.isPrivate; + + return mnemonicFeature.feature?.Value && hasMigratedKeys && !isNonPrivateUser; }; export default useIsMnemonicAvailable;
183fb365f1557185ad185971d67245589115d86d
src/app/components/dashboard/dashboard.component.ts
src/app/components/dashboard/dashboard.component.ts
import { Component, OnInit } from '@angular/core'; import { StocksService } from '../../services/stocks.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { public stocks:any; constructor(stocksService: StocksService) { stocksService .load() .subscribe(res => this.stocks = JSON.parse(res.text().replace("//",""))); } ngOnInit() { } }
import { Component, OnInit } from '@angular/core'; import { StocksService } from '../../services/stocks.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { public stocks:any; constructor(private stocksService: StocksService) { } ngOnInit() { this.stocksService .load() .subscribe(res => this.stocks = JSON.parse(res.text().replace("//",""))); } }
Move stocksService load to ngOnInit
Move stocksService load to ngOnInit
TypeScript
mit
mbarmawi/stocks-tracker,mbarmawi/stocks-tracker,mbarmawi/stocks-tracker
--- +++ @@ -8,12 +8,12 @@ }) export class DashboardComponent implements OnInit { public stocks:any; - constructor(stocksService: StocksService) { - stocksService + constructor(private stocksService: StocksService) { + } + + ngOnInit() { + this.stocksService .load() .subscribe(res => this.stocks = JSON.parse(res.text().replace("//",""))); } - - ngOnInit() { - } }
7b0884c482f9962a8a81af12acb8007aa38df53c
src/app/components/devlog/post/edit/edit-service.ts
src/app/components/devlog/post/edit/edit-service.ts
import { Injectable, Inject } from 'ng-metadata/core'; import { Fireside_Post } from './../../../../../lib/gj-lib-client/components/fireside/post/post-model'; import template from './edit.html'; @Injectable() export class DevlogPostEdit { constructor( @Inject( '$modal' ) private $modal: any ) { } show( post: Fireside_Post ): ng.IPromise<Fireside_Post> { const modalInstance = this.$modal.open( { template, controller: 'Devlog.Post.EditModalCtrl', controllerAs: '$ctrl', resolve: { post: () => post, }, } ); return modalInstance.result; } }
import { Injectable, Inject } from 'ng-metadata/core'; import { Fireside_Post } from './../../../../../lib/gj-lib-client/components/fireside/post/post-model'; import template from './edit.html'; @Injectable() export class DevlogPostEdit { constructor( @Inject( '$modal' ) private $modal: any ) { } show( post: Fireside_Post ): ng.IPromise<Fireside_Post> { const modalInstance = this.$modal.open( { template, controller: 'Devlog.Post.EditModalCtrl', controllerAs: '$ctrl', resolve: { // They may load this on the game page without having dash stuff loaded in yet. init: [ '$ocLazyLoad', $ocLazyLoad => $ocLazyLoad.load( '/app/modules/dash.js' ) ], post: () => post, }, } ); return modalInstance.result; } }
Fix edit post not loading correctly on game page.
Fix edit post not loading correctly on game page.
TypeScript
mit
gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt
--- +++ @@ -18,6 +18,8 @@ controller: 'Devlog.Post.EditModalCtrl', controllerAs: '$ctrl', resolve: { + // They may load this on the game page without having dash stuff loaded in yet. + init: [ '$ocLazyLoad', $ocLazyLoad => $ocLazyLoad.load( '/app/modules/dash.js' ) ], post: () => post, }, } );
5a61ae2e9f6603961e7498cc0cc02e678fd38671
src/server/main.tsx
src/server/main.tsx
import api from './api' import { runHotMiddleware } from './middleware' import { listen } from './listen' import { monitorExceptions } from './exceptionMonitoring' import { serveFrontend } from './serveFrontend' import { sequelize } from './db' import { setupSession } from './session' const config = require('./config.js') const app = require('express')() app.use(require('helmet')()) monitorExceptions(config)(app) api(app) serveFrontend(app) setupSession(app) if (config.env !== 'production') { runHotMiddleware(app) } sequelize.sync().then(() => listen(app, config))
import api from './api' import { runHotMiddleware } from './middleware' import { listen } from './listen' import { monitorExceptions } from './exceptionMonitoring' import { serveFrontend } from './serveFrontend' import { sequelize } from './db' import { setupSession } from './session' const config = require('./config.js') const app = require('express')() app.use(require('helmet')()) monitorExceptions(config)(app) api(app) setupSession(app) if (config.env !== 'production') { runHotMiddleware(app) } serveFrontend(app) sequelize.sync().then(() => listen(app, config))
Fix frontend serving for development
Fix frontend serving for development
TypeScript
mit
devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity
--- +++ @@ -13,11 +13,12 @@ monitorExceptions(config)(app) api(app) -serveFrontend(app) setupSession(app) if (config.env !== 'production') { runHotMiddleware(app) } +serveFrontend(app) + sequelize.sync().then(() => listen(app, config))
484c5bd0a65e508991a673a4e2c762c45f61489f
src/ts/environment.ts
src/ts/environment.ts
import {PreDestroy, Bean, Qualifier, Autowired, PostConstruct, Optional, Context} from "./context/context"; const themes = [ 'fresh', 'dark', 'blue', 'bootstrap', 'material', 'theme-material']; const themeCLass = new RegExp(`ag-(${themes.join('|')})`); @Bean('environment') export class Environment { @Autowired('eGridDiv') private eGridDiv: HTMLElement; public getTheme(): string { let themeMatch:RegExpMatchArray; let element:HTMLElement = this.eGridDiv; while (element != document.documentElement && themeMatch == null) { themeMatch = element.className.match(themeCLass); element = element.parentElement; } if (themeMatch) { return themeMatch[0]; } else { return 'ag-fresh'; } } }
import {PreDestroy, Bean, Qualifier, Autowired, PostConstruct, Optional, Context} from "./context/context"; const themes = [ 'fresh', 'dark', 'blue', 'bootstrap', 'material', 'theme-material']; const themeCLass = new RegExp(`ag-(${themes.join('|')})`); @Bean('environment') export class Environment { @Autowired('eGridDiv') private eGridDiv: HTMLElement; public getTheme(): string { let themeMatch:RegExpMatchArray; let element:HTMLElement = this.eGridDiv; while (element != document.documentElement && themeMatch == null) { themeMatch = element.className.match(themeCLass); element = element.parentElement; if (element == null) { break; } } if (themeMatch) { return themeMatch[0]; } else { return 'ag-fresh'; } } }
Handle the case of getting theme when detached
Handle the case of getting theme when detached
TypeScript
mit
seanlandsman/ag-grid,ceolter/angular-grid,ceolter/angular-grid,killyosaur/ag-grid,ceolter/ag-grid,seanlandsman/ag-grid,ceolter/ag-grid,seanlandsman/ag-grid,killyosaur/ag-grid,killyosaur/ag-grid
--- +++ @@ -14,6 +14,9 @@ while (element != document.documentElement && themeMatch == null) { themeMatch = element.className.match(themeCLass); element = element.parentElement; + if (element == null) { + break; + } } if (themeMatch) {
c5446891631c96de20b4f4736de6d9a3d4ae08d6
packages/lesswrong/lib/collections/subscriptions/mutations.ts
packages/lesswrong/lib/collections/subscriptions/mutations.ts
import { Subscriptions } from './collection'; import { subscriptionTypes } from './schema' import { runCallbacksAsync, Utils } from '../../vulcan-lib'; import Users from '../users/collection'; export const defaultSubscriptionTypeTable = { "Comments": subscriptionTypes.newReplies, "Posts": subscriptionTypes.newComments, "Users": subscriptionTypes.newPosts, "Localgroups": subscriptionTypes.newEvents, } /** * @summary Perform the un/subscription after verification: update the collection item & the user * @param {String} action * @param {Collection} collection * @param {String} itemId * @param {Object} user: current user (xxx: legacy, to replace with this.userId) * @returns {Boolean} */ export const performSubscriptionAction = async (action, collection, itemId, user) => { const collectionName = collection.options.collectionName const newSubscription = { state: action === "subscribe" ? 'subscribed' : 'supressed', documentId: itemId, collectionName, type: defaultSubscriptionTypeTable[collectionName] } await Utils.newMutator({ collection: Subscriptions, document: newSubscription, validate: true, currentUser: user, context: { currentUser: user, Users: Users, }, }) if (action === 'subscribe') { await runCallbacksAsync('users.subscribe.async', action, collection, itemId, user); } else { await runCallbacksAsync('users.unsubscribe.async', action, collection, itemId, user); } };
import { Subscriptions } from './collection'; import { subscriptionTypes } from './schema' import { runCallbacksAsync, Utils } from '../../vulcan-lib'; import Users from '../users/collection'; export const defaultSubscriptionTypeTable = { "Comments": subscriptionTypes.newReplies, "Posts": subscriptionTypes.newComments, "Users": subscriptionTypes.newPosts, "Localgroups": subscriptionTypes.newEvents, } /** * @summary Perform the un/subscription after verification: update the collection item & the user * @param {String} action * @param {Collection} collection * @param {String} itemId * @param {Object} user: current user (xxx: legacy, to replace with this.userId) * @returns {Boolean} */ export const performSubscriptionAction = async (action, collection, itemId, user) => { const collectionName = collection.options.collectionName const newSubscription = { state: action === "subscribe" ? 'subscribed' : 'supressed', documentId: itemId, collectionName, type: defaultSubscriptionTypeTable[collectionName] } await Utils.createMutator({ collection: Subscriptions, document: newSubscription, validate: true, currentUser: user, context: { currentUser: user, Users: Users, }, }) if (action === 'subscribe') { await runCallbacksAsync('users.subscribe.async', action, collection, itemId, user); } else { await runCallbacksAsync('users.unsubscribe.async', action, collection, itemId, user); } };
Fix a crash introduced by Vulcan unpackaging, revealed by unit test
Fix a crash introduced by Vulcan unpackaging, revealed by unit test
TypeScript
mit
Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope
--- +++ @@ -26,7 +26,7 @@ collectionName, type: defaultSubscriptionTypeTable[collectionName] } - await Utils.newMutator({ + await Utils.createMutator({ collection: Subscriptions, document: newSubscription, validate: true,
30483114fc36b48c90a7ab6af711b83abc9aebf6
src/homebridge.ts
src/homebridge.ts
import 'hap-nodejs'; export interface Homebridge { hap: HAPNodeJS.HAPNodeJS; log: Homebridge.Log; registerAccessory(pluginName: string, accessoryName: string, constructor: Function) } export namespace Homebridge { export interface Log { debug: (...message: string[]) => void info: (...message: string[]) => void warn: (...message: string[]) => void error: (...message: string[]) => void } } export default Homebridge;
import 'hap-nodejs'; export interface Homebridge { hap: HAPNodeJS.HAPNodeJS; log: Homebridge.Log; registerAccessory(pluginName: string, accessoryName: string, constructor: Function): void } export namespace Homebridge { export interface Log { debug: (...message: string[]) => void info: (...message: string[]) => void warn: (...message: string[]) => void error: (...message: string[]) => void } } export default Homebridge;
Add missing return type for registerAccessory
Add missing return type for registerAccessory
TypeScript
mit
JosephDuffy/homebridge-pc-volume,JosephDuffy/homebridge-pc-volume,JosephDuffy/homebridge-pc-volume
--- +++ @@ -3,7 +3,7 @@ export interface Homebridge { hap: HAPNodeJS.HAPNodeJS; log: Homebridge.Log; - registerAccessory(pluginName: string, accessoryName: string, constructor: Function) + registerAccessory(pluginName: string, accessoryName: string, constructor: Function): void } export namespace Homebridge {
ecbb0fd37a2d7fd7e8f69fa91790a61d8bf7accd
packages/components/containers/app/TopBanner.tsx
packages/components/containers/app/TopBanner.tsx
import React from 'react'; import { Icon, classnames } from '../../index'; interface Props { children: React.ReactNode; className?: string; onClose?: () => void; } const TopBanner = ({ children, className, onClose }: Props) => { return ( <div className={classnames(['aligncenter p0-5 relative', className])}> {children} {onClose ? ( <button type="button" className="right" onClick={onClose}> <Icon name="off" /> </button> ) : null} </div> ); }; export default TopBanner;
import React from 'react'; import { Icon, classnames } from '../../index'; interface Props { children: React.ReactNode; className?: string; onClose?: () => void; } const TopBanner = ({ children, className, onClose }: Props) => { return ( <div className={classnames(['aligncenter p0-5 relative bold', className])}> {children} {onClose ? ( <button type="button" className="right" onClick={onClose}> <Icon name="off" /> </button> ) : null} </div> ); }; export default TopBanner;
Use bold font in top banners
[MAILWEB-930] Use bold font in top banners
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -10,7 +10,7 @@ const TopBanner = ({ children, className, onClose }: Props) => { return ( - <div className={classnames(['aligncenter p0-5 relative', className])}> + <div className={classnames(['aligncenter p0-5 relative bold', className])}> {children} {onClose ? ( <button type="button" className="right" onClick={onClose}>
9cacd0735f7bca85c1735a8e468c759d23c3e976
src/SyntaxNodes/OrderedListNode.ts
src/SyntaxNodes/OrderedListNode.ts
import { OutlineSyntaxNode } from './OutlineSyntaxNode' export class OrderedListNode implements OutlineSyntaxNode { constructor(public items: OrderedListNode.Item[]) { } start(): number { return this.items[0].ordinal } order(): OrderedListNode.Order { const withExplicitOrdinals = this.items.filter(item => item.ordinal != null) if (withExplicitOrdinals.length < 2) { return OrderedListNode.Order.Ascending } return ( withExplicitOrdinals[0].ordinal > withExplicitOrdinals[1].ordinal ? OrderedListNode.Order.Descrending : OrderedListNode.Order.Ascending ) } OUTLINE_SYNTAX_NODE(): void { } } export module OrderedListNode { export class Item { // During parsing, `ordinal` can be either `null` or a number. Defaulting `ordinal` to `null` // rather than `undefined` allows our unit tests to be cleaner. constructor(public children: OutlineSyntaxNode[], public ordinal: number = null) { } protected ORDERED_LIST_ITEM(): void { } } export enum Order { Ascending = 1, Descrending } }
import { OutlineSyntaxNode } from './OutlineSyntaxNode' import { OutlineSyntaxNodeContainer } from './OutlineSyntaxNodeContainer' export class OrderedListNode implements OutlineSyntaxNode { constructor(public items: OrderedListNode.Item[]) { } start(): number { return this.items[0].ordinal } order(): OrderedListNode.Order { const withExplicitOrdinals = this.items.filter(item => item.ordinal != null) if (withExplicitOrdinals.length < 2) { return OrderedListNode.Order.Ascending } return ( withExplicitOrdinals[0].ordinal > withExplicitOrdinals[1].ordinal ? OrderedListNode.Order.Descrending : OrderedListNode.Order.Ascending ) } OUTLINE_SYNTAX_NODE(): void { } } export module OrderedListNode { export class Item extends OutlineSyntaxNodeContainer { // During parsing, `ordinal` can be either `null` or a number. Defaulting `ordinal` to `null` // rather than `undefined` allows our unit tests to be cleaner. constructor(public children: OutlineSyntaxNode[], public ordinal: number = null) { super(children) } protected ORDERED_LIST_ITEM(): void { } } export enum Order { Ascending = 1, Descrending } }
Make ordered list item extend outline container
Make ordered list item extend outline container
TypeScript
mit
start/up,start/up
--- +++ @@ -1,4 +1,5 @@ import { OutlineSyntaxNode } from './OutlineSyntaxNode' +import { OutlineSyntaxNodeContainer } from './OutlineSyntaxNodeContainer' export class OrderedListNode implements OutlineSyntaxNode { @@ -28,10 +29,12 @@ export module OrderedListNode { - export class Item { + export class Item extends OutlineSyntaxNodeContainer { // During parsing, `ordinal` can be either `null` or a number. Defaulting `ordinal` to `null` // rather than `undefined` allows our unit tests to be cleaner. - constructor(public children: OutlineSyntaxNode[], public ordinal: number = null) { } + constructor(public children: OutlineSyntaxNode[], public ordinal: number = null) { + super(children) + } protected ORDERED_LIST_ITEM(): void { } }
1d8e036bcbf779faaf4e70c30cefbe0805a7b7eb
public/app/core/components/Page/PageContents.tsx
public/app/core/components/Page/PageContents.tsx
// Libraries import React, { Component } from 'react'; // Components import CustomScrollbar from '../CustomScrollbar/CustomScrollbar'; import PageLoader from '../PageLoader/PageLoader'; interface Props { isLoading?: boolean; children: JSX.Element[] | JSX.Element; } class PageContents extends Component<Props> { render() { const { isLoading } = this.props; return ( <div className="page-container page-body"> <CustomScrollbar> {isLoading && <PageLoader />} {this.props.children} </CustomScrollbar> </div> ); } } export default PageContents;
// Libraries import React, { Component } from 'react'; // Components import { CustomScrollbar } from '@grafana/ui'; import PageLoader from '../PageLoader/PageLoader'; interface Props { isLoading?: boolean; children: JSX.Element[] | JSX.Element; } class PageContents extends Component<Props> { render() { const { isLoading } = this.props; return ( <div className="page-container page-body"> <CustomScrollbar> {isLoading && <PageLoader />} {this.props.children} </CustomScrollbar> </div> ); } } export default PageContents;
Fix import path after Scrollbar move to @grafana/ui
fix: Fix import path after Scrollbar move to @grafana/ui
TypeScript
agpl-3.0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
--- +++ @@ -2,7 +2,7 @@ import React, { Component } from 'react'; // Components -import CustomScrollbar from '../CustomScrollbar/CustomScrollbar'; +import { CustomScrollbar } from '@grafana/ui'; import PageLoader from '../PageLoader/PageLoader'; interface Props {
7cefb91669306fe4fa6f59d8971a1cf19bf5b893
src/index.ts
src/index.ts
import * as app from 'app'; import * as BrowserWindow from 'browser-window'; import * as Menu from 'menu'; import * as platform from './models/platform'; if (!platform.isOSX) { app.on('window-all-closed', () => app.quit()); } app.on('ready', () => { let mainWindow = new BrowserWindow({ width: 800, height: 600, title: 'Disskey', frame: false, show: false, icon: './built/images/icon.png' }); mainWindow.on('closed', () => { mainWindow = null; }); Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: 'View', submenu: [{ label: 'Reload', accelerator: 'Ctrl+R', click: () => mainWindow.reload() }, { label: 'Toggle &Developer Tools', accelerator: 'Ctrl+Shift+I', click: () => mainWindow.toggleDevTools() }] }])); mainWindow.loadUrl(`file://${__dirname}/main/main.html`); });
import * as app from 'app'; import * as BrowserWindow from 'browser-window'; import * as Menu from 'menu'; import * as platform from './models/platform'; if (!platform.isOSX) { app.on('window-all-closed', () => app.quit()); } app.on('ready', () => { let mainWindow = new BrowserWindow({ width: 800, height: 600, 'min-width': 200, 'min-height': 200, title: 'Disskey', frame: false, show: false, icon: './built/images/icon.png' }); mainWindow.on('closed', () => { mainWindow = null; }); Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: 'View', submenu: [{ label: 'Reload', accelerator: 'Ctrl+R', click: () => mainWindow.reload() }, { label: 'Toggle &Developer Tools', accelerator: 'Ctrl+Shift+I', click: () => mainWindow.toggleDevTools() }] }])); mainWindow.loadUrl(`file://${__dirname}/main/main.html`); });
Set minumum width and height for window
Set minumum width and height for window
TypeScript
mit
AyaMorisawa/Disskey,AyaMorisawa/Disskey,AyaMorisawa/Disskey
--- +++ @@ -11,6 +11,8 @@ let mainWindow = new BrowserWindow({ width: 800, height: 600, + 'min-width': 200, + 'min-height': 200, title: 'Disskey', frame: false, show: false,
019fa89f70b824d44b561181cedd8a3cdaf3e25b
src/utils.ts
src/utils.ts
"use strict"; import * as path from "path"; import * as fs from "fs"; import { workspace } from "vscode"; export const dartVMPath = "bin/dart.exe"; export const analyzerPath = "bin/snapshots/analysis_server.dart.snapshot"; const configExtensionName = "dart"; const configSdkPathName = "sdkPath"; const configSetIndentName = "setIndentSettings"; let config = workspace.getConfiguration(configExtensionName); export function findDartSdk(): string { let paths = (<string>process.env.PATH).split(";"); // We don't expect the user to add .\bin in config, but it would be in the PATHs if (config.has(configSdkPathName)) paths.unshift(path.join(config.get<string>(configSdkPathName), 'bin')); let sdkPath = paths.find(isValidDartSdk); if (sdkPath) return path.join(sdkPath, ".."); // Take .\bin back off. return null; } function isValidDartSdk(pathToTest: string): boolean { // Apparently this is the "correct" way to check files exist synchronously in Node :'( try { fs.accessSync(path.join(pathToTest, "..", analyzerPath), fs.R_OK); return true; // If no error, we found a match! } catch (e) { } return false; // Didn't find it, so must be an invalid path. }
"use strict"; import * as path from "path"; import * as fs from "fs"; import { workspace } from "vscode"; export const dartVMPath = "bin/dart"; export const analyzerPath = "bin/snapshots/analysis_server.dart.snapshot"; const configExtensionName = "dart"; const configSdkPathName = "sdkPath"; const configSetIndentName = "setIndentSettings"; let config = workspace.getConfiguration(configExtensionName); export function findDartSdk(): string { let paths = (<string>process.env.PATH).split(";"); // We don't expect the user to add .\bin in config, but it would be in the PATHs if (config.has(configSdkPathName)) paths.unshift(path.join(config.get<string>(configSdkPathName), 'bin')); let sdkPath = paths.find(isValidDartSdk); if (sdkPath) return path.join(sdkPath, ".."); // Take .\bin back off. return null; } function isValidDartSdk(pathToTest: string): boolean { // Apparently this is the "correct" way to check files exist synchronously in Node :'( try { fs.accessSync(path.join(pathToTest, "..", analyzerPath), fs.R_OK); return true; // If no error, we found a match! } catch (e) { } return false; // Didn't find it, so must be an invalid path. }
Remove .exe extension from Dart so it's not Windows-sepcific.
Remove .exe extension from Dart so it's not Windows-sepcific.
TypeScript
mit
Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code
--- +++ @@ -4,7 +4,7 @@ import * as fs from "fs"; import { workspace } from "vscode"; -export const dartVMPath = "bin/dart.exe"; +export const dartVMPath = "bin/dart"; export const analyzerPath = "bin/snapshots/analysis_server.dart.snapshot"; const configExtensionName = "dart"; const configSdkPathName = "sdkPath";
1845cfe1f1f9abe81c993e936b51628956854f58
patcher/src/widgets/Controller/components/PatcherError/index.tsx
patcher/src/widgets/Controller/components/PatcherError/index.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'; import { PatcherError } from '../../../../services/patcher'; const Alert = styled('div')` overflow: hidden; background-color: orange; color: black; padding: 3px 15px; position: relative; pointer-events: bounding-box; cursor: pointer; ::after { content: 'X'; position: absolute; right: 0; height: 100%; width: 30px; pointer-events: none; } `; export interface PatcherErrorProps { errors: PatcherError[]; onClear?: any; } /* tslint:disable:function-name */ function PatcherError(props: PatcherErrorProps) { if (props.errors.length === 0) return null; return <Alert onClick={props.onClear}> { props.errors.length > 1 ? `(1/${props.errors.length}) ` : '' } { props.errors[0].message } </Alert>; } export default PatcherError;
/** * 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'; import { PatcherError } from '../../../../services/patcher'; const Alert = styled('div')` overflow: hidden; background: repeating-linear-gradient(45deg, darkorange, orange 2px, orange 1px, darkorange 4px); color: black; padding: 3px 15px; position: relative; pointer-events: all; cursor: pointer; ::after { content: 'X'; position: absolute; right: 0; height: 100%; width: 30px; pointer-events: none; } `; export interface PatcherErrorProps { errors: PatcherError[]; onClear?: () => void; } /* tslint:disable:function-name */ function PatcherError(props: PatcherErrorProps) { if (props.errors.length === 0) return null; return <Alert onClick={props.onClear}> { props.errors.length > 1 ? `(1/${props.errors.length}) ` : '' } { props.errors[0].message } </Alert>; } export default PatcherError;
Fix review issues, also fix gradient
Fix review issues, also fix gradient
TypeScript
mpl-2.0
saddieeiddas/Camelot-Unchained,csegames/Camelot-Unchained,CUModSquad/Camelot-Unchained,saddieeiddas/Camelot-Unchained,Mehuge/Camelot-Unchained,Mehuge/Camelot-Unchained,Ajackster/Camelot-Unchained,csegames/Camelot-Unchained,Ajackster/Camelot-Unchained,saddieeiddas/Camelot-Unchained,CUModSquad/Camelot-Unchained,CUModSquad/Camelot-Unchained,Mehuge/Camelot-Unchained,Ajackster/Camelot-Unchained,csegames/Camelot-Unchained
--- +++ @@ -10,11 +10,11 @@ const Alert = styled('div')` overflow: hidden; - background-color: orange; + background: repeating-linear-gradient(45deg, darkorange, orange 2px, orange 1px, darkorange 4px); color: black; padding: 3px 15px; position: relative; - pointer-events: bounding-box; + pointer-events: all; cursor: pointer; ::after { content: 'X'; @@ -28,7 +28,7 @@ export interface PatcherErrorProps { errors: PatcherError[]; - onClear?: any; + onClear?: () => void; } /* tslint:disable:function-name */
d7a5a35376fba4831e3177e93bc941fd1c1e99a8
packages/data-mate/src/vector/interfaces.ts
packages/data-mate/src/vector/interfaces.ts
import { Maybe } from '@terascope/types'; /** * The Vector Type, this will change how the data is stored and read */ export enum VectorType { /** * Currently this operates like String * but I imagine will be expanding it. * But will need to add format options */ Date = 'Date', String = 'String', Int = 'Int', Float = 'Float', BigInt = 'BigInt', Boolean = 'Boolean', GeoPoint = 'GeoPoint', GeoJSON = 'GeoJSON', /** @todo */ Object = 'Object', /** * Arbitrary data can be stored with this */ Any = 'Any', /** * The list type is used for fields marked as Arrays * where each item in the Vector is a child element */ List = 'List', } /** * A data type agnostic in-memory representation of the data * for a Vector and potential indices. * This should be generated by the builder. */ export type Data<T> = Readonly<{ readonly values: readonly Maybe<T>[]; }>;
import { Maybe } from '@terascope/types'; /** * The Vector Type, this will change how the data is stored and read * * @todo add IP and IP_RANGE support */ export enum VectorType { /** * Currently this operates like String * but I imagine will be expanding it. * But will need to add format options */ Date = 'Date', String = 'String', Int = 'Int', Float = 'Float', BigInt = 'BigInt', Boolean = 'Boolean', GeoPoint = 'GeoPoint', GeoJSON = 'GeoJSON', IP = 'IP', IP_RANGE = 'IP_RANGE', Object = 'Object', /** * Arbitrary data can be stored with this. Not recommended for use. */ Any = 'Any', /** * The list type is used for fields marked as Arrays * where each item in the Vector is a child element */ List = 'List', } /** * A data type agnostic in-memory representation of the data * for a Vector and potential indices. * This should be generated by the builder. */ export type Data<T> = Readonly<{ readonly values: readonly Maybe<T>[]; }>;
Add todo for IP and IP_RANGE vectors
Add todo for IP and IP_RANGE vectors
TypeScript
apache-2.0
terascope/teraslice,terascope/teraslice,terascope/teraslice,terascope/teraslice
--- +++ @@ -2,6 +2,8 @@ /** * The Vector Type, this will change how the data is stored and read + * + * @todo add IP and IP_RANGE support */ export enum VectorType { /** @@ -17,10 +19,11 @@ Boolean = 'Boolean', GeoPoint = 'GeoPoint', GeoJSON = 'GeoJSON', - /** @todo */ + IP = 'IP', + IP_RANGE = 'IP_RANGE', Object = 'Object', /** - * Arbitrary data can be stored with this + * Arbitrary data can be stored with this. Not recommended for use. */ Any = 'Any', /**