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 |
|---|---|---|---|---|---|---|---|---|---|---|
aa3feeb438edc2390157f55340bf159ff5c67670 | src/elmFormat.ts | src/elmFormat.ts | import * as vscode from 'vscode'
import { Range, TextEdit } from 'vscode'
import { execCmd } from './elmUtils'
export class ElmFormatProvider implements vscode.DocumentFormattingEditProvider {
provideDocumentFormattingEdits(
document: vscode.TextDocument,
options: vscode.FormattingOptions,
token: vscode.CancellationToken)
: Thenable<TextEdit[]>
{
const format = execCmd('elm-format --stdin');
format.stdin.write(document.getText());
format.stdin.end();
return format
.then(({ stdout }) => {
const wholeDocument = new Range(0, 0, Number.MAX_VALUE, Number.MAX_VALUE);
return [TextEdit.replace(wholeDocument, stdout)];
})
.catch((err) => {
const message = (<string>err.message).includes('SYNTAX PROBLEM')
? "Running elm-format failed. Check the file for syntax errors."
: "Running elm-format failed. Install from "
+ "https://github.com/avh4/elm-format and make sure it's on your path";
return vscode.window.showErrorMessage(message).then(() => [])
})
}
} | import * as vscode from 'vscode'
import { Range, TextEdit } from 'vscode'
import { execCmd } from './elmUtils'
export class ElmFormatProvider implements vscode.DocumentFormattingEditProvider {
provideDocumentFormattingEdits(
document: vscode.TextDocument,
options: vscode.FormattingOptions,
token: vscode.CancellationToken)
: Thenable<TextEdit[]>
{
const format = execCmd('elm-format --stdin');
format.stdin.write(document.getText());
format.stdin.end();
return format
.then(({ stdout }) => {
const wholeDocument = new Range(0, 0, document.lineCount, document.getText().length);
return [TextEdit.replace(wholeDocument, stdout)];
})
.catch((err) => {
const message = (<string>err.message).includes('SYNTAX PROBLEM')
? "Running elm-format failed. Check the file for syntax errors."
: "Running elm-format failed. Install from "
+ "https://github.com/avh4/elm-format and make sure it's on your path";
return vscode.window.showErrorMessage(message).then(() => [])
})
}
} | Fix issue with duplicate content after elm-format on v1.1.0 | Fix issue with duplicate content after elm-format on v1.1.0
| TypeScript | mit | Krzysztof-Cieslak/vscode-elm,sbrink/vscode-elm | ---
+++
@@ -18,7 +18,7 @@
return format
.then(({ stdout }) => {
- const wholeDocument = new Range(0, 0, Number.MAX_VALUE, Number.MAX_VALUE);
+ const wholeDocument = new Range(0, 0, document.lineCount, document.getText().length);
return [TextEdit.replace(wholeDocument, stdout)];
})
.catch((err) => { |
8a04609bdfda87de3b2c363abfe5ce405535e555 | test/unit/core/datastore/cached/get-sorted-ids.spec.ts | test/unit/core/datastore/cached/get-sorted-ids.spec.ts | import {getSortedIds} from '../../../../../app/core/datastore/cached/get-sorted-ids';
/**
* @author Daniel de Oliveira
*/
describe('getSortedIds', () => {
it('base', () => {
const as = [{ id: 'a', identifier: '1.a' }, { id: 'b', identifier: '1' }];
const result = getSortedIds(as as any, { q: '1',
sort: 'default' // <- TODO why would we need exactMatchFirst? alnumCompare seems to do the trick here, right?
});
expect(result).toEqual(['b', 'a'])
});
});
| import {getSortedIds} from '../../../../../app/core/datastore/cached/get-sorted-ids';
/**
* @author Daniel de Oliveira
*/
describe('getSortedIds', () => {
it('exactMatchFirst', () => {
const as = [
{ id: 'a', identifier: 'AB-C1' },
{ id: 'b', identifier: 'AB-C2' },
{ id: 'c', identifier: 'C2' }
];
const result1 = getSortedIds(as as any, { q: 'C2',
sort: 'default'
});
expect(result1).toEqual(['a', 'b', 'c']);
const result2 = getSortedIds(as as any, { q: 'C2',
sort: 'exactMatchFirst'
});
expect(result2).toEqual(['c', 'a', 'b']);
});
});
| Adjust test for intended use case | Adjust test for intended use case
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -5,13 +5,22 @@
*/
describe('getSortedIds', () => {
- it('base', () => {
+ it('exactMatchFirst', () => {
- const as = [{ id: 'a', identifier: '1.a' }, { id: 'b', identifier: '1' }];
+ const as = [
+ { id: 'a', identifier: 'AB-C1' },
+ { id: 'b', identifier: 'AB-C2' },
+ { id: 'c', identifier: 'C2' }
+ ];
- const result = getSortedIds(as as any, { q: '1',
- sort: 'default' // <- TODO why would we need exactMatchFirst? alnumCompare seems to do the trick here, right?
+ const result1 = getSortedIds(as as any, { q: 'C2',
+ sort: 'default'
});
- expect(result).toEqual(['b', 'a'])
+ expect(result1).toEqual(['a', 'b', 'c']);
+
+ const result2 = getSortedIds(as as any, { q: 'C2',
+ sort: 'exactMatchFirst'
+ });
+ expect(result2).toEqual(['c', 'a', 'b']);
});
}); |
e7577d7a0f6c1c91fdccc89745cf4ef484349fa3 | src/app/overview-page/store/studies/studies.reducer.ts | src/app/overview-page/store/studies/studies.reducer.ts | import { EntityAdapter, EntityState, createEntityAdapter } from '@ngrx/entity'
import { Study } from '../../../shared/models/study.model'
import * as actions from './studies.actions'
export interface State extends EntityState<Study> {
isLoaded: boolean
}
export const adapter: EntityAdapter<Study> = createEntityAdapter<Study>()
export const initialState: State = adapter.getInitialState({
isLoaded: false
})
export function reducer(state = initialState, action: actions.Actions): State {
switch (action.type) {
case actions.LOAD: {
return { ...state, isLoaded: false }
}
case actions.LOAD_SUCCESS: {
return { ...adapter.addAll(action.payload, state), isLoaded: true }
}
case actions.LOAD_FAIL: {
return { ...initialState }
}
default:
return state
}
}
export const getIsLoaded = (state: State) => state.isLoaded
| import { EntityAdapter, EntityState, createEntityAdapter } from '@ngrx/entity'
import { Study } from '../../../shared/models/study.model'
import * as actions from './studies.actions'
export interface State extends EntityState<Study> {
isLoaded: boolean
}
export const adapter: EntityAdapter<Study> = createEntityAdapter<Study>({
selectId: (study: Study) => study.projectName
})
export const initialState: State = adapter.getInitialState({
isLoaded: false
})
export function reducer(state = initialState, action: actions.Actions): State {
switch (action.type) {
case actions.LOAD: {
return { ...state, isLoaded: false }
}
case actions.LOAD_SUCCESS: {
return { ...adapter.addAll(action.payload, state), isLoaded: true }
}
case actions.LOAD_FAIL: {
return { ...initialState }
}
default:
return state
}
}
export const getIsLoaded = (state: State) => state.isLoaded
| Change entity id to projectName | Change entity id to projectName
| TypeScript | apache-2.0 | RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard,RADAR-CNS/RADAR-Dashboard | ---
+++
@@ -7,7 +7,9 @@
isLoaded: boolean
}
-export const adapter: EntityAdapter<Study> = createEntityAdapter<Study>()
+export const adapter: EntityAdapter<Study> = createEntityAdapter<Study>({
+ selectId: (study: Study) => study.projectName
+})
export const initialState: State = adapter.getInitialState({
isLoaded: false |
63de6c3f5164a16e60064400899b1079afb852ba | jovo-platforms/jovo-platform-lindenbaum/src/index.ts | jovo-platforms/jovo-platform-lindenbaum/src/index.ts | import { TestSuite } from 'jovo-core';
import { LindenbaumBot } from './core/LindenbaumBot';
import { LindenbaumRequestBuilder } from './core/LindenbaumRequestBuilder';
import { LindenbaumResponseBuilder } from './core/LindenbaumResponseBuilder';
export interface LindenbaumTestSuite
extends TestSuite<LindenbaumRequestBuilder, LindenbaumResponseBuilder> {}
declare module 'jovo-core/dist/src/core/Jovo' {
interface Jovo {
$lindenbaumBot?: LindenbaumBot;
lindenbaumBot(): LindenbaumBot;
}
}
declare module 'jovo-core/dist/src/Interfaces' {
export interface Output {
// tslint:disable-next-line:no-any
Lindenbaum: any[];
}
}
export * from './Lindenbaum';
export * from './ExpressJsMiddleware';
export * from './core/LindenbaumBot';
export * from './core/LindenbaumRequest';
export * from './core/LindenbaumResponse';
export * from './core/LindenbaumSpeechBuilder';
export * from './core/LindenbaumUser';
| import { TestSuite } from 'jovo-core';
import { LindenbaumBot } from './core/LindenbaumBot';
import { LindenbaumRequestBuilder } from './core/LindenbaumRequestBuilder';
import { LindenbaumResponseBuilder } from './core/LindenbaumResponseBuilder';
export interface LindenbaumTestSuite
extends TestSuite<LindenbaumRequestBuilder, LindenbaumResponseBuilder> {}
declare module 'jovo-core/dist/src/core/Jovo' {
interface Jovo {
$lindenbaumBot?: LindenbaumBot;
lindenbaumBot(): LindenbaumBot;
}
}
declare module 'jovo-core/dist/src/Interfaces' {
export interface Output {
Lindenbaum: any[]; // tslint:disable-line:no-any
}
}
export * from './Lindenbaum';
export * from './ExpressJsMiddleware';
export * from './core/LindenbaumBot';
export * from './core/LindenbaumRequest';
export * from './core/LindenbaumResponse';
export * from './core/LindenbaumSpeechBuilder';
export * from './core/LindenbaumUser';
| Add change to trigger version bump | :recycle: Add change to trigger version bump
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -16,8 +16,7 @@
declare module 'jovo-core/dist/src/Interfaces' {
export interface Output {
- // tslint:disable-next-line:no-any
- Lindenbaum: any[];
+ Lindenbaum: any[]; // tslint:disable-line:no-any
}
}
|
af55e9851843c7b31b456f58471f8c9e546a9a5c | src/name-input-list/item.tsx | src/name-input-list/item.tsx | import * as React from 'react'
import flowRight from 'lodash-es/flowRight'
import {translate} from 'react-i18next'
import {SortableElement} from 'react-sortable-hoc'
import IconButton from '@material-ui/core/IconButton'
import TextField from '@material-ui/core/TextField'
import Tooltip from '@material-ui/core/Tooltip'
import ActionDelete from '@material-ui/icons/Delete'
import {DragHandle} from './drag-handle'
import {ITranslateMixin} from '../types'
import classes from './name-input-list.pcss'
interface ISortableItemProps extends ITranslateMixin {
value: string,
error: string | null
onChange: React.EventHandler<React.KeyboardEvent<{}>>,
remove(): void,
}
export function SortableItemImpl({value, onChange, remove, error, t}: ISortableItemProps) {
return (
<div className={classes.itemContainer}>
<DragHandle />
<TextField type="text" fullWidth label={t('Player name')}
margin="normal"
value={value} error={error != null} helperText={error}
onChange={(event: any) => onChange(event.target.value)} />
<Tooltip title={t('Delete name')}>
<IconButton onClick={remove}><ActionDelete width="24px" height="24px" /></IconButton>
</Tooltip>
</div>
)
}
export const SortableItem = flowRight(
SortableElement,
translate()
)(SortableItemImpl) as React.ComponentType<any>
| import * as React from 'react'
import flowRight from 'lodash-es/flowRight'
import {translate} from 'react-i18next'
import {SortableElement} from 'react-sortable-hoc'
import IconButton from '@material-ui/core/IconButton'
import TextField from '@material-ui/core/TextField'
import Tooltip from '@material-ui/core/Tooltip'
import ActionDelete from '@material-ui/icons/Delete'
import {DragHandle} from './drag-handle'
import {ITranslateMixin} from '../types'
import classes from './name-input-list.pcss'
interface ISortableItemProps extends ITranslateMixin {
value: string,
error: string | null
onChange: React.EventHandler<React.KeyboardEvent<{}>>,
remove(): void,
}
export function SortableItemImpl({value, onChange, remove, error, t}: ISortableItemProps) {
return (
<div className={classes.itemContainer}>
<DragHandle />
<TextField type="text" fullWidth label={t('Player name')}
margin="normal"
value={value} error={error != null && error !== ''} helperText={error}
onChange={(event: any) => onChange(event.target.value)} />
<Tooltip title={t('Delete name')}>
<IconButton onClick={remove}><ActionDelete width="24px" height="24px" /></IconButton>
</Tooltip>
</div>
)
}
export const SortableItem = flowRight(
SortableElement,
translate()
)(SortableItemImpl) as React.ComponentType<any>
| Fix incorrect error highlight in player name input list | Fix incorrect error highlight in player name input list
| TypeScript | mit | Holi0317/bridge-calc,Holi0317/bridge-calc,Holi0317/bridge-calc | ---
+++
@@ -23,7 +23,7 @@
<DragHandle />
<TextField type="text" fullWidth label={t('Player name')}
margin="normal"
- value={value} error={error != null} helperText={error}
+ value={value} error={error != null && error !== ''} helperText={error}
onChange={(event: any) => onChange(event.target.value)} />
<Tooltip title={t('Delete name')}>
<IconButton onClick={remove}><ActionDelete width="24px" height="24px" /></IconButton> |
fd112336e4018a329fd31d9b048d4894d1cd2b6a | src/app.tsx | src/app.tsx | import 'core-js/features/array';
import 'core-js/features/promise';
import React from 'react';
import ReactDOM from 'react-dom';
import Me from './Me';
const rootEl = document.getElementById('app');
ReactDOM.render(
<Me />,
rootEl,
);
| import 'core-js/features/array';
import 'core-js/features/object';
import 'core-js/features/promise';
import React from 'react';
import ReactDOM from 'react-dom';
import Me from './Me';
const rootEl = document.getElementById('app');
ReactDOM.render(
<Me />,
rootEl,
);
| Add object polyfill for IE11 | Add object polyfill for IE11
| TypeScript | mit | durasj/website,durasj/website,durasj/website | ---
+++
@@ -1,4 +1,5 @@
import 'core-js/features/array';
+import 'core-js/features/object';
import 'core-js/features/promise';
import React from 'react'; |
c12099fd8b5c53afae4ef43caa51a8f938ecace7 | src/ts/components/audiotrackselectbox.ts | src/ts/components/audiotrackselectbox.ts | import {SelectBox} from './selectbox';
import {ListSelectorConfig} from './listselector';
import {UIInstanceManager} from '../uimanager';
/**
* A select box providing a selection between available audio tracks (e.g. different languages).
*/
export class AudioTrackSelectBox extends SelectBox {
constructor(config: ListSelectorConfig = {}) {
super(config);
}
configure(player: bitmovin.player.Player, uimanager: UIInstanceManager): void {
super.configure(player, uimanager);
let updateAudioTracks = () => {
let audioTracks = player.getAvailableAudio();
this.clearItems();
// Add audio tracks
for (let audioTrack of audioTracks) {
this.addItem(audioTrack.id, audioTrack.label);
}
};
this.onItemSelected.subscribe((sender: AudioTrackSelectBox, value: string) => {
player.setAudio(value);
});
let audioTrackHandler = () => {
let currentAudioTrack = player.getAudio();
this.selectItem(currentAudioTrack.id);
};
// Update selection when selected track has changed
player.addEventHandler(player.EVENT.ON_AUDIO_CHANGED, audioTrackHandler);
// Update tracks when source goes away
player.addEventHandler(player.EVENT.ON_SOURCE_UNLOADED, updateAudioTracks);
// Update tracks when a new source is loaded
player.addEventHandler(player.EVENT.ON_READY, updateAudioTracks);
// Populate tracks at startup
updateAudioTracks();
}
} | import {SelectBox} from './selectbox';
import {ListSelectorConfig} from './listselector';
import {UIInstanceManager} from '../uimanager';
/**
* A select box providing a selection between available audio tracks (e.g. different languages).
*/
export class AudioTrackSelectBox extends SelectBox {
constructor(config: ListSelectorConfig = {}) {
super(config);
}
configure(player: bitmovin.player.Player, uimanager: UIInstanceManager): void {
super.configure(player, uimanager);
let updateAudioTracks = () => {
let audioTracks = player.getAvailableAudio();
this.clearItems();
// Add audio tracks
for (let audioTrack of audioTracks) {
this.addItem(audioTrack.id, audioTrack.label);
}
};
this.onItemSelected.subscribe((sender: AudioTrackSelectBox, value: string) => {
player.setAudio(value);
});
let audioTrackHandler = () => {
let currentAudioTrack = player.getAudio();
this.selectItem(currentAudioTrack.id);
};
// Update selection when selected track has changed
player.addEventHandler(player.EVENT.ON_AUDIO_CHANGED, audioTrackHandler);
// Update tracks when source goes away
player.addEventHandler(player.EVENT.ON_SOURCE_UNLOADED, updateAudioTracks);
// Update tracks when a new source is loaded
player.addEventHandler(player.EVENT.ON_READY, updateAudioTracks);
// Populate tracks at startup
updateAudioTracks();
// When `playback.audioLanguage` is set, the `ON_AUDIO_CHANGED` event for that change is triggered before the
// UI is created. Therefore we need to set the audio track on configure.
audioTrackHandler();
}
} | Set initial selected audio track | Set initial selected audio track
| TypeScript | mit | bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui | ---
+++
@@ -43,5 +43,9 @@
// Populate tracks at startup
updateAudioTracks();
+
+ // When `playback.audioLanguage` is set, the `ON_AUDIO_CHANGED` event for that change is triggered before the
+ // UI is created. Therefore we need to set the audio track on configure.
+ audioTrackHandler();
}
} |
fc84c81a47039d998589372eedc95efaea42bcf7 | src/lib/util.ts | src/lib/util.ts | import { Component, ComponentProps } from 'preact';
type WhenProps = ComponentProps<When> & {
value: boolean,
children?: (JSX.Element | (() => JSX.Element))[]
};
type WhenState = {
ready: boolean
};
export class When extends Component<WhenProps, WhenState> {
state: WhenState = {
ready: !!this.props.value
};
render({ value, children = [] }: WhenProps, { ready }: WhenState) {
let child = children[0];
if (value && !ready) this.setState({ ready: true });
return ready ? (typeof child === 'function' ? child() : child) : null;
}
}
/**
* A decorator that binds values to their class instance.
* @example
* class C {
* @bind
* foo () {
* return this;
* }
* }
* let f = new C().foo;
* f() instanceof C; // true
*/
export function bind(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
return {
// the first time the prototype property is accessed for an instance,
// define an instance property pointing to the bound function.
// This effectively "caches" the bound prototype method as an instance property.
get() {
let boundFunction = descriptor.value.bind(this);
Object.defineProperty(this, propertyKey, {
value: boundFunction
});
return boundFunction;
}
};
}
| import { Component, ComponentProps } from 'preact';
type WhenProps = ComponentProps<When> & {
value: boolean,
children?: (JSX.Element | (() => JSX.Element))[]
};
type WhenState = {
ready: boolean
};
export class When extends Component<WhenProps, WhenState> {
state: WhenState = {
ready: !!this.props.value
};
render({ value, children = [] }: WhenProps, { ready }: WhenState) {
let child = children[0];
if (value && !ready) this.setState({ ready: true });
return ready ? (typeof child === 'function' ? child() : child) : null;
}
}
/**
* A decorator that binds values to their class instance.
* @example
* class C {
* @bind
* foo () {
* return this;
* }
* }
* let f = new C().foo;
* f() instanceof C; // true
*/
export function bind(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
return {
// the first time the prototype property is accessed for an instance,
// define an instance property pointing to the bound function.
// This effectively "caches" the bound prototype method as an instance property.
get() {
let bound = descriptor.value.bind(this);
Object.defineProperty(this, propertyKey, {
value: bound
});
return bound;
}
};
}
| Make `@bind` the same as Surma's implementation | Make `@bind` the same as Surma's implementation
| TypeScript | apache-2.0 | GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh | ---
+++
@@ -39,11 +39,11 @@
// define an instance property pointing to the bound function.
// This effectively "caches" the bound prototype method as an instance property.
get() {
- let boundFunction = descriptor.value.bind(this);
+ let bound = descriptor.value.bind(this);
Object.defineProperty(this, propertyKey, {
- value: boundFunction
+ value: bound
});
- return boundFunction;
+ return bound;
}
};
} |
9b4e7b9eae24cdbc5634fbe4618c39748c44e93f | test/tools.ts | test/tools.ts | let customElId = 0;
export function customElName() {
++customElId;
return `x-${customElId}`;
}
| let customElId = 0;
export function customElName() {
++customElId;
return `x-${customElId}`;
}
declare global {
interface Window {
ShadowRoot: any;
}
}
| Add global ShadowRoot declaration on Window | Add global ShadowRoot declaration on Window
| TypeScript | mit | marcoms/make-element,marcoms/make-element,marcoms/make-element | ---
+++
@@ -4,3 +4,9 @@
++customElId;
return `x-${customElId}`;
}
+
+declare global {
+ interface Window {
+ ShadowRoot: any;
+ }
+} |
c9f76c1f147f33411b0f6e7dcc6dc054d0610ef9 | components/tf-audio-dashboard/test/audioDashboardTests.ts | components/tf-audio-dashboard/test/audioDashboardTests.ts | declare function stub(el: string, obj: any): void;
describe('audio dashboard tests', function() {
var audioDash;
var reloadCount = 0;
beforeEach(function() {
audioDash = fixture('testElementFixture');
var router = TF.Backend.router('data', true);
var backend = new TF.Backend.Backend(router);
audioDash.backend = backend;
stub('tf-audio-loader', {
reload: function() { reloadCount++; },
});
});
it('calling reload on dashboard reloads the audio-loaders',
function(done) {
audioDash.backendReload().then(() => {
reloadCount = 0;
var loaders = [].slice.call(
audioDash.getElementsByTagName('tf-audio-loader'));
audioDash.frontendReload();
setTimeout(function() {
assert.isAbove(reloadCount, 3);
done();
});
});
});
});
| /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
declare function stub(el: string, obj: any): void;
describe('audio dashboard tests', function() {
var audioDash;
var reloadCount = 0;
beforeEach(function() {
audioDash = fixture('testElementFixture');
var router = TF.Backend.router('data', true);
var backend = new TF.Backend.Backend(router);
audioDash.backend = backend;
stub('tf-audio-loader', {
reload: function() { reloadCount++; },
});
});
it('calling reload on dashboard reloads the audio-loaders',
function(done) {
audioDash.backendReload().then(() => {
reloadCount = 0;
var loaders = [].slice.call(
audioDash.getElementsByTagName('tf-audio-loader'));
audioDash.frontendReload();
setTimeout(function() {
assert.isAbove(reloadCount, 3);
done();
});
});
});
});
| Add license header to file. Change: 134564823 | Add license header to file.
Change: 134564823
| TypeScript | apache-2.0 | agrubb/tensorboard,qiuminxu/tensorboard,tensorflow/tensorboard,ioeric/tensorboard,agrubb/tensorboard,qiuminxu/tensorboard,tensorflow/tensorboard,shakedel/tensorboard,francoisluus/tensorboard-supervise,agrubb/tensorboard,tensorflow/tensorboard,francoisluus/tensorboard-supervise,qiuminxu/tensorboard,ioeric/tensorboard,tensorflow/tensorboard,agrubb/tensorboard,shakedel/tensorboard,francoisluus/tensorboard-supervise,tensorflow/tensorboard,francoisluus/tensorboard-supervise,shakedel/tensorboard,tensorflow/tensorboard,ioeric/tensorboard,ioeric/tensorboard,qiuminxu/tensorboard,shakedel/tensorboard,qiuminxu/tensorboard,ioeric/tensorboard,agrubb/tensorboard,agrubb/tensorboard,francoisluus/tensorboard-supervise,shakedel/tensorboard,francoisluus/tensorboard-supervise,shakedel/tensorboard,tensorflow/tensorboard,qiuminxu/tensorboard,ioeric/tensorboard | ---
+++
@@ -1,3 +1,17 @@
+/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
+
+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.
+==============================================================================*/
declare function stub(el: string, obj: any): void;
describe('audio dashboard tests', function() { |
669a1618daf227930cbc9c7574ef17d7c2d0ad40 | packages/third-parties/schema-formio/src/decorators/index.ts | packages/third-parties/schema-formio/src/decorators/index.ts | export * from "./component";
export * from "./currency";
export * from "./dataSourceJson";
export * from "./dataSourceUrl";
export * from "./hidden";
export * from "./inputTags";
export * from "./multiple";
export * from "./password";
export * from "./select";
export * from "./tableView";
export * from "./textarea";
export * from "./errorMessage";
export * from "./errorLabel";
export * from "./minWords";
export * from "./maxWords";
export * from "./validate";
export * from "./form";
export * from "./tabs";
export * from "./placeholder";
export * from "./tooltip";
export * from "./label";
export * from "./customClass";
export * from "./modalEdit";
export * from "./mask";
export * from "./prefix";
export * from "./suffix";
export * from "./textCase";
export * from "./conditional";
export * from "./customConditional";
| export * from "./component";
export * from "./currency";
export * from "./dataSourceJson";
export * from "./dataSourceUrl";
export * from "./hidden";
export * from "./inputTags";
export * from "./multiple";
export * from "./password";
export * from "./select";
export * from "./tableView";
export * from "./textarea";
export * from "./errorMessage";
export * from "./errorLabel";
export * from "./minWords";
export * from "./maxWords";
export * from "./validate";
export * from "./form";
export * from "./tabs";
export * from "./placeholder";
export * from "./tooltip";
export * from "./label";
export * from "./customClass";
export * from "./modalEdit";
export * from "./mask";
export * from "./prefix";
export * from "./suffix";
export * from "./textCase";
export * from "./conditional";
export * from "./customConditional";
export * from "./openWhenEmpty";
| Add missing export for OpenWhenEmpty | fix(schema-formio): Add missing export for OpenWhenEmpty
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -27,3 +27,4 @@
export * from "./textCase";
export * from "./conditional";
export * from "./customConditional";
+export * from "./openWhenEmpty"; |
4089b913035698bf23bd8d876144b0f0fe826b60 | src/modules/articles/components/extensions/MediaExtension.tsx | src/modules/articles/components/extensions/MediaExtension.tsx | import * as React from 'react';
import { IExtensionProps } from './extensions';
import { ArticleMedia } from '../ArticleMedia';
interface IParsedProps {
mediumIds: string[]
}
export const MediaExtension: React.FunctionComponent<IExtensionProps> = ({ props, article }) => {
const parsedProps = props as IParsedProps;
//makes a copy so media filtering doesn't affect other components
article = Object.assign({}, article);
if (parsedProps.mediumIds && article.media) {
article.media = article.media.filter(m => parsedProps.mediumIds.indexOf(m.id) >= 0);
return <ArticleMedia article={article} media={article.media} />
}
else return null;
} | import * as React from 'react';
import { IExtensionProps } from './extensions';
import { ArticleMedia } from '../ArticleMedia';
interface IParsedProps {
mediumIds: string[]
}
export const MediaExtension: React.FunctionComponent<IExtensionProps> = ({ props, article }) => {
const parsedProps = props as IParsedProps;
//makes a copy so media filtering doesn't affect other components
article = {...article};
if (parsedProps.mediumIds && parsedProps.mediumIds.filter && article.media) {
//Set used in case many media present to avoid quadratic complexity.
const selectedMedia = new Set(parsedProps.mediumIds);
article.media = article.media.filter(m => selectedMedia.has(m.id));
return <ArticleMedia article={article} media={article.media} />
}
else return null;
} | Use set for filtering media. | Use set for filtering media.
| TypeScript | mit | stuyspec/client-app | ---
+++
@@ -11,9 +11,11 @@
const parsedProps = props as IParsedProps;
//makes a copy so media filtering doesn't affect other components
- article = Object.assign({}, article);
- if (parsedProps.mediumIds && article.media) {
- article.media = article.media.filter(m => parsedProps.mediumIds.indexOf(m.id) >= 0);
+ article = {...article};
+ if (parsedProps.mediumIds && parsedProps.mediumIds.filter && article.media) {
+ //Set used in case many media present to avoid quadratic complexity.
+ const selectedMedia = new Set(parsedProps.mediumIds);
+ article.media = article.media.filter(m => selectedMedia.has(m.id));
return <ArticleMedia article={article} media={article.media} />
|
e70138391bbfc88a036b752621d94a6d51698e3d | ui/src/app/tasks-jobs/executions/cleanup/cleanup.component.ts | ui/src/app/tasks-jobs/executions/cleanup/cleanup.component.ts | import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { TaskExecution } from '../../../shared/model/task-execution.model';
import { TaskService } from '../../../shared/api/task.service';
import { NotificationService } from '../../../shared/service/notification.service';
@Component({
selector: 'app-execution-cleanup',
templateUrl: './cleanup.component.html'
})
export class CleanupComponent {
isOpen = false;
isRunning = false;
executions: TaskExecution[];
@Output() onCleaned = new EventEmitter();
constructor(private taskService: TaskService,
private notificationService: NotificationService) {
}
open(executions: TaskExecution[]) {
this.executions = executions;
this.isOpen = true;
}
clean() {
this.isRunning = true;
this.taskService.executionsClean(this.executions)
.subscribe(
data => {
this.notificationService.success('Clean up task execution(s)', `${data.length} task execution(s) cleaned up.`);
this.onCleaned.emit(data);
this.isOpen = false;
this.executions = null;
}, error => {
this.notificationService.error('An error occurred', error);
this.isOpen = false;
this.executions = null;
});
}
}
| import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { TaskExecution } from '../../../shared/model/task-execution.model';
import { TaskService } from '../../../shared/api/task.service';
import { NotificationService } from '../../../shared/service/notification.service';
@Component({
selector: 'app-execution-cleanup',
templateUrl: './cleanup.component.html'
})
export class CleanupComponent {
isOpen = false;
isRunning = false;
executions: TaskExecution[];
@Output() onCleaned = new EventEmitter();
constructor(private taskService: TaskService,
private notificationService: NotificationService) {
}
open(executions: TaskExecution[]) {
this.executions = executions;
this.isRunning = false;
this.isOpen = true;
}
clean() {
this.isRunning = true;
this.taskService.executionsClean(this.executions)
.subscribe(
data => {
this.notificationService.success('Clean up task execution(s)', `${data.length} task execution(s) cleaned up.`);
this.onCleaned.emit(data);
this.isOpen = false;
this.executions = null;
}, error => {
this.notificationService.error('An error occurred', error);
this.isOpen = false;
this.executions = null;
});
}
}
| Fix task execution clean up blocking loading | Fix task execution clean up blocking loading
Resolves #1591
| TypeScript | apache-2.0 | BoykoAlex/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui | ---
+++
@@ -19,6 +19,7 @@
open(executions: TaskExecution[]) {
this.executions = executions;
+ this.isRunning = false;
this.isOpen = true;
}
|
2ed7a4260060614b45e206ac3f4a2db2c8923e71 | src/app/daily-queue/daily-queue-list/daily-queue-list.component.ts | src/app/daily-queue/daily-queue-list/daily-queue-list.component.ts | import { Queue } from './../shared/queue.model';
import { DailyQueueService } from '../shared/daily-queue.service';
import { QueueElement } from '../shared/queueElement.model';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-daily-queue-list',
templateUrl: './daily-queue-list.component.html',
styleUrls: ['./daily-queue-list.component.css'],
providers: [DailyQueueService]
})
export class DailyQueueListComponent implements OnInit {
dailyQueue: Queue;
constructor(private dailyQueueService: DailyQueueService) {}
ngOnInit() {
this.dailyQueue = new Queue();
//this.dailyQueueService.getDailyQueue()
// .then(dailyQueue => this.dailyQueue = dailyQueue);
this.dailyQueue = this.dailyQueueService.mockQueue();
}
deleteElement(index: number) {
this.dailyQueue.matches.splice(index, 1);
}
}
| import { Queue } from './../shared/queue.model';
import { DailyQueueService } from '../shared/daily-queue.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-daily-queue-list',
templateUrl: './daily-queue-list.component.html',
styleUrls: ['./daily-queue-list.component.css'],
providers: [DailyQueueService]
})
export class DailyQueueListComponent implements OnInit {
dailyQueue: Queue;
constructor(private dailyQueueService: DailyQueueService) {}
ngOnInit() {
this.dailyQueue = new Queue();
//this.dailyQueueService.getDailyQueue()
// .then(dailyQueue => this.dailyQueue = dailyQueue);
this.dailyQueue = this.dailyQueueService.mockQueue();
}
deleteElement(index: number) {
this.dailyQueue.matches.splice(index, 1);
}
}
| Use new matches element and remove QueueElement model | Use new matches element and remove QueueElement model
| TypeScript | apache-2.0 | tomek199/elo-rating,tomek199/elo-rating,tomek199/elo-rating,tomek199/elo-rating | ---
+++
@@ -1,6 +1,5 @@
import { Queue } from './../shared/queue.model';
import { DailyQueueService } from '../shared/daily-queue.service';
-import { QueueElement } from '../shared/queueElement.model';
import { Component, OnInit } from '@angular/core';
@Component({ |
8a1a962c23f0bb762d28e38601b72960ae18c897 | src/responseFormatUtility.ts | src/responseFormatUtility.ts | 'use strict'
import { window } from 'vscode';
import { MimeUtility } from './mimeUtility';
var pd = require('pretty-data').pd;
export class ResponseFormatUtility {
public static FormatBody(body: string, contentType: string): string {
if (contentType) {
let mime = MimeUtility.parse(contentType);
let type = mime.type;
let suffix = mime.suffix;
if (type === 'application/json') {
if (ResponseFormatUtility.IsJsonString(body)) {
body = JSON.stringify(JSON.parse(body), null, 2);
} else {
window.showWarningMessage('The content type of response is application/json, while response body is not a valid json string');
}
} else if (type === 'application/xml' ||
type === 'text/xml' ||
(type === 'application/atom' && suffix === '+xml')) {
body = pd.xml(body);
} else if (type === 'text/css') {
body = pd.css(body);
}
}
return body;
}
public static IsJsonString(data: string) {
try {
JSON.parse(data);
return true;
} catch (e) {
return false;
}
}
} | 'use strict'
import { window } from 'vscode';
import { MimeUtility } from './mimeUtility';
var pd = require('pretty-data').pd;
export class ResponseFormatUtility {
public static FormatBody(body: string, contentType: string): string {
if (contentType) {
let mime = MimeUtility.parse(contentType);
let type = mime.type;
let suffix = mime.suffix;
if (type === 'application/json' ||
suffix === '+json') {
if (ResponseFormatUtility.IsJsonString(body)) {
body = JSON.stringify(JSON.parse(body), null, 2);
} else {
window.showWarningMessage('The content type of response is application/json, while response body is not a valid json string');
}
} else if (type === 'application/xml' ||
type === 'text/xml' ||
(type === 'application/atom' && suffix === '+xml')) {
body = pd.xml(body);
} else if (type === 'text/css') {
body = pd.css(body);
}
}
return body;
}
public static IsJsonString(data: string) {
try {
JSON.parse(data);
return true;
} catch (e) {
return false;
}
}
} | Support mime type with json suffix | Support mime type with json suffix
| TypeScript | mit | Huachao/vscode-restclient,Huachao/vscode-restclient | ---
+++
@@ -10,7 +10,8 @@
let mime = MimeUtility.parse(contentType);
let type = mime.type;
let suffix = mime.suffix;
- if (type === 'application/json') {
+ if (type === 'application/json' ||
+ suffix === '+json') {
if (ResponseFormatUtility.IsJsonString(body)) {
body = JSON.stringify(JSON.parse(body), null, 2);
} else { |
da673b146bbaa81884c98c960f41d5a03f71081c | web/src/App.tsx | web/src/App.tsx | import * as React from 'react';
import './App.css';
import logo from './logo.svg';
class App extends React.Component<{}, { apiMessage: string }> {
constructor(props: object) {
super(props);
this.state = { apiMessage: "" };
}
public componentDidMount() {
fetch("/api").then(r => r.text()).then(apiMessage => {
this.setState({
apiMessage
});
});
}
public render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
<p>
{this.state.apiMessage}
</p>
</div>
);
}
}
export default App;
| import * as React from 'react';
import './App.css';
import logo from './logo.svg';
class App extends React.Component<{}, { apiMessage: string }> {
constructor(props: object) {
super(props);
this.state = { apiMessage: "Loading... (If this takes too long, the database might be down.)" };
}
public componentDidMount() {
fetch("/api")
.then(r => r.status === 500
? `(The server reported an error or cannot be reached. Is it compiling...?)`
: r.text()
)
.then(apiMessage =>
this.setState({
apiMessage
})
);
}
public render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
<p>
{this.state.apiMessage}
</p>
</div>
);
}
}
export default App;
| Improve error responses on client side | Improve error responses on client side
| TypeScript | mit | ghotiphud/rust-web-starter,ghotiphud/rust-web-starter,ghotiphud/rust-web-starter,ghotiphud/rust-web-starter | ---
+++
@@ -7,15 +7,20 @@
constructor(props: object) {
super(props);
- this.state = { apiMessage: "" };
+ this.state = { apiMessage: "Loading... (If this takes too long, the database might be down.)" };
}
public componentDidMount() {
- fetch("/api").then(r => r.text()).then(apiMessage => {
- this.setState({
- apiMessage
- });
- });
+ fetch("/api")
+ .then(r => r.status === 500
+ ? `(The server reported an error or cannot be reached. Is it compiling...?)`
+ : r.text()
+ )
+ .then(apiMessage =>
+ this.setState({
+ apiMessage
+ })
+ );
}
public render() { |
ed76e5eade81e34d7847a0673d12cfdc1f744077 | tests/src/service.spec.ts | tests/src/service.spec.ts | import { expect } from 'chai';
import { DebugService } from '../../lib/service';
describe('DebugService', () => {
let service = new DebugService();
describe('#constructor()', () => {
it('should create a new instance', () => {
expect(service).to.be.an.instanceOf(DebugService);
});
});
});
| import { expect } from 'chai';
import { ClientSession, IClientSession } from '@jupyterlab/apputils';
import { createClientSession } from '@jupyterlab/testutils';
import { DebugService } from '../../lib/service';
import { DebugSession } from '../../lib/session';
import { IDebugger } from '../../lib/tokens';
describe('DebugService', () => {
let client: IClientSession;
let session: IDebugger.ISession;
let service: IDebugger;
beforeEach(async () => {
client = await createClientSession({
kernelPreference: {
name: 'xpython'
}
});
await (client as ClientSession).initialize();
await client.kernel.ready;
session = new DebugSession({ client });
service = new DebugService();
});
afterEach(async () => {
await client.shutdown();
session.dispose();
service.dispose();
});
describe('#constructor()', () => {
it('should create a new instance', () => {
expect(service).to.be.an.instanceOf(DebugService);
});
});
describe('#start()', () => {
it('should start the service if the session is set', async () => {
service.session = session;
await service.start();
expect(service.isStarted()).to.equal(true);
});
it('should throw an error if the session is not set', async () => {
try {
await service.start();
} catch (err) {
expect(err.message).to.contain("Cannot read property 'start' of null");
}
});
});
describe('#stop()', () => {
it('should stop the service if the session is set', async () => {
service.session = session;
await service.start();
await service.stop();
expect(service.isStarted()).to.equal(false);
});
});
});
| Add tests for start and stop for DebugService | Add tests for start and stop for DebugService
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -1,13 +1,66 @@
import { expect } from 'chai';
+
+import { ClientSession, IClientSession } from '@jupyterlab/apputils';
+
+import { createClientSession } from '@jupyterlab/testutils';
import { DebugService } from '../../lib/service';
+import { DebugSession } from '../../lib/session';
+
+import { IDebugger } from '../../lib/tokens';
+
describe('DebugService', () => {
- let service = new DebugService();
+ let client: IClientSession;
+ let session: IDebugger.ISession;
+ let service: IDebugger;
+
+ beforeEach(async () => {
+ client = await createClientSession({
+ kernelPreference: {
+ name: 'xpython'
+ }
+ });
+ await (client as ClientSession).initialize();
+ await client.kernel.ready;
+ session = new DebugSession({ client });
+ service = new DebugService();
+ });
+
+ afterEach(async () => {
+ await client.shutdown();
+ session.dispose();
+ service.dispose();
+ });
describe('#constructor()', () => {
it('should create a new instance', () => {
expect(service).to.be.an.instanceOf(DebugService);
});
});
+
+ describe('#start()', () => {
+ it('should start the service if the session is set', async () => {
+ service.session = session;
+ await service.start();
+ expect(service.isStarted()).to.equal(true);
+ });
+
+ it('should throw an error if the session is not set', async () => {
+ try {
+ await service.start();
+ } catch (err) {
+ expect(err.message).to.contain("Cannot read property 'start' of null");
+ }
+ });
+ });
+
+ describe('#stop()', () => {
+ it('should stop the service if the session is set', async () => {
+ service.session = session;
+ await service.start();
+ await service.stop();
+ expect(service.isStarted()).to.equal(false);
+ });
+ });
}); |
5c808ff99ed8c701dad23cf4fbfc45217e05ee38 | polygerrit-ui/app/elements/shared/gr-avatar/gr-avatar_html.ts | polygerrit-ui/app/elements/shared/gr-avatar/gr-avatar_html.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 {html} from '@polymer/polymer/lib/utils/html-tag';
export const htmlTemplate = html`
<style>
:host {
display: inline-block;
border-radius: 50%;
background-size: cover;
background-color: var(--avatar-background-color, var(--gray-background));
}
</style>
`;
| /**
* @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 {html} from '@polymer/polymer/lib/utils/html-tag';
export const htmlTemplate = html`
<style>
:host([hidden]) {
display: none;
}
:host {
display: inline-block;
border-radius: 50%;
background-size: cover;
background-color: var(--avatar-background-color, var(--gray-background));
}
</style>
`;
| Fix bug in gr-avatar which wasn't hiding avatars when "hidden" is set | Fix bug in gr-avatar which wasn't hiding avatars when "hidden" is set
This happened for sites that did not set an avatar. Seems a recent
regression as it works on gerrit 3.3.
Release-Notes: skip
Change-Id: I148716b36c3d57e3eb3f1486b9539f1741d7288b
(cherry picked from commit e0358c2e4e7db76a7efe01de9cc14ef16af03a2e)
| TypeScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -18,6 +18,9 @@
export const htmlTemplate = html`
<style>
+ :host([hidden]) {
+ display: none;
+ }
:host {
display: inline-block;
border-radius: 50%; |
7f4b9a5ed47d815a369dad2291181215f5e072bb | yamcs-web/src/main/webapp/src/app/appbase/pages/ContextSwitchPage.ts | yamcs-web/src/main/webapp/src/app/appbase/pages/ContextSwitchPage.ts | import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
/*
* This component is a hack around the Angular routing system. It forces a full
* reload of a component by navigating away and back to a component.
*
* Without this code, each component from which the context can be changed,
* would need listen to route events separately.
*/
@Component({
template: '',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ContextSwitchPage implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) {
}
ngOnInit() {
// Get information only from route params.
// Query params do not work, because we use skipLocationChange to get here.
const paramMap = this.route.snapshot.paramMap;
const context = paramMap.get('context');
const url = paramMap.get('current')!;
const tree = this.router.parseUrl(url);
const urlWithoutParams = '/' + tree.root.children['primary'].segments.map(it => it.path).join('/');
this.router.navigate([urlWithoutParams], {
queryParams: {
...tree.queryParams,
c: context,
}
});
}
}
| import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
/*
* This component is a hack around the Angular routing system. It forces a full
* reload of a component by navigating away and back to a component.
*
* Without this code, each component from which the context can be changed,
* would need listen to route events separately.
*/
@Component({
template: '',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ContextSwitchPage implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) {
}
ngOnInit() {
// Get information only from route params.
// Query params do not work, because we use skipLocationChange to get here.
const paramMap = this.route.snapshot.paramMap;
const context = paramMap.get('context');
let url = paramMap.get('current')!;
// Carefully obtain a URL string with the querystring removed
// We must specially 'preserve' % escape patterns, because the parseUrl will decode them
url = url.replace(/\%/g, '__TEMP__');
const tree = this.router.parseUrl(url);
let urlWithoutParams = '/' + tree.root.children['primary'].segments.map(it => it.path).join('/');
urlWithoutParams = urlWithoutParams.replace(/__TEMP__/g, '%');
// Now we have a string that matches exactly what we passed in, but
// with query param removed. Next, we need to break it in URI fragments
// because otherwise the navigation will also decode % escape patterns.
const fragments = urlWithoutParams.split('/');
fragments[0] = '/';
for (let i = 1; i < fragments.length; i++) {
fragments[i] = decodeURIComponent(fragments[i]);
}
// Pass an array of fragments, job done!
this.router.navigate(fragments, {
queryParams: {
...tree.queryParams,
c: context,
}
});
}
}
| Fix context switcher on parameter detail pages | Fix context switcher on parameter detail pages
| TypeScript | agpl-3.0 | m-sc/yamcs,fqqb/yamcs,fqqb/yamcs,m-sc/yamcs,yamcs/yamcs,yamcs/yamcs,m-sc/yamcs,m-sc/yamcs,yamcs/yamcs,yamcs/yamcs,yamcs/yamcs,m-sc/yamcs,fqqb/yamcs,yamcs/yamcs,m-sc/yamcs,fqqb/yamcs,fqqb/yamcs,fqqb/yamcs | ---
+++
@@ -22,12 +22,26 @@
// Query params do not work, because we use skipLocationChange to get here.
const paramMap = this.route.snapshot.paramMap;
const context = paramMap.get('context');
- const url = paramMap.get('current')!;
+ let url = paramMap.get('current')!;
+ // Carefully obtain a URL string with the querystring removed
+ // We must specially 'preserve' % escape patterns, because the parseUrl will decode them
+ url = url.replace(/\%/g, '__TEMP__');
const tree = this.router.parseUrl(url);
- const urlWithoutParams = '/' + tree.root.children['primary'].segments.map(it => it.path).join('/');
+ let urlWithoutParams = '/' + tree.root.children['primary'].segments.map(it => it.path).join('/');
+ urlWithoutParams = urlWithoutParams.replace(/__TEMP__/g, '%');
- this.router.navigate([urlWithoutParams], {
+ // Now we have a string that matches exactly what we passed in, but
+ // with query param removed. Next, we need to break it in URI fragments
+ // because otherwise the navigation will also decode % escape patterns.
+ const fragments = urlWithoutParams.split('/');
+ fragments[0] = '/';
+ for (let i = 1; i < fragments.length; i++) {
+ fragments[i] = decodeURIComponent(fragments[i]);
+ }
+
+ // Pass an array of fragments, job done!
+ this.router.navigate(fragments, {
queryParams: {
...tree.queryParams,
c: context, |
d4fa30511b6e9d27f0d87a89a8139fa9abe22ceb | DeadBaseSample/src/DeadBaseSample/TypeScriptSource/deadbase.ts | DeadBaseSample/src/DeadBaseSample/TypeScriptSource/deadbase.ts | import { bootstrap, Component, NgModel } from 'angular2/angular2';
class ConcertSet {
date: Date;
venue: string;
set: number;
}
@Component({
selector: 'deadbase-app',
template: `
<h1>{{title}}</h1>
<h2>{{concert.date.toDateString()}} -- {{concert.venue}} Details!</h2>
<div><label>date: </label><input [(ng-model)]="concert.date"></div>
<div><label>venue: </label><input [(ng-model)]="concert.venue" placeholder="venue"></div>
<div><label>set: </label><input [(ng-model)]="concert.set" type="number"></div>
`,
directives: [NgModel]
})
class DeadBaseAppComponent {
public title = "Deadbase - Grateful Dead Concert Archive";
public concert: ConcertSet = {
date: new Date(1971, 7, 2),
venue: "Filmore West",
set: 2
}
}
bootstrap(DeadBaseAppComponent);
| import { bootstrap, Component, FORM_DIRECTIVES } from 'angular2/angular2';
class ConcertSet {
date: string;
venue: string;
set: number;
}
@Component({
selector: 'deadbase-app',
template: `
<h1>{{title}}</h1>
<h2>{{concert.date}} -- {{concert.venue}} Details!</h2>
<div><label>date: </label><input [(ng-model)]="concert.date" type="date"></div>
<div><label>venue: </label><input [(ng-model)]="concert.venue" placeholder="venue"></div>
<div><label>set: </label><input [(ng-model)]="concert.set" type="number"></div>
`,
directives: [FORM_DIRECTIVES]
})
class DeadBaseAppComponent {
public title = "Deadbase - Grateful Dead Concert Archive";
public concert: ConcertSet = {
date: "1971-07-02",
venue: "Filmore West",
set: 2
}
}
bootstrap(DeadBaseAppComponent);
| Add Form Directives, change date type | Add Form Directives, change date type
Because databinding doesn't work the way we want with the JS Date Type.
| TypeScript | mit | BillWagner/TypeScriptAngular2,BillWagner/TypeScriptAngular2,BillWagner/TypeScriptAngular2,BillWagner/TypeScriptAngular2 | ---
+++
@@ -1,7 +1,7 @@
-import { bootstrap, Component, NgModel } from 'angular2/angular2';
+import { bootstrap, Component, FORM_DIRECTIVES } from 'angular2/angular2';
class ConcertSet {
- date: Date;
+ date: string;
venue: string;
set: number;
}
@@ -11,17 +11,17 @@
selector: 'deadbase-app',
template: `
<h1>{{title}}</h1>
- <h2>{{concert.date.toDateString()}} -- {{concert.venue}} Details!</h2>
- <div><label>date: </label><input [(ng-model)]="concert.date"></div>
+ <h2>{{concert.date}} -- {{concert.venue}} Details!</h2>
+ <div><label>date: </label><input [(ng-model)]="concert.date" type="date"></div>
<div><label>venue: </label><input [(ng-model)]="concert.venue" placeholder="venue"></div>
<div><label>set: </label><input [(ng-model)]="concert.set" type="number"></div>
`,
- directives: [NgModel]
+ directives: [FORM_DIRECTIVES]
})
class DeadBaseAppComponent {
public title = "Deadbase - Grateful Dead Concert Archive";
public concert: ConcertSet = {
- date: new Date(1971, 7, 2),
+ date: "1971-07-02",
venue: "Filmore West",
set: 2
} |
eb088e38f392f2deb19871376e535cffbb51b6ce | webpack/account/dev_mode.tsx | webpack/account/dev_mode.tsx | import * as React from "react";
import { warning } from "farmbot-toastr";
import { setWebAppConfigValue } from "../config_storage/actions";
import { BooleanConfigKey } from "farmbot/dist/resources/configs/web_app";
interface S { count: number; }
interface P { dispatch: Function; }
const clicksLeft =
(x: number) => () => warning(`${x} more clicks`);
const key = "show_dev_menu" as BooleanConfigKey;
const activateDevMode = (dispatch: Function) => {
localStorage.setItem("IM_A_DEVELOPER", "1000.0.0");
dispatch(setWebAppConfigValue(key, true));
};
const triggers: Record<number, Function> = {
5: clicksLeft(10),
10: clicksLeft(5),
15: activateDevMode,
};
export class DevMode extends React.Component<P, S> {
state: S = { count: 0 };
bump = () => {
const { count } = this.state;
const cb = triggers[count];
cb && cb(this.props.dispatch);
this.setState({ count: count + 1 });
};
render() {
return <div onClick={this.bump}>
<hr />
</div>;
}
}
| import * as React from "react";
import { warning } from "farmbot-toastr";
import { setWebAppConfigValue } from "../config_storage/actions";
import { BooleanConfigKey } from "farmbot/dist/resources/configs/web_app";
interface S { count: number; }
interface P { dispatch: Function; }
const clicksLeft =
(x: number) => () => warning(`${x} more clicks`);
const key = "show_dev_menu" as BooleanConfigKey;
const activateDevMode = (dispatch: Function) => {
localStorage.setItem("IM_A_DEVELOPER", "1000.0.0");
dispatch(setWebAppConfigValue(key, true));
};
const triggers: Record<number, Function> = {
5: clicksLeft(10),
10: clicksLeft(5),
15: activateDevMode,
};
export class DevMode extends React.Component<P, S> {
state: S = { count: 0 };
bump = () => {
const { count } = this.state;
const cb = triggers[count];
cb && cb(this.props.dispatch);
this.setState({ count: count + 1 });
console.log(count);
};
render() {
return <div style={{ height: "100px" }} onClick={this.bump}>
<hr />
</div>;
}
}
| Increase CSS height for easier accesibility | Increase CSS height for easier accesibility
| TypeScript | mit | FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app | ---
+++
@@ -29,10 +29,11 @@
const cb = triggers[count];
cb && cb(this.props.dispatch);
this.setState({ count: count + 1 });
+ console.log(count);
};
render() {
- return <div onClick={this.bump}>
+ return <div style={{ height: "100px" }} onClick={this.bump}>
<hr />
</div>;
} |
3a75b00db03cf2de4df3a6760cfd394183f43c3b | sample/23-type-graphql/src/recipes/dto/new-recipe.input.ts | sample/23-type-graphql/src/recipes/dto/new-recipe.input.ts | import { Length, MaxLength } from 'class-validator';
import { Field, InputType } from 'type-graphql';
@InputType()
export class NewRecipeInput {
@Field()
@MaxLength(30)
title: string;
@Field({ nullable: true })
@Length(30, 255)
description?: string;
@Field(type => [String])
ingredients: string[];
}
| import { IsOptional, Length, MaxLength } from 'class-validator';
import { Field, InputType } from 'type-graphql';
@InputType()
export class NewRecipeInput {
@Field()
@MaxLength(30)
title: string;
@Field({ nullable: true })
@IsOptional()
@Length(30, 255)
description?: string;
@Field(type => [String])
ingredients: string[];
}
| Add missing isOptional on optional field in Sample-23 | Add missing isOptional on optional field in Sample-23
| TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -1,4 +1,4 @@
-import { Length, MaxLength } from 'class-validator';
+import { IsOptional, Length, MaxLength } from 'class-validator';
import { Field, InputType } from 'type-graphql';
@InputType()
@@ -8,6 +8,7 @@
title: string;
@Field({ nullable: true })
+ @IsOptional()
@Length(30, 255)
description?: string;
|
a2e1a18d9987d608c4987c072e32b5e1299e80da | packages/components/components/dropdown/DropdownMenu.tsx | packages/components/components/dropdown/DropdownMenu.tsx | import React from 'react';
import { classnames } from '../../helpers/component';
interface Props {
children: React.ReactNode;
className?: string;
}
const DropdownMenu = ({ children, className = '' }: Props) => {
return (
<div className="dropDown-content">
<ul className={classnames(['unstyled mt0 mb0 ml1 mr1', className])}>
{React.Children.toArray(children).map((child, i) => {
return React.isValidElement(child) ? (
<li className="dropDown-item" key={child.key || i}>
{child}
</li>
) : null;
})}
</ul>
</div>
);
};
export default DropdownMenu;
| import React from 'react';
import { classnames } from '../../helpers/component';
interface Props {
children: React.ReactNode;
className?: string;
}
const DropdownMenu = ({ children, className = '' }: Props) => {
return (
<div className="dropDown-content">
<ul className={classnames(['unstyled mt0 mb0', className])}>
{React.Children.toArray(children).map((child, i) => {
return React.isValidElement(child) ? (
<li className="dropDown-item pl1 pr1" key={child.key || i}>
{child}
</li>
) : null;
})}
</ul>
</div>
);
};
export default DropdownMenu;
| Fix - MAILWEB-428 - hover effect in dropdown | Fix - MAILWEB-428 - hover effect in dropdown
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -9,10 +9,10 @@
const DropdownMenu = ({ children, className = '' }: Props) => {
return (
<div className="dropDown-content">
- <ul className={classnames(['unstyled mt0 mb0 ml1 mr1', className])}>
+ <ul className={classnames(['unstyled mt0 mb0', className])}>
{React.Children.toArray(children).map((child, i) => {
return React.isValidElement(child) ? (
- <li className="dropDown-item" key={child.key || i}>
+ <li className="dropDown-item pl1 pr1" key={child.key || i}>
{child}
</li>
) : null; |
ea23156ab50212746f94a79961eb0a3a8c5e4761 | src/lib/Scenes/Artwork/Components/OtherWorks/ContextGridCTA.tsx | src/lib/Scenes/Artwork/Components/OtherWorks/ContextGridCTA.tsx | import { navigate } from "lib/navigation/navigate"
import { Schema, track } from "lib/utils/track"
import { ArrowRightIcon, Flex, Sans } from "palette"
import React from "react"
import { TouchableWithoutFeedback } from "react-native"
interface ContextGridCTAProps {
href?: string
contextModule?: string
label: string
}
@track()
export class ContextGridCTA extends React.Component<ContextGridCTAProps> {
@track((props) => ({
action_name: Schema.ActionNames.ViewAll,
action_type: Schema.ActionTypes.Tap,
flow: Schema.Flow.RecommendedArtworks,
context_module: props.contextModule,
}))
openLink() {
const { href } = this.props
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
navigate(href)
}
render() {
const { href, label } = this.props
if (href && label) {
return (
<TouchableWithoutFeedback onPress={() => this.openLink()}>
<Flex flexDirection="row" alignContent="center">
<Sans size="3" textAlign="left" weight="medium">
{label}
</Sans>
<ArrowRightIcon fill="black30" ml={1} mt={0.3} />
</Flex>
</TouchableWithoutFeedback>
)
} else {
return null
}
}
}
| import { navigate } from "lib/navigation/navigate"
import { Schema, track } from "lib/utils/track"
import { ArrowRightIcon, Flex, Sans } from "palette"
import React from "react"
import { TouchableWithoutFeedback } from "react-native"
interface ContextGridCTAProps {
href?: string
contextModule?: string
label: string
}
@track()
export class ContextGridCTA extends React.Component<ContextGridCTAProps> {
@track((props) => ({
action_name: Schema.ActionNames.ViewAll,
action_type: Schema.ActionTypes.Tap,
flow: Schema.Flow.RecommendedArtworks,
context_module: props.contextModule,
}))
openLink() {
const { href } = this.props
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
navigate(href)
}
render() {
const { href, label } = this.props
if (href && label) {
return (
<TouchableWithoutFeedback onPress={() => this.openLink()}>
<Flex flexDirection="row" alignContent="center">
<Flex justifyContent="center">
<Sans size="3" textAlign="left" weight="medium">
{label}
</Sans>
</Flex>
<Flex justifyContent="center">
<ArrowRightIcon fill="black30" ml={1} />
</Flex>
</Flex>
</TouchableWithoutFeedback>
)
} else {
return null
}
}
}
| Align context grid CTA text with icon | fix: Align context grid CTA text with icon
| TypeScript | mit | artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen | ---
+++
@@ -31,10 +31,14 @@
return (
<TouchableWithoutFeedback onPress={() => this.openLink()}>
<Flex flexDirection="row" alignContent="center">
- <Sans size="3" textAlign="left" weight="medium">
- {label}
- </Sans>
- <ArrowRightIcon fill="black30" ml={1} mt={0.3} />
+ <Flex justifyContent="center">
+ <Sans size="3" textAlign="left" weight="medium">
+ {label}
+ </Sans>
+ </Flex>
+ <Flex justifyContent="center">
+ <ArrowRightIcon fill="black30" ml={1} />
+ </Flex>
</Flex>
</TouchableWithoutFeedback>
) |
15088f91513522c242552f38caee4b53015fc993 | src/components/SearchTable/SearchCard/BlockActionsPopover.tsx | src/components/SearchTable/SearchCard/BlockActionsPopover.tsx | import * as React from 'react';
import { Button } from '@shopify/polaris';
export interface Handlers {
readonly onBlockRequester: () => void;
}
class BlockActionsPopover extends React.PureComponent<Handlers, never> {
public render() {
return (
<Button destructive size="slim" onClick={this.props.onBlockRequester}>
Block Requester
</Button>
);
}
}
export default BlockActionsPopover;
| import * as React from 'react';
import { Button, Tooltip } from '@shopify/polaris';
export interface Handlers {
readonly onBlockRequester: () => void;
}
class BlockActionsPopover extends React.PureComponent<Handlers, never> {
public render() {
return (
<Tooltip content="You can manage your blocked requesters in the Blocklist tab. ">
<Button destructive size="slim" onClick={this.props.onBlockRequester}>
Block Requester
</Button>
</Tooltip>
);
}
}
export default BlockActionsPopover;
| Add tooltip to block requester button. | Add tooltip to block requester button.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { Button } from '@shopify/polaris';
+import { Button, Tooltip } from '@shopify/polaris';
export interface Handlers {
readonly onBlockRequester: () => void;
@@ -8,9 +8,11 @@
class BlockActionsPopover extends React.PureComponent<Handlers, never> {
public render() {
return (
- <Button destructive size="slim" onClick={this.props.onBlockRequester}>
- Block Requester
- </Button>
+ <Tooltip content="You can manage your blocked requesters in the Blocklist tab. ">
+ <Button destructive size="slim" onClick={this.props.onBlockRequester}>
+ Block Requester
+ </Button>
+ </Tooltip>
);
}
} |
f777cbd4c0a53c64334b51b50c60021073ad93a2 | tools/env/base.ts | tools/env/base.ts | import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.6.0',
RELEASEVERSION: '0.6.0'
};
export = BaseConfig;
| import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.7.0',
RELEASEVERSION: '0.7.0'
};
export = BaseConfig;
| Update release version to 0.7.0 | Update release version to 0.7.0
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -3,8 +3,8 @@
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
- RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.6.0',
- RELEASEVERSION: '0.6.0'
+ RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.7.0',
+ RELEASEVERSION: '0.7.0'
};
export = BaseConfig; |
ddd2cd1f25b079a9559a501cc35555c461116550 | src/reducers/audioFiles.ts | src/reducers/audioFiles.ts | import { AudioFiles } from '../types';
const initial: AudioFiles = {
audioNewSearch: new Audio(
'https://k003.kiwi6.com/hotlink/85iq6xu5ul/coins.ogg'
)
};
export default (state = initial, action: {}) => {
return state;
};
| import { AudioFiles } from '../types';
const initial: AudioFiles = {
audioNewSearch: new Audio(
'https://k003.kiwi6.com/hotlink/w9aqj8az8t/ping.wav'
)
};
export default (state = initial, action: {}) => {
return state;
};
| Use new audio for new search result sound notification. | Use new audio for new search result sound notification.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -2,7 +2,7 @@
const initial: AudioFiles = {
audioNewSearch: new Audio(
- 'https://k003.kiwi6.com/hotlink/85iq6xu5ul/coins.ogg'
+ 'https://k003.kiwi6.com/hotlink/w9aqj8az8t/ping.wav'
)
};
|
e81afc060726f0d77a3fe2d841138e966d5d6146 | frontend/src/app/controls/base/stringControl/stringControl.component.ts | frontend/src/app/controls/base/stringControl/stringControl.component.ts | /*
* Angular 2 decorators and services
*/
import { Component, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
// The selector is what angular internally uses
selector: 'cb-string-control',
styles: [``],
template: `
<div [formGroup]="inputGroup">
<label>{{label}}</label>
<input type="text" [value]="value" formControlName="item" />
</div>
`,
})
export class StringControlComponent {
@Input() label: string;
@Input() value: string;
@Input() inputGroup: FormGroup;
constructor() { }
ngOnInit() {}
}
| /*
* Angular 2 decorators and services
*/
import { Component, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
// The selector is what angular internally uses
selector: 'cb-string-control',
styles: [``],
template: `
<div [formGroup]="inputGroup">
<label>{{label}}</label>
<input type="text" [(ngModel)]="value" formControlName="item" />
</div>
`,
})
export class StringControlComponent {
@Input() label: string;
@Input() value: string;
@Input() inputGroup: FormGroup;
constructor() { }
ngOnInit() {}
}
| Fix variation string input control binding | fix(variations): Fix variation string input control binding
| TypeScript | mit | joaogarin/carte-blanche-angular2,joaogarin/carte-blanche-angular2 | ---
+++
@@ -11,7 +11,7 @@
template: `
<div [formGroup]="inputGroup">
<label>{{label}}</label>
- <input type="text" [value]="value" formControlName="item" />
+ <input type="text" [(ngModel)]="value" formControlName="item" />
</div>
`,
}) |
0802fbec3bff61683cf84e6ae5bce7492e94b7a4 | packages/internal-test-helpers/lib/ember-dev/setup-qunit.ts | packages/internal-test-helpers/lib/ember-dev/setup-qunit.ts | import { getDebugFunction, setDebugFunction } from '@ember/debug';
// @ts-ignore
import EmberDevTestHelperAssert from './index';
export interface Assertion {
reset(): void;
inject(): void;
assert(): void;
restore(): void;
}
export default function setupQUnit({ runningProdBuild }: { runningProdBuild: boolean }) {
let assertion = new EmberDevTestHelperAssert({
runningProdBuild,
getDebugFunction,
setDebugFunction,
});
let originalModule = QUnit.module;
QUnit.module = function(name: string, _options: any) {
let options = _options || {};
let originalSetup = options.setup || options.beforeEach || function() {};
let originalTeardown = options.teardown || options.afterEach || function() {};
delete options.setup;
delete options.teardown;
options.beforeEach = function() {
assertion.reset();
assertion.inject();
return originalSetup.apply(this, arguments);
};
options.afterEach = function() {
let result = originalTeardown.apply(this, arguments);
assertion.assert();
assertion.restore();
return result;
};
return originalModule(name, options);
};
}
| import { getDebugFunction, setDebugFunction } from '@ember/debug';
// @ts-ignore
import EmberDevTestHelperAssert from './index';
export interface Assertion {
reset(): void;
inject(): void;
assert(): void;
restore(): void;
}
export default function setupQUnit({ runningProdBuild }: { runningProdBuild: boolean }) {
let assertion = new EmberDevTestHelperAssert({
runningProdBuild,
getDebugFunction,
setDebugFunction,
});
let originalModule = QUnit.module;
QUnit.module = function(name: string, _options: any) {
if (typeof _options === 'function') {
let callback = _options;
return originalModule(name, function(hooks) {
hooks.beforeEach(function() {
assertion.reset();
assertion.inject();
});
hooks.afterEach(function() {
assertion.assert();
assertion.restore();
});
callback(hooks);
});
}
let options = _options || {};
let originalSetup = options.setup || options.beforeEach || function() {};
let originalTeardown = options.teardown || options.afterEach || function() {};
delete options.setup;
delete options.teardown;
options.beforeEach = function() {
assertion.reset();
assertion.inject();
return originalSetup.apply(this, arguments);
};
options.afterEach = function() {
let result = originalTeardown.apply(this, arguments);
assertion.assert();
assertion.restore();
return result;
};
return originalModule(name, options);
};
}
| Add nested module API support to `setupQUnit()` function | internal-test-helpers: Add nested module API support to `setupQUnit()` function
| TypeScript | mit | miguelcobain/ember.js,givanse/ember.js,mfeckie/ember.js,kellyselden/ember.js,GavinJoyce/ember.js,emberjs/ember.js,intercom/ember.js,givanse/ember.js,stefanpenner/ember.js,intercom/ember.js,intercom/ember.js,sly7-7/ember.js,bekzod/ember.js,stefanpenner/ember.js,mixonic/ember.js,qaiken/ember.js,GavinJoyce/ember.js,fpauser/ember.js,emberjs/ember.js,fpauser/ember.js,jaswilli/ember.js,qaiken/ember.js,cibernox/ember.js,asakusuma/ember.js,GavinJoyce/ember.js,mfeckie/ember.js,kellyselden/ember.js,miguelcobain/ember.js,GavinJoyce/ember.js,asakusuma/ember.js,knownasilya/ember.js,elwayman02/ember.js,kellyselden/ember.js,givanse/ember.js,mfeckie/ember.js,elwayman02/ember.js,qaiken/ember.js,bekzod/ember.js,bekzod/ember.js,jaswilli/ember.js,knownasilya/ember.js,knownasilya/ember.js,sandstrom/ember.js,emberjs/ember.js,elwayman02/ember.js,cibernox/ember.js,stefanpenner/ember.js,sly7-7/ember.js,mixonic/ember.js,givanse/ember.js,cibernox/ember.js,elwayman02/ember.js,fpauser/ember.js,bekzod/ember.js,kellyselden/ember.js,qaiken/ember.js,tildeio/ember.js,sandstrom/ember.js,intercom/ember.js,sly7-7/ember.js,sandstrom/ember.js,jaswilli/ember.js,miguelcobain/ember.js,mixonic/ember.js,fpauser/ember.js,asakusuma/ember.js,tildeio/ember.js,jaswilli/ember.js,cibernox/ember.js,mfeckie/ember.js,asakusuma/ember.js,tildeio/ember.js,miguelcobain/ember.js | ---
+++
@@ -20,6 +20,24 @@
let originalModule = QUnit.module;
QUnit.module = function(name: string, _options: any) {
+ if (typeof _options === 'function') {
+ let callback = _options;
+
+ return originalModule(name, function(hooks) {
+ hooks.beforeEach(function() {
+ assertion.reset();
+ assertion.inject();
+ });
+
+ hooks.afterEach(function() {
+ assertion.assert();
+ assertion.restore();
+ });
+
+ callback(hooks);
+ });
+ }
+
let options = _options || {};
let originalSetup = options.setup || options.beforeEach || function() {};
let originalTeardown = options.teardown || options.afterEach || function() {}; |
216e05f2d40a99f054bbfab2a86d0cbf5ceec1ec | main/src/extension/api/ApplicationImpl.ts | main/src/extension/api/ApplicationImpl.ts | /*
* Copyright 2022 Simon Edwards <simon@simonzone.com>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import * as open from "open";
import * as fs from "node:fs";
import * as path from "node:path";
import * as ExtensionApi from "@extraterm/extraterm-extension-api";
import { ClipboardImpl } from "./ClipboardImpl.js";
export class ApplicationImpl implements ExtensionApi.Application {
#clipboard = new ClipboardImpl();
#version = "";
constructor(version: string) {
this.#version = version;
}
get clipboard(): ExtensionApi.Clipboard {
return this.#clipboard;
}
openExternal(url: string): void {
if (url == null) {
return;
}
open(url);
}
showItemInFileManager(itemPath: string): void {
if (itemPath == null) {
return;
}
const stats = fs.statSync(itemPath);
let cleanPath = itemPath;
if (!stats.isDirectory()) {
cleanPath = path.dirname(itemPath);
}
open(cleanPath);
}
get isLinux(): boolean {
return process.platform === "linux";
}
get isMacOS(): boolean {
return process.platform === "darwin";
}
get isWindows(): boolean {
return process.platform === "win32";
}
get version(): string {
return this.#version;
}
}
| /*
* Copyright 2022 Simon Edwards <simon@simonzone.com>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import open from "open";
import * as fs from "node:fs";
import * as path from "node:path";
import * as ExtensionApi from "@extraterm/extraterm-extension-api";
import { ClipboardImpl } from "./ClipboardImpl.js";
export class ApplicationImpl implements ExtensionApi.Application {
#clipboard = new ClipboardImpl();
#version = "";
constructor(version: string) {
this.#version = version;
}
get clipboard(): ExtensionApi.Clipboard {
return this.#clipboard;
}
openExternal(url: string): void {
if (url == null) {
return;
}
open(url);
}
showItemInFileManager(itemPath: string): void {
if (itemPath == null) {
return;
}
const stats = fs.statSync(itemPath);
let cleanPath = itemPath;
if (!stats.isDirectory()) {
cleanPath = path.dirname(itemPath);
}
open(cleanPath);
}
get isLinux(): boolean {
return process.platform === "linux";
}
get isMacOS(): boolean {
return process.platform === "darwin";
}
get isWindows(): boolean {
return process.platform === "win32";
}
get version(): string {
return this.#version;
}
}
| Fix `open()` in our extension API | Fix `open()` in our extension API
| TypeScript | mit | sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm | ---
+++
@@ -3,7 +3,7 @@
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
-import * as open from "open";
+import open from "open";
import * as fs from "node:fs";
import * as path from "node:path";
import * as ExtensionApi from "@extraterm/extraterm-extension-api"; |
90ce2cbe4726916eadc14fee40ce778452f4178a | src/app/global/keybindings/keybindings-actions.service.ts | src/app/global/keybindings/keybindings-actions.service.ts | import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { SelectorService } from '../../controller/selector/selector.service';
import { Action } from './keybindings.service';
@Injectable()
export class KeybindingsActionsService {
constructor(private selectorService: SelectorService) {
}
getAction(action: Action): () => void {
switch (action) {
case Action.SelectNext:
return () => this.selectorService.selectNext();
case Action.SelectPrevious:
return () => this.selectorService.selectPrevious();
}
return () => undefined; // remove later
}
}
| import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { SelectorService } from '../../controller/selector/selector.service';
import { Action } from './keybindings.service';
@Injectable()
export class KeybindingsActionsService {
constructor(private selectorService: SelectorService) {
}
getAction(action: Action): () => void {
switch (action) {
case Action.SelectNext:
return () => this.selectorService.selectNext();
case Action.SelectPrevious:
return () => this.selectorService.selectPrevious();
case Action.AudioPlayOrPause:
return () => undefined;
case Action.AudioStop:
return () => undefined;
case Action.AudioRepeat:
return () => undefined;
case Action.AddNote:
return () => undefined;
case Action.AddBPMChange:
return () => undefined;
case Action.AddTSChange:
return () => undefined;
case Action.AddPracticeSection:
return () => undefined;
case Action.AddSoloToggle:
return () => undefined;
case Action.AddStarPowerToggle:
return () => undefined;
case Action.ControlToggleNote1:
return () => undefined;
case Action.ControlToggleNote2:
return () => undefined;
case Action.ControlToggleNote3:
return () => undefined;
case Action.ControlToggleNote4:
return () => undefined;
case Action.ControlToggleNote5:
return () => undefined;
case Action.ControlToggleNote6:
return () => undefined;
case Action.ControlMoveForwards:
return () => undefined;
case Action.ControlMoveBackwards:
return () => undefined;
case Action.ControlSnapForwards:
return () => undefined;
case Action.ControlSnapBackwards:
return () => undefined;
case Action.ControlIncreaseLength:
return () => undefined;
case Action.ControlDecreaseLength:
return () => undefined;
case Action.ControlToggleHOPO:
return () => undefined;
case Action.ControlToggleTap:
return () => undefined;
case Action.ControlDelete:
return () => undefined;
case Action.TapInputSelectAll:
return () => undefined;
case Action.TapInputDeselectAll:
return () => undefined;
case Action.TapInputCreateNotes:
return () => undefined;
case Action.TapInputDeleteTimes:
return () => undefined;
case Action.DownloadChart:
return () => undefined;
}
}
}
| Add stubs for all unimplemented keybinding actions | feat: Add stubs for all unimplemented keybinding actions
| TypeScript | mit | nb48/chart-hero,nb48/chart-hero,nb48/chart-hero | ---
+++
@@ -16,7 +16,64 @@
return () => this.selectorService.selectNext();
case Action.SelectPrevious:
return () => this.selectorService.selectPrevious();
+ case Action.AudioPlayOrPause:
+ return () => undefined;
+ case Action.AudioStop:
+ return () => undefined;
+ case Action.AudioRepeat:
+ return () => undefined;
+ case Action.AddNote:
+ return () => undefined;
+ case Action.AddBPMChange:
+ return () => undefined;
+ case Action.AddTSChange:
+ return () => undefined;
+ case Action.AddPracticeSection:
+ return () => undefined;
+ case Action.AddSoloToggle:
+ return () => undefined;
+ case Action.AddStarPowerToggle:
+ return () => undefined;
+ case Action.ControlToggleNote1:
+ return () => undefined;
+ case Action.ControlToggleNote2:
+ return () => undefined;
+ case Action.ControlToggleNote3:
+ return () => undefined;
+ case Action.ControlToggleNote4:
+ return () => undefined;
+ case Action.ControlToggleNote5:
+ return () => undefined;
+ case Action.ControlToggleNote6:
+ return () => undefined;
+ case Action.ControlMoveForwards:
+ return () => undefined;
+ case Action.ControlMoveBackwards:
+ return () => undefined;
+ case Action.ControlSnapForwards:
+ return () => undefined;
+ case Action.ControlSnapBackwards:
+ return () => undefined;
+ case Action.ControlIncreaseLength:
+ return () => undefined;
+ case Action.ControlDecreaseLength:
+ return () => undefined;
+ case Action.ControlToggleHOPO:
+ return () => undefined;
+ case Action.ControlToggleTap:
+ return () => undefined;
+ case Action.ControlDelete:
+ return () => undefined;
+ case Action.TapInputSelectAll:
+ return () => undefined;
+ case Action.TapInputDeselectAll:
+ return () => undefined;
+ case Action.TapInputCreateNotes:
+ return () => undefined;
+ case Action.TapInputDeleteTimes:
+ return () => undefined;
+ case Action.DownloadChart:
+ return () => undefined;
}
- return () => undefined; // remove later
}
} |
9818dec74f94693ae4b88820bf2f72424ffb7a14 | app/scripts/modules/core/src/pagerDuty/js-worker-search.d.ts | app/scripts/modules/core/src/pagerDuty/js-worker-search.d.ts | declare module 'js-worker-search' {
type IndexMode = 'ALL_SUBSTRINGS' | 'EXACT_WORDS' | 'PREFIXES';
class SearchApi {
constructor(indexMode?: IndexMode, tokenizePattern?: RegExp, caseSensitive?: boolean);
public indexDocument(uid: any, text: string): SearchApi;
public search(query: string): Promise<Array<any>>;
}
export default SearchApi;
}
| declare module 'js-worker-search' {
type IndexMode = 'ALL_SUBSTRINGS' | 'EXACT_WORDS' | 'PREFIXES';
class SearchApi {
constructor(indexMode?: IndexMode, tokenizePattern?: RegExp, caseSensitive?: boolean);
public indexDocument(uid: any, text: string): SearchApi;
public search(query: string): Promise<any[]>;
}
export default SearchApi;
}
| Fix eslint warnings for @typescript-eslint/array-type | fix(eslint): Fix eslint warnings for @typescript-eslint/array-type
| TypeScript | apache-2.0 | duftler/deck,ajordens/deck,duftler/deck,icfantv/deck,spinnaker/deck,sgarlick987/deck,icfantv/deck,ajordens/deck,ajordens/deck,ajordens/deck,duftler/deck,spinnaker/deck,icfantv/deck,spinnaker/deck,sgarlick987/deck,sgarlick987/deck,duftler/deck,sgarlick987/deck,spinnaker/deck,icfantv/deck | ---
+++
@@ -4,7 +4,7 @@
class SearchApi {
constructor(indexMode?: IndexMode, tokenizePattern?: RegExp, caseSensitive?: boolean);
public indexDocument(uid: any, text: string): SearchApi;
- public search(query: string): Promise<Array<any>>;
+ public search(query: string): Promise<any[]>;
}
export default SearchApi; |
5119bb7c571e885790d1e71d7b57fe584f344563 | src/v2/Apps/Partner/Components/__tests__/NavigationTabs.jest.tsx | src/v2/Apps/Partner/Components/__tests__/NavigationTabs.jest.tsx | import { NavigationTabs_Test_PartnerQueryRawResponse } from "v2/__generated__/NavigationTabs_Test_PartnerQuery.graphql"
import { NavigationTabsFragmentContainer as NavigationTabs } from "v2/Apps/Partner/Components/NavigationTabs"
import { renderRelayTree } from "v2/DevTools"
import React from "react"
import { graphql } from "react-relay"
jest.unmock("react-relay")
jest.mock("v2/Components/RouteTabs")
describe("PartnerNavigationTabs", () => {
const getWrapper = async (
response: NavigationTabs_Test_PartnerQueryRawResponse["partner"] = NavigationTabsFixture
) => {
return await renderRelayTree({
Component: ({ partner }: any) => {
return <NavigationTabs partner={partner} />
},
query: graphql`
query NavigationTabs_Test_PartnerQuery @raw_response_type {
partner(id: "white-cube") {
...NavigationTabs_partner
}
}
`,
mockData: {
partner: response,
} as NavigationTabs_Test_PartnerQueryRawResponse,
})
}
it("renders all tabs by default", async () => {
const wrapper = await getWrapper()
const html = wrapper.html()
expect(html).toContain("Overview")
expect(html).toContain("Shows")
expect(html).toContain("Works")
expect(html).toContain("Artists")
expect(html).toContain("Articles")
expect(html).toContain("Contact")
})
})
const NavigationTabsFixture: NavigationTabs_Test_PartnerQueryRawResponse["partner"] = {
id: "white-cube",
slug: "white-cube",
}
| import React from "react"
import { graphql } from "react-relay"
import { setupTestWrapper } from "v2/DevTools/setupTestWrapper"
import { NavigationTabs_Test_PartnerQuery } from "v2/__generated__/NavigationTabs_Test_PartnerQuery.graphql"
import { NavigationTabsFragmentContainer as NavigationTabs } from "v2/Apps/Partner/Components/NavigationTabs"
jest.unmock("react-relay")
jest.mock("v2/Components/RouteTabs")
const { getWrapper } = setupTestWrapper<NavigationTabs_Test_PartnerQuery>({
Component: ({ partner }: any) => {
return <NavigationTabs partner={partner} />
},
query: graphql`
query NavigationTabs_Test_PartnerQuery @raw_response_type {
partner(id: "white-cube") {
...NavigationTabs_partner
}
}
`,
})
describe("PartnerNavigationTabs", () => {
it("renders all tabs by default", async () => {
const wrapper = await getWrapper({
Partner: () => ({ id: "white-cube", slug: "white-cube" }),
})
const html = wrapper.html()
expect(html).toContain("Overview")
expect(html).toContain("Shows")
expect(html).toContain("Works")
expect(html).toContain("Artists")
expect(html).toContain("Articles")
expect(html).toContain("Contact")
})
})
| Update navigation tabs tests to use setupTestWrapper | Update navigation tabs tests to use setupTestWrapper
| TypeScript | mit | joeyAghion/force,artsy/force,joeyAghion/force,artsy/force-public,artsy/force-public,joeyAghion/force,artsy/force,artsy/force,artsy/force,joeyAghion/force | ---
+++
@@ -1,35 +1,30 @@
-import { NavigationTabs_Test_PartnerQueryRawResponse } from "v2/__generated__/NavigationTabs_Test_PartnerQuery.graphql"
-import { NavigationTabsFragmentContainer as NavigationTabs } from "v2/Apps/Partner/Components/NavigationTabs"
-import { renderRelayTree } from "v2/DevTools"
import React from "react"
import { graphql } from "react-relay"
+import { setupTestWrapper } from "v2/DevTools/setupTestWrapper"
+import { NavigationTabs_Test_PartnerQuery } from "v2/__generated__/NavigationTabs_Test_PartnerQuery.graphql"
+import { NavigationTabsFragmentContainer as NavigationTabs } from "v2/Apps/Partner/Components/NavigationTabs"
jest.unmock("react-relay")
jest.mock("v2/Components/RouteTabs")
+const { getWrapper } = setupTestWrapper<NavigationTabs_Test_PartnerQuery>({
+ Component: ({ partner }: any) => {
+ return <NavigationTabs partner={partner} />
+ },
+ query: graphql`
+ query NavigationTabs_Test_PartnerQuery @raw_response_type {
+ partner(id: "white-cube") {
+ ...NavigationTabs_partner
+ }
+ }
+ `,
+})
+
describe("PartnerNavigationTabs", () => {
- const getWrapper = async (
- response: NavigationTabs_Test_PartnerQueryRawResponse["partner"] = NavigationTabsFixture
- ) => {
- return await renderRelayTree({
- Component: ({ partner }: any) => {
- return <NavigationTabs partner={partner} />
- },
- query: graphql`
- query NavigationTabs_Test_PartnerQuery @raw_response_type {
- partner(id: "white-cube") {
- ...NavigationTabs_partner
- }
- }
- `,
- mockData: {
- partner: response,
- } as NavigationTabs_Test_PartnerQueryRawResponse,
+ it("renders all tabs by default", async () => {
+ const wrapper = await getWrapper({
+ Partner: () => ({ id: "white-cube", slug: "white-cube" }),
})
- }
-
- it("renders all tabs by default", async () => {
- const wrapper = await getWrapper()
const html = wrapper.html()
expect(html).toContain("Overview")
@@ -40,8 +35,3 @@
expect(html).toContain("Contact")
})
})
-
-const NavigationTabsFixture: NavigationTabs_Test_PartnerQueryRawResponse["partner"] = {
- id: "white-cube",
- slug: "white-cube",
-} |
56daa5974b80d786c56b596dc6bcaadc7e34f119 | NavigationReactNative/src/NavigationBackAndroid.android.ts | NavigationReactNative/src/NavigationBackAndroid.android.ts | import { StateNavigator } from 'navigation';
import * as React from 'react';
import { BackAndroid } from 'react-native';
class NavigationBackAndroid extends React.Component<any, any> {
private onBack = () => {
var stateNavigator = this.getStateNavigator();
if (stateNavigator.canNavigateBack(1)) {
stateNavigator.navigateBack(1);
return true;
}
return false;
}
static contextTypes = {
stateNavigator: React.PropTypes.object
}
private getStateNavigator(): StateNavigator {
return this.props.stateNavigator || (this.context as any).stateNavigator;
}
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', this.onBack);
}
componentWillUnmount() {
BackAndroid.removeEventListener('hardwareBackPress', this.onBack);
}
}
export default NavigationBackAndroid;
| import { StateNavigator } from 'navigation';
import * as React from 'react';
import { BackAndroid } from 'react-native';
class NavigationBackAndroid extends React.Component<any, any> {
private onBack = () => {
var stateNavigator = this.getStateNavigator();
if (this.state.state === stateNavigator.stateContext.state) {
var listener = this.props.navigating;
var navigate = true;
if (listener)
navigate = listener();
if (navigate && stateNavigator.canNavigateBack(1))
stateNavigator.navigateBack(1);
return true;
}
return false;
}
constructor(props, context) {
super(props, context);
this.state = { state: this.getStateNavigator().stateContext.state };
}
static contextTypes = {
stateNavigator: React.PropTypes.object
}
private getStateNavigator(): StateNavigator {
return this.props.stateNavigator || (this.context as any).stateNavigator;
}
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', this.onBack);
}
componentWillUnmount() {
BackAndroid.removeEventListener('hardwareBackPress', this.onBack);
}
}
export default NavigationBackAndroid;
| Return false if context state doesn't match state | Return false if context state doesn't match state
Each scene will have its own NavigationBackAndroid component but only
the one corresponding to the current state should handle the back press
| TypeScript | apache-2.0 | grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation | ---
+++
@@ -5,11 +5,20 @@
class NavigationBackAndroid extends React.Component<any, any> {
private onBack = () => {
var stateNavigator = this.getStateNavigator();
- if (stateNavigator.canNavigateBack(1)) {
- stateNavigator.navigateBack(1);
+ if (this.state.state === stateNavigator.stateContext.state) {
+ var listener = this.props.navigating;
+ var navigate = true;
+ if (listener)
+ navigate = listener();
+ if (navigate && stateNavigator.canNavigateBack(1))
+ stateNavigator.navigateBack(1);
return true;
}
return false;
+ }
+ constructor(props, context) {
+ super(props, context);
+ this.state = { state: this.getStateNavigator().stateContext.state };
}
static contextTypes = {
stateNavigator: React.PropTypes.object |
1d303e0be4ddc9a4b476227a2f01d923aafeda13 | client/test/buildEncounter.ts | client/test/buildEncounter.ts | import { Encounter } from "../Encounter/Encounter";
import { SpellLibrary } from "../Library/SpellLibrary";
import { PlayerViewClient } from "../Player/PlayerViewClient";
import { DefaultRules, IRules } from "../Rules/Rules";
import { TextEnricher } from "../TextEnricher/TextEnricher";
export function buildStatBlockTextEnricher(rules: IRules) {
return new TextEnricher(jest.fn(), jest.fn(), jest.fn(), new SpellLibrary(null), rules);
}
export function buildEncounter() {
const rules = new DefaultRules();
const enricher = buildStatBlockTextEnricher(rules);
const encounter = new Encounter(null, jest.fn().mockReturnValue(null), jest.fn(), rules, enricher);
return encounter;
} | import { Encounter } from "../Encounter/Encounter";
import { DefaultRules, IRules } from "../Rules/Rules";
export function buildEncounter() {
const rules = new DefaultRules();
const encounter = new Encounter(null, jest.fn().mockReturnValue(null), jest.fn(), rules);
return encounter;
} | Remove enricher from test encounter | Remove enricher from test encounter
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -1,16 +1,8 @@
import { Encounter } from "../Encounter/Encounter";
-import { SpellLibrary } from "../Library/SpellLibrary";
-import { PlayerViewClient } from "../Player/PlayerViewClient";
import { DefaultRules, IRules } from "../Rules/Rules";
-import { TextEnricher } from "../TextEnricher/TextEnricher";
-
-export function buildStatBlockTextEnricher(rules: IRules) {
- return new TextEnricher(jest.fn(), jest.fn(), jest.fn(), new SpellLibrary(null), rules);
-}
export function buildEncounter() {
const rules = new DefaultRules();
- const enricher = buildStatBlockTextEnricher(rules);
- const encounter = new Encounter(null, jest.fn().mockReturnValue(null), jest.fn(), rules, enricher);
+ const encounter = new Encounter(null, jest.fn().mockReturnValue(null), jest.fn(), rules);
return encounter;
} |
2385558bea54b4abebbc5917921f1d0b477b2254 | packages/apollo-cache-control/src/__tests__/cacheControlSupport.ts | packages/apollo-cache-control/src/__tests__/cacheControlSupport.ts | import { buildSchema } from 'graphql';
import { makeExecutableSchema } from 'graphql-tools';
type FirstArg<F> = F extends (arg: infer A) => any ? A : never;
export function augmentTypeDefsWithCacheControlSupport(typeDefs) {
return (
`
enum CacheControlScope {
PUBLIC
PRIVATE
}
directive @cacheControl(
maxAge: Int
scope: CacheControlScope
) on FIELD_DEFINITION | OBJECT | INTERFACE
` + typeDefs
);
}
export function buildSchemaWithCacheControlSupport(source: string) {
return buildSchema(augmentTypeDefsWithCacheControlSupport(source));
}
export function makeExecutableSchemaWithCacheControlSupport(
options: FirstArg<typeof makeExecutableSchema>,
) {
return makeExecutableSchema({
...options,
typeDefs: augmentTypeDefsWithCacheControlSupport(options.typeDefs),
});
}
| import { buildSchema } from 'graphql';
import { makeExecutableSchema } from 'graphql-tools';
type FirstArg<F> = F extends (arg: infer A) => any ? A : never;
export function augmentTypeDefsWithCacheControlSupport(typeDefs: string) {
return (
`
enum CacheControlScope {
PUBLIC
PRIVATE
}
directive @cacheControl(
maxAge: Int
scope: CacheControlScope
) on FIELD_DEFINITION | OBJECT | INTERFACE
` + typeDefs
);
}
export function buildSchemaWithCacheControlSupport(source: string) {
return buildSchema(augmentTypeDefsWithCacheControlSupport(source));
}
export function makeExecutableSchemaWithCacheControlSupport(
options: FirstArg<typeof makeExecutableSchema> & { typeDefs: string },
) {
return makeExecutableSchema({
...options,
typeDefs: augmentTypeDefsWithCacheControlSupport(options.typeDefs),
});
}
| Fix types in `apollo-cache-control` test helper | Fix types in `apollo-cache-control` test helper
| TypeScript | mit | apollostack/apollo-server | ---
+++
@@ -3,7 +3,7 @@
type FirstArg<F> = F extends (arg: infer A) => any ? A : never;
-export function augmentTypeDefsWithCacheControlSupport(typeDefs) {
+export function augmentTypeDefsWithCacheControlSupport(typeDefs: string) {
return (
`
enum CacheControlScope {
@@ -24,7 +24,7 @@
}
export function makeExecutableSchemaWithCacheControlSupport(
- options: FirstArg<typeof makeExecutableSchema>,
+ options: FirstArg<typeof makeExecutableSchema> & { typeDefs: string },
) {
return makeExecutableSchema({
...options, |
8eff3d4139ee947e8063c787f591e65bd1b77749 | packages/skatejs/src/name.ts | packages/skatejs/src/name.ts | function dashCase(str: string): string {
return typeof str === 'string'
? str.split(/([_A-Z])/).reduce((one, two, idx) => {
const dash = !one || idx % 2 === 0 ? '' : '-';
two = two === '_' ? '' : two;
return `${one}${dash}${two.toLowerCase()}`;
})
: str;
}
function format(prefix: string, suffix: number): string {
return (
(prefix.indexOf('-') === -1 ? `x-${prefix}` : prefix) +
(suffix ? `-${suffix}` : '')
);
}
export function name(prefix: string = 'element'): string {
prefix = dashCase(prefix);
let suffix: number = 0;
while (customElements.get(format(prefix, suffix))) ++suffix;
return format(prefix, suffix);
}
| function dashcase(str: string): string {
return str.split(/([_A-Z])/).reduce((one, two, idx) => {
const dash = !one || idx % 2 === 0 ? '' : '-';
two = two === '_' ? '' : two;
return `${one}${dash}${two.toLowerCase()}`;
});
}
function format(prefix: string, suffix: number): string {
return (
(prefix.indexOf('-') === -1 ? `x-${prefix}` : prefix) +
(suffix ? `-${suffix}` : '')
);
}
export function name(prefix: string): string {
prefix = dashcase(prefix || 'element');
let suffix: number = 0;
while (customElements.get(format(prefix, suffix))) ++suffix;
return format(prefix, suffix);
}
| Remove redundant code from dash-casing function. Ensure 'element' is the prefix even if empty string is passed (or falsy if not using types). | Remove redundant code from dash-casing function. Ensure 'element' is the prefix even if empty string is passed (or falsy if not using types).
| TypeScript | mit | skatejs/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -1,11 +1,9 @@
-function dashCase(str: string): string {
- return typeof str === 'string'
- ? str.split(/([_A-Z])/).reduce((one, two, idx) => {
- const dash = !one || idx % 2 === 0 ? '' : '-';
- two = two === '_' ? '' : two;
- return `${one}${dash}${two.toLowerCase()}`;
- })
- : str;
+function dashcase(str: string): string {
+ return str.split(/([_A-Z])/).reduce((one, two, idx) => {
+ const dash = !one || idx % 2 === 0 ? '' : '-';
+ two = two === '_' ? '' : two;
+ return `${one}${dash}${two.toLowerCase()}`;
+ });
}
function format(prefix: string, suffix: number): string {
@@ -15,8 +13,8 @@
);
}
-export function name(prefix: string = 'element'): string {
- prefix = dashCase(prefix);
+export function name(prefix: string): string {
+ prefix = dashcase(prefix || 'element');
let suffix: number = 0;
while (customElements.get(format(prefix, suffix))) ++suffix;
return format(prefix, suffix); |
ad42e0e70fab75560b2ac67d278f6e0f1ef2681b | src/on_exit.ts | src/on_exit.ts | const signals: NodeJS.Signals[] = ['SIGINT', 'SIGHUP', 'SIGTERM', 'SIGQUIT'];
export function onExit(callback: () => Promise<void> | void) {
let callbackInvoked = false;
const callbackOnce = async () => {
if (!callbackInvoked) {
callbackInvoked = true;
await callback();
}
};
process.on('beforeExit', callbackOnce);
for (const signal of signals) {
process.on(signal, async signal => {
// https://nodejs.org/api/process.html#process_signal_events
process.exitCode = 128 /* TODO(dotdoom): + signal number */;
try {
await callbackOnce();
} finally {
// eslint-disable-next-line no-process-exit
process.exit();
}
});
}
process.on('uncaughtException', () => {
// https://nodejs.org/api/process.html#process_event_uncaughtexception
process.exitCode = 1;
callbackOnce();
});
}
| const signals: NodeJS.Signals[] = ['SIGINT', 'SIGHUP', 'SIGTERM', 'SIGQUIT'];
export function onExit(callback: () => Promise<void> | void) {
let callbackInvoked = false;
const callbackOnce = async () => {
if (!callbackInvoked) {
callbackInvoked = true;
await callback();
}
};
process.on('beforeExit', callbackOnce);
for (const signal of signals) {
process.on(signal, async signal => {
process.exitCode = 0;
try {
await callbackOnce();
} finally {
// eslint-disable-next-line no-process-exit
process.exit();
}
});
}
process.on('uncaughtException', () => {
// https://nodejs.org/api/process.html#process_event_uncaughtexception
process.exitCode = 1;
callbackOnce();
});
}
| Exit with code 0 when terminated gracefully | Exit with code 0 when terminated gracefully
| TypeScript | mit | dotdoom/comicsbot,dotdoom/comicsbot | ---
+++
@@ -12,8 +12,7 @@
process.on('beforeExit', callbackOnce);
for (const signal of signals) {
process.on(signal, async signal => {
- // https://nodejs.org/api/process.html#process_signal_events
- process.exitCode = 128 /* TODO(dotdoom): + signal number */;
+ process.exitCode = 0;
try {
await callbackOnce();
} finally { |
a8dd5da9969b88d4c28a441293ae1c805a0e974f | src/util/encode-blob.ts | src/util/encode-blob.ts | export default (blob: Blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = function() {
let result = reader.result as string
if (!result) {
return // result.onerror has already been called at this point
}
// Remove `data:*/*;base64,` prefix:
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
result = result.split(',')[1]
resolve(result)
}
reader.onerror = function() {
reject(reader.error)
}
})
| export default (blob: Blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = function() {
let result = reader.result as string
if (!result) {
return // result.onerror has already been called at this point
}
// Remove `data:*/*;base64,` prefix:
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
result = result.split(',')[1]
resolve(result)
}
reader.onerror = function() {
console.log('Got error encoding this blob', blob)
reject(reader.error)
}
})
| Add debugging line for blob encoding bug | Add debugging line for blob encoding bug
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -17,6 +17,7 @@
}
reader.onerror = function() {
+ console.log('Got error encoding this blob', blob)
reject(reader.error)
}
}) |
8b5fd086928403c22268958e7218c3d685944e01 | src/client/app/dashboard/realtime-statistic/realtime-statistic.module.ts | src/client/app/dashboard/realtime-statistic/realtime-statistic.module.ts | import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ChartModule } from 'angular2-highcharts';
import { RealtimeStatisticComponent } from './realtime-statistic.component';
// Import sub Components
import { RealtimeStreetComponent } from './sub-component/realtime-street.component';
// Import services
import { StreetService } from '../../service/street-service';
import { CSSHelper } from '../../utils/css.helper';
@NgModule({
imports: [
BrowserModule,
RouterModule,
HttpModule,
ChartModule
],
declarations: [
RealtimeStatisticComponent,
RealtimeStreetComponent
],
exports: [RealtimeStatisticComponent],
providers: [
StreetService,
CSSHelper
]
})
export class RealtimeStatisticModule { }
| import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ChartModule } from 'angular2-highcharts';
import { RealtimeStatisticComponent } from './realtime-statistic.component';
// Import sub Components
import { RealtimeStreetComponent } from './sub-component/realtime-street.component';
import { MinimapComponent } from './sub-component/minimap.component';
import { Typeahead } from 'ng2-typeahead';
// Import services
import { StreetService } from '../../service/street-service';
import { CameraService } from '../../service/camera-service';
import { CSSHelper } from '../../utils/css.helper';
@NgModule({
imports: [
BrowserModule,
RouterModule,
HttpModule,
ChartModule,
FormsModule
],
declarations: [
RealtimeStatisticComponent,
RealtimeStreetComponent,
MinimapComponent,
Typeahead
],
exports: [RealtimeStatisticComponent],
providers: [
StreetService,
CameraService,
CSSHelper
]
})
export class RealtimeStatisticModule { }
| Add minimap, typeahead (autocomplete for search bar) component | Add minimap, typeahead (autocomplete for search bar) component
| TypeScript | mit | CaoDuyThanh/WebAppClient,CaoDuyThanh/WebAppClient,CaoDuyThanh/WebAppClient | ---
+++
@@ -1,4 +1,5 @@
import { CommonModule } from '@angular/common';
+import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
@@ -9,9 +10,12 @@
// Import sub Components
import { RealtimeStreetComponent } from './sub-component/realtime-street.component';
+import { MinimapComponent } from './sub-component/minimap.component';
+import { Typeahead } from 'ng2-typeahead';
// Import services
import { StreetService } from '../../service/street-service';
+import { CameraService } from '../../service/camera-service';
import { CSSHelper } from '../../utils/css.helper';
@NgModule({
@@ -19,15 +23,19 @@
BrowserModule,
RouterModule,
HttpModule,
- ChartModule
+ ChartModule,
+ FormsModule
],
declarations: [
RealtimeStatisticComponent,
- RealtimeStreetComponent
+ RealtimeStreetComponent,
+ MinimapComponent,
+ Typeahead
],
exports: [RealtimeStatisticComponent],
providers: [
StreetService,
+ CameraService,
CSSHelper
]
}) |
06176008000a386fa6afb5c0f489576e6cdb5f0b | src/app/modules/wallet/components/guards/default-redirect-guard.component.ts | src/app/modules/wallet/components/guards/default-redirect-guard.component.ts | /**
* Redirects to route set in WalletTabHistoryService
* if one exists.
* @author Ben Hayward
*/
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { WalletTabHistoryService } from '../tab-history.service';
@Injectable()
export class DefaultRedirectGuard implements CanActivate {
constructor(
private router: Router,
private tabHistory: WalletTabHistoryService
) {}
/**
* Returns false, and handles conditional redirect
* dependant on whether history is set in WalletTabHistoryService
* @returns false
*/
canActivate() {
const lastTab = this.tabHistory.lastTab;
if (lastTab) {
this.router.navigateByUrl(`/wallet${lastTab}`);
return false;
}
// default redirect
this.router.navigateByUrl('/wallet/cash/earnings');
return true;
}
}
| /**
* Redirects to route set in WalletTabHistoryService
* if one exists.
* @author Ben Hayward
*/
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { WalletTabHistoryService } from '../tab-history.service';
@Injectable()
export class DefaultRedirectGuard implements CanActivate {
constructor(
private router: Router,
private tabHistory: WalletTabHistoryService
) {}
/**
* Returns false, and handles conditional redirect
* dependant on whether history is set in WalletTabHistoryService
* @returns false
*/
canActivate() {
const lastTab = this.tabHistory.lastTab;
if (lastTab) {
this.router.navigateByUrl(`/wallet${lastTab}`);
return false;
}
// default redirect
this.router.navigateByUrl('/wallet/tokens/rewards');
return true;
}
}
| Change default wallet page to tokens | Change default wallet page to tokens
| TypeScript | agpl-3.0 | Minds/front,Minds/front,Minds/front,Minds/front | ---
+++
@@ -28,7 +28,7 @@
}
// default redirect
- this.router.navigateByUrl('/wallet/cash/earnings');
+ this.router.navigateByUrl('/wallet/tokens/rewards');
return true;
}
} |
968bc904766891b6d7d5dc322d1a123888331a68 | src/lib/relay/config.tsx | src/lib/relay/config.tsx | import { NativeModules } from "react-native"
const { Emission } = NativeModules
let metaphysicsURL
let gravityURL
if (Emission && Emission.gravityAPIHost && Emission.metaphysicsAPIHost) {
metaphysicsURL = Emission.metaphysicsAPIHost
gravityURL = Emission.gravityAPIHost
} else {
metaphysicsURL = "https://metaphysics-production.artsy.net"
gravityURL = "https://api.artsy.net"
}
export { metaphysicsURL, gravityURL }
// Disable the native polyfill during development, which will make network requests show-up in the Chrome dev-tools.
// Specifically, in our case, we get to see the Relay requests.
//
// It will be `undefined` unless running inside Chrome.
//
declare var global: any
if (__DEV__ && global.originalXMLHttpRequest !== undefined) {
global.XMLHttpRequest = global.originalXMLHttpRequest
// tslint:disable-next-line:no-var-requires
require("react-relay/lib/RelayNetworkDebug").init()
}
| import { NativeModules } from "react-native"
const { Emission } = NativeModules
let metaphysicsURL
let gravityURL
if (Emission && Emission.gravityAPIHost && Emission.metaphysicsAPIHost) {
metaphysicsURL = Emission.metaphysicsAPIHost
gravityURL = Emission.gravityAPIHost
} else {
metaphysicsURL = "https://metaphysics-production.artsy.net"
gravityURL = "https://api.artsy.net"
}
export { metaphysicsURL, gravityURL }
// Disable the native polyfill during development, which will make network requests show-up in the Chrome dev-tools.
// Specifically, in our case, we get to see the Relay requests.
//
// It will be `undefined` unless running inside Chrome.
//
declare var global: any
if (__DEV__ && global.originalXMLHttpRequest !== undefined) {
/**
* TODO: Recording network access in Chrome Dev Tools is disabled for now.
*
* @see https://github.com/jhen0409/react-native-debugger/issues/209
*/
// global.XMLHttpRequest = global.originalXMLHttpRequest
// tslint:disable-next-line:no-var-requires
require("react-relay/lib/RelayNetworkDebug").init()
}
| Disable recording network activity in dev tools for now. | Disable recording network activity in dev tools for now.
| TypeScript | mit | artsy/eigen,artsy/eigen,artsy/emission,artsy/emission,artsy/eigen,artsy/eigen,artsy/emission,artsy/eigen,artsy/emission,artsy/emission,artsy/emission,artsy/emission,artsy/eigen,artsy/eigen | ---
+++
@@ -21,7 +21,13 @@
//
declare var global: any
if (__DEV__ && global.originalXMLHttpRequest !== undefined) {
- global.XMLHttpRequest = global.originalXMLHttpRequest
+ /**
+ * TODO: Recording network access in Chrome Dev Tools is disabled for now.
+ *
+ * @see https://github.com/jhen0409/react-native-debugger/issues/209
+ */
+ // global.XMLHttpRequest = global.originalXMLHttpRequest
+
// tslint:disable-next-line:no-var-requires
require("react-relay/lib/RelayNetworkDebug").init()
} |
45fc9b3ea1500f89544731aa698ce9cbfaf233ae | src/app/core/sync/sync-process.ts | src/app/core/sync/sync-process.ts | import {Observable} from 'rxjs';
export interface SyncProcess {
url: string;
cancel(): void;
observer: Observable<SyncStatus>;
}
export enum SyncStatus {
Offline = "OFFLINE",
Pushing = "PUSHING",
Pulling = "PULLING",
InSync = "IN_SYNC",
Error = "ERROR",
AuthenticationError = "AUTHENTICATION_ERROR",
AuthorizationError = "AUTHORIZATION_ERROR"
}
| import {Observable} from 'rxjs';
export interface SyncProcess {
url: string;
cancel(): void;
observer: Observable<SyncStatus>;
}
export enum SyncStatus {
Offline = 'OFFLINE',
Pushing = 'PUSHING',
Pulling = 'PULLING',
InSync = 'IN_SYNC',
Error = 'ERROR',
AuthenticationError = 'AUTHENTICATION_ERROR',
AuthorizationError = 'AUTHORIZATION_ERROR'
}
| Adjust to code style rules | Adjust to code style rules
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -11,11 +11,11 @@
export enum SyncStatus {
- Offline = "OFFLINE",
- Pushing = "PUSHING",
- Pulling = "PULLING",
- InSync = "IN_SYNC",
- Error = "ERROR",
- AuthenticationError = "AUTHENTICATION_ERROR",
- AuthorizationError = "AUTHORIZATION_ERROR"
+ Offline = 'OFFLINE',
+ Pushing = 'PUSHING',
+ Pulling = 'PULLING',
+ InSync = 'IN_SYNC',
+ Error = 'ERROR',
+ AuthenticationError = 'AUTHENTICATION_ERROR',
+ AuthorizationError = 'AUTHORIZATION_ERROR'
} |
8f8bab1cc286c946d2c3acacb46798aedb477b66 | src/components/Tabs/Tab/styled.ts | src/components/Tabs/Tab/styled.ts | import { override, styled } from "../../styles";
export interface ContainerProps {
isSelected: boolean;
theme: any;
}
export const Container = styled("div")<ContainerProps>(
{
boxSizing: "border-box",
cursor: "pointer",
display: ["inline-block", "-moz-inline-stack"],
fontSize: 16,
margin: 0,
padding: ".45em .9em .5em",
userSelect: "none"
},
({ theme, isSelected }) =>
isSelected
? {
borderBottom: "3px solid",
color: theme.colors?.brand?.primary ?? "#333"
}
: {
"&:hover": {
color: theme.colors?.brand?.primary ?? "#333"
},
borderBottom: "3px solid transparent"
},
override
);
| import { override, styled, Theme } from "../../styles";
export interface ContainerProps {
isSelected: boolean;
theme: Theme;
}
export const Container = styled("div")<ContainerProps>(
{
boxSizing: "border-box",
cursor: "pointer",
display: ["inline-block", "-moz-inline-stack"],
fontSize: 16,
margin: 0,
padding: ".45em .9em .5em",
userSelect: "none"
},
({ theme, isSelected }) =>
isSelected
? {
borderBottom: "3px solid",
color: theme.colors?.brand?.primary ?? "#333"
}
: {
"&:hover": {
color: theme.colors?.brand?.primary ?? "#333"
},
borderBottom: "3px solid transparent"
},
override
);
| Use correct type as per Thanh’s feedback | Use correct type as per Thanh’s feedback
| TypeScript | mit | sajari/sajari-sdk-react,sajari/sajari-sdk-react | ---
+++
@@ -1,8 +1,8 @@
-import { override, styled } from "../../styles";
+import { override, styled, Theme } from "../../styles";
export interface ContainerProps {
isSelected: boolean;
- theme: any;
+ theme: Theme;
}
export const Container = styled("div")<ContainerProps>( |
39821ac26433fe507ecafdf3b4b0b9e66e95c6cf | packages/apollo-server-core/src/utils/isDirectiveDefined.ts | packages/apollo-server-core/src/utils/isDirectiveDefined.ts | import { DocumentNode, Kind } from 'graphql/language';
import { gql } from '../';
export const isDirectiveDefined = (
typeDefs: DocumentNode[] | string,
directiveName: string,
): boolean => {
if (typeof typeDefs === 'string') {
return isDirectiveDefined([gql(typeDefs)], directiveName);
}
return typeDefs.some(typeDef =>
typeDef.hasOwnProperty('definitions')
? typeDef.definitions.some(
definition =>
definition.kind === Kind.DIRECTIVE_DEFINITION &&
definition.name.value === directiveName,
)
: false,
);
};
| import { DocumentNode, Kind } from 'graphql/language';
import { gql } from '../';
export const isDirectiveDefined = (
typeDefs: DocumentNode[] | string,
directiveName: string,
): boolean => {
if (typeof typeDefs === 'string') {
return isDirectiveDefined([gql(typeDefs)], directiveName);
}
return typeDefs.some(typeDef =>
Object.prototype.hasOwnProperty.call(typeDef, 'definitions')
? typeDef.definitions.some(
definition =>
definition.kind === Kind.DIRECTIVE_DEFINITION &&
definition.name.value === directiveName,
)
: false,
);
};
| Use `Object.prototype.hasOwnProperty.call` to be extra defensive. | Use `Object.prototype.hasOwnProperty.call` to be extra defensive.
| TypeScript | mit | apollostack/apollo-server | ---
+++
@@ -9,7 +9,7 @@
return isDirectiveDefined([gql(typeDefs)], directiveName);
}
return typeDefs.some(typeDef =>
- typeDef.hasOwnProperty('definitions')
+ Object.prototype.hasOwnProperty.call(typeDef, 'definitions')
? typeDef.definitions.some(
definition =>
definition.kind === Kind.DIRECTIVE_DEFINITION && |
ae6853c196932a6c472f6d98935d8697bb772fa8 | index.ts | index.ts | interface PolicyResult {
[key: string]: string[];
}
export = function (policy: string): PolicyResult {
return policy.split(';').reduce<PolicyResult>((result, directive) => {
const trimmed = directive.trim();
if (!trimmed) {
return result;
}
const split = trimmed.split(/\s+/g);
const key = split.shift() as string;
if (!Object.prototype.hasOwnProperty.call(result, key)) {
result[key] = split;
}
return result;
}, {});
}
| interface PolicyResult {
[key: string]: string[];
}
export = (policy: string): PolicyResult =>
policy.split(';').reduce<PolicyResult>((result, directive) => {
const [directiveKey, ...directiveValue] = directive.trim().split(/\s+/g);
if (!directiveKey || Object.prototype.hasOwnProperty.call(result, directiveKey)) {
return result;
} else {
return {
...result,
[directiveKey]: directiveValue,
};
}
}, {})
| Rewrite internals to reduce LOC and remove a type cast | Rewrite internals to reduce LOC and remove a type cast
| TypeScript | mit | helmetjs/content-security-policy-parser | ---
+++
@@ -2,20 +2,17 @@
[key: string]: string[];
}
-export = function (policy: string): PolicyResult {
- return policy.split(';').reduce<PolicyResult>((result, directive) => {
- const trimmed = directive.trim();
- if (!trimmed) {
+export = (policy: string): PolicyResult =>
+ policy.split(';').reduce<PolicyResult>((result, directive) => {
+ const [directiveKey, ...directiveValue] = directive.trim().split(/\s+/g);
+
+ if (!directiveKey || Object.prototype.hasOwnProperty.call(result, directiveKey)) {
return result;
+ } else {
+ return {
+ ...result,
+ [directiveKey]: directiveValue,
+ };
}
+ }, {})
- const split = trimmed.split(/\s+/g);
- const key = split.shift() as string;
-
- if (!Object.prototype.hasOwnProperty.call(result, key)) {
- result[key] = split;
- }
-
- return result;
- }, {});
-} |
8d789703755de018437fc9e122f8727367959a55 | src/app/map/rainfall-map-panel/rainfall-map-panel.component.spec.ts | src/app/map/rainfall-map-panel/rainfall-map-panel.component.spec.ts | /* tslint:disable:no-unused-variable */
/*!
* Rainfall Map Panel Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { LeafletMapService } from '../../leaflet';
import { RainfallMapPanelComponent } from './rainfall-map-panel.component';
describe('Component: RainfallMapPanel', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
Renderer,
LeafletMapService,
RainfallMapPanelComponent
]
});
});
it('should create an instance', inject([RainfallMapPanelComponent], (component: RainfallMapPanelComponent) => {
expect(component).toBeTruthy();
}));
});
| /* tslint:disable:no-unused-variable */
/*!
* Rainfall Map Panel Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { LeafletMapService } from '../../leaflet';
import { MockRouter } from '../../mocks/router';
import { RainfallMapPanelComponent } from './rainfall-map-panel.component';
describe('Component: RainfallMapPanel', () => {
const mockRouter = new MockRouter();
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
Renderer,
LeafletMapService,
RainfallMapPanelComponent,
{ provide: Router, useValue: mockRouter },
]
});
});
it('should create an instance', inject([RainfallMapPanelComponent], (component: RainfallMapPanelComponent) => {
expect(component).toBeTruthy();
}));
});
| Fix broken unit test due to newly injected dependency | Fix broken unit test due to newly injected dependency
| TypeScript | mit | ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps | ---
+++
@@ -9,17 +9,22 @@
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
+import { Router } from '@angular/router';
import { LeafletMapService } from '../../leaflet';
+import { MockRouter } from '../../mocks/router';
import { RainfallMapPanelComponent } from './rainfall-map-panel.component';
describe('Component: RainfallMapPanel', () => {
+ const mockRouter = new MockRouter();
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
Renderer,
LeafletMapService,
- RainfallMapPanelComponent
+ RainfallMapPanelComponent,
+
+ { provide: Router, useValue: mockRouter },
]
});
}); |
68881f35fc5020b944eae6ad0cf4b9f1e4f4099a | src/dispatcher/index.tsx | src/dispatcher/index.tsx | /**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import androidDevice from './androidDevice';
import iOSDevice from './iOSDevice';
import desktopDevice from './desktopDevice';
import application from './application';
import tracking from './tracking';
import server from './server';
import notifications from './notifications';
import plugins from './plugins';
import user from './user';
import {Logger} from '../fb-interfaces/Logger';
import {Store} from '../reducers/index';
import {Dispatcher} from './types';
export default function(store: Store, logger: Logger): () => Promise<void> {
const dispatchers: Array<Dispatcher> = [
application,
androidDevice,
iOSDevice,
desktopDevice,
tracking,
server,
notifications,
plugins,
user,
];
const globalCleanup = dispatchers
.map(dispatcher => dispatcher(store, logger))
.filter(Boolean);
return () => {
return Promise.all(globalCleanup).then(() => {});
};
}
| /**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import androidDevice from './androidDevice';
import iOSDevice from './iOSDevice';
import desktopDevice from './desktopDevice';
import application from './application';
import tracking from './tracking';
import server from './server';
import notifications from './notifications';
import plugins from './plugins';
import user from './user';
import {Logger} from '../fb-interfaces/Logger';
import {Store} from '../reducers/index';
import {Dispatcher} from './types';
import {notNull} from '../utils/typeUtils';
export default function(store: Store, logger: Logger): () => Promise<void> {
const dispatchers: Array<Dispatcher> = [
application,
store.getState().settingsState.enableAndroid ? androidDevice : null,
iOSDevice,
desktopDevice,
tracking,
server,
notifications,
plugins,
user,
].filter(notNull);
const globalCleanup = dispatchers
.map(dispatcher => dispatcher(store, logger))
.filter(Boolean);
return () => {
return Promise.all(globalCleanup).then(() => {});
};
}
| Use androidEnabled setting in dispatcher | Use androidEnabled setting in dispatcher
Summary:
Takes the androidEnabled setting and uses it to gate the android dispatcher.
Enables people without android sdk to use flipper (e.g. iOS engineers).
Reviewed By: priteshrnandgaonkar
Differential Revision: D17829810
fbshipit-source-id: 7d25580e65dee93ebfda7c5cc4c4cea03744e2ca
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -18,11 +18,12 @@
import {Logger} from '../fb-interfaces/Logger';
import {Store} from '../reducers/index';
import {Dispatcher} from './types';
+import {notNull} from '../utils/typeUtils';
export default function(store: Store, logger: Logger): () => Promise<void> {
const dispatchers: Array<Dispatcher> = [
application,
- androidDevice,
+ store.getState().settingsState.enableAndroid ? androidDevice : null,
iOSDevice,
desktopDevice,
tracking,
@@ -30,7 +31,7 @@
notifications,
plugins,
user,
- ];
+ ].filter(notNull);
const globalCleanup = dispatchers
.map(dispatcher => dispatcher(store, logger))
.filter(Boolean); |
a450b9ec76f7b2770482f772a86a16e9fe880807 | src/v2/Apps/Partner/Components/PartnerHeader/PartnerHeaderAddress.tsx | src/v2/Apps/Partner/Components/PartnerHeader/PartnerHeaderAddress.tsx | import React from "react"
import styled from "styled-components"
import { uniq } from "lodash"
import { PartnerHeader_partner } from "v2/__generated__/PartnerHeader_partner.graphql"
export const TextWithNoWrap = styled.span`
white-space: nowrap;
`
export const PartnerHeaderAddress: React.FC<
PartnerHeader_partner["locations"]
> = ({ edges }) => {
return (
<>
{uniq(edges.map(edge => edge.node.city?.trim()))
.filter(city => !!city)
.map<React.ReactNode>((city, index) => (
<TextWithNoWrap key={`${city}${index}`}>{city}</TextWithNoWrap>
))
.reduce((prev, curr, index) => [
prev,
// The last space character is used instead of a non-breaking character
// for better text wrapping behavior.
<React.Fragment key={index}> • </React.Fragment>,
curr,
])}
</>
)
}
| import React from "react"
import styled from "styled-components"
import { uniq } from "lodash"
import { media } from "@artsy/palette"
import { PartnerHeader_partner } from "v2/__generated__/PartnerHeader_partner.graphql"
export const TextWithNoWrap = styled.span`
white-space: nowrap;
${media.sm`
white-space: normal;
`};
`
export const PartnerHeaderAddress: React.FC<
PartnerHeader_partner["locations"]
> = ({ edges }) => {
return (
<>
{uniq(edges.map(edge => edge.node.city?.trim()))
.filter(city => !!city)
.map<React.ReactNode>((city, index) => (
<TextWithNoWrap key={`${city}${index}`}>{city}</TextWithNoWrap>
))
.reduce((prev, curr, index) => [
prev,
// The last space character is used instead of a non-breaking character
// for better text wrapping behavior.
<React.Fragment key={index}> • </React.Fragment>,
curr,
])}
</>
)
}
| Allow text wrapping for mobile | Allow text wrapping for mobile
| TypeScript | mit | artsy/force,joeyAghion/force,artsy/force-public,artsy/force-public,artsy/force,artsy/force,artsy/force,joeyAghion/force,joeyAghion/force,joeyAghion/force | ---
+++
@@ -1,10 +1,15 @@
import React from "react"
import styled from "styled-components"
import { uniq } from "lodash"
+import { media } from "@artsy/palette"
import { PartnerHeader_partner } from "v2/__generated__/PartnerHeader_partner.graphql"
export const TextWithNoWrap = styled.span`
white-space: nowrap;
+
+ ${media.sm`
+ white-space: normal;
+ `};
`
export const PartnerHeaderAddress: React.FC<
PartnerHeader_partner["locations"] |
593c2fe1ebe619d740dbf7b0111a091bc22fdf8c | src/main/webapp/assets/grunt/ts/filter/SeasonColorFilter.ts | src/main/webapp/assets/grunt/ts/filter/SeasonColorFilter.ts | module Filter {
"use strict";
export function SeasonColorFilter() {
return (input:any):any => {
if (input === "winter") {
return "#5141D9";
} else if (input === "spring") {
return "#B2F63D";
} else if (input === "summer") {
return "#FF4540";
} else if (input === "autumn") {
return "#FFAC40";
} else {
return "#000000";
}
};
}
}
| module Filter {
"use strict";
export function SeasonColorFilter() {
return (input:number):string => {
if (input === 1) {
return "#5141D9";
} else if (input === 2) {
return "#B2F63D";
} else if (input === 3) {
return "#FF4540";
} else if (input === 4) {
return "#FFAC40";
} else {
return "#000000";
}
};
}
}
| Fix season type. string to number. | Fix season type. string to number.
| TypeScript | mit | tsukaby/anime-lineup,tsukaby/anime-lineup,tsukaby/anime-lineup,tsukaby/anime-lineup | ---
+++
@@ -2,14 +2,14 @@
"use strict";
export function SeasonColorFilter() {
- return (input:any):any => {
- if (input === "winter") {
+ return (input:number):string => {
+ if (input === 1) {
return "#5141D9";
- } else if (input === "spring") {
+ } else if (input === 2) {
return "#B2F63D";
- } else if (input === "summer") {
+ } else if (input === 3) {
return "#FF4540";
- } else if (input === "autumn") {
+ } else if (input === 4) {
return "#FFAC40";
} else {
return "#000000"; |
53752835231af5b4d837411fafc02ab157970020 | app/login/login.component.ts | app/login/login.component.ts | import { Component, OnInit, ViewChild } from "@angular/core";
import { UserService } from "../services";
import { User } from "../models";
import { Observable } from "rxjs/Observable";
import { EventData } from "data/observable";
import { Router } from "@angular/router";
@Component({
selector: "Login",
moduleId: module.id,
templateUrl: "./login.component.html"
})
export class LoginComponent implements OnInit {
public userId = "";
constructor(private router: Router, private userService: UserService) {
this.userService.currentUserId = undefined;
}
ngOnInit(): void {
}
onTap(): void {
const numUserId = Number(this.userId);
if (numUserId != NaN) {
this.userService.currentUserId = numUserId;
console.log(this.userService.currentUserId);
this.router.navigate(["/"]);
} else {
// handle error
}
}
} | import { Component, OnInit, ViewChild } from "@angular/core";
import { UserService } from "../services";
import { User } from "../models";
import { Observable } from "rxjs/Observable";
import { EventData } from "data/observable";
import { Router } from "@angular/router";
import { Page } from "ui/page";
@Component({
selector: "Login",
moduleId: module.id,
templateUrl: "./login.component.html"
})
export class LoginComponent implements OnInit {
public userId = "";
constructor(private _page: Page, private router: Router, private userService: UserService) {
this._page.actionBarHidden = true;
this.userService.currentUserId = undefined;
}
ngOnInit(): void {
}
onTap(): void {
const numUserId = Number(this.userId);
if (numUserId != NaN) {
this.userService.currentUserId = numUserId;
console.log(this.userService.currentUserId);
this.router.navigate(["/home"]);
} else {
// handle error
}
}
} | Remove actionbar on login page | Remove actionbar on login page
| TypeScript | mit | etabakov/fivekmrun-app,etabakov/fivekmrun-app,etabakov/fivekmrun-app | ---
+++
@@ -4,6 +4,7 @@
import { Observable } from "rxjs/Observable";
import { EventData } from "data/observable";
import { Router } from "@angular/router";
+import { Page } from "ui/page";
@Component({
selector: "Login",
@@ -13,7 +14,8 @@
export class LoginComponent implements OnInit {
public userId = "";
- constructor(private router: Router, private userService: UserService) {
+ constructor(private _page: Page, private router: Router, private userService: UserService) {
+ this._page.actionBarHidden = true;
this.userService.currentUserId = undefined;
}
@@ -26,7 +28,7 @@
if (numUserId != NaN) {
this.userService.currentUserId = numUserId;
console.log(this.userService.currentUserId);
- this.router.navigate(["/"]);
+ this.router.navigate(["/home"]);
} else {
// handle error
} |
bcc6f3117f19dd5ee2198dc2f2caddb7883261a9 | src/webauthn.ts | src/webauthn.ts | import {base64urlToBuffer, bufferToBase64url} from "./base64url";
import {CredentialCreationOptionsJSON, CredentialRequestOptionsJSON, PublicKeyCredentialWithAssertionJSON, PublicKeyCredentialWithAttestationJSON} from "./json";
import {convert} from "./schema-format";
import {credentialCreationOptions, credentialRequestOptions, publicKeyCredentialWithAssertion, publicKeyCredentialWithAttestation} from "./webauthn-schema";
export async function create(requestJSON: CredentialCreationOptionsJSON): Promise<PublicKeyCredentialWithAttestationJSON> {
const request = convert(base64urlToBuffer, credentialCreationOptions, requestJSON);
const credential = (await navigator.credentials.create(request)) as PublicKeyCredential;
return convert(bufferToBase64url, publicKeyCredentialWithAttestation, credential);
}
export async function get(requestJSON: CredentialRequestOptionsJSON): Promise<PublicKeyCredentialWithAssertionJSON> {
const request = convert(base64urlToBuffer, credentialRequestOptions, requestJSON);
const response = (await navigator.credentials.get(request)) as PublicKeyCredential;
return convert(bufferToBase64url, publicKeyCredentialWithAssertion, response);
}
declare global {
interface Window {
PublicKeyCredential: any | undefined;
}
}
// This function does a simple check to test for the credential management API
// functions we need, and an indication of public credential authentication
// support.
// https://developers.google.com/web/updates/2018/03/webauthn-credential-management
export function supported(): boolean {
return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential);
}
| import {base64urlToBuffer, bufferToBase64url} from "./base64url";
import {CredentialCreationOptionsJSON, CredentialRequestOptionsJSON, PublicKeyCredentialWithAssertionJSON, PublicKeyCredentialWithAttestationJSON} from "./json";
import {convert} from "./schema-format";
import {credentialCreationOptions, credentialRequestOptions, publicKeyCredentialWithAssertion, publicKeyCredentialWithAttestation} from "./webauthn-schema";
export async function create(requestJSON: CredentialCreationOptionsJSON): Promise<PublicKeyCredentialWithAttestationJSON> {
const request = convert(base64urlToBuffer, credentialCreationOptions, requestJSON);
const credential = (await navigator.credentials.create(request)) as PublicKeyCredential;
return convert(bufferToBase64url, publicKeyCredentialWithAttestation, credential);
}
export async function get(requestJSON: CredentialRequestOptionsJSON): Promise<PublicKeyCredentialWithAssertionJSON> {
const request = convert(base64urlToBuffer, credentialRequestOptions, requestJSON);
const response = (await navigator.credentials.get(request)) as PublicKeyCredential;
return convert(bufferToBase64url, publicKeyCredentialWithAssertion, response);
}
declare global {
interface Window {
PublicKeyCredential: any | undefined;
}
}
// This function does a simple check to test for the credential management API
// functions we need, and an indication of public key credential authentication
// support.
// https://developers.google.com/web/updates/2018/03/webauthn-credential-management
export function supported(): boolean {
return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential);
}
| Fix documentation: s/public credential/public key credential/ | Fix documentation: s/public credential/public key credential/
| TypeScript | mit | github/webauthn-json,github/webauthn-json,github/webauthn-json | ---
+++
@@ -22,7 +22,7 @@
}
// This function does a simple check to test for the credential management API
-// functions we need, and an indication of public credential authentication
+// functions we need, and an indication of public key credential authentication
// support.
// https://developers.google.com/web/updates/2018/03/webauthn-credential-management
export function supported(): boolean { |
8ab504cb23a256636c5a542d6eae1553ed27b56f | source/CroquetAustralia.Website/app/tournaments/scripts/Tournament.ts | source/CroquetAustralia.Website/app/tournaments/scripts/Tournament.ts | module App {
export class Tournament {
constructor(
public id: string,
public title: string,
public startsOn: Date,
public endsOn: Date,
public location: string,
public events: TournamentItem[],
public functions: TournamentItem[],
public merchandise: TournamentItem[]) {
}
discountChanged(player: TournamentPlayer) {
const discountPercentage = (player.fullTimeStudentUnder25 || player.under21) ? 50 : 0;
this.events.forEach((event: TournamentItem) => {
event.discountPercentage = discountPercentage;
});
}
eventsAreOpen(): boolean {
return false;
}
eventsAreClosed(): boolean {
return !this.eventsAreOpen();
}
isClosed(): boolean {
return !this.isOpen();
}
isOpen(): boolean {
return true;
}
totalPayable(): number {
return this.allTournamentItems()
.filter(item => item.quantity > 0)
.map(item => item.totalPrice())
.reduce((previousValue, currentValue) => (previousValue + currentValue), 0);
}
private allTournamentItems(): TournamentItem[] {
return this.events.concat(this.functions).concat(this.merchandise);
}
}
} | module App {
export class Tournament {
constructor(
public id: string,
public title: string,
public startsOn: Date,
public endsOn: Date,
public location: string,
public events: TournamentItem[],
public functions: TournamentItem[],
public merchandise: TournamentItem[]) {
}
discountChanged(player: TournamentPlayer) {
const discountPercentage = (player.fullTimeStudentUnder25 || player.under21) ? 50 : 0;
this.events.forEach((event: TournamentItem) => {
event.discountPercentage = discountPercentage;
});
}
eventsAreOpen(): boolean {
return false;
}
eventsAreClosed(): boolean {
return !this.eventsAreOpen();
}
isClosed(): boolean {
return !this.isOpen();
}
isOpen(): boolean {
return false;
}
totalPayable(): number {
return this.allTournamentItems()
.filter(item => item.quantity > 0)
.map(item => item.totalPrice())
.reduce((previousValue, currentValue) => (previousValue + currentValue), 0);
}
private allTournamentItems(): TournamentItem[] {
return this.events.concat(this.functions).concat(this.merchandise);
}
}
} | Fix 'Stop accepting entries at 4 March 2016 15:00 AEST' | Fix 'Stop accepting entries at 4 March 2016 15:00 AEST'
| TypeScript | mit | croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/website-application | ---
+++
@@ -32,7 +32,7 @@
}
isOpen(): boolean {
- return true;
+ return false;
}
totalPayable(): number { |
32115111602ceacfc55691016636215d9c1b9ca0 | packages/core/src/index.ts | packages/core/src/index.ts | /**
* FoalTS
* Copyright(c) 2017-2020 Loïc Poullain <loic.poullain@centraliens.net>
* Released under the MIT License.
*/
export * from './common';
export * from './core';
export * from './express';
export * from './openapi';
export * from './sessions';
| /**
* FoalTS
* Copyright(c) 2017-2020 Loïc Poullain <loic.poullain@centraliens.net>
* Released under the MIT License.
*/
try {
const version = process.versions.node;
const NODE_MAJOR_VERSION = parseInt(version.split('.')[0], 10);
if (NODE_MAJOR_VERSION < 10) {
console.warn(`[Warning] You are using version ${version} of Node. FoalTS requires at least version 10.`);
}
} finally {}
export * from './common';
export * from './core';
export * from './express';
export * from './openapi';
export * from './sessions';
| Add warning on Node supported versions | Add warning on Node supported versions
| TypeScript | mit | FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal | ---
+++
@@ -4,6 +4,14 @@
* Released under the MIT License.
*/
+try {
+ const version = process.versions.node;
+ const NODE_MAJOR_VERSION = parseInt(version.split('.')[0], 10);
+ if (NODE_MAJOR_VERSION < 10) {
+ console.warn(`[Warning] You are using version ${version} of Node. FoalTS requires at least version 10.`);
+ }
+} finally {}
+
export * from './common';
export * from './core';
export * from './express'; |
8aeff70e48dc4d9221b57e9810b0e5e4a4920af8 | tests/cases/conformance/es6/Symbols/symbolDeclarationEmit11.ts | tests/cases/conformance/es6/Symbols/symbolDeclarationEmit11.ts | //@target: ES6
//@declaration: true
class C {
static [Symbol.iterator] = 0;
static [Symbol.toPrimitive]() { }
static get [Symbol.toPrimitive]() { return ""; }
static set [Symbol.toPrimitive](x) { }
} | //@target: ES6
//@declaration: true
class C {
static [Symbol.iterator] = 0;
static [Symbol.isConcatSpreadable]() { }
static get [Symbol.toPrimitive]() { return ""; }
static set [Symbol.toPrimitive](x) { }
} | Fix a test so that we don't get duplicate declaration errors. | Fix a test so that we don't get duplicate declaration errors.
| TypeScript | apache-2.0 | gdi2290/TypeScript,jwbay/TypeScript,mmoskal/TypeScript,bpowers/TypeScript,weswigham/TypeScript,synaptek/TypeScript,SaschaNaz/TypeScript,fabioparra/TypeScript,jeremyepling/TypeScript,sassson/TypeScript,alexeagle/TypeScript,billti/TypeScript,AbubakerB/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,mihailik/TypeScript,OlegDokuka/TypeScript,keir-rex/TypeScript,chuckjaz/TypeScript,ropik/TypeScript,nagyistoce/TypeScript,nojvek/TypeScript,kumikumi/TypeScript,shovon/TypeScript,ropik/TypeScript,mihailik/TypeScript,samuelhorwitz/typescript,jwbay/TypeScript,Eyas/TypeScript,jeremyepling/TypeScript,DLehenbauer/TypeScript,ziacik/TypeScript,jeremyepling/TypeScript,evgrud/TypeScript,RReverser/TypeScript,ZLJASON/TypeScript,donaldpipowitch/TypeScript,zhengbli/TypeScript,ionux/TypeScript,donaldpipowitch/TypeScript,Raynos/TypeScript,msynk/TypeScript,nycdotnet/TypeScript,fearthecowboy/TypeScript,fearthecowboy/TypeScript,enginekit/TypeScript,Microsoft/TypeScript,nycdotnet/TypeScript,shanexu/TypeScript,microsoft/TypeScript,basarat/TypeScript,SimoneGianni/TypeScript,enginekit/TypeScript,moander/TypeScript,sassson/TypeScript,SmallAiTT/TypeScript,hoanhtien/TypeScript,samuelhorwitz/typescript,moander/TypeScript,synaptek/TypeScript,DanielRosenwasser/TypeScript,bpowers/TypeScript,ZLJASON/TypeScript,zmaruo/TypeScript,evgrud/TypeScript,enginekit/TypeScript,DLehenbauer/TypeScript,kumikumi/TypeScript,OlegDokuka/TypeScript,mszczepaniak/TypeScript,mcanthony/TypeScript,Viromo/TypeScript,rodrigues-daniel/TypeScript,chocolatechipui/TypeScript,erikmcc/TypeScript,moander/TypeScript,ziacik/TypeScript,Eyas/TypeScript,RyanCavanaugh/TypeScript,shiftkey/TypeScript,plantain-00/TypeScript,mmoskal/TypeScript,Raynos/TypeScript,weswigham/TypeScript,webhost/TypeScript,ziacik/TypeScript,SmallAiTT/TypeScript,weswigham/TypeScript,shovon/TypeScript,TukekeSoft/TypeScript,nojvek/TypeScript,webhost/TypeScript,rodrigues-daniel/TypeScript,impinball/TypeScript,webhost/TypeScript,yazeng/TypeScript,shiftkey/TypeScript,AbubakerB/TypeScript,Eyas/TypeScript,zmaruo/TypeScript,chocolatechipui/TypeScript,RyanCavanaugh/TypeScript,Mqgh2013/TypeScript,hitesh97/TypeScript,blakeembrey/TypeScript,tinganho/TypeScript,suto/TypeScript,kitsonk/TypeScript,HereSinceres/TypeScript,sassson/TypeScript,hoanhtien/TypeScript,hoanhtien/TypeScript,vilic/TypeScript,progre/TypeScript,moander/TypeScript,SaschaNaz/TypeScript,TukekeSoft/TypeScript,bpowers/TypeScript,progre/TypeScript,HereSinceres/TypeScript,basarat/TypeScript,Viromo/TypeScript,synaptek/TypeScript,thr0w/Thr0wScript,kimamula/TypeScript,fabioparra/TypeScript,MartyIX/TypeScript,mcanthony/TypeScript,matthewjh/TypeScript,rodrigues-daniel/TypeScript,nycdotnet/TypeScript,tempbottle/TypeScript,kumikumi/TypeScript,germ13/TypeScript,rgbkrk/TypeScript,erikmcc/TypeScript,plantain-00/TypeScript,tempbottle/TypeScript,shovon/TypeScript,HereSinceres/TypeScript,kitsonk/TypeScript,Eyas/TypeScript,kingland/TypeScript,rgbkrk/TypeScript,yortus/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,ropik/TypeScript,JohnZ622/TypeScript,suto/TypeScript,yortus/TypeScript,matthewjh/TypeScript,Microsoft/TypeScript,kingland/TypeScript,MartyIX/TypeScript,DanielRosenwasser/TypeScript,mihailik/TypeScript,DanielRosenwasser/TypeScript,shanexu/TypeScript,donaldpipowitch/TypeScript,ionux/TypeScript,OlegDokuka/TypeScript,pcan/TypeScript,JohnZ622/TypeScript,nagyistoce/TypeScript,SimoneGianni/TypeScript,germ13/TypeScript,donaldpipowitch/TypeScript,chocolatechipui/TypeScript,jbondc/TypeScript,ZLJASON/TypeScript,tinganho/TypeScript,msynk/TypeScript,kingland/TypeScript,pcan/TypeScript,gonifade/TypeScript,basarat/TypeScript,yortus/TypeScript,jdavidberger/TypeScript,zhengbli/TypeScript,mszczepaniak/TypeScript,vilic/TypeScript,Mqgh2013/TypeScript,MartyIX/TypeScript,impinball/TypeScript,gonifade/TypeScript,SmallAiTT/TypeScript,abbasmhd/TypeScript,matthewjh/TypeScript,ziacik/TypeScript,jamesrmccallum/TypeScript,blakeembrey/TypeScript,mcanthony/TypeScript,SimoneGianni/TypeScript,vilic/TypeScript,chuckjaz/TypeScript,kpreisser/TypeScript,abbasmhd/TypeScript,DLehenbauer/TypeScript,basarat/TypeScript,samuelhorwitz/typescript,alexeagle/TypeScript,evgrud/TypeScript,keir-rex/TypeScript,blakeembrey/TypeScript,mszczepaniak/TypeScript,MartyIX/TypeScript,pcan/TypeScript,kpreisser/TypeScript,synaptek/TypeScript,Mqgh2013/TypeScript,erikmcc/TypeScript,jdavidberger/TypeScript,jteplitz602/TypeScript,Raynos/TypeScript,progre/TypeScript,ionux/TypeScript,blakeembrey/TypeScript,JohnZ622/TypeScript,yazeng/TypeScript,plantain-00/TypeScript,SaschaNaz/TypeScript,AbubakerB/TypeScript,vilic/TypeScript,nycdotnet/TypeScript,thr0w/Thr0wScript,kimamula/TypeScript,nagyistoce/TypeScript,suto/TypeScript,jamesrmccallum/TypeScript,kpreisser/TypeScript,chuckjaz/TypeScript,RReverser/TypeScript,samuelhorwitz/typescript,TukekeSoft/TypeScript,ionux/TypeScript,zhengbli/TypeScript,billti/TypeScript,billti/TypeScript,jbondc/TypeScript,yortus/TypeScript,germ13/TypeScript,Viromo/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,Viromo/TypeScript,ropik/TypeScript,mcanthony/TypeScript,minestarks/TypeScript,gonifade/TypeScript,jbondc/TypeScript,jwbay/TypeScript,jteplitz602/TypeScript,erikmcc/TypeScript,SaschaNaz/TypeScript,evgrud/TypeScript,mmoskal/TypeScript,mmoskal/TypeScript,microsoft/TypeScript,shanexu/TypeScript,Microsoft/TypeScript,Raynos/TypeScript,hitesh97/TypeScript,mihailik/TypeScript,zmaruo/TypeScript,hitesh97/TypeScript,thr0w/Thr0wScript,jwbay/TypeScript,microsoft/TypeScript,impinball/TypeScript,chuckjaz/TypeScript,fearthecowboy/TypeScript,plantain-00/TypeScript,jteplitz602/TypeScript,AbubakerB/TypeScript,abbasmhd/TypeScript,shiftkey/TypeScript,fabioparra/TypeScript,RReverser/TypeScript,yazeng/TypeScript,tempbottle/TypeScript,tinganho/TypeScript,thr0w/Thr0wScript,msynk/TypeScript,rodrigues-daniel/TypeScript,kimamula/TypeScript,jamesrmccallum/TypeScript,kimamula/TypeScript,rgbkrk/TypeScript,minestarks/TypeScript,shanexu/TypeScript,minestarks/TypeScript,JohnZ622/TypeScript,keir-rex/TypeScript,jdavidberger/TypeScript,DanielRosenwasser/TypeScript,fabioparra/TypeScript | ---
+++
@@ -2,7 +2,7 @@
//@declaration: true
class C {
static [Symbol.iterator] = 0;
- static [Symbol.toPrimitive]() { }
+ static [Symbol.isConcatSpreadable]() { }
static get [Symbol.toPrimitive]() { return ""; }
static set [Symbol.toPrimitive](x) { }
} |
d4e2a7d642f17addc2ede2f4672c0cd287dda90c | web/frontend/app/App.tsx | web/frontend/app/App.tsx | 'use strict';
import * as React from 'react';
import { Router, browserHistory } from 'react-router';
import { Provider } from 'react-redux'
import {routes} from './routes'
import { createStore } from './store'
import { isTokenValid, getToken, setToken, removeToken } from '../common/lib/token'
import { fetch } from '../common/lib/fetch'
let store = createStore()
export default class App extends React.Component<{}, {}> {
componentWillMount() {
store.dispatch(dispatch => {
if(isTokenValid()) {
return fetch({
admin: false,
method: 'POST',
args: {
token: getToken(),
},
resource: '/renew-token',
token: getToken(),
})
.then((result:any) => {
if (result.success) {
setToken(result.token)
dispatch({
type: "INIT_AUTH",
username: result.username,
accessLevel: result.accessLevel,
})
} else {
removeToken()
}
})
}
})
}
render() {
return (
<Provider store={store}>
<Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)} />
</Provider>
);
}
} | 'use strict';
import * as React from 'react';
import { Router, browserHistory } from 'react-router';
import { Provider } from 'react-redux'
import {routes} from './routes'
import { createStore } from './store'
import { isTokenValid, getToken, setToken, removeToken } from '../common/lib/token'
import { fetch } from '../common/lib/fetch'
let store = createStore()
export default class App extends React.Component<{}, {}> {
componentWillMount() {
store.dispatch(dispatch => {
if(isTokenValid()) {
return fetch({
admin: false,
method: 'POST',
args: {
token: getToken(),
},
resource: '/renew-token',
token: getToken(),
})
.then((result:any) => {
if (result.success) {
setToken(result.token)
dispatch({
type: "INIT_AUTH",
username: result.username,
accessLevel: result.accessLevel,
})
} else {
removeToken()
dispatch({
type: "INIT_AUTH",
username: "guest",
accessLevel: "guest",
})
}
})
} else {
dispatch({
type: "INIT_AUTH",
username: "guest",
accessLevel: "guest",
})
}
})
}
render() {
return (
<Provider store={store}>
<Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)} />
</Provider>
);
}
} | Initialize to username and accessLevel to guest if no valid token is found. | Initialize to username and accessLevel to guest if no valid token is found.
| TypeScript | mit | sainthkh/ko-academy,sainthkh/ko-academy | ---
+++
@@ -34,7 +34,18 @@
})
} else {
removeToken()
+ dispatch({
+ type: "INIT_AUTH",
+ username: "guest",
+ accessLevel: "guest",
+ })
}
+ })
+ } else {
+ dispatch({
+ type: "INIT_AUTH",
+ username: "guest",
+ accessLevel: "guest",
})
}
}) |
7f0b70290038f48392f14e1841cd3e418bf0146c | src/invitations/RoleField.tsx | src/invitations/RoleField.tsx | import * as React from 'react';
import { Link } from '@waldur/core/Link';
import { getUUID } from '@waldur/core/utils';
import { translate } from '@waldur/i18n';
export const RoleField = ({ invitation }) => {
if (invitation.customer_role) {
return <>{translate('owner')}</>;
} else if (invitation.project_role) {
return (
<Link
state="project.details"
params={{ uuid: getUUID(invitation.project) }}
label={translate('{role} in {project}', {
role: translate(invitation.project_role),
project: invitation.project_name,
})}
/>
);
}
};
| import * as React from 'react';
import { Link } from '@waldur/core/Link';
import { getUUID } from '@waldur/core/utils';
import { translate } from '@waldur/i18n';
export const RoleField = ({ invitation }) => {
if (invitation.customer_role) {
return <>{translate('owner')}</>;
} else if (invitation.project_role) {
if (!invitation.project) {
return invitation.project_role;
}
return (
<Link
state="project.details"
params={{ uuid: getUUID(invitation.project) }}
label={translate('{role} in {project}', {
role: translate(invitation.project_role),
project: invitation.project_name,
})}
/>
);
}
};
| Fix invitation role rendering if project has been deleted. | Fix invitation role rendering if project has been deleted.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -8,6 +8,9 @@
if (invitation.customer_role) {
return <>{translate('owner')}</>;
} else if (invitation.project_role) {
+ if (!invitation.project) {
+ return invitation.project_role;
+ }
return (
<Link
state="project.details" |
e2ee129d34958cf0fe83427ebb937831ebea1e5d | src/utils/index.ts | src/utils/index.ts | export function getRows<T>(grid: T[]): T[][] {
const size = Math.sqrt(grid.length);
const copy = grid.concat([]);
return getArray(size).map(() => copy.splice(0, size));
}
export function getColumns<T>(grid: T[]): T[][] {
return getRows(transpose(grid));
}
export function getDiagonals<T>(grid: T[]): T[][] {
const size = Math.sqrt(grid.length);
const lesser = size - 1;
const last = grid.length - 1;
return [
grid.filter((x, i) => Math.floor(i / size) === i % size),
grid.filter((x, i) => i > 0 && i % lesser === 0 && i !== last)
];
}
function getArray(length: number): number[] {
return Array.apply(null, { length }).map(Number.call, Number);
}
export function transpose<T>(grid: Array<T>): Array<T> {
const size = Math.sqrt(grid.length);
return grid.map((x, i) => grid[Math.floor(i / size) + ((i % size) * size)]);
}
| export function getRows<T>(grid: T[]): T[][] {
const size = Math.sqrt(grid.length);
const copy = grid.concat([]);
return getArray(size).map(() => copy.splice(0, size));
}
export function getColumns<T>(grid: T[]): T[][] {
return getRows(transpose(grid));
}
export function getDiagonals<T>(grid: T[]): T[][] {
const size = Math.sqrt(grid.length);
const lesser = size - 1;
const last = grid.length - 1;
return [
grid.filter((x, i) => Math.floor(i / size) === i % size),
grid.filter((x, i) => i > 0 && i < last && i % lesser === 0)
];
}
function getArray(length: number): number[] {
return Array.apply(null, { length }).map(Number.call, Number);
}
export function transpose<T>(grid: Array<T>): Array<T> {
const size = Math.sqrt(grid.length);
return grid.map((x, i) => grid[Math.floor(i / size) + ((i % size) * size)]);
}
| Optimize filter condition to fail earlier | Optimize filter condition to fail earlier
| TypeScript | mit | artfuldev/tictactoe-ai,artfuldev/tictactoe-ai | ---
+++
@@ -14,7 +14,7 @@
const last = grid.length - 1;
return [
grid.filter((x, i) => Math.floor(i / size) === i % size),
- grid.filter((x, i) => i > 0 && i % lesser === 0 && i !== last)
+ grid.filter((x, i) => i > 0 && i < last && i % lesser === 0)
];
}
|
51fba105b7f95193ec2eb234751030e87d3b4181 | src/Components/UserSettings/TwoFactorAuthentication/Components/ApiErrorModal.tsx | src/Components/UserSettings/TwoFactorAuthentication/Components/ApiErrorModal.tsx | import { Modal, Sans } from "@artsy/palette"
import React from "react"
import { ApiError } from "../ApiError"
interface ApiErrorModalProps {
errors: ApiError[]
onClose: () => void
show?: boolean
}
export const ApiErrorModal: React.FC<ApiErrorModalProps> = props => {
const { errors, onClose, show } = props
const errorMessage = errors.map(error => error.message).join("\n")
return (
<Modal
forcedScroll={false}
title="An error occurred"
show={show}
onClose={onClose}
>
<Sans color="black60" textAlign="center" size="3t">
{errorMessage}
</Sans>
</Modal>
)
}
| import { Dialog } from "@artsy/palette"
import React from "react"
import { ApiError } from "../ApiError"
interface ApiErrorModalProps {
errors: ApiError[]
onClose: () => void
show?: boolean
}
export const ApiErrorModal: React.FC<ApiErrorModalProps> = props => {
const { errors, onClose, show } = props
const errorMessage = errors.map(error => error.message).join("\n")
return (
<Dialog
show={show}
detail={errorMessage}
title="An error occurred"
primaryCta={{
action: onClose,
text: "OK",
}}
/>
)
}
| Update 2FA enrollment API modal to use Palette dialog | Update 2FA enrollment API modal to use Palette dialog
| TypeScript | mit | artsy/reaction-force,artsy/reaction,artsy/reaction,artsy/reaction,artsy/reaction-force | ---
+++
@@ -1,4 +1,4 @@
-import { Modal, Sans } from "@artsy/palette"
+import { Dialog } from "@artsy/palette"
import React from "react"
import { ApiError } from "../ApiError"
@@ -14,15 +14,14 @@
const errorMessage = errors.map(error => error.message).join("\n")
return (
- <Modal
- forcedScroll={false}
+ <Dialog
+ show={show}
+ detail={errorMessage}
title="An error occurred"
- show={show}
- onClose={onClose}
- >
- <Sans color="black60" textAlign="center" size="3t">
- {errorMessage}
- </Sans>
- </Modal>
+ primaryCta={{
+ action: onClose,
+ text: "OK",
+ }}
+ />
)
} |
43245a30fd051904f90b80cebbcc97d38c4484ee | src/runtime/animate/index.ts | src/runtime/animate/index.ts | import { cubicOut } from 'svelte/easing';
import { is_function } from 'svelte/internal';
import { TransitionConfig } from 'svelte/transition';
export interface AnimationConfig extends TransitionConfig {}
interface FlipParams {
delay: number;
duration: number | ((len: number) => number);
easing: (t: number) => number;
}
export function flip(node: Element, animation: { from: DOMRect; to: DOMRect }, params: FlipParams): AnimationConfig {
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
const dx = animation.from.left - animation.to.left;
const dy = animation.from.top - animation.to.top;
const d = Math.sqrt(dx * dx + dy * dy);
const {
delay = 0,
duration = (d: number) => Math.sqrt(d) * 120,
easing = cubicOut
} = params;
return {
delay,
duration: is_function(duration) ? duration(d) : duration,
easing,
css: (_t, u) => `transform: ${transform} translate(${u * dx}px, ${u * dy}px);`
};
}
| import { cubicOut } from 'svelte/easing';
import { is_function } from 'svelte/internal';
// todo: same as Transition, should it be shared?
export interface AnimationConfig {
delay?: number;
duration?: number;
easing?: (t: number) => number;
css?: (t: number, u: number) => string;
tick?: (t: number, u: number) => void;
}
interface FlipParams {
delay: number;
duration: number | ((len: number) => number);
easing: (t: number) => number;
}
export function flip(node: Element, animation: { from: DOMRect; to: DOMRect }, params: FlipParams): AnimationConfig {
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
const dx = animation.from.left - animation.to.left;
const dy = animation.from.top - animation.to.top;
const d = Math.sqrt(dx * dx + dy * dy);
const {
delay = 0,
duration = (d: number) => Math.sqrt(d) * 120,
easing = cubicOut
} = params;
return {
delay,
duration: is_function(duration) ? duration(d) : duration,
easing,
css: (_t, u) => `transform: ${transform} translate(${u * dx}px, ${u * dy}px);`
};
}
| Revert "chore: resolve TODO for reusing of TransitionConfig" | Revert "chore: resolve TODO for reusing of TransitionConfig"
This reverts commit 0831887ef91b3a3a2439722bf95c0d367bac926d.
This was causing TypeScript linting errors, and can be revisited at another time.
| TypeScript | mit | sveltejs/svelte,sveltejs/svelte | ---
+++
@@ -1,8 +1,14 @@
import { cubicOut } from 'svelte/easing';
import { is_function } from 'svelte/internal';
-import { TransitionConfig } from 'svelte/transition';
-export interface AnimationConfig extends TransitionConfig {}
+// todo: same as Transition, should it be shared?
+export interface AnimationConfig {
+ delay?: number;
+ duration?: number;
+ easing?: (t: number) => number;
+ css?: (t: number, u: number) => string;
+ tick?: (t: number, u: number) => void;
+}
interface FlipParams {
delay: number; |
e18267c9b2c7867c44a2504e4a0b7915e91d8a47 | src/routes/ExpressRouter.ts | src/routes/ExpressRouter.ts | /**
* Express routes configurations
*/
export abstract class ExpressRouter {
protected express: any;
public abstract start(): void;
constructor(express: any) {
this.express = express;
this.defaultRoutes();
}
private defaultRoutes(): void {
this.express.get("/", (req, res) =>
res.json({ status: "NTask API TEste" }));
this.express.get("/routes", (req, res) =>
res.json({ routes: this.express._router.stack }));
}
} | /**
* Express routes configurations
*/
export abstract class ExpressRouter {
protected express: any;
public abstract start(): void;
constructor(express: any) {
this.express = express;
this.defaultRoutes();
}
private defaultRoutes(): void {
this.express.get("/", (req, res) =>
res.json({ status: "NTask API TEste" }));
this.express.get("/routes", (req, res) =>
res.json({ routes: this.printRoutes() }));
}
private printRoutes(): string[] {
let routes: string[] = [];
this.express._router.stack.forEach(r => {
if (r.route && r.route.path) {
routes.push(r.route.path);
}
});
return routes;
}
} | Add route to list available routes | Add route to list available routes
| TypeScript | mit | linck/protontype | ---
+++
@@ -15,6 +15,16 @@
this.express.get("/", (req, res) =>
res.json({ status: "NTask API TEste" }));
this.express.get("/routes", (req, res) =>
- res.json({ routes: this.express._router.stack }));
+ res.json({ routes: this.printRoutes() }));
+ }
+
+ private printRoutes(): string[] {
+ let routes: string[] = [];
+ this.express._router.stack.forEach(r => {
+ if (r.route && r.route.path) {
+ routes.push(r.route.path);
+ }
+ });
+ return routes;
}
} |
a1608db52decd5b99dfdd6f160305ad412fb4b23 | app/services/instagram.ts | app/services/instagram.ts | import {XHR} from '../libs/xhr';
let ENDPOINT = 'api.instagram.com'
let API_VERSION = 'v1'
let ACCESS_TOKEN = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0'
let CLIENT_ID = '5c1de8fe2653445489b480a72803a44c'
export class InstagramClient {
endpoint: string;
protocol: string;
token: string;
xhr: XHR;
constructor() {
this.protocol = 'https://'
this.xhr = new XHR();
this.endpoint = [this.protocol, ENDPOINT, API_VERSION].join('/')
}
getMedias(tag){
let ref = `/tags/${tag}/media/recent?access_token=${ACCESS_TOKEN}`
return this.xhr.get(this.endpoint + ref).then(console.log.bind(console))
}
} | import {XHR} from '../libs/xhr';
let ENDPOINT = 'api.instagram.com'
let API_VERSION = 'v1'
let ACCESS_TOKEN = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0'
let CLIENT_ID = '5c1de8fe2653445489b480a72803a44c'
export class InstagramClient {
endpoint: string
protocol: string = 'https://'
xhr: XHR;
constructor() {
this.xhr = new XHR();
this.endpoint = [this.protocol, ENDPOINT, API_VERSION].join('/')
}
getMedias(tag){
let ref = `/tags/${tag}/media/recent?access_token=${ACCESS_TOKEN}`
return this.xhr.get(this.endpoint + ref).then(console.log.bind(console))
}
} | Use direct style variable initilisation | Use direct style variable initilisation
| TypeScript | mit | yadomi/lastagram,yadomi/lastagram,yadomi/lastagram | ---
+++
@@ -8,14 +8,12 @@
export class InstagramClient {
- endpoint: string;
- protocol: string;
- token: string;
+ endpoint: string
+ protocol: string = 'https://'
xhr: XHR;
constructor() {
- this.protocol = 'https://'
this.xhr = new XHR();
this.endpoint = [this.protocol, ENDPOINT, API_VERSION].join('/')
}
@@ -25,5 +23,4 @@
return this.xhr.get(this.endpoint + ref).then(console.log.bind(console))
}
-
} |
8bc1815d567ee953e59224ee0dbb483489e1e268 | src/types.ts | src/types.ts | import * as React from 'react';
type Callback = (...args: any[]) => void;
export type ErrorCallback = (error: Error | FetchError) => void;
export type LoadCallback = (src: string, isCached: boolean) => void;
export type PreProcessorCallback = (code: string) => string;
export interface Props extends Omit<React.HTMLProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> {
baseURL?: string;
cacheRequests?: boolean;
children?: React.ReactNode;
description?: string;
innerRef?: React.Ref<SVGElement>;
loader?: React.ReactNode;
onError?: ErrorCallback;
onLoad?: LoadCallback;
preProcessor?: PreProcessorCallback;
src: string;
title?: string;
uniqueHash?: string;
uniquifyIDs?: boolean;
}
export interface State {
content: string;
element: React.ReactNode;
hasCache: boolean;
status: string;
}
export interface FetchError extends Error {
code: string;
errno: string;
message: string;
type: string;
}
export interface StorageItem {
content: string;
queue: Callback[];
status: string;
}
| import * as React from 'react';
type Callback = (...args: any[]) => void;
export type ErrorCallback = (error: Error | FetchError) => void;
export type LoadCallback = (src: string, isCached: boolean) => void;
export type PreProcessorCallback = (code: string) => string;
export interface Props extends Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> {
baseURL?: string;
cacheRequests?: boolean;
children?: React.ReactNode;
description?: string;
innerRef?: React.Ref<SVGElement>;
loader?: React.ReactNode;
onError?: ErrorCallback;
onLoad?: LoadCallback;
preProcessor?: PreProcessorCallback;
src: string;
title?: string;
uniqueHash?: string;
uniquifyIDs?: boolean;
}
export interface State {
content: string;
element: React.ReactNode;
hasCache: boolean;
status: string;
}
export interface FetchError extends Error {
code: string;
errno: string;
message: string;
type: string;
}
export interface StorageItem {
content: string;
queue: Callback[];
status: string;
}
| Update typings to use React.SVGProps instead of React.HTMLProps | Update typings to use React.SVGProps instead of React.HTMLProps
| TypeScript | mit | matthewwithanm/react-inlinesvg | ---
+++
@@ -6,7 +6,7 @@
export type LoadCallback = (src: string, isCached: boolean) => void;
export type PreProcessorCallback = (code: string) => string;
-export interface Props extends Omit<React.HTMLProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> {
+export interface Props extends Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> {
baseURL?: string;
cacheRequests?: boolean;
children?: React.ReactNode; |
db4f902d71a2336121ab9249d5ba9779cc52f220 | src/index.ts | src/index.ts |
import * as React from 'react';
export { React };
import * as mui from 'material-ui';
export { mui };
import * as redux from 'redux';
export { redux };
import * as reactRedux from 'react-redux';
export { reactRedux };
import * as actions from './actions';
export { actions };
export { hypract } from './hypract';
import * as reducer from './reducer';
export { reducer };
import * as core from './core';
export { core };
import * as firebase from './firebase';
export { firebase };
import * as form from './form';
export { form };
import * as material from './material';
export { material };
import * as middlewares from './middlewares';
export { middlewares };
import * as types from './types';
export { types };
|
import * as React from 'react';
export { React };
import * as materialUi from 'material-ui';
export { materialUi };
import * as redux from 'redux';
export { redux };
import * as reactRedux from 'react-redux';
export { reactRedux };
import * as actions from './actions';
export { actions };
export { hypract } from './hypract';
import * as reducer from './reducer';
export { reducer };
import * as core from './core';
export { core };
import * as firebase from './firebase';
export { firebase };
import * as form from './form';
export { form };
import * as material from './material';
export { material };
import * as middlewares from './middlewares';
export { middlewares };
import * as types from './types';
export { types };
| Rename export mui to materialUi | Rename export mui to materialUi
| TypeScript | mit | Mytrill/hypract,Mytrill/hypract | ---
+++
@@ -2,8 +2,8 @@
import * as React from 'react';
export { React };
-import * as mui from 'material-ui';
-export { mui };
+import * as materialUi from 'material-ui';
+export { materialUi };
import * as redux from 'redux';
export { redux }; |
378a4cbde41bba36cce8a777b8950e1248539bb3 | src/features/CodeActions.ts | src/features/CodeActions.ts | import vscode = require('vscode');
import { LanguageClient, RequestType, NotificationType } from 'vscode-languageclient';
import Window = vscode.window;
export function registerCodeActionCommands(client: LanguageClient): void {
vscode.commands.registerCommand('PowerShell.ApplyCodeActionEdits', (edit: any) => {
console.log("Applying edits");
console.log(edit);
var workspaceEdit = new vscode.WorkspaceEdit();
workspaceEdit.set(
vscode.Uri.file(edit.File),
[
new vscode.TextEdit(
new vscode.Range(
edit.StartLineNumber - 1,
edit.StartColumnNumber - 1,
edit.EndLineNumber - 1,
edit.EndColumnNumber - 1),
edit.Text)
]);
vscode.workspace.applyEdit(workspaceEdit);
});
} | import vscode = require('vscode');
import { LanguageClient, RequestType, NotificationType } from 'vscode-languageclient';
import Window = vscode.window;
export function registerCodeActionCommands(client: LanguageClient): void {
vscode.commands.registerCommand('PowerShell.ApplyCodeActionEdits', (edit: any) => {
console.log("Applying edits");
console.log(edit);
var editor = Window.activeTextEditor;
var filePath = editor.document.fileName;
var workspaceEdit = new vscode.WorkspaceEdit();
workspaceEdit.set(
vscode.Uri.file(filePath),
[
new vscode.TextEdit(
new vscode.Range(
edit.StartLineNumber - 1,
edit.StartColumnNumber - 1,
edit.EndLineNumber - 1,
edit.EndColumnNumber - 1),
edit.Text)
]);
vscode.workspace.applyEdit(workspaceEdit);
});
} | Set file path in ApplyCodeActionEdits | Set file path in ApplyCodeActionEdits
EditorServices invokes PSScriptAnalyzer by passing `ScriptDefinition` paramter and not `Path` parameter. This results in null value of `ScriptPath` property of the returned diagnostic record which in turns leads to null value of `edit.file`. Therefore, we need to retrieve file path from the active editor.
| TypeScript | mit | PowerShell/vscode-powershell | ---
+++
@@ -6,10 +6,11 @@
vscode.commands.registerCommand('PowerShell.ApplyCodeActionEdits', (edit: any) => {
console.log("Applying edits");
console.log(edit);
-
+ var editor = Window.activeTextEditor;
+ var filePath = editor.document.fileName;
var workspaceEdit = new vscode.WorkspaceEdit();
workspaceEdit.set(
- vscode.Uri.file(edit.File),
+ vscode.Uri.file(filePath),
[
new vscode.TextEdit(
new vscode.Range( |
ccc59d8668edb60089805d3bc65ea6935fd8304a | src/index.ts | src/index.ts | export * from './tick-tock.module';
| export { TickTockService } from './services';
export { TickTockComponent } from './components';
export { TickTockModule } from './tick-tock.module';
| Fix for AOT build in CLI. | Fix for AOT build in CLI.
| TypeScript | mit | trekhleb/ng-library-starter,trekhleb/ng-library-starter,trekhleb/angular-library-seed,nowzoo/nowzoo-angular-bootstrap-lite,nowzoo/nowzoo-angular-bootstrap-lite,trekhleb/ng-library-starter,nowzoo/nowzoo-angular-bootstrap-lite,trekhleb/angular-library-seed,trekhleb/angular-library-seed | ---
+++
@@ -1 +1,3 @@
-export * from './tick-tock.module';
+export { TickTockService } from './services';
+export { TickTockComponent } from './components';
+export { TickTockModule } from './tick-tock.module'; |
b45d5c0bcba2c63a77a57576d0beebfdcd2ef66f | applications/mail/src/app/components/message/recipients/RecipientsList.tsx | applications/mail/src/app/components/message/recipients/RecipientsList.tsx | import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal';
import { MapStatusIcons } from '../../../models/crypto';
import RecipientItem from './RecipientItem';
import { RecipientOrGroup } from '../../../models/address';
interface Props {
recipientsOrGroup: RecipientOrGroup[];
mapStatusIcons?: MapStatusIcons;
isLoading: boolean;
showDropdown?: boolean;
isOutside?: boolean;
isPrintModal?: boolean;
onContactDetails: (contactID: string) => void;
onContactEdit: (props: ContactEditProps) => void;
}
const RecipientsList = ({
recipientsOrGroup,
mapStatusIcons,
isLoading,
showDropdown,
isOutside,
isPrintModal,
onContactDetails,
onContactEdit,
}: Props) => {
return (
<>
{recipientsOrGroup.map((recipientOrGroup, index) => (
<>
<RecipientItem
key={index} // eslint-disable-line react/no-array-index-key
recipientOrGroup={recipientOrGroup}
mapStatusIcons={mapStatusIcons}
isLoading={isLoading}
showDropdown={showDropdown}
isOutside={isOutside}
isRecipient={true}
isExpanded={true}
onContactDetails={onContactDetails}
onContactEdit={onContactEdit}
/>
{isPrintModal && index < recipientsOrGroup.length - 1 && <span>, </span>}
</>
))}
</>
);
};
export default RecipientsList;
| import { Fragment } from 'react';
import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal';
import { MapStatusIcons } from '../../../models/crypto';
import RecipientItem from './RecipientItem';
import { RecipientOrGroup } from '../../../models/address';
interface Props {
recipientsOrGroup: RecipientOrGroup[];
mapStatusIcons?: MapStatusIcons;
isLoading: boolean;
showDropdown?: boolean;
isOutside?: boolean;
isPrintModal?: boolean;
onContactDetails: (contactID: string) => void;
onContactEdit: (props: ContactEditProps) => void;
}
const RecipientsList = ({
recipientsOrGroup,
mapStatusIcons,
isLoading,
showDropdown,
isOutside,
isPrintModal,
onContactDetails,
onContactEdit,
}: Props) => (
<Fragment>
{recipientsOrGroup.map((recipientOrGroup, index) => (
<Fragment
key={index} // eslint-disable-line react/no-array-index-key
>
<RecipientItem
recipientOrGroup={recipientOrGroup}
mapStatusIcons={mapStatusIcons}
isLoading={isLoading}
showDropdown={showDropdown}
isOutside={isOutside}
isRecipient={true}
isExpanded={true}
onContactDetails={onContactDetails}
onContactEdit={onContactEdit}
/>
{isPrintModal && index < recipientsOrGroup.length - 1 && <span>, </span>}
</Fragment>
))}
</Fragment>
);
export default RecipientsList;
| Move index prop on RecipienList | Move index prop on RecipienList
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,3 +1,4 @@
+import { Fragment } from 'react';
import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal';
import { MapStatusIcons } from '../../../models/crypto';
import RecipientItem from './RecipientItem';
@@ -23,28 +24,27 @@
isPrintModal,
onContactDetails,
onContactEdit,
-}: Props) => {
- return (
- <>
- {recipientsOrGroup.map((recipientOrGroup, index) => (
- <>
- <RecipientItem
- key={index} // eslint-disable-line react/no-array-index-key
- recipientOrGroup={recipientOrGroup}
- mapStatusIcons={mapStatusIcons}
- isLoading={isLoading}
- showDropdown={showDropdown}
- isOutside={isOutside}
- isRecipient={true}
- isExpanded={true}
- onContactDetails={onContactDetails}
- onContactEdit={onContactEdit}
- />
- {isPrintModal && index < recipientsOrGroup.length - 1 && <span>, </span>}
- </>
- ))}
- </>
- );
-};
+}: Props) => (
+ <Fragment>
+ {recipientsOrGroup.map((recipientOrGroup, index) => (
+ <Fragment
+ key={index} // eslint-disable-line react/no-array-index-key
+ >
+ <RecipientItem
+ recipientOrGroup={recipientOrGroup}
+ mapStatusIcons={mapStatusIcons}
+ isLoading={isLoading}
+ showDropdown={showDropdown}
+ isOutside={isOutside}
+ isRecipient={true}
+ isExpanded={true}
+ onContactDetails={onContactDetails}
+ onContactEdit={onContactEdit}
+ />
+ {isPrintModal && index < recipientsOrGroup.length - 1 && <span>, </span>}
+ </Fragment>
+ ))}
+ </Fragment>
+);
export default RecipientsList; |
f98dbdfdabd9a3773f59e11c4941e734be9b2133 | src/polyfills.ts | src/polyfills.ts | // This file includes polyfills needed by Angular 2 and is loaded before
// the app. You can add your own extra polyfills to this file.
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
// Proxy stub
console.log('Proxy', Proxy);
if (!('Proxy' in window)) {
console.log('No proxy! Patching...');
window['Proxy'] = {};
console.log('Proxy', Proxy);
}
| // This file includes polyfills needed by Angular 2 and is loaded before
// the app. You can add your own extra polyfills to this file.
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
// Proxy stub
if (!('Proxy' in window)) {
window['Proxy'] = {};
}
| Remove console debug info from build | test(proxy): Remove console debug info from build
| TypeScript | mit | gund/ng-http-interceptor,gund/ng2-http-interceptor,gund/ng-http-interceptor,gund/ng2-http-interceptor,gund/ng2-http-interceptor,gund/ng-http-interceptor | ---
+++
@@ -19,9 +19,6 @@
import 'zone.js/dist/zone';
// Proxy stub
-console.log('Proxy', Proxy);
if (!('Proxy' in window)) {
- console.log('No proxy! Patching...');
window['Proxy'] = {};
- console.log('Proxy', Proxy);
} |
e8616236493468c1f736d8362429d77d2e1939b5 | app/src/ui/branches/branch.tsx | app/src/ui/branches/branch.tsx | import * as React from 'react'
import * as moment from 'moment'
import { Octicon, OcticonSymbol } from '../octicons'
interface IBranchProps {
readonly name: string
readonly isCurrentBranch: boolean
/** The date may be null if we haven't loaded the tip commit yet. */
readonly lastCommitDate: Date | null
}
/** The branch component. */
export function BranchListItem({ name, isCurrentBranch, lastCommitDate }: IBranchProps) {
const date = lastCommitDate ? moment(lastCommitDate).fromNow() : ''
const info = isCurrentBranch ? <Octicon symbol={OcticonSymbol.check} /> : date
const infoTitle = isCurrentBranch ? 'Current branch' : (lastCommitDate ? lastCommitDate.toString() : '')
return (
<div className='branches-list-content'>
<span className='branches-list-item'>{name}</span>
<span title={infoTitle}>{info}</span>
</div>
)
}
| import * as React from 'react'
import * as moment from 'moment'
import { Octicon, OcticonSymbol } from '../octicons'
interface IBranchProps {
readonly name: string
readonly isCurrentBranch: boolean
/** The date may be null if we haven't loaded the tip commit yet. */
readonly lastCommitDate: Date | null
}
/** The branch component. */
export class BranchListItem extends React.Component<IBranchProps, void> {
public render() {
const lastCommitDate = this.props.lastCommitDate
const isCurrentBranch = this.props.isCurrentBranch
const name = this.props.name
const date = lastCommitDate ? moment(lastCommitDate).fromNow() : ''
const info = isCurrentBranch ? <Octicon symbol={OcticonSymbol.check} /> : date
const infoTitle = isCurrentBranch ? 'Current branch' : (lastCommitDate ? lastCommitDate.toString() : '')
return (
<div className='branches-list-content'>
<span className='branches-list-item'>{name}</span>
<span title={infoTitle}>{info}</span>
</div>
)
}
}
| Convert BranchListItem to class for unused-props rule | Convert BranchListItem to class for unused-props rule
The react-unused props rule currently only understands classes
| TypeScript | mit | gengjiawen/desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,BugTesterTest/desktops,artivilla/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,j-f1/forked-desktop,BugTesterTest/desktops,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,hjobrien/desktop,hjobrien/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,say25/desktop,hjobrien/desktop,gengjiawen/desktop,gengjiawen/desktop,kactus-io/kactus,hjobrien/desktop,say25/desktop,say25/desktop,gengjiawen/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,BugTesterTest/desktops,artivilla/desktop,BugTesterTest/desktops | ---
+++
@@ -12,14 +12,20 @@
}
/** The branch component. */
-export function BranchListItem({ name, isCurrentBranch, lastCommitDate }: IBranchProps) {
- const date = lastCommitDate ? moment(lastCommitDate).fromNow() : ''
- const info = isCurrentBranch ? <Octicon symbol={OcticonSymbol.check} /> : date
- const infoTitle = isCurrentBranch ? 'Current branch' : (lastCommitDate ? lastCommitDate.toString() : '')
- return (
- <div className='branches-list-content'>
- <span className='branches-list-item'>{name}</span>
- <span title={infoTitle}>{info}</span>
- </div>
- )
+export class BranchListItem extends React.Component<IBranchProps, void> {
+ public render() {
+ const lastCommitDate = this.props.lastCommitDate
+ const isCurrentBranch = this.props.isCurrentBranch
+ const name = this.props.name
+
+ const date = lastCommitDate ? moment(lastCommitDate).fromNow() : ''
+ const info = isCurrentBranch ? <Octicon symbol={OcticonSymbol.check} /> : date
+ const infoTitle = isCurrentBranch ? 'Current branch' : (lastCommitDate ? lastCommitDate.toString() : '')
+ return (
+ <div className='branches-list-content'>
+ <span className='branches-list-item'>{name}</span>
+ <span title={infoTitle}>{info}</span>
+ </div>
+ )
+ }
} |
d195bdf557dfa6cbea7a73b81105c9ea5665686e | scripts/generateTagTable.ts | scripts/generateTagTable.ts | import Tags from "../src/tags";
import { getMarkdownTable } from 'markdown-table-ts';
let tags = new Tags();
let formatted: string[][] = [];
tags.list.forEach(tag => {
formatted.push([tag.tag, tag.snippet]);
});
let table = getMarkdownTable({
table: {
head: ['Tag', 'Snippet'],
body: formatted
},
});
console.log(table); | import * as fs from 'fs';
import Tags from "../src/tags";
import { getMarkdownTable } from 'markdown-table-ts';
let tags = new Tags();
let formatted: string[][] = [];
tags.list.forEach(tag => {
formatted.push([tag.tag, tag.snippet]);
});
let table = getMarkdownTable({
table: {
head: ['Tag', 'Snippet'],
body: formatted
},
});
console.log('');
console.log(table);
console.log('');
fs.writeFile('./out/TAGS.md', table, 'utf8', function (err) {
if (err) {
throw err;
}
});
| Add output file as well | Add output file as well
| TypeScript | mit | neild3r/vscode-php-docblocker | ---
+++
@@ -1,3 +1,4 @@
+import * as fs from 'fs';
import Tags from "../src/tags";
import { getMarkdownTable } from 'markdown-table-ts';
@@ -15,4 +16,12 @@
},
});
+console.log('');
console.log(table);
+console.log('');
+
+fs.writeFile('./out/TAGS.md', table, 'utf8', function (err) {
+ if (err) {
+ throw err;
+ }
+}); |
ddea73671eff362ce4b3c2e34d2962be0cb4a5d7 | projects/hslayers/src/components/add-layers/add-layers.service.ts | projects/hslayers/src/components/add-layers/add-layers.service.ts | import BaseLayer from 'ol/layer/Base';
import {HsConfig} from './../../config.service';
import {HsMapService} from '../map/map.service';
import {HsUtilsService} from '../utils/utils.service';
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class HsAddLayersService {
constructor(
public hsMapService: HsMapService,
public hsUtilsService: HsUtilsService,
public HsConfig: HsConfig
) {}
addLayer(layer: BaseLayer, addBefore?: BaseLayer) {
if (addBefore) {
let prevLayerZIndex: number;
const layers = this.hsMapService.map.getLayers();
if (this.HsConfig.reverseLayerList) {
layer.setZIndex(addBefore.getZIndex() + 1);
} else {
layer.setZIndex(addBefore.getZIndex());
}
layers.forEach((mapLayer) => {
if (layer.get('base') != true) {
if (
mapLayer.getZIndex() == layer.getZIndex() ||
mapLayer.getZIndex() == prevLayerZIndex
) {
mapLayer.setZIndex(mapLayer.getZIndex() + 1);
prevLayerZIndex = mapLayer.getZIndex();
}
}
});
const ix = layers.getArray().indexOf(addBefore);
layers.insertAt(ix, layer);
} else {
this.hsMapService.map.addLayer(layer);
}
}
}
| import BaseLayer from 'ol/layer/Base';
import {HsConfig} from './../../config.service';
import {HsMapService} from '../map/map.service';
import {HsUtilsService} from '../utils/utils.service';
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class HsAddLayersService {
constructor(
public hsMapService: HsMapService,
public hsUtilsService: HsUtilsService,
public HsConfig: HsConfig
) {}
addLayer(layer: BaseLayer, underLayer?: BaseLayer) {
if (underLayer) {
const layers = this.hsMapService.getLayersArray();
const underZ = underLayer.getZIndex();
layer.setZIndex(underZ);
for (const iLayer of layers.filter((l) => !l.get('base'))) {
if (iLayer.getZIndex() >= underZ) {
iLayer.setZIndex(iLayer.getZIndex() + 1);
}
}
const ix = layers.indexOf(underLayer);
this.hsMapService.map.getLayers().insertAt(ix, layer);
} else {
this.hsMapService.map.addLayer(layer);
}
}
}
| Simplify zIndex shifting when adding before layer | Simplify zIndex shifting when adding before layer
| TypeScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -14,29 +14,18 @@
public HsConfig: HsConfig
) {}
- addLayer(layer: BaseLayer, addBefore?: BaseLayer) {
- if (addBefore) {
- let prevLayerZIndex: number;
- const layers = this.hsMapService.map.getLayers();
- if (this.HsConfig.reverseLayerList) {
- layer.setZIndex(addBefore.getZIndex() + 1);
- } else {
- layer.setZIndex(addBefore.getZIndex());
+ addLayer(layer: BaseLayer, underLayer?: BaseLayer) {
+ if (underLayer) {
+ const layers = this.hsMapService.getLayersArray();
+ const underZ = underLayer.getZIndex();
+ layer.setZIndex(underZ);
+ for (const iLayer of layers.filter((l) => !l.get('base'))) {
+ if (iLayer.getZIndex() >= underZ) {
+ iLayer.setZIndex(iLayer.getZIndex() + 1);
+ }
}
- layers.forEach((mapLayer) => {
- if (layer.get('base') != true) {
- if (
- mapLayer.getZIndex() == layer.getZIndex() ||
- mapLayer.getZIndex() == prevLayerZIndex
- ) {
- mapLayer.setZIndex(mapLayer.getZIndex() + 1);
- prevLayerZIndex = mapLayer.getZIndex();
- }
- }
- });
-
- const ix = layers.getArray().indexOf(addBefore);
- layers.insertAt(ix, layer);
+ const ix = layers.indexOf(underLayer);
+ this.hsMapService.map.getLayers().insertAt(ix, layer);
} else {
this.hsMapService.map.addLayer(layer);
} |
eb4403f7335e2759745629ee17ff1489d65f5fe2 | src/app/js/component/feed-list.tsx | src/app/js/component/feed-list.tsx | import * as ReactDOM from "react-dom";
import * as React from "react";
import { CustomComponent } from "./../custom-component";
import { ComponentsRefs } from "./../components-refs";
import { Feed, FeedProp } from "./feed";
export class FeedList extends CustomComponent<{}, FeedListState> {
feedComponents: Feed[] = [];
constructor() {
super();
this.state = {
feeds: []
};
ComponentsRefs.feedList = this;
}
render() {
return (
<ul className="rss list">
{
this.state.feeds.map(feed => {
return <Feed ref={feed => this.feedComponents[this.feedComponents.length] = feed} key={feed.uuid} uuid={feed.uuid} title={feed.title} link={feed.link} />
})
}
</ul>
);
}
addFeed(newFeed: FeedProp) {
const newFeeds = this.state.feeds.slice(0);
newFeeds[newFeeds.length] = newFeed;
this.editState({ feeds: newFeeds })
}
}
interface FeedListState {
feeds: FeedProp[];
} | import * as ReactDOM from "react-dom";
import * as React from "react";
import { CustomComponent } from "./../custom-component";
import { ComponentsRefs } from "./../components-refs";
import { Feed, FeedProp } from "./feed";
export class FeedList extends CustomComponent<{}, FeedListState> {
feedComponents: Feed[] = [];
constructor() {
super();
this.state = {
feeds: []
};
ComponentsRefs.feedList = this;
}
render() {
return (
<ul className="rss list">
{
this.state.feeds.map(feed => {
return <Feed ref={feed => this.feedComponents[this.feedComponents.length] = feed} key={feed.uuid} uuid={feed.uuid} title={feed.title} link={feed.link} />
})
}
</ul>
);
}
isIdAlreadyUsed(uuid: string) {
return !!this.state.feeds.find(feed => {
return feed.uuid === uuid;
});
}
addFeed(newFeed: FeedProp) {
const newFeeds = this.state.feeds.slice(0);
newFeeds[newFeeds.length] = newFeed;
this.editState({ feeds: newFeeds })
}
}
interface FeedListState {
feeds: FeedProp[];
} | Check if UUID is already used | Check if UUID is already used
| TypeScript | mit | Xstoudi/alduin,Xstoudi/alduin,Xstoudi/alduin | ---
+++
@@ -31,6 +31,12 @@
);
}
+ isIdAlreadyUsed(uuid: string) {
+ return !!this.state.feeds.find(feed => {
+ return feed.uuid === uuid;
+ });
+ }
+
addFeed(newFeed: FeedProp) {
const newFeeds = this.state.feeds.slice(0);
newFeeds[newFeeds.length] = newFeed; |
71f008559afcfaf3cc0271d1f901b96f30101121 | src/renderer/padTimestamp.ts | src/renderer/padTimestamp.ts | export function padToHoursMinutesSeconds(timestamp) {
const shortTimestampPattern = /^\d{1,2}:\d\d$/;
const paddedTimestamp = `00:${timestamp}`;
if (shortTimestampPattern.test(timestamp)) {
return (paddedTimestamp);
} else {
return (timestamp);
}
}
| const padToHoursMinutesSeconds: (s: string) => string = (timestamp: string) => {
const shortTimestampPattern: RegExp = /^\d{1,2}:\d\d$/;
const paddedTimestamp: string = `00:${timestamp}`;
if (shortTimestampPattern.test(timestamp)) {
return paddedTimestamp;
} else {
return timestamp;
}
};
export { padToHoursMinutesSeconds };
| Add type annotations to timestamp-padding function | Add type annotations to timestamp-padding function
| TypeScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -1,10 +1,12 @@
-export function padToHoursMinutesSeconds(timestamp) {
- const shortTimestampPattern = /^\d{1,2}:\d\d$/;
- const paddedTimestamp = `00:${timestamp}`;
+const padToHoursMinutesSeconds: (s: string) => string = (timestamp: string) => {
+ const shortTimestampPattern: RegExp = /^\d{1,2}:\d\d$/;
+ const paddedTimestamp: string = `00:${timestamp}`;
if (shortTimestampPattern.test(timestamp)) {
- return (paddedTimestamp);
+ return paddedTimestamp;
} else {
- return (timestamp);
+ return timestamp;
}
-}
+};
+
+export { padToHoursMinutesSeconds }; |
2bfc8fa97a2da018bffbc76354576b7e6a7f73ee | src/selectors/watcherTree.ts | src/selectors/watcherTree.ts | import { createSelector } from 'reselect';
import { watcherTreeSelector } from './index';
import { normalizedWatchers } from './watchers';
export const getCurrentlySelectedWatcherIdOrNull = createSelector(
[watcherTreeSelector, normalizedWatchers],
(watcherSettings, watchers) => {
const { selectionId, selectionKind } = watcherSettings;
if (selectionId && selectionKind !== 'folder') {
return watchers.get(selectionId).groupId;
} else {
return null;
}
}
);
| import { createSelector } from 'reselect';
import { watcherTreeSelector } from './index';
import { normalizedWatchers } from './watchers';
import { Watcher } from '../types';
export const getCurrentlySelectedWatcherIdOrNull = createSelector(
[watcherTreeSelector, normalizedWatchers],
(watcherSettings, watchers) => {
const { selectionId, selectionKind } = watcherSettings;
if (selectionId && selectionKind !== 'folder') {
const maybeSelectedWatcher: Watcher | undefined = watchers.get(
selectionId,
undefined
);
return maybeSelectedWatcher ? maybeSelectedWatcher.groupId : null;
} else {
return null;
}
}
);
| Fix crash when deleting a selected watcher. | Fix crash when deleting a selected watcher.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,6 +1,7 @@
import { createSelector } from 'reselect';
import { watcherTreeSelector } from './index';
import { normalizedWatchers } from './watchers';
+import { Watcher } from '../types';
export const getCurrentlySelectedWatcherIdOrNull = createSelector(
[watcherTreeSelector, normalizedWatchers],
@@ -8,7 +9,11 @@
const { selectionId, selectionKind } = watcherSettings;
if (selectionId && selectionKind !== 'folder') {
- return watchers.get(selectionId).groupId;
+ const maybeSelectedWatcher: Watcher | undefined = watchers.get(
+ selectionId,
+ undefined
+ );
+ return maybeSelectedWatcher ? maybeSelectedWatcher.groupId : null;
} else {
return null;
} |
6472e895915e84019b5edd5afcfe1b1b4616f335 | packages/react-day-picker/src/hooks/useModifiers/useModifiers.ts | packages/react-day-picker/src/hooks/useModifiers/useModifiers.ts | import { ModifierStatus } from '../../types';
import { useDayPicker } from '../useDayPicker';
import { useSelection } from '../useSelection';
import { getModifierStatus } from './utils/getModifierStatus';
/** Return the status for the modifiers given the specified date */
export function useModifiers(date: Date): ModifierStatus {
const context = useDayPicker();
const selection = useSelection();
const modifiers = Object.assign({}, context.modifiers);
if (context.mode !== 'uncontrolled') {
const { single, multiple, range } = selection ?? {};
switch (context.mode) {
case 'range':
if (!range.selected) break;
modifiers.selected = range.selected;
modifiers['range-middle'] = {
after: range.selected.from,
before: range.selected.to
};
modifiers['range-start'] = range.selected.from;
if (range.selected.to) modifiers['range-end'] = range.selected.to;
break;
case 'multiple':
if (!multiple.selected) break;
modifiers.selected = multiple.selected;
break;
default:
case 'single':
if (!single.selected) break;
modifiers.selected = single.selected;
break;
}
}
const status = getModifierStatus(date, modifiers);
return status;
}
| import { ModifierStatus } from '../../types';
import { useDayPicker } from '../useDayPicker';
import { useSelection } from '../useSelection';
import { getModifierStatus } from './utils/getModifierStatus';
/** Return the status for the modifiers given the specified date */
export function useModifiers(date: Date): ModifierStatus {
const context = useDayPicker();
const selection = useSelection();
const modifiers = Object.assign({}, context.modifiers);
modifiers.today = context.today;
if (context.mode !== 'uncontrolled') {
const { single, multiple, range } = selection ?? {};
switch (context.mode) {
case 'range':
if (!range.selected) break;
modifiers.selected = range.selected;
modifiers['range-middle'] = {
after: range.selected.from,
before: range.selected.to
};
modifiers['range-start'] = range.selected.from;
if (range.selected.to) modifiers['range-end'] = range.selected.to;
break;
case 'multiple':
if (!multiple.selected) break;
modifiers.selected = multiple.selected;
break;
default:
case 'single':
if (!single.selected) break;
modifiers.selected = single.selected;
break;
}
}
const status = getModifierStatus(date, modifiers);
return status;
}
| Fix for today modifier not being added | Fix for today modifier not being added
| TypeScript | mit | gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -8,6 +8,8 @@
const context = useDayPicker();
const selection = useSelection();
const modifiers = Object.assign({}, context.modifiers);
+
+ modifiers.today = context.today;
if (context.mode !== 'uncontrolled') {
const { single, multiple, range } = selection ?? {}; |
d67708d7e293ec86cf1551c4cea5c56263803874 | components/error/page/page-components.ts | components/error/page/page-components.ts | import Vue from 'vue';
import { State } from 'vuex-class';
import { Component } from 'vue-property-decorator';
import View400 from '!view!./page-400.html';
import View403 from '!view!./page-403.html';
import View500 from '!view!./page-500.html';
import View404 from '!view!./page-404.html';
import ViewOffline from '!view!./page-offline.html';
import { Navigate } from '../../navigate/navigate.service';
@View400
@Component({})
export class AppErrorPage400 extends Vue {}
@View403
@Component({})
export class AppErrorPage403 extends Vue {}
@View404
@Component({})
export class AppErrorPage404 extends Vue {}
@View500
@Component({})
export class AppErrorPage500 extends Vue {}
@ViewOffline
@Component({})
export class AppErrorPageOffline extends Vue {
@State
retry() {
Navigate.reload();
}
}
export const ErrorPages: any = {
400: AppErrorPage400,
403: AppErrorPage403,
404: AppErrorPage404,
500: AppErrorPage500,
offline: AppErrorPageOffline,
};
| import Vue from 'vue';
import { State } from 'vuex-class';
import { Component } from 'vue-property-decorator';
import View400 from '!view!./page-400.html';
import View403 from '!view!./page-403.html';
import View500 from '!view!./page-500.html';
import View404 from '!view!./page-404.html';
import ViewOffline from '!view!./page-offline.html';
import { Navigate } from '../../navigate/navigate.service';
@View400
@Component({})
export class AppErrorPage400 extends Vue {}
@View403
@Component({})
export class AppErrorPage403 extends Vue {}
@View404
@Component({})
export class AppErrorPage404 extends Vue {}
@View500
@Component({})
export class AppErrorPage500 extends Vue {}
@ViewOffline
@Component({})
export class AppErrorPageOffline extends Vue {
retry() {
Navigate.reload();
}
}
export const ErrorPages: any = {
400: AppErrorPage400,
403: AppErrorPage403,
404: AppErrorPage404,
500: AppErrorPage500,
offline: AppErrorPageOffline,
};
| Fix error page's retry button | Fix error page's retry button
| TypeScript | mit | gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib | ---
+++
@@ -27,7 +27,6 @@
@ViewOffline
@Component({})
export class AppErrorPageOffline extends Vue {
- @State
retry() {
Navigate.reload();
} |
060debc9c618a17b76ea86071dc3658407dc5c6e | src/dependument.manager.ts | src/dependument.manager.ts | import { IFileSystem } from './filesystem/filesystem.i';
import { ITemplateFileSystem } from './templates/templatefilesystem.i';
import * as Path from 'path';
export class DependumentManager {
private _fileSystem : IFileSystem;
private _templateFileSystem : ITemplateFileSystem;
constructor(fileSystem: IFileSystem, templateFileSystem: ITemplateFileSystem) {
let rootName = Path.resolve(__dirname, '../');
this._fileSystem = fileSystem;
this._templateFileSystem = templateFileSystem;
console.log(this._fileSystem.getDependencies(rootName + "/package.json"));
console.log(this._fileSystem.getDevDependencies(rootName + "/package.json"));
}
}
| import { IFileSystem } from './filesystem/filesystem.i';
import { ITemplateFileSystem } from './templates/templatefilesystem.i';
import * as Path from 'path';
export class DependumentManager {
private _fileSystem : IFileSystem;
private _templateFileSystem : ITemplateFileSystem;
constructor(fileSystem: IFileSystem, templateFileSystem: ITemplateFileSystem) {
this._fileSystem = fileSystem;
this._templateFileSystem = templateFileSystem;
}
}
| Remove unnecessary code from DependumentManager constructor | Remove unnecessary code from DependumentManager constructor
| TypeScript | unlicense | dependument/dependument,Jameskmonger/dependument,Jameskmonger/dependument,dependument/dependument | ---
+++
@@ -7,12 +7,7 @@
private _templateFileSystem : ITemplateFileSystem;
constructor(fileSystem: IFileSystem, templateFileSystem: ITemplateFileSystem) {
- let rootName = Path.resolve(__dirname, '../');
-
this._fileSystem = fileSystem;
this._templateFileSystem = templateFileSystem;
-
- console.log(this._fileSystem.getDependencies(rootName + "/package.json"));
- console.log(this._fileSystem.getDevDependencies(rootName + "/package.json"));
}
} |
b5f927e2317331c5abc4d3c64fcf931f450f7623 | projects/showcase-e2e/src/popup.e2e-spec.ts | projects/showcase-e2e/src/popup.e2e-spec.ts | import { browser, element, by, ExpectedConditions as EC } from 'protractor';
const browserLogs = require('protractor-browser-logs');
describe('Popup', () => {
let logs: any;
beforeEach(() => {
logs = browserLogs(browser);
});
afterEach(() => {
return logs.verify();
});
it('should show', async () => {
await browser.get('/demo/popup');
const canvas = element(by.tagName('canvas'));
await browser.wait(EC.presenceOf(canvas), 2000);
const popup = element(by.className('mapboxgl-popup'));
await browser.wait(EC.presenceOf(popup), 1000);
expect(popup).toHaveClass('custom-popup-class1');
expect(popup).toHaveClass('custom-popup-class2');
const popupContent = element(by.className('mapboxgl-popup-content'));
await browser.wait(EC.presenceOf(popupContent), 1000);
expect(popupContent.element(by.tagName('div')).getText()).toBe('Hello world !');
});
});
| import { browser, element, by, ExpectedConditions as EC } from 'protractor';
const browserLogs = require('protractor-browser-logs');
describe('Popup', () => {
let logs: any;
beforeEach(() => {
logs = browserLogs(browser);
});
afterEach(() => {
return logs.verify();
});
it('should show', async () => {
await browser.get('/demo/popup');
const canvas = element(by.tagName('canvas'));
await browser.wait(EC.presenceOf(canvas), 2000);
const popup = element(by.className('mapboxgl-popup'));
await browser.wait(EC.presenceOf(popup), 1000);
const popupClasses = popup.getAttribute('class').then(c => c.split(' ').filter(c => c.length > 0));
expect(popupClasses).toContain('custom-popup-class1');
expect(popupClasses).toContain('custom-popup-class2');
const popupContent = element(by.className('mapboxgl-popup-content'));
await browser.wait(EC.presenceOf(popupContent), 1000);
expect(popupContent.element(by.tagName('div')).getText()).toBe('Hello world !');
});
});
| Fix CI error "toHaveClass is not a function" | Fix CI error "toHaveClass is not a function"
| TypeScript | mit | Wykks/ngx-mapbox-gl,Wykks/ngx-mapbox-gl,Wykks/ngx-mapbox-gl,Wykks/ngx-mapbox-gl | ---
+++
@@ -19,8 +19,9 @@
const popup = element(by.className('mapboxgl-popup'));
await browser.wait(EC.presenceOf(popup), 1000);
- expect(popup).toHaveClass('custom-popup-class1');
- expect(popup).toHaveClass('custom-popup-class2');
+ const popupClasses = popup.getAttribute('class').then(c => c.split(' ').filter(c => c.length > 0));
+ expect(popupClasses).toContain('custom-popup-class1');
+ expect(popupClasses).toContain('custom-popup-class2');
const popupContent = element(by.className('mapboxgl-popup-content'));
await browser.wait(EC.presenceOf(popupContent), 1000); |
0cae42913e5a0fb9bfce82053956580525d958b6 | src/rancher/template/ClusterTemplateList.tsx | src/rancher/template/ClusterTemplateList.tsx | import * as React from 'react';
import { Table, connectTable, createFetcher } from '@waldur/table-react';
const TableComponent = props => {
const { translate } = props;
return (
<Table
{...props}
columns={[
{
title: translate('Name'),
render: ({ row }) => <span>{row.name}</span>,
},
{
title: translate('Description'),
render: ({ row }) => <span>{row.description}</span>,
},
{
title: translate('Catalog'),
render: ({ row }) => <span>{row.catalog_name}</span>,
},
{
title: translate('State'),
render: ({ row }) => <span>{row.runtime_state}</span>,
},
]}
verboseName={translate('application templates')}
/>
);
};
const TableOptions = {
table: 'rancher-cluster-templates',
fetchData: createFetcher('rancher-templates'),
exportFields: ['name', 'description', 'catalog'],
exportRow: row => [row.name, row.description, row.catalog_name],
mapPropsToFilter: props => ({
cluster_uuid: props.resource.uuid,
}),
};
export const ClusterTemplatesList = connectTable(TableOptions)(TableComponent);
| import * as React from 'react';
import { Link } from '@waldur/core/Link';
import { Table, connectTable, createFetcher } from '@waldur/table-react';
const TableComponent = props => {
const { translate } = props;
return (
<Table
{...props}
columns={[
{
title: translate('Name'),
render: ({ row }) => (
<Link
state="rancher-template-details"
params={{
uuid: props.resource.project_uuid,
clusterUuid: props.resource.uuid,
templateUuid: row.uuid,
}}
>
{row.name}
</Link>
),
},
{
title: translate('Description'),
render: ({ row }) => <span>{row.description}</span>,
},
{
title: translate('Catalog'),
render: ({ row }) => <span>{row.catalog_name}</span>,
},
{
title: translate('State'),
render: ({ row }) => <span>{row.runtime_state}</span>,
},
]}
verboseName={translate('application templates')}
/>
);
};
const TableOptions = {
table: 'rancher-cluster-templates',
fetchData: createFetcher('rancher-templates'),
exportFields: ['name', 'description', 'catalog'],
exportRow: row => [row.name, row.description, row.catalog_name],
mapPropsToFilter: props => ({
cluster_uuid: props.resource.uuid,
}),
};
export const ClusterTemplatesList = connectTable(TableOptions)(TableComponent);
| Allow Application creation from Application template list | Allow Application creation from Application template list [WAL-3082]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,5 +1,6 @@
import * as React from 'react';
+import { Link } from '@waldur/core/Link';
import { Table, connectTable, createFetcher } from '@waldur/table-react';
const TableComponent = props => {
@@ -10,7 +11,18 @@
columns={[
{
title: translate('Name'),
- render: ({ row }) => <span>{row.name}</span>,
+ render: ({ row }) => (
+ <Link
+ state="rancher-template-details"
+ params={{
+ uuid: props.resource.project_uuid,
+ clusterUuid: props.resource.uuid,
+ templateUuid: row.uuid,
+ }}
+ >
+ {row.name}
+ </Link>
+ ),
},
{
title: translate('Description'), |
87570f71c62cb11b44d8056f1f38c9e744330970 | src/app/components/forms/dashboard/game/dev-stage-selector/dev-stage-selector-directive.ts | src/app/components/forms/dashboard/game/dev-stage-selector/dev-stage-selector-directive.ts | import { Component, Inject, Input } from 'ng-metadata/core';
import { FormDashboardGameDevStageSelectorConfirm } from './confirm-service';
import template from 'html!./dev-stage-selector.html';
@Component({
selector: 'gj-form-dashboard-game-dev-stage-selector',
template,
})
export class DevStageSelectorComponent
{
@Input( '<' ) game: any;
constructor(
@Inject( 'Game' ) public gameModel: any,
@Inject( 'FormDashboardGameDevStageSelectorConfirm' ) private confirm: FormDashboardGameDevStageSelectorConfirm
)
{
}
select( stage: number )
{
if ( !this.isEnabled( stage ) || stage == this.game.development_status ) {
return;
}
this.confirm.show( this.game, stage )
.then( () =>
{
this.game.$setDevStage( stage );
} );
}
isEnabled( stage: number )
{
if ( (stage == this.gameModel.DEVELOPMENT_STATUS_WIP || stage == this.gameModel.DEVELOPMENT_STATUS_FINISHED) && !this.game.has_active_builds ) {
return false;
}
return true;
}
}
| import { Component, Inject, Input } from 'ng-metadata/core';
import { FormDashboardGameDevStageSelectorConfirm } from './confirm-service';
import template from 'html!./dev-stage-selector.html';
@Component({
selector: 'gj-form-dashboard-game-dev-stage-selector',
template,
})
export class DevStageSelectorComponent
{
@Input( '<' ) game: any;
constructor(
@Inject( 'Game' ) public gameModel: any,
@Inject( 'FormDashboardGameDevStageSelectorConfirm' ) private confirm: FormDashboardGameDevStageSelectorConfirm,
@Inject( 'Growls' ) private growls: any,
@Inject( 'gettextCatalog' ) private gettextCatalog: ng.gettext.gettextCatalog,
)
{
}
select( stage: number )
{
if ( !this.isEnabled( stage ) || stage == this.game.development_status ) {
return;
}
this.confirm.show( this.game, stage )
.then( () => this.game.$setDevStage( stage ) )
.then( () =>
{
this.growls.success(
this.gettextCatalog.getString( "Your game's development stage has been changed!" ),
this.gettextCatalog.getString( 'Stage Changed' ),
);
} );
}
isEnabled( stage: number )
{
if ( (stage == this.gameModel.DEVELOPMENT_STATUS_WIP || stage == this.gameModel.DEVELOPMENT_STATUS_FINISHED) && !this.game.has_active_builds ) {
return false;
}
return true;
}
}
| Add a growl when switching your dev stage. | Add a growl when switching your dev stage.
| TypeScript | mit | gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt | ---
+++
@@ -12,7 +12,9 @@
constructor(
@Inject( 'Game' ) public gameModel: any,
- @Inject( 'FormDashboardGameDevStageSelectorConfirm' ) private confirm: FormDashboardGameDevStageSelectorConfirm
+ @Inject( 'FormDashboardGameDevStageSelectorConfirm' ) private confirm: FormDashboardGameDevStageSelectorConfirm,
+ @Inject( 'Growls' ) private growls: any,
+ @Inject( 'gettextCatalog' ) private gettextCatalog: ng.gettext.gettextCatalog,
)
{
}
@@ -24,9 +26,13 @@
}
this.confirm.show( this.game, stage )
+ .then( () => this.game.$setDevStage( stage ) )
.then( () =>
{
- this.game.$setDevStage( stage );
+ this.growls.success(
+ this.gettextCatalog.getString( "Your game's development stage has been changed!" ),
+ this.gettextCatalog.getString( 'Stage Changed' ),
+ );
} );
}
|
dc3557df9449513b308d2a216f62407fb3e597d0 | src/client/components/DemographicsChart.tsx | src/client/components/DemographicsChart.tsx | /** @jsx jsx */
import mapValues from "lodash/mapValues";
import { Box, Flex, jsx } from "theme-ui";
import { demographicsColors } from "../constants/colors";
const Bar = ({ width, color }: { readonly width: string; readonly color: string }) => (
<Box
sx={{
width,
backgroundColor: color,
flex: "1"
}}
></Box>
);
const DemographicsChart = ({
demographics
}: {
readonly demographics: { readonly [id: string]: number };
}) => {
const percentages = mapValues(
demographics,
(population: number) =>
`${(demographics.population ? population / demographics.population : 0) * 100}%`
);
return (
<Flex sx={{ flexDirection: "column", width: "100%", minHeight: "100%" }}>
<Bar width={percentages.white} color={demographicsColors.white} />
<Bar width={percentages.black} color={demographicsColors.black} />
<Bar width={percentages.asian} color={demographicsColors.asian} />
<Bar width={percentages.hispanic} color={demographicsColors.hispanic} />
<Bar width={percentages.other} color={demographicsColors.other} />
</Flex>
);
};
export default DemographicsChart;
| /** @jsx jsx */
import mapValues from "lodash/mapValues";
import { Box, Flex, jsx } from "theme-ui";
import { demographicsColors } from "../constants/colors";
const Bar = ({ width, color }: { readonly width: string; readonly color: string }) => (
<Box
sx={{
width,
backgroundColor: color,
flex: "1"
}}
></Box>
);
const DemographicsChart = ({
demographics
}: {
readonly demographics: { readonly [id: string]: number };
}) => {
const percentages = mapValues(
demographics,
(population: number) =>
`${(demographics.population ? population / demographics.population : 0) * 100}%`
);
return (
<Flex sx={{ flexDirection: "column", width: "40px", minHeight: "20px", flexShrink: 0 }}>
<Bar width={percentages.white} color={demographicsColors.white} />
<Bar width={percentages.black} color={demographicsColors.black} />
<Bar width={percentages.asian} color={demographicsColors.asian} />
<Bar width={percentages.hispanic} color={demographicsColors.hispanic} />
<Bar width={percentages.other} color={demographicsColors.other} />
</Flex>
);
};
export default DemographicsChart;
| Fix size for race chart | Fix size for race chart
| TypeScript | apache-2.0 | PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder,PublicMapping/DistrictBuilder | ---
+++
@@ -25,7 +25,7 @@
`${(demographics.population ? population / demographics.population : 0) * 100}%`
);
return (
- <Flex sx={{ flexDirection: "column", width: "100%", minHeight: "100%" }}>
+ <Flex sx={{ flexDirection: "column", width: "40px", minHeight: "20px", flexShrink: 0 }}>
<Bar width={percentages.white} color={demographicsColors.white} />
<Bar width={percentages.black} color={demographicsColors.black} />
<Bar width={percentages.asian} color={demographicsColors.asian} /> |
e77d5cf1dd175040d341101cf03fd5e9542a9fb0 | source/renderer/app/components/wallet/summary/WalletSummaryHeaderRewards.spec.ts | source/renderer/app/components/wallet/summary/WalletSummaryHeaderRewards.spec.ts | import BigNumber from 'bignumber.js';
import {
discreetRewardsAmount,
getFormattedRewardAmount,
} from './WalletSummaryHeaderRewards';
describe('getFormattedRewardAmount', () => {
it('should render integer amounts without decimal places', () => {
expect(getFormattedRewardAmount(new BigNumber(1))).toEqual('1 ADA');
});
it('should render fraction amounts with a single decimal place', () => {
expect(getFormattedRewardAmount(new BigNumber(0.512))).toEqual('0.5 ADA');
});
it('should indicate values below 0.1', () => {
expect(getFormattedRewardAmount(new BigNumber(0.05))).toEqual('< 0.1 ADA');
});
});
describe('discreetRewardsAmount', () => {
const symbol = '***';
it('should replace the amount with a dash while restoring', () => {
const replacer = discreetRewardsAmount(true);
expect(replacer(true, symbol, new BigNumber(0))).toEqual('-');
});
it('should replace the amount with a discreet value', () => {
const replacer = discreetRewardsAmount();
expect(replacer(true, symbol, new BigNumber(0))).toEqual('*** ADA');
});
it('should return the formatted ADA value', () => {
const replacer = discreetRewardsAmount();
expect(replacer(false, symbol, new BigNumber(0.5))).toEqual('0.5 ADA');
});
});
| import BigNumber from 'bignumber.js';
import {
discreetRewardsAmount,
getFormattedRewardAmount,
} from './WalletSummaryHeaderRewards';
describe('getFormattedRewardAmount', () => {
it('should render integer amounts without decimal places', () => {
expect(getFormattedRewardAmount(new BigNumber(1))).toEqual('1 ADA');
});
it('should render fraction amounts with a single decimal place', () => {
expect(getFormattedRewardAmount(new BigNumber(0.512))).toEqual('0.5 ADA');
});
it('should indicate values below 0.1', () => {
expect(getFormattedRewardAmount(new BigNumber(0.05))).toEqual('< 0.1 ADA');
});
});
describe('discreetRewardsAmount', () => {
const symbol = '***';
it('should replace the amount with a dash while restoring', () => {
const replacer = discreetRewardsAmount(true);
expect(replacer(true, symbol, new BigNumber(0))).toEqual('–');
});
it('should replace the amount with a discreet value', () => {
const replacer = discreetRewardsAmount();
expect(replacer(true, symbol, new BigNumber(0))).toEqual('*** ADA');
});
it('should return the formatted ADA value', () => {
const replacer = discreetRewardsAmount();
expect(replacer(false, symbol, new BigNumber(0.5))).toEqual('0.5 ADA');
});
});
| Fix broken test case about dash | [DDW-614] Fix broken test case about dash
| TypeScript | apache-2.0 | input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus | ---
+++
@@ -19,7 +19,7 @@
const symbol = '***';
it('should replace the amount with a dash while restoring', () => {
const replacer = discreetRewardsAmount(true);
- expect(replacer(true, symbol, new BigNumber(0))).toEqual('-');
+ expect(replacer(true, symbol, new BigNumber(0))).toEqual('–');
});
it('should replace the amount with a discreet value', () => {
const replacer = discreetRewardsAmount(); |
716a112b8d60d8b321a0894d096cd1adcef94795 | app/src/lib/editors/linux.ts | app/src/lib/editors/linux.ts | import { IFoundEditor } from './found-editor'
import { pathExists } from '../file-system'
import { assertNever } from '../fatal-error'
export enum ExternalEditor {
VisualStudioCode = 'Visual Studio Code',
}
export function parse(label: string): ExternalEditor | null {
if (label === ExternalEditor.VisualStudioCode) {
return ExternalEditor.VisualStudioCode
}
return null
}
async function getPathIfAvailable(path: string): Promise<string | null> {
return (await pathExists(path)) ? path : null
}
function getEditorPath(editor: ExternalEditor): Promise<string | null> {
switch (editor) {
case ExternalEditor.VisualStudioCode:
return getPathIfAvailable('/usr/bin/code')
default:
return assertNever(editor, `Unknown editor: ${editor}`)
}
}
export async function getAvailableEditors(): Promise<
ReadonlyArray<IFoundEditor<ExternalEditor>>
> {
const results: Array<IFoundEditor<ExternalEditor>> = []
const [codePath] = await Promise.all([
getEditorPath(ExternalEditor.VisualStudioCode),
])
if (codePath) {
results.push({ editor: ExternalEditor.VisualStudioCode, path: codePath })
}
return results
}
| import { IFoundEditor } from './found-editor'
import { pathExists } from '../file-system'
import { assertNever } from '../fatal-error'
export enum ExternalEditor {
Atom = 'Atom',
VisualStudioCode = 'Visual Studio Code',
}
export function parse(label: string): ExternalEditor | null {
if (label === ExternalEditor.Atom) {
return ExternalEditor.Atom
}
if (label === ExternalEditor.VisualStudioCode) {
return ExternalEditor.VisualStudioCode
}
return null
}
async function getPathIfAvailable(path: string): Promise<string | null> {
return (await pathExists(path)) ? path : null
}
function getEditorPath(editor: ExternalEditor): Promise<string | null> {
switch (editor) {
case ExternalEditor.VisualStudioCode:
return getPathIfAvailable('/usr/bin/code')
case ExternalEditor.Atom:
return getPathIfAvailable('/usr/bin/atom')
default:
return assertNever(editor, `Unknown editor: ${editor}`)
}
}
export async function getAvailableEditors(): Promise<
ReadonlyArray<IFoundEditor<ExternalEditor>>
> {
const results: Array<IFoundEditor<ExternalEditor>> = []
const [atomPath, codePath] = await Promise.all([
getEditorPath(ExternalEditor.Atom),
getEditorPath(ExternalEditor.VisualStudioCode),
])
if (atomPath) {
results.push({ editor: ExternalEditor.Atom, path: atomPath })
}
if (codePath) {
results.push({ editor: ExternalEditor.VisualStudioCode, path: codePath })
}
return results
}
| Add Atom support on Linux | Add Atom support on Linux
| TypeScript | mit | say25/desktop,artivilla/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,desktop/desktop,kactus-io/kactus,say25/desktop | ---
+++
@@ -3,10 +3,15 @@
import { assertNever } from '../fatal-error'
export enum ExternalEditor {
+ Atom = 'Atom',
VisualStudioCode = 'Visual Studio Code',
}
export function parse(label: string): ExternalEditor | null {
+ if (label === ExternalEditor.Atom) {
+ return ExternalEditor.Atom
+ }
+
if (label === ExternalEditor.VisualStudioCode) {
return ExternalEditor.VisualStudioCode
}
@@ -22,6 +27,8 @@
switch (editor) {
case ExternalEditor.VisualStudioCode:
return getPathIfAvailable('/usr/bin/code')
+ case ExternalEditor.Atom:
+ return getPathIfAvailable('/usr/bin/atom')
default:
return assertNever(editor, `Unknown editor: ${editor}`)
}
@@ -32,9 +39,14 @@
> {
const results: Array<IFoundEditor<ExternalEditor>> = []
- const [codePath] = await Promise.all([
+ const [atomPath, codePath] = await Promise.all([
+ getEditorPath(ExternalEditor.Atom),
getEditorPath(ExternalEditor.VisualStudioCode),
])
+
+ if (atomPath) {
+ results.push({ editor: ExternalEditor.Atom, path: atomPath })
+ }
if (codePath) {
results.push({ editor: ExternalEditor.VisualStudioCode, path: codePath }) |
967f22210dca8f79ce3894ae954393c256c04771 | components/locale-provider/it_IT.tsx | components/locale-provider/it_IT.tsx | import Pagination from 'rc-pagination/lib/locale/it_IT';
import DatePicker from '../date-picker/locale/it_IT';
import TimePicker from '../time-picker/locale/it_IT';
import Calendar from '../calendar/locale/it_IT';
export default {
locale: 'it',
Pagination,
DatePicker,
TimePicker,
Calendar,
Table: {
filterTitle: 'Menù Filtro',
filterConfirm: 'OK',
filterReset: 'Reset',
selectAll: 'Seleziona pagina corrente',
selectInvert: 'Inverti selezione nella pagina corrente',
sortTitle: 'Ordina',
},
Modal: {
okText: 'OK',
cancelText: 'Annulla',
justOkText: 'OK',
},
Popconfirm: {
okText: 'OK',
cancelText: 'Annulla',
},
Transfer: {
searchPlaceholder: 'Cerca qui',
itemUnit: 'articolo',
itemsUnit: 'elementi',
},
Upload: {
uploading: 'Caricamento...',
removeFile: 'Rimuovi il file',
uploadError: 'Errore di caricamento',
previewFile: 'Anteprima file',
},
Empty: {
description: 'Nessun dato',
},
};
| import Pagination from 'rc-pagination/lib/locale/it_IT';
import DatePicker from '../date-picker/locale/it_IT';
import TimePicker from '../time-picker/locale/it_IT';
import Calendar from '../calendar/locale/it_IT';
export default {
locale: 'it',
Pagination,
DatePicker,
TimePicker,
Calendar,
global: {
placeholder: 'Selezionare',
},
Table: {
filterTitle: 'Menù Filtro',
filterConfirm: 'OK',
filterReset: 'Reset',
selectAll: 'Seleziona pagina corrente',
selectInvert: 'Inverti selezione nella pagina corrente',
sortTitle: 'Ordina',
},
Modal: {
okText: 'OK',
cancelText: 'Annulla',
justOkText: 'OK',
},
Popconfirm: {
okText: 'OK',
cancelText: 'Annulla',
},
Transfer: {
searchPlaceholder: 'Cerca qui',
itemUnit: 'articolo',
itemsUnit: 'elementi',
},
Upload: {
uploading: 'Caricamento...',
removeFile: 'Rimuovi il file',
uploadError: 'Errore di caricamento',
previewFile: 'Anteprima file',
},
Empty: {
description: 'Nessun dato',
},
Icon: {
icon: 'icona',
},
Text: {
edit: 'modifica',
copy: 'copia',
copied: 'copia effettuata',
expand: 'espandi',
},
};
| Add Italian localization of Icon, Text and global components | Add Italian localization of Icon, Text and global components
| TypeScript | mit | ant-design/ant-design,icaife/ant-design,icaife/ant-design,elevensky/ant-design,elevensky/ant-design,zheeeng/ant-design,elevensky/ant-design,icaife/ant-design,icaife/ant-design,ant-design/ant-design,elevensky/ant-design,ant-design/ant-design,zheeeng/ant-design,zheeeng/ant-design,zheeeng/ant-design,ant-design/ant-design | ---
+++
@@ -9,6 +9,9 @@
DatePicker,
TimePicker,
Calendar,
+ global: {
+ placeholder: 'Selezionare',
+ },
Table: {
filterTitle: 'Menù Filtro',
filterConfirm: 'OK',
@@ -40,4 +43,13 @@
Empty: {
description: 'Nessun dato',
},
+ Icon: {
+ icon: 'icona',
+ },
+ Text: {
+ edit: 'modifica',
+ copy: 'copia',
+ copied: 'copia effettuata',
+ expand: 'espandi',
+ },
}; |
9886dce63dfa876e00a088655bed49370466dd43 | packages/components/containers/referral/rewards/table/RewardCell.tsx | packages/components/containers/referral/rewards/table/RewardCell.tsx | import { c, msgid } from 'ttag';
import { Referral, ReferralState } from '@proton/shared/lib/interfaces';
interface Props {
referral: Referral;
}
const RewardCell = ({ referral }: Props) => {
let reward: string | React.ReactNode = '-';
const monthsRewarded = referral.RewardMonths || 0;
switch (referral.State) {
case ReferralState.SIGNED_UP:
case ReferralState.COMPLETED:
/*
* translator : We are in a table cell.
* A user referee have signed up or completed a subscription
* We show the reward user would be allowed to get.
* Example : "3 months pending"
*/
reward = c('Label').ngettext(
msgid`${monthsRewarded} month pending`,
`${monthsRewarded} months pending`,
monthsRewarded
);
break;
case ReferralState.REWARDED:
/*
* translator : We are in a table cell.
* A user referee have signed up or completed a subscription
* We show the reward user has been credited.
* Example : "3 months credited"
*/
reward = c('Label').ngettext(
msgid`${monthsRewarded} month credited`,
`${monthsRewarded} months credited`,
monthsRewarded
);
break;
}
return <>{reward}</>;
};
export default RewardCell;
| import { c, msgid } from 'ttag';
import { Referral, ReferralState } from '@proton/shared/lib/interfaces';
interface Props {
referral: Referral;
}
const RewardCell = ({ referral }: Props) => {
let reward: string | React.ReactNode = '-';
const monthsRewarded = referral.RewardMonths || 0;
switch (referral.State) {
case ReferralState.COMPLETED:
/*
* translator : We are in a table cell.
* A user referee have signed up or completed a subscription
* We show the reward user would be allowed to get.
* Example : "3 months pending"
*/
reward = c('Label').ngettext(
msgid`${monthsRewarded} month pending`,
`${monthsRewarded} months pending`,
monthsRewarded
);
break;
case ReferralState.REWARDED:
/*
* translator : We are in a table cell.
* A user referee have signed up or completed a subscription
* We show the reward user has been credited.
* Example : "3 months credited"
*/
reward = c('Label').ngettext(
msgid`${monthsRewarded} month credited`,
`${monthsRewarded} months credited`,
monthsRewarded
);
break;
}
return <>{reward}</>;
};
export default RewardCell;
| Remove pending months in reward cell when signedup or trial | Remove pending months in reward cell when signedup or trial
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -11,7 +11,6 @@
const monthsRewarded = referral.RewardMonths || 0;
switch (referral.State) {
- case ReferralState.SIGNED_UP:
case ReferralState.COMPLETED:
/*
* translator : We are in a table cell. |
a2ab817973adb45acf67a62f2d481300e5a6b017 | src/kayenta/metricStore/stackdriver/domain/IStackdriverCanaryMetricSetQueryConfig.ts | src/kayenta/metricStore/stackdriver/domain/IStackdriverCanaryMetricSetQueryConfig.ts | import { ICanaryMetricSetQueryConfig } from 'kayenta/domain';
export interface IStackdriverCanaryMetricSetQueryConfig extends ICanaryMetricSetQueryConfig {
metricType: string;
groupByFields: string[];
}
| import { ICanaryMetricSetQueryConfig } from 'kayenta/domain';
export interface IStackdriverCanaryMetricSetQueryConfig extends ICanaryMetricSetQueryConfig {
metricType: string;
resourceType: string;
crossSeriesReducer: string;
perSeriesAligner: string;
groupByFields: string[];
}
| Add new metric config fields. | feat(stackdriver): Add new metric config fields.
| TypeScript | apache-2.0 | spinnaker/deck-kayenta,spinnaker/deck-kayenta,spinnaker/deck-kayenta,spinnaker/deck-kayenta | ---
+++
@@ -2,5 +2,8 @@
export interface IStackdriverCanaryMetricSetQueryConfig extends ICanaryMetricSetQueryConfig {
metricType: string;
+ resourceType: string;
+ crossSeriesReducer: string;
+ perSeriesAligner: string;
groupByFields: string[];
} |
a77c3a31d97fb70028c7bce6cf1fcf6abf895d6b | html/ts/reports/cmdtable.tsx | html/ts/reports/cmdtable.tsx |
function reportCmdTable(profile: Profile[], search: Prop<Search>): HTMLElement {
return cmdTableData(search.get());
}
function cmdTableData(search: Search): HTMLElement {
const res: MapString< {count: int, total: seconds, max: seconds} > = {};
search.forEachProfile(p =>
p.traces.forEach(t => {
const time = t.stop - t.start;
if (!(t.command in res))
res[t.command] = {count: 1, total: time, max: time};
else {
const ans = res[t.command];
ans.count++;
ans.total += time;
ans.max = Math.max(ans.max, time);
}
})
);
const columns: Column[] =
[ {field: "name", label: "Name", width: 200}
, {field: "count", label: "Count", width: 75, alignRight: true, show: showInt}
, {field: "total", label: "Total", width: 75, alignRight: true, show: showTime}
, {field: "average", label: "Average", width: 75, alignRight: true, show: showTime}
, {field: "max", label: "Max", width: 75, alignRight: true, show: showTime}
];
const res2 = [];
for (const i in res)
res2.push({name: i, average: res[i].total / res[i].count, ...res[i]});
return newTable(columns, new Prop(res2));
}
|
function reportCmdTable(profile: Profile[], search: Prop<Search>): HTMLElement {
const columns: Column[] =
[ {field: "name", label: "Name", width: 200}
, {field: "count", label: "Count", width: 75, alignRight: true, show: showInt}
, {field: "total", label: "Total", width: 75, alignRight: true, show: showTime}
, {field: "average", label: "Average", width: 75, alignRight: true, show: showTime}
, {field: "max", label: "Max", width: 75, alignRight: true, show: showTime}
];
return newTable(columns, new Prop(cmdTableData(search.get())));
}
function cmdTableData(search: Search): object[] {
const res: MapString< {count: int, total: seconds, max: seconds} > = {};
search.forEachProfile(p =>
p.traces.forEach(t => {
const time = t.stop - t.start;
if (!(t.command in res))
res[t.command] = {count: 1, total: time, max: time};
else {
const ans = res[t.command];
ans.count++;
ans.total += time;
ans.max = Math.max(ans.max, time);
}
})
);
const res2 = [];
for (const i in res)
res2.push({name: i, average: res[i].total / res[i].count, ...res[i]});
return res2;
}
| Simplify the command, split out data from UI | Simplify the command, split out data from UI
| TypeScript | bsd-3-clause | ndmitchell/shake,ndmitchell/shake,ndmitchell/shake,ndmitchell/shake,ndmitchell/shake,ndmitchell/shake | ---
+++
@@ -1,9 +1,16 @@
function reportCmdTable(profile: Profile[], search: Prop<Search>): HTMLElement {
- return cmdTableData(search.get());
+ const columns: Column[] =
+ [ {field: "name", label: "Name", width: 200}
+ , {field: "count", label: "Count", width: 75, alignRight: true, show: showInt}
+ , {field: "total", label: "Total", width: 75, alignRight: true, show: showTime}
+ , {field: "average", label: "Average", width: 75, alignRight: true, show: showTime}
+ , {field: "max", label: "Max", width: 75, alignRight: true, show: showTime}
+ ];
+ return newTable(columns, new Prop(cmdTableData(search.get())));
}
-function cmdTableData(search: Search): HTMLElement {
+function cmdTableData(search: Search): object[] {
const res: MapString< {count: int, total: seconds, max: seconds} > = {};
search.forEachProfile(p =>
p.traces.forEach(t => {
@@ -18,15 +25,8 @@
}
})
);
- const columns: Column[] =
- [ {field: "name", label: "Name", width: 200}
- , {field: "count", label: "Count", width: 75, alignRight: true, show: showInt}
- , {field: "total", label: "Total", width: 75, alignRight: true, show: showTime}
- , {field: "average", label: "Average", width: 75, alignRight: true, show: showTime}
- , {field: "max", label: "Max", width: 75, alignRight: true, show: showTime}
- ];
const res2 = [];
for (const i in res)
res2.push({name: i, average: res[i].total / res[i].count, ...res[i]});
- return newTable(columns, new Prop(res2));
+ return res2;
} |
9693c1ab1302d8c51f48829d6b7701b4ed580d44 | packages/machinomy/src/storage/postgresql/migrations/20180115082606-create-payment.ts | packages/machinomy/src/storage/postgresql/migrations/20180115082606-create-payment.ts | import { Base, CallbackFunction } from 'db-migrate-base'
import bigNumberColumn from './util/bigNumberColumn'
export function up (db: Base, callback: CallbackFunction) {
const createTableOptions = {
columns: {
channelId: {
type: 'string',
notNull: true,
foreignKey: {
name: 'tokens_channel_id_fk',
table: 'channel',
mapping: 'channelId',
rules: {
onDelete: 'CASCADE'
}
}
},
kind: 'string',
token: {
type: 'string',
notNull: true,
unique: true
},
sender: 'string',
receiver: 'string',
price: bigNumberColumn,
value: bigNumberColumn,
channelValue: bigNumberColumn,
v: 'int',
r: 'string',
s: 'string',
meta: 'string',
contractAddress: 'string'
},
ifNotExists: true
}
db.createTable('payment', createTableOptions, callback)
}
export function down (db: Base, callback: CallbackFunction) {
db.dropTable('payment', callback)
}
| import { Base, CallbackFunction } from 'db-migrate-base'
import bigNumberColumn from './util/bigNumberColumn'
export function up (db: Base, callback: CallbackFunction) {
const createTableOptions = {
columns: {
channelId: {
type: 'string',
notNull: true
},
kind: 'string',
token: {
type: 'string',
notNull: true,
unique: true
},
sender: 'string',
receiver: 'string',
price: bigNumberColumn,
value: bigNumberColumn,
channelValue: bigNumberColumn,
v: 'int',
r: 'string',
s: 'string',
meta: 'string',
contractAddress: 'string'
},
ifNotExists: true
}
db.createTable('payment', createTableOptions, callback)
}
export function down (db: Base, callback: CallbackFunction) {
db.dropTable('payment', callback)
}
| Remove one more constraint on db level | Remove one more constraint on db level
| TypeScript | apache-2.0 | machinomy/machinomy,machinomy/machinomy,machinomy/machinomy | ---
+++
@@ -6,15 +6,7 @@
columns: {
channelId: {
type: 'string',
- notNull: true,
- foreignKey: {
- name: 'tokens_channel_id_fk',
- table: 'channel',
- mapping: 'channelId',
- rules: {
- onDelete: 'CASCADE'
- }
- }
+ notNull: true
},
kind: 'string',
token: { |
c6c31a69852893edd7aa62d64e8865d484139703 | src/actions/GrabbedAction.ts | src/actions/GrabbedAction.ts | import { Action } from "./Action";
import { ActionType } from "./ActionType";
import { StrayKittyState } from "../StrayKittyState";
import { StandingAction } from "./StandingAction";
import { ActionHelpers } from "./ActionHelpers";
export class GrabbedAction implements Action {
do(kitty: StrayKittyState, dt: number) {
if (kitty.y < window.innerHeight - 32) {
kitty.yVector += dt / 250;
} else {
if (Math.abs(kitty.yVector) < dt / 100) {
kitty.y = window.innerHeight - 32;
kitty.action = new StandingAction();
}
kitty.yVector *= -0.5;
}
}
readonly type = ActionType.Falling;
readonly frames = [1, 2, 3];
}
| import { Action } from "./Action";
import { ActionType } from "./ActionType";
import { StrayKittyState } from "../StrayKittyState";
import { StandingAction } from "./StandingAction";
import { ActionHelpers } from "./ActionHelpers";
export class GrabbedAction implements Action {
do(kitty: StrayKittyState, dt: number) {
}
readonly type = ActionType.Grabbed;
readonly frames = [1, 2, 3];
}
| Fix kitties can't be grabbed | Fix kitties can't be grabbed
| TypeScript | mit | xianbaum/StrayKitty,xianbaum/StrayKitty,xianbaum/StrayKitty | ---
+++
@@ -6,18 +6,9 @@
export class GrabbedAction implements Action {
do(kitty: StrayKittyState, dt: number) {
- if (kitty.y < window.innerHeight - 32) {
- kitty.yVector += dt / 250;
- } else {
- if (Math.abs(kitty.yVector) < dt / 100) {
- kitty.y = window.innerHeight - 32;
- kitty.action = new StandingAction();
- }
- kitty.yVector *= -0.5;
- }
}
- readonly type = ActionType.Falling;
+ readonly type = ActionType.Grabbed;
readonly frames = [1, 2, 3];
} |
b9c3c760a9dcc9884e175fa4d8ac2e841639f7f7 | app/src/config.ts | app/src/config.ts | /*
* The MIT License (MIT)
* Copyright (c) 2016 Heat Ledger Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* */
heat.Loader.config(['$mdThemingProvider', 'noCAPTCHAProvider',
($mdThemingProvider, noCAPTCHAProvider) => {
$mdThemingProvider.theme('default')
.primaryPalette('teal')
.accentPalette('grey');
noCAPTCHAProvider.setSiteKey('6Le7pBITAAAAANPHWrIsoP_ZvlxWr0bSjOPrlszc');
noCAPTCHAProvider.setTheme('light');
}]); | /*
* The MIT License (MIT)
* Copyright (c) 2016 Heat Ledger Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* */
heat.Loader.config(['$mdThemingProvider', 'noCAPTCHAProvider',
($mdThemingProvider, noCAPTCHAProvider) => {
$mdThemingProvider.theme('default')
.primaryPalette('indigo')
.accentPalette('pink');
noCAPTCHAProvider.setSiteKey('6Le7pBITAAAAANPHWrIsoP_ZvlxWr0bSjOPrlszc');
noCAPTCHAProvider.setTheme('light');
}]); | Set default theme to indigo | Set default theme to indigo
| TypeScript | mit | Heat-Ledger-Ltd/heat-ui,Heat-Ledger-Ltd/heat-ui,Heat-Ledger-Ltd/heat-ui | ---
+++
@@ -24,8 +24,8 @@
($mdThemingProvider, noCAPTCHAProvider) => {
$mdThemingProvider.theme('default')
- .primaryPalette('teal')
- .accentPalette('grey');
+ .primaryPalette('indigo')
+ .accentPalette('pink');
noCAPTCHAProvider.setSiteKey('6Le7pBITAAAAANPHWrIsoP_ZvlxWr0bSjOPrlszc');
noCAPTCHAProvider.setTheme('light'); |
781c4563dbf7f5bff7a4fb72d663b867bfb98889 | src/ng2-restangular-helper.ts | src/ng2-restangular-helper.ts | import {URLSearchParams, Headers, RequestOptions, RequestMethod} from '@angular/http';
export class RestangularHelper {
static createRequestOptions(options) {
let requestQueryParams = RestangularHelper.createRequestQueryParams(options.params);
let requestHeaders = RestangularHelper.createRequestHeaders(options.headers);
let methodName = options.method.charAt(0).toUpperCase() + options.method.substr(1).toLowerCase();
let withCredentials = options.withCredentials || false;
let requestOptions = new RequestOptions({
method: RequestMethod[methodName],
headers: requestHeaders,
search: requestQueryParams,
url: options.url,
body: options.data,
withCredentials
});
return requestOptions;
}
static createRequestQueryParams(queryParams) {
let requestQueryParams = Object.assign({}, queryParams);
let search: URLSearchParams = new URLSearchParams();
for (let key in requestQueryParams) {
let value: any = requestQueryParams[key];
if (typeof value === 'object') {
value = JSON.stringify(value);
}
search.append(key, value);
}
return search;
}
static createRequestHeaders(headers) {
for (let key in headers) {
let value: any = headers[key];
if (typeof value === 'undefined') {
delete headers[key];
}
}
return new Headers(Object.assign({}, headers));
}
}
| import {URLSearchParams, Headers, RequestOptions, RequestMethod} from '@angular/http';
export class RestangularHelper {
static createRequestOptions(options) {
let requestQueryParams = RestangularHelper.createRequestQueryParams(options.params);
let requestHeaders = RestangularHelper.createRequestHeaders(options.headers);
let methodName = options.method.charAt(0).toUpperCase() + options.method.substr(1).toLowerCase();
let withCredentials = options.withCredentials || false;
let requestOptions = new RequestOptions({
method: RequestMethod[methodName],
headers: requestHeaders,
search: requestQueryParams,
url: options.url,
body: options.data,
withCredentials
});
return requestOptions;
}
static createRequestQueryParams(queryParams) {
let requestQueryParams = Object.assign({}, queryParams);
let search: URLSearchParams = new URLSearchParams();
for (let key in requestQueryParams) {
let value: any = requestQueryParams[key];
if (Array.isArray(value)) {
value.forEach(function(val){
search.append(key, val);
});
} else {
if (typeof value === 'object') {
value = JSON.stringify(value);
}
search.append(key, value);
}
}
return search;
}
static createRequestHeaders(headers) {
for (let key in headers) {
let value: any = headers[key];
if (typeof value === 'undefined') {
delete headers[key];
}
}
return new Headers(Object.assign({}, headers));
}
}
| Fix URLSearchParams for query params of type Array | Fix URLSearchParams for query params of type Array
| TypeScript | mit | 2muchcoffeecom/ng2-restangular,2muchcoffeecom/ng2-restangular,2muchcoffeecom/ngx-restangular,2muchcoffeecom/ngx-restangular | ---
+++
@@ -26,10 +26,18 @@
for (let key in requestQueryParams) {
let value: any = requestQueryParams[key];
- if (typeof value === 'object') {
- value = JSON.stringify(value);
+
+ if (Array.isArray(value)) {
+ value.forEach(function(val){
+ search.append(key, val);
+ });
+ } else {
+ if (typeof value === 'object') {
+ value = JSON.stringify(value);
+ }
+ search.append(key, value);
}
- search.append(key, value);
+
}
return search; |
c24131f80483d0d4ca4a3f7efff58fd43286b617 | config.service.ts | config.service.ts | export class HsConfig {
componentsEnabled: any;
mapInteractionsEnabled: boolean;
allowAddExternalDatasets: boolean;
sidebarClosed: boolean;
layer_order: string
constructor() {
}
} | export class HsConfig {
componentsEnabled: any;
mapInteractionsEnabled: boolean;
allowAddExternalDatasets: boolean;
sidebarClosed: boolean;
layer_order: string;
box_layers: Array<any>;
constructor() {
}
} | Add box layer to config class definition | Add box layer to config class definition
| TypeScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -3,7 +3,8 @@
mapInteractionsEnabled: boolean;
allowAddExternalDatasets: boolean;
sidebarClosed: boolean;
- layer_order: string
+ layer_order: string;
+ box_layers: Array<any>;
constructor() {
} |
035be40c5869ea9e65dd89c0ea16aafac2636a3e | frontend/src/lib/StatusCalculator.ts | frontend/src/lib/StatusCalculator.ts | import Status from 'models/Status';
import Step from 'models/Step';
import Feature from 'models/Feature';
type ScenarioDetails = {
backgroundSteps: Step[];
steps: Step[];
};
const STATUS_PRIORITY_ORDER = [Status.Failed, Status.Undefined, Status.Skipped, Status.Passed];
export const calculateFeatureStatus = (feature: Feature): Status => {
const scenarioStatuses = feature.scenarios.map(scenario => scenario.calculatedStatus || scenario.originalAutomatedStatus);
const featureStatus = STATUS_PRIORITY_ORDER.find(status => scenarioStatuses.includes(status));
if (featureStatus) {
return featureStatus;
}
return Status.Passed;
};
const calculateStatus = (scenario: ScenarioDetails, getStepStatus: (step: Step) => Status): Status => {
const statuses: Status[] = [];
statuses.push(...scenario.backgroundSteps.map(getStepStatus));
statuses.push(...scenario.steps.map(getStepStatus));
statuses.sort((status1, status2) => STATUS_PRIORITY_ORDER.indexOf(status1) - STATUS_PRIORITY_ORDER.indexOf(status2));
if (statuses.length > 0) {
return statuses[0];
}
return Status.Passed;
};
export const calculateManualStatus = (scenario: ScenarioDetails): Status =>
calculateStatus(scenario, step => step.manualStatus || step.status);
export const calculateAutoStatus = (scenario: ScenarioDetails): Status => calculateStatus(scenario, step => step.status);
| import Status from 'models/Status';
import Step from 'models/Step';
import Feature from 'models/Feature';
type ScenarioDetails = {
backgroundSteps: Step[];
steps: Step[];
};
const STATUS_PRIORITY_ORDER = [Status.Failed, Status.Undefined, Status.Skipped, Status.Passed];
export const calculateFeatureStatus = (feature: Feature): Status => {
const scenarioStatuses = feature.scenarios.map(scenario => scenario.calculatedStatus || scenario.originalAutomatedStatus);
const featureStatus = STATUS_PRIORITY_ORDER.find(status => scenarioStatuses.includes(status));
if (featureStatus) {
return featureStatus;
}
return Status.Passed;
};
const calculateStatus = (scenario: ScenarioDetails, getStepStatus: (step: Step) => Status): Status => {
const statuses: Status[] = [];
if (scenario.backgroundSteps) {
statuses.push(...scenario.backgroundSteps.map(getStepStatus));
}
statuses.push(...scenario.steps.map(getStepStatus));
statuses.sort((status1, status2) => STATUS_PRIORITY_ORDER.indexOf(status1) - STATUS_PRIORITY_ORDER.indexOf(status2));
if (statuses.length > 0) {
return statuses[0];
}
return Status.Passed;
};
export const calculateManualStatus = (scenario: ScenarioDetails): Status =>
calculateStatus(scenario, step => step.manualStatus || step.status);
export const calculateAutoStatus = (scenario: ScenarioDetails): Status => calculateStatus(scenario, step => step.status);
| Check for null backgroundSteps just in case. | Check for null backgroundSteps just in case.
| TypeScript | apache-2.0 | orionhealth/XBDD,orionhealth/XBDD,orionhealth/XBDD,orionhealth/XBDD,orionhealth/XBDD | ---
+++
@@ -19,7 +19,9 @@
const calculateStatus = (scenario: ScenarioDetails, getStepStatus: (step: Step) => Status): Status => {
const statuses: Status[] = [];
- statuses.push(...scenario.backgroundSteps.map(getStepStatus));
+ if (scenario.backgroundSteps) {
+ statuses.push(...scenario.backgroundSteps.map(getStepStatus));
+ }
statuses.push(...scenario.steps.map(getStepStatus));
statuses.sort((status1, status2) => STATUS_PRIORITY_ORDER.indexOf(status1) - STATUS_PRIORITY_ORDER.indexOf(status2));
if (statuses.length > 0) { |
60b8bf7007ce05266dc5034dddba03c986a5f07d | test/lexer-spec.ts | test/lexer-spec.ts | import test from "ava";
import HclLexer from '../src/lexer';
test('Should find tokens correctly', t => {
const SOURCE_TEXT = `
foo = {
bar = "baz \$\${quux} \${var.mumble}"
quux = 42
}
// Example of a heredoc
mumble = <<EOF
foo bar \${baz(2 + 2)}
EOF
more_content = true
`;
const lex = new HclLexer(SOURCE_TEXT);
const output = [];
let token;
while (token = lex.next()) {
output.push(token);
}
t.snapshot(output);
})
| import test from "ava";
import HclLexer from '../src/lexer';
function stringChars(str: string, type = 'stringChar') {
return str.split('').map((c: string) => [type, c]);
}
test('Should find tokens correctly', t => {
const SOURCE_TEXT = `
foo = {
bar = "baz \$\${quux} \${var.mumble}"
quux = 42
}
// Example of a heredoc
mumble = <<EOF
foo bar \${baz(2 + 2)}
EOF
more_content = true
`;
const lex = new HclLexer(SOURCE_TEXT);
const output = [];
let token;
while (token = lex.next()) {
output.push(token);
}
t.deepEqual(
output.filter(token => token.type !== 'ws')
.map(token => [token.type, token.value]),
[
['identifier', 'foo'],
['equal', '='],
['openBrace', '{'],
['identifier', 'bar'],
['equal', '='],
['beginString', '"'],
...stringChars('baz '),
['escapedDollar', '$$'],
...stringChars('{quux} '),
['beginInterpolation', '${'],
['identifier', 'var'],
['dot', '.'],
['identifier', 'mumble'],
['endInterpolation', '}'],
['endString', '"'],
['identifier', 'quux'],
['equal', '='],
['baseTenNumber', '42'],
['closeBrace', '}'],
['beginLineComment', '//'],
...stringChars(' Example of a heredoc', 'commentText'),
['endComment', '\n'],
['identifier', 'mumble'],
['equal', '='],
['beginHeredoc', '<<EOF\n'],
...stringChars('foo bar '),
['beginInterpolation', '${'],
['identifier', 'baz'],
['openParen', '('],
['baseTenNumber', '2'],
['plus', '+'],
['baseTenNumber', '2'],
['closeParen', ')'],
['endInterpolation', '}'],
['newline', '\n'],
['endHeredoc', 'EOF\n'],
['identifier', 'more_content'],
['equal', '='],
['boolean', 'true'],
]
);
});
| Make lexer test more robust | Make lexer test more robust
| TypeScript | mit | r24y/tf-hcl | ---
+++
@@ -1,5 +1,9 @@
import test from "ava";
import HclLexer from '../src/lexer';
+
+function stringChars(str: string, type = 'stringChar') {
+ return str.split('').map((c: string) => [type, c]);
+}
test('Should find tokens correctly', t => {
const SOURCE_TEXT = `
@@ -23,5 +27,49 @@
output.push(token);
}
- t.snapshot(output);
-})
+ t.deepEqual(
+ output.filter(token => token.type !== 'ws')
+ .map(token => [token.type, token.value]),
+ [
+ ['identifier', 'foo'],
+ ['equal', '='],
+ ['openBrace', '{'],
+ ['identifier', 'bar'],
+ ['equal', '='],
+ ['beginString', '"'],
+ ...stringChars('baz '),
+ ['escapedDollar', '$$'],
+ ...stringChars('{quux} '),
+ ['beginInterpolation', '${'],
+ ['identifier', 'var'],
+ ['dot', '.'],
+ ['identifier', 'mumble'],
+ ['endInterpolation', '}'],
+ ['endString', '"'],
+ ['identifier', 'quux'],
+ ['equal', '='],
+ ['baseTenNumber', '42'],
+ ['closeBrace', '}'],
+ ['beginLineComment', '//'],
+ ...stringChars(' Example of a heredoc', 'commentText'),
+ ['endComment', '\n'],
+ ['identifier', 'mumble'],
+ ['equal', '='],
+ ['beginHeredoc', '<<EOF\n'],
+ ...stringChars('foo bar '),
+ ['beginInterpolation', '${'],
+ ['identifier', 'baz'],
+ ['openParen', '('],
+ ['baseTenNumber', '2'],
+ ['plus', '+'],
+ ['baseTenNumber', '2'],
+ ['closeParen', ')'],
+ ['endInterpolation', '}'],
+ ['newline', '\n'],
+ ['endHeredoc', 'EOF\n'],
+ ['identifier', 'more_content'],
+ ['equal', '='],
+ ['boolean', 'true'],
+ ]
+ );
+}); |
879c48c7304a766b02e926eca5b09ab45c60df4e | app/scripts/components/marketplace/offerings/OfferingConfigureStep.tsx | app/scripts/components/marketplace/offerings/OfferingConfigureStep.tsx | import * as React from 'react';
import { FieldArray } from 'redux-form';
import {
SelectAsyncField,
FormContainer,
SelectField,
} from '@waldur/form-react';
import { OfferingAttributes } from './OfferingAttributes';
import { OfferingOptions } from './OfferingOptions';
import { OfferingPlans } from './OfferingPlans';
export const OfferingConfigureStep = props => (
<>
<FormContainer
submitting={props.submitting}
labelClass="col-sm-3"
controlClass="col-sm-9"
clearOnUnmount={false}>
<SelectField
name="type"
label={props.translate('Type')}
required={true}
options={props.offeringTypes}
/>
<SelectAsyncField
name="category"
label={props.translate('Category')}
loadOptions={props.loadCategories}
required={true}
labelKey="title"
valueKey="url"
/>
</FormContainer>
{props.category && <OfferingAttributes {...props}/>}
<FieldArray name="plans" component={OfferingPlans} />
{props.showOptions && <FieldArray name="options" component={OfferingOptions}/>}
</>
);
| import * as React from 'react';
import { FieldArray } from 'redux-form';
import {
SelectAsyncField,
FormContainer,
SelectField,
} from '@waldur/form-react';
import { OfferingAttributes } from './OfferingAttributes';
import { OfferingOptions } from './OfferingOptions';
import { OfferingPlans } from './OfferingPlans';
export const OfferingConfigureStep = props => (
<>
<FormContainer
submitting={props.submitting}
labelClass="col-sm-3"
controlClass="col-sm-9"
clearOnUnmount={false}>
<SelectField
name="type"
label={props.translate('Type')}
required={true}
options={props.offeringTypes}
clearable={false}
/>
<SelectAsyncField
name="category"
label={props.translate('Category')}
loadOptions={props.loadCategories}
required={true}
labelKey="title"
valueKey="url"
clearable={false}
/>
</FormContainer>
{props.category && <OfferingAttributes {...props}/>}
<FieldArray name="plans" component={OfferingPlans} />
{props.showOptions && <FieldArray name="options" component={OfferingOptions}/>}
</>
);
| Make type and category fields in offering configuration form non-clearable. | Make type and category fields in offering configuration form non-clearable.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -23,6 +23,7 @@
label={props.translate('Type')}
required={true}
options={props.offeringTypes}
+ clearable={false}
/>
<SelectAsyncField
name="category"
@@ -31,6 +32,7 @@
required={true}
labelKey="title"
valueKey="url"
+ clearable={false}
/>
</FormContainer>
{props.category && <OfferingAttributes {...props}/>} |
7dc2daf44e2128b04141a9559c71c700d1ba64c0 | lib/msal-node/src/utils/Constants.ts | lib/msal-node/src/utils/Constants.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* http methods
*/
export enum HttpMethod {
GET = 'get',
POST = 'post',
}
/**
* Constant used for PKCE
*/
export const RANDOM_OCTET_SIZE = 32;
/**
* Constants used in PKCE
*/
export const Hash = {
SHA256: 'sha256',
};
/**
* Constants for encoding schemes
*/
export const CharSet = {
CV_CHARSET:
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~',
};
/**
* Cache Constants
*/
export const CACHE = {
FILE_CACHE: 'fileCache',
EXTENSION_LIB: 'extenstion_library',
};
/**
* Constants for headers
*/
export const Constants = {
MSAL_SKU: 'msal.js.node',
};
// Telemetry Constants
export enum ApiId {
acquireTokenSilent = 62,
acquireTokenByCode = 871,
acquireTokenByRefreshToken = 872,
acquireTokenByDeviceCode = 671
};
| /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* http methods
*/
export enum HttpMethod {
GET = 'get',
POST = 'post',
}
/**
* Constant used for PKCE
*/
export const RANDOM_OCTET_SIZE = 32;
/**
* Constants used in PKCE
*/
export const Hash = {
SHA256: 'sha256',
};
/**
* Constants for encoding schemes
*/
export const CharSet = {
CV_CHARSET:
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~',
};
/**
* Cache Constants
*/
export const CACHE = {
FILE_CACHE: 'fileCache',
EXTENSION_LIB: 'extenstion_library',
};
/**
* Constants for headers
*/
export const Constants = {
MSAL_SKU: 'msal.js.node',
};
/**
* API Codes for Telemetry purposes.
* Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs
* 0-99 Silent Flow
* 600-699 Device Code Flow
* 800-899 Auth Code Flow
*/
export enum ApiId {
acquireTokenSilent = 62,
acquireTokenByCode = 871,
acquireTokenByRefreshToken = 872,
acquireTokenByDeviceCode = 671
};
| Add comment to API codes | Add comment to API codes
| TypeScript | mit | AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js | ---
+++
@@ -46,7 +46,13 @@
MSAL_SKU: 'msal.js.node',
};
-// Telemetry Constants
+/**
+ * API Codes for Telemetry purposes.
+ * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs
+ * 0-99 Silent Flow
+ * 600-699 Device Code Flow
+ * 800-899 Auth Code Flow
+ */
export enum ApiId {
acquireTokenSilent = 62,
acquireTokenByCode = 871, |
32434858c17adaa610f3505cea713a59c325d2c0 | src/app/components/header-navigation/header-navigation.component.ts | src/app/components/header-navigation/header-navigation.component.ts | import { Component, ViewEncapsulation } from '@angular/core';
import { Navigation } from '../../models/navigation';
@Component({
selector: 'header-navigation',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./header-navigation.component.css'],
templateUrl: './header-navigation.component.html'
})
export class HeaderNavigationComponent {
public navigations: Navigation[] = [
{url: 'attack-patterns', label: 'Attack Patterns'},
{url: 'campaigns', label: 'Campaigns'},
{url: 'course-of-actions', label: 'Courses of Action'},
{url: 'indicators', label: 'Indicators'},
{url: 'identities', label: 'Identities'},
{url: 'malwares', label: 'Malware'},
{url: 'relationships', label: 'Relationships'},
{url: 'sightings', label: 'Sightings'},
{url: 'tools', label: 'Tools'},
{url: 'threat-actors', label: 'Threat Actors'},
{url: 'intrusion-sets', label: 'Intrusion Sets'},
{url: 'reports', label: 'Reports'}
];
}
| import { Component, ViewEncapsulation } from '@angular/core';
import { Navigation } from '../../models/navigation';
@Component({
selector: 'header-navigation',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./header-navigation.component.css'],
templateUrl: './header-navigation.component.html'
})
export class HeaderNavigationComponent {
public navigations: Navigation[] = [
{url: 'attack-patterns', label: 'Attack Patterns'},
{url: 'campaigns', label: 'Campaigns'},
{url: 'course-of-actions', label: 'Courses of Action'},
{url: 'indicators', label: 'Indicators'},
{url: 'identities', label: 'Identities'},
{url: 'malwares', label: 'Malware'},
// {url: 'relationships', label: 'Relationships'},
{url: 'sightings', label: 'Sightings'},
{url: 'tools', label: 'Tools'},
{url: 'threat-actors', label: 'Threat Actors'},
{url: 'intrusion-sets', label: 'Intrusion Sets'},
{url: 'reports', label: 'Reports'}
];
}
| Remove the main relationship list page | Remove the main relationship list page
| TypeScript | mit | unfetter-discover/unfetter-ui,unfetter-discover/unfetter-ui,unfetter-discover/unfetter-ui,unfetter-discover/unfetter-ui | ---
+++
@@ -14,7 +14,7 @@
{url: 'indicators', label: 'Indicators'},
{url: 'identities', label: 'Identities'},
{url: 'malwares', label: 'Malware'},
- {url: 'relationships', label: 'Relationships'},
+ // {url: 'relationships', label: 'Relationships'},
{url: 'sightings', label: 'Sightings'},
{url: 'tools', label: 'Tools'},
{url: 'threat-actors', label: 'Threat Actors'}, |
51650f462319e0aca97f59a714a107c814c5dc1f | templates/Angular2Spa/ClientApp/components/fetch-data/fetch-data.ts | templates/Angular2Spa/ClientApp/components/fetch-data/fetch-data.ts | import * as ng from 'angular2/core';
import { Http } from 'angular2/http';
@ng.Component({
selector: 'fetch-data',
template: require('./fetch-data.html')
})
export class FetchData {
public forecasts: WeatherForecast[];
constructor(http: Http) {
// TODO: Switch to relative URL once angular-universal supports them
// https://github.com/angular/universal/issues/348
http.get('http://localhost:5000/api/SampleData/WeatherForecasts', {
headers: <any>{ Connection: 'keep-alive' } // Workaround for RC1 bug. TODO: Remove this after updating to RC2
}).subscribe(result => {
this.forecasts = result.json();
});
}
}
interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
| import * as ng from 'angular2/core';
import { Http } from 'angular2/http';
@ng.Component({
selector: 'fetch-data',
template: require('./fetch-data.html')
})
export class FetchData {
public forecasts: WeatherForecast[];
constructor(http: Http) {
// Workaround for RC1 bug. This can be removed with ASP.NET Core 1.0 RC2.
let isServerSide = typeof window === 'undefined';
let options: any = isServerSide ? { headers: { Connection: 'keep-alive' } } : null;
// TODO: Switch to relative URL once angular-universal supports them
// https://github.com/angular/universal/issues/348
http.get('http://localhost:5000/api/SampleData/WeatherForecasts', options).subscribe(result => {
this.forecasts = result.json();
});
}
}
interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
| Clean up RC1 bug workaround | Clean up RC1 bug workaround
| TypeScript | apache-2.0 | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | ---
+++
@@ -9,11 +9,13 @@
public forecasts: WeatherForecast[];
constructor(http: Http) {
+ // Workaround for RC1 bug. This can be removed with ASP.NET Core 1.0 RC2.
+ let isServerSide = typeof window === 'undefined';
+ let options: any = isServerSide ? { headers: { Connection: 'keep-alive' } } : null;
+
// TODO: Switch to relative URL once angular-universal supports them
// https://github.com/angular/universal/issues/348
- http.get('http://localhost:5000/api/SampleData/WeatherForecasts', {
- headers: <any>{ Connection: 'keep-alive' } // Workaround for RC1 bug. TODO: Remove this after updating to RC2
- }).subscribe(result => {
+ http.get('http://localhost:5000/api/SampleData/WeatherForecasts', options).subscribe(result => {
this.forecasts = result.json();
});
} |
f33f63185aa6840cc5f2922cd696578a4007d099 | ui/src/cloud/utils/limits.ts | ui/src/cloud/utils/limits.ts | import {get} from 'lodash'
import {RATE_LIMIT_ERROR_STATUS} from 'src/cloud/constants/index'
import {LimitsState} from 'src/cloud/reducers/limits'
import {LimitStatus} from 'src/cloud/actions/limits'
export const isLimitError = (error): boolean => {
return get(error, 'response.status', '') === RATE_LIMIT_ERROR_STATUS
}
export const extractBucketLimits = (limits: LimitsState): LimitStatus => {
return get(limits, 'buckets.limitStatus')
}
export const extractBucketMax = (limits: LimitsState): number => {
return get(limits, 'buckets.maxAllowed', Infinity)
}
export const extractDashboardLimits = (limits: LimitsState): LimitStatus => {
return get(limits, 'dashboards.limitStatus')
}
export const extractDashboardMax = (limits: LimitsState): number => {
return get(limits, 'dashboard.maxAllowed', Infinity)
}
export const extractTaskLimits = (limits: LimitsState): LimitStatus => {
return get(limits, 'tasks.limitStatus')
}
export const extractTaskMax = (limits: LimitsState): number => {
return get(limits, 'task.maxAllowed', Infinity)
}
| import {get} from 'lodash'
import {RATE_LIMIT_ERROR_STATUS} from 'src/cloud/constants/index'
import {LimitsState} from 'src/cloud/reducers/limits'
import {LimitStatus} from 'src/cloud/actions/limits'
export const isLimitError = (error): boolean => {
return get(error, 'response.status', '') === RATE_LIMIT_ERROR_STATUS
}
export const extractBucketLimits = (limits: LimitsState): LimitStatus => {
return get(limits, 'buckets.limitStatus')
}
export const extractBucketMax = (limits: LimitsState): number => {
return get(limits, 'buckets.maxAllowed', Infinity)
}
export const extractDashboardLimits = (limits: LimitsState): LimitStatus => {
return get(limits, 'dashboards.limitStatus')
}
export const extractDashboardMax = (limits: LimitsState): number => {
return get(limits, 'dashboards.maxAllowed', Infinity)
}
export const extractTaskLimits = (limits: LimitsState): LimitStatus => {
return get(limits, 'tasks.limitStatus')
}
export const extractTaskMax = (limits: LimitsState): number => {
return get(limits, 'tasks.maxAllowed', Infinity)
}
| Fix reference to redux state in get | Fix reference to redux state in get
| TypeScript | mit | li-ang/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -20,7 +20,7 @@
}
export const extractDashboardMax = (limits: LimitsState): number => {
- return get(limits, 'dashboard.maxAllowed', Infinity)
+ return get(limits, 'dashboards.maxAllowed', Infinity)
}
export const extractTaskLimits = (limits: LimitsState): LimitStatus => {
@@ -28,5 +28,5 @@
}
export const extractTaskMax = (limits: LimitsState): number => {
- return get(limits, 'task.maxAllowed', Infinity)
+ return get(limits, 'tasks.maxAllowed', Infinity)
} |
9b7ee514167575097046af369ae1c6389c9e9811 | tools/env/base.ts | tools/env/base.ts | import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.3',
RELEASEVERSION: '1.0.3'
};
export = BaseConfig;
| import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.4',
RELEASEVERSION: '1.0.4'
};
export = BaseConfig;
| Increase release version number to 1.0.4 | Increase release version number to 1.0.4
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -3,8 +3,8 @@
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
- RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.3',
- RELEASEVERSION: '1.0.3'
+ RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/1.0.4',
+ RELEASEVERSION: '1.0.4'
};
export = BaseConfig; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.