Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix view of notes in record activities - CR changes | {% import 'OroUIBundle::macros.html.twig' as UI %}
<div class="widget-content form-horizontal box-content row-fluid">
<div class="responsive-block">
{{ UI.renderHtmlProperty('oro.note.message.label'|trans, entity.message|raw) }}
</div>
</div>
| {% import 'OroUIBundle::macros.html.twig' as UI %}
<div class="widget-content form-horizontal box-content row-fluid">
<div class="responsive-block">
{{ UI.renderHtmlProperty('oro.note.message.label'|trans, entity.message) }}
</div>
</div>
|
Add id for html edit fields | {#=== OPTIONS ========================================================================================================#}
{% set option = {
class: field.class|default(''),
height: field.height|default(''),
label: field.label|default(''),
required: field.required|default(false),
errortext: field.error|default(''),
info: field.info|default(''),
options: field.options.ckeditor|default('')
} %}
{#=== INIT ===========================================================================================================#}
{% set attr_html = {
class: option.class ~ ' ckeditor',
data_field_options: option.options ? option.options|json_encode : '',
name: key,
required: option.required,
data_errortext: option.errortext,
style: (option.height) ? 'height: ' ~ option.height : '',
} %}
{#=== FIELDSET =======================================================================================================#}
<fieldset class="html">
<div class="col-sm-12">
<label class="control-label">{{ (option.info) ? macro.infopop(labelkey, option.info) : labelkey }}</label>
<textarea{{ macro.attr(attr_html) }}>{{ context.content.get(key)|default('') }}</textarea>
</div>
</fieldset>
| {#=== OPTIONS ========================================================================================================#}
{% set option = {
class: field.class|default(''),
height: field.height|default(''),
label: field.label|default(''),
required: field.required|default(false),
errortext: field.error|default(''),
info: field.info|default(''),
options: field.options.ckeditor|default('')
} %}
{#=== INIT ===========================================================================================================#}
{% set attr_html = {
class: option.class ~ ' ckeditor',
data_field_options: option.options ? option.options|json_encode : '',
name_id: key,
required: option.required,
data_errortext: option.errortext,
style: (option.height) ? 'height: ' ~ option.height : '',
} %}
{#=== FIELDSET =======================================================================================================#}
<fieldset class="html">
<div class="col-sm-12">
<label class="control-label">{{ (option.info) ? macro.infopop(labelkey, option.info) : labelkey }}</label>
<textarea{{ macro.attr(attr_html) }}>{{ context.content.get(key)|default('') }}</textarea>
</div>
</fieldset>
|
Disable the news. We want the film now! | {##
# Sidebar-Panel: Displays the latest news on Bolt
# (Usage Example: Dashboards sidebar)
#}
{% for news in context %}
{{ include('@bolt/components/panel-news-item.twig') }}
{% endfor %}
| {##
# Sidebar-Panel: Displays the latest news on Bolt
# (Usage Example: Dashboards sidebar)
#}
{% for news in context if not context.disable %}
{{ include('@bolt/components/panel-news-item.twig') }}
{% endfor %}
|
Update icon macro markup to 3.0 | {% macro icon(name, inverted) %}
<i class="icon-{{ name }}{% if inverted|default(false) %} icon-white{% endif %}"></i>
{% endmacro %}
| {% macro icon(name, inverted) %}
<span class="glyphicon glyphicon-{{ name }}"{% if inverted|default(false) %} style="color: white;"{% endif %}></span>
{% endmacro %}
|
Change transition default animation from slide to fade | /**
* Code is from https://medium.com/google-developer-experts/
* angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8
*/
import {
sequence,
trigger,
stagger,
animate,
style,
group,
query,
transition,
keyframes,
animateChild } from '@angular/animations';
export const routerTransition = trigger('routerTransition', [
transition('* => *', [
query(':enter, :leave', style({ position: 'fixed', width: '100%' }), {optional: true}),
query(':enter', style({ transform: 'translateX(100%)' }), {optional: true}),
sequence([
query(':leave', animateChild(), {optional: true}),
group([
query(':leave', [
style({ transform: 'translateX(0%)' }),
animate('500ms cubic-bezier(.75,-0.48,.26,1.52)',
style({ transform: 'translateX(-100%)' }))
], {optional: true}),
query(':enter', [
style({ transform: 'translateX(100%)' }),
animate('500ms cubic-bezier(.75,-0.48,.26,1.52)',
style({ transform: 'translateX(0%)' }))
], {optional: true}),
]),
query(':enter', animateChild(), {optional: true})
])
])
]);
| /**
* Code is from https://medium.com/google-developer-experts/
* angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8
*/
import {
sequence,
trigger,
stagger,
animate,
style,
group,
query,
transition,
keyframes,
animateChild } from '@angular/animations';
export const routerTransition = trigger('routerTransition', [
transition('* => *', [
query(':enter, :leave', style({ position: 'fixed', width: '100%' }), {optional: true}),
query(':enter', style({ opacity: 0 }), {optional: true}),
sequence([
query(':leave', animateChild(), {optional: true}),
group([
query(':leave', [
style({ opacity: 1 }),
animate('500ms cubic-bezier(.75,-0.48,.26,1.52)',
style({ opacity: 0 }))
], {optional: true}),
query(':enter', [
style({ opacity: 0 }),
animate('500ms cubic-bezier(.75,-0.48,.26,1.52)',
style({ opacity: 1 }))
], {optional: true}),
]),
query(':enter', animateChild(), {optional: true})
])
])
]);
|
Change order of imports in header class for better logical ordering. | import { Component, EventEmitter, Output, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class HeaderComponent {
@Output() navToggled = new EventEmitter();
navOpen: boolean = false;
toggleNav() {
this.navOpen = !this.navOpen;
this.navToggled.emit(this.navOpen);
}
}
| import { Component, ViewEncapsulation, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class HeaderComponent {
@Output() navToggled = new EventEmitter();
navOpen: boolean = false;
toggleNav() {
this.navOpen = !this.navOpen;
this.navToggled.emit(this.navOpen);
}
}
|
Fix sniffed language reducer (need object rest spread real bad..) |
import os from "../util/os";
import {app} from "../electron";
import {handleActions} from "redux-actions";
import {
IAction,
ILanguageSniffedPayload,
IFreeSpaceUpdatedPayload,
} from "../constants/action-types";
import {ISystemState} from "../types";
const initialState = {
appVersion: app.getVersion(),
osx: (os.platform() === "darwin"),
macos: (os.platform() === "darwin"),
windows: (os.platform() === "win32"),
linux: (os.platform() === "linux"),
sniffedLanguage: null,
homePath: app.getPath("home"),
userDataPath: app.getPath("userData"),
diskInfo: {
parts: [],
total: {
free: 0,
size: 0,
},
},
} as ISystemState;
export default handleActions<ISystemState, any>({
LANGUAGE_SNIFFED: (state: ISystemState, action: IAction<ILanguageSniffedPayload>) => {
const sniffedLanguage = action.payload;
return Object.assign({}, state, {sniffedLanguage});
},
FREE_SPACE_UPDATED: (state: ISystemState, action: IAction<IFreeSpaceUpdatedPayload>) => {
const {diskInfo} = action.payload;
return Object.assign({}, state, {diskInfo});
},
}, initialState);
|
import os from "../util/os";
import {app} from "../electron";
import {handleActions} from "redux-actions";
import {
IAction,
ILanguageSniffedPayload,
IFreeSpaceUpdatedPayload,
} from "../constants/action-types";
import {ISystemState} from "../types";
const initialState = {
appVersion: app.getVersion(),
osx: (os.platform() === "darwin"),
macos: (os.platform() === "darwin"),
windows: (os.platform() === "win32"),
linux: (os.platform() === "linux"),
sniffedLanguage: null,
homePath: app.getPath("home"),
userDataPath: app.getPath("userData"),
diskInfo: {
parts: [],
total: {
free: 0,
size: 0,
},
},
} as ISystemState;
export default handleActions<ISystemState, any>({
LANGUAGE_SNIFFED: (state: ISystemState, action: IAction<ILanguageSniffedPayload>) => {
const sniffedLanguage: string = action.payload.lang;
return Object.assign({}, state, {sniffedLanguage});
},
FREE_SPACE_UPDATED: (state: ISystemState, action: IAction<IFreeSpaceUpdatedPayload>) => {
const {diskInfo} = action.payload;
return Object.assign({}, state, {diskInfo});
},
}, initialState);
|
Add Loader IO route verification | import { Controller, Get } from 'routing-controllers';
@Controller()
export default class IndexController {
@Get('/health')
public health() {
return { status: 'OK' };
}
}
| import { Controller, Get } from 'routing-controllers';
@Controller()
export default class IndexController {
@Get('/health')
public health() {
return { status: 'OK' };
}
// Loader.io only
@Get('/loaderio-deb75e3581d893735fd6e5050757bdb2')
public loaderio() {
return true;
}
}
|
Update guard since create-merchant flow has persistence now | import Route from '@ember/routing/route';
import '../../css/card-pay/balances.css';
import * as short from 'short-uuid';
export default class CardPayTabBaseRoute extends Route {
queryParams = {
flow: {
refreshModel: true,
},
workflowPersistenceId: {
refreshModel: true,
},
};
model(params: any, transition: any) {
if (params.flow && !params.workflowPersistenceId) {
// TODO: remove me once all flows have persistence support
if (params.flow !== 'deposit' && params.flow !== 'issue-prepaid-card')
return;
transition.abort();
this.transitionTo(this.routeName, {
queryParams: {
flow: params.flow,
workflowPersistenceId: short.generate(),
},
});
}
}
}
| import Route from '@ember/routing/route';
import '../../css/card-pay/balances.css';
import * as short from 'short-uuid';
export default class CardPayTabBaseRoute extends Route {
queryParams = {
flow: {
refreshModel: true,
},
workflowPersistenceId: {
refreshModel: true,
},
};
model(params: any, transition: any) {
if (params.flow && !params.workflowPersistenceId) {
// TODO: remove me once all flows have persistence support
if (
params.flow !== 'deposit' &&
params.flow !== 'issue-prepaid-card' &&
params.flow !== 'create-merchant'
)
return;
transition.abort();
this.transitionTo(this.routeName, {
queryParams: {
flow: params.flow,
workflowPersistenceId: short.generate(),
},
});
}
}
}
|
Add explicit return types, planning for a lint to enforce this later | import { buildCapabilities } from '../util/capabilities';
import type { CapturedArguments as Arguments, HelperCapabilities } from '@glimmer/interfaces';
type FnArgs<Args extends Arguments = Arguments> =
| [...Args['positional'], Args['named']]
| [...Args['positional']];
type AnyFunction = (...args: any[]) => unknown;
interface State {
fn: AnyFunction;
args: Arguments;
}
export class FunctionHelperManager implements HelperManagerWithValue<State> {
capabilities = buildCapabilities({
hasValue: true,
hasDestroyable: false,
hasScheduledEffect: false,
}) as HelperCapabilities;
createHelper(fn: AnyFunction, args: Arguments) {
return { fn, args };
}
getValue({ fn, args }: State) {
if (Object.keys(args.named).length > 0) {
let argsForFn: FnArgs<Arguments> = [...args.positional, args.named];
return fn(...argsForFn);
}
return fn(...args.positional);
}
getDebugName(fn: AnyFunction) {
if (fn.name) {
return `(helper function ${fn.name})`;
}
return '(anonymous helper function)';
}
}
| import { buildCapabilities } from '../util/capabilities';
import type {
CapturedArguments as Arguments,
HelperCapabilities,
HelperManagerWithValue,
} from '@glimmer/interfaces';
type FnArgs<Args extends Arguments = Arguments> =
| [...Args['positional'], Args['named']]
| [...Args['positional']];
type AnyFunction = (...args: any[]) => unknown;
interface State {
fn: AnyFunction;
args: Arguments;
}
export class FunctionHelperManager implements HelperManagerWithValue<State> {
capabilities = buildCapabilities({
hasValue: true,
hasDestroyable: false,
hasScheduledEffect: false,
}) as HelperCapabilities;
createHelper(fn: AnyFunction, args: Arguments): State {
return { fn, args };
}
getValue({ fn, args }: State): unknown {
if (Object.keys(args.named).length > 0) {
let argsForFn: FnArgs<Arguments> = [...args.positional, args.named];
return fn(...argsForFn);
}
return fn(...args.positional);
}
getDebugName(fn: AnyFunction): string {
if (fn.name) {
return `(helper function ${fn.name})`;
}
return '(anonymous helper function)';
}
}
|
Use an actual SpellLibrary in test StatBlockTextEnricher | import { PromptQueue } from "../Commands/Prompts/PromptQueue";
import { Encounter } from "../Encounter/Encounter";
import { DefaultRules, IRules } from "../Rules/Rules";
import { StatBlockTextEnricher } from "../StatBlock/StatBlockTextEnricher";
export function buildStatBlockTextEnricher(rules: IRules) {
return new StatBlockTextEnricher(jest.fn(), jest.fn(), jest.fn(), null, rules);
}
export function buildEncounter() {
const rules = new DefaultRules();
const enricher = buildStatBlockTextEnricher(rules);
const encounter = new Encounter(new PromptQueue(), null, jest.fn().mockReturnValue(null), jest.fn(), rules, enricher);
return encounter;
} | import { PromptQueue } from "../Commands/Prompts/PromptQueue";
import { Encounter } from "../Encounter/Encounter";
import { SpellLibrary } from "../Library/SpellLibrary";
import { DefaultRules, IRules } from "../Rules/Rules";
import { StatBlockTextEnricher } from "../StatBlock/StatBlockTextEnricher";
export function buildStatBlockTextEnricher(rules: IRules) {
return new StatBlockTextEnricher(jest.fn(), jest.fn(), jest.fn(), new SpellLibrary(), rules);
}
export function buildEncounter() {
const rules = new DefaultRules();
const enricher = buildStatBlockTextEnricher(rules);
const encounter = new Encounter(new PromptQueue(), null, jest.fn().mockReturnValue(null), jest.fn(), rules, enricher);
return encounter;
} |
Update `HorizonalRule` to be hairline height | import { Fragment } from "react"
const HorizontalRule = () => (
<Fragment>
<hr></hr>
<style jsx>{`
hr {
margin: 8px 0;
height: 1px;
border: 0;
background-image: linear-gradient(
to left,
rgba(84, 84, 88, 0.35),
rgba(84, 84, 88, 1),
rgba(84, 84, 88, 0.35)
);
}
@media (prefers-color-scheme: light) {
hr {
background-image: linear-gradient(
to left,
rgba(1, 1, 1, 0),
rgba(1, 1, 1, 0.75),
rgba(1, 1, 1, 0)
);
}
}
`}</style>
</Fragment>
)
export default HorizontalRule
| import { Fragment } from "react"
const HorizontalRule = () => (
<Fragment>
<hr></hr>
<style jsx>{`
hr {
margin: 8px 0;
height: 1px;
border: 0;
background-image: linear-gradient(
to left,
rgba(84, 84, 88, 0.35),
rgba(84, 84, 88, 1),
rgba(84, 84, 88, 0.35)
);
}
@media (min-resolution: 2dppx) {
hr {
height: 0.5px;
}
}
@media (min-resolution: 3dppx) {
hr {
height: calc(1/3)px;
}
}
@media (prefers-color-scheme: light) {
hr {
background-image: linear-gradient(
to left,
rgba(1, 1, 1, 0),
rgba(1, 1, 1, 0.75),
rgba(1, 1, 1, 0)
);
}
}
`}</style>
</Fragment>
)
export default HorizontalRule
|
Resolve missing hammerjs for materialize. | import 'materialize-css';
import 'angular2-materialize';
import { AnimationBuilder } from 'css-animator/builder';
AnimationBuilder.defaults.fixed = true;
| import * as Hammer from 'hammerjs';
(window as any).Hammer = Hammer;
import { AnimationBuilder } from 'css-animator/builder';
import 'materialize-css';
import 'angular2-materialize';
AnimationBuilder.defaults.fixed = true;
|
Add export for digest availability checking function | import * as encryption from './encryption';
export const hashPassword = encryption.hashPassword;
export const comparePasswordWithHash = encryption.comparePasswordWithHash;
module.exports = encryption;
| import * as encryption from './encryption';
export const isValidDigestAlgorithm = encryption.isValidDigestAlgorithm;
export const hashPassword = encryption.hashPassword;
export const comparePasswordWithHash = encryption.comparePasswordWithHash;
module.exports = encryption;
|
Use `import = require` syntax. | import * as CleanWebpackPlugin from 'clean-webpack-plugin';
const paths = [
'path',
'glob/**/*.js',
];
new CleanWebpackPlugin(paths);
new CleanWebpackPlugin(paths, 'root-directory');
new CleanWebpackPlugin(paths, {});
new CleanWebpackPlugin(paths, {
root: 'root-directory',
verbose: true,
dry: true,
watch: true,
exclude: ['a, b'],
});
| import CleanWebpackPlugin = require('clean-webpack-plugin');
const paths = [
'path',
'glob/**/*.js',
];
new CleanWebpackPlugin(paths);
new CleanWebpackPlugin(paths, 'root-directory');
new CleanWebpackPlugin(paths, {});
new CleanWebpackPlugin(paths, {
root: 'root-directory',
verbose: true,
dry: true,
watch: true,
exclude: ['a, b'],
});
|
Fix some mistake on PR. | import { add } from '../../../_modules/i18n';
import nl from './nl';
import fa from './fa';
import de from './de';
import ru from './ru';
import pt_br from './pt_br';
export default function() {
add(nl, 'nl');
add(fa, 'fa');
add(de, 'de');
add(pt_br, 'pt_br');
}
| import { add } from '../../../_modules/i18n';
import nl from './nl';
import fa from './fa';
import de from './de';
import ru from './ru';
import pt_br from './pt_br';
export default function() {
add(nl, 'nl');
add(fa, 'fa');
add(de, 'de');
add(ru, 'ru');
add(pt_br, 'pt_br');
}
|
Update tests because of linting | var map: L.Map;
// Defaults
L.control.locate().addTo(map);
// Simple
var lc = L.control.locate({
position: 'topright',
strings: {
title: "Show me where I am, yo!"
}
}).addTo(map);
// Locate Options
map.addControl(L.control.locate({
locateOptions: {
maxZoom: 10,
enableHighAccuracy: true
}})); | var map = L.map('map', {
center: [51.505, -0.09],
zoom: 13
});
// Defaults
L.control.locate().addTo(map);
// Simple
var lc = L.control.locate({
position: 'topright',
strings: {
title: "Show me where I am, yo!"
}
}).addTo(map);
// Locate Options
map.addControl(L.control.locate({
locateOptions: {
maxZoom: 10,
enableHighAccuracy: true
}})); |
Add webp and avif as image format | /**
* Extensions of all assets that can be served via url
*/
export const imageAssetsExtensions = [
'bmp',
'gif',
'ico',
'jpeg',
'jpg',
'png',
'svg',
'tif',
'tiff',
];
| /**
* Extensions of all assets that can be served via url
*/
export const imageAssetsExtensions = [
'bmp',
'gif',
'ico',
'jpeg',
'jpg',
'png',
'svg',
'tif',
'tiff',
'webp',
'avif',
];
|
Implement unit test for map layers reducer | /* tslint:disable:no-unused-variable */
/*!
* Map Layers Reducer Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { async, inject } from '@angular/core/testing';
import { MapLayersReducer } from './map-layers.reducer';
describe('NgRx Store Reducer: Map Layers', () => {
it('should create an instance', () => {
expect(MapLayersReducer).toBeTruthy();
});
});
| /* tslint:disable:no-unused-variable */
/*!
* Map Layers Reducer Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { async, inject } from '@angular/core/testing';
import { MapLayersReducer, LayerState } from './map-layers.reducer';
import { assign } from 'lodash';
describe('NgRx Store Reducer: Map Layers', () => {
const initialState: LayerState = {
ids: ['layer-1'],
layers: {
'layer-1': {
id: 'layer-1',
url: 'http://google.com.ph/',
type: 'dummy-layer',
layerOptions: {}
}
},
};
const blankState: LayerState = {
ids: [],
layers: {}
};
it('should create an instance', () => {
expect(MapLayersReducer).toBeTruthy();
});
it('should return the current state when invalid action is supplied', () => {
const actualState = MapLayersReducer(initialState, {
type: 'INVALID_ACTION',
payload: {
id: 'layer-2',
url: 'http://google.com.ph/',
type: 'dummy-layer',
layerOptions: {}
}
});
expect(actualState).toBe(initialState);
});
it('should add the new layer', () => {
const payload = {
id: 'layer-2',
url: 'http://google.com.ph/',
type: 'dummy-layer',
layerOptions: {}
};
const actualState = MapLayersReducer(initialState, {
type: 'ADD_LAYER',
payload
});
// check if layer-2 is in the array of ids
expect(actualState.ids).toContain('layer-2');
// check if layer-2 data is in the collection layer data
expect(actualState.layers).toEqual(jasmine.objectContaining({
'layer-2': payload
}));
});
it('should clear all layers', () => {
const payload = {
id: 'layer-2',
url: 'http://google.com.ph/',
type: 'dummy-layer',
layerOptions: {}
};
// add new layer
let currentState = MapLayersReducer(blankState, {
type: 'ADD_LAYER',
payload
});
// remove all layers from the store
currentState = MapLayersReducer(currentState, {
type: 'REMOVE_ALL_LAYERS'
});
// check if ids length is 0
expect(currentState.ids.length).toBe(0);
// check if layers collection is empty
expect(Object.keys(currentState.layers).length).toBe(0);
});
});
|
Fix ordered list start ordinal test |
import { expect } from 'chai'
import * as Up from '../../index'
import { OrderedListNode } from '../../SyntaxNodes/OrderedListNode'
function listStart(text: string): number {
const list = <OrderedListNode>Up.toAst(text).children[0]
return list.start()
}
describe('An ordered list that does not start with a numeral bullet', () => {
it('does not have an explicit starting ordinal', () => {
const text =
`
#. Hello, world!
# Goodbye, world!
#) Goodbye, world!`
expect(listStart(text)).to.be.eql(null)
})
it('does not have an explicit starting ordinal even if the second list item has a numeral bullet', () => {
const text =
`
#. Hello, world!
5 Goodbye, world!
#) Goodbye, world!`
expect(listStart(text)).to.be.eql(null)
})
})
describe('An ordered list that starts with a numeral bullet', () => {
it('has an explicit starting ordinal equal to the numeral value', () => {
const text =
`
10) Hello, world!
#. Goodbye, world!
#) Goodbye, world!`
expect(listStart(text)).to.be.eql(10)
})
})
|
import { expect } from 'chai'
import * as Up from '../../index'
import { OrderedListNode } from '../../SyntaxNodes/OrderedListNode'
function listStart(text: string): number {
const list = <OrderedListNode>Up.toAst(text).children[0]
return list.start()
}
describe('An ordered list that does not start with a numeral bullet', () => {
it('does not have an explicit starting ordinal', () => {
const text =
`
#. Hello, world!
# Goodbye, world!
#) Goodbye, world!`
expect(listStart(text)).to.be.eql(null)
})
it('does not have an explicit starting ordinal even if the second list item has a numeral bullet', () => {
const text =
`
#. Hello, world!
5) Goodbye, world!
#) Goodbye, world!`
expect(listStart(text)).to.be.eql(null)
})
})
describe('An ordered list that starts with a numeral bullet', () => {
it('has an explicit starting ordinal equal to the numeral value', () => {
const text =
`
10) Hello, world!
#. Goodbye, world!
#) Goodbye, world!`
expect(listStart(text)).to.be.eql(10)
})
})
|
Revert "reverting to old style, using async didn't achieve anything" | import { ComponentFixture, async } from '@angular/core/testing';
import { TestUtils } from '../../test-utils';
import { ClickerButton } from './clickerButton';
import { ClickerMock } from '../../models/clicker.mock';
let fixture: ComponentFixture<ClickerButton> = null;
let instance: any = null;
describe('ClickerButton', () => {
beforeEach(async(() => TestUtils.beforeEachCompiler([ClickerButton]).then(compiled => {
fixture = compiled.fixture;
instance = compiled.instance;
instance.clicker = new ClickerMock();
fixture.detectChanges();
})));
afterEach(() => {
fixture.destroy();
});
it('initialises', () => {
expect(instance).not.toBeNull();
});
it('displays the clicker name and count', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.button-inner')[0].innerHTML).toEqual('TEST CLICKER (10)');
});
it('does a click', () => {
fixture.detectChanges();
spyOn(instance['clickerService'], 'doClick');
TestUtils.eventFire(fixture.nativeElement.querySelectorAll('button')[0], 'click');
expect(instance['clickerService'].doClick).toHaveBeenCalled();
});
});
| import { ComponentFixture, async } from '@angular/core/testing';
import { TestUtils } from '../../test-utils';
import { ClickerButton } from './clickerButton';
import { ClickerMock } from '../../models/clicker.mock';
let fixture: ComponentFixture<ClickerButton> = null;
let instance: any = null;
describe('ClickerButton', () => {
beforeEach(async(() => TestUtils.beforeEachCompiler([ClickerButton]).then(compiled => {
fixture = compiled.fixture;
instance = compiled.instance;
instance.clicker = new ClickerMock();
fixture.detectChanges();
})));
afterEach(() => {
fixture.destroy();
});
it('initialises', () => {
expect(instance).not.toBeNull();
});
it('displays the clicker name and count', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.button-inner')[0].innerHTML).toEqual('TEST CLICKER (10)');
});
it('does a click', async(() => {
spyOn(instance['clickerService'], 'doClick');
let button: any = fixture.debugElement.nativeElement.querySelector('button');
button.click();
fixture.whenStable().then(() => {
expect(instance['clickerService'].doClick).toHaveBeenCalled();
});
}));
});
|
Fix a mistake in an Error message | import Day from './Day'
export default class Model {
private _checkInDate: Day
private _checkOutDate: Day
constructor(checkInDate: Day, checkOutDate: Day) {
if (checkOutDate.toMoment().isBefore(checkInDate.toMoment())) {
throw new Error(
`Check-out date can be before check-in. Got ${checkInDate}, ${checkOutDate}`
)
}
this._checkInDate = checkInDate
this._checkOutDate = checkOutDate
}
get checkInDate(): Day {
return this._checkInDate
}
get checkOutDate(): Day {
return this._checkOutDate
}
}
| import Day from './Day'
export default class Model {
private _checkInDate: Day
private _checkOutDate: Day
constructor(checkInDate: Day, checkOutDate: Day) {
if (checkOutDate.toMoment().isBefore(checkInDate.toMoment())) {
throw new Error(
`Check-out date can't be before check-in. Got ${checkInDate}, ${checkOutDate}`
)
}
this._checkInDate = checkInDate
this._checkOutDate = checkOutDate
}
get checkInDate(): Day {
return this._checkInDate
}
get checkOutDate(): Day {
return this._checkOutDate
}
}
|
Disable firebase logging on production | import {applyMiddleware, createStore} from 'redux'
import flowRight from 'lodash-es/flowRight'
import * as firebase from 'firebase/app'
import {reducer} from './reducer'
import {reactReduxFirebase} from 'react-redux-firebase'
const middlewares = []
// Redux-logger plugin
if (process.env.NODE_ENV === 'development') {
// tslint:disable-next-line:no-var-requires
const {createLogger} = require('redux-logger')
const logger = createLogger({
collapsed: true
})
middlewares.push(logger)
}
// Firebase plugin
const firebaseConfig = {
enableLogging: true,
userProfile: 'users'
}
export const store = flowRight(
(reactReduxFirebase as any)(firebase, firebaseConfig),
applyMiddleware(...middlewares)
)(createStore)(reducer)
| import {applyMiddleware, createStore} from 'redux'
import flowRight from 'lodash-es/flowRight'
import * as firebase from 'firebase/app'
import {reducer} from './reducer'
import {reactReduxFirebase} from 'react-redux-firebase'
const middlewares = []
// Redux-logger plugin
if (process.env.NODE_ENV === 'development') {
// tslint:disable-next-line:no-var-requires
const {createLogger} = require('redux-logger')
const logger = createLogger({
collapsed: true
})
middlewares.push(logger)
}
// Firebase plugin
const firebaseConfig = {
enableLogging: process.env.NODE_ENV === 'development',
userProfile: 'users'
}
export const store = flowRight(
(reactReduxFirebase as any)(firebase, firebaseConfig),
applyMiddleware(...middlewares)
)(createStore)(reducer)
|
Fix test helpers import path | import { TestContext } from 'ember-test-helpers';
import Pretender from 'pretender';
export default function setupPretender(hooks: NestedHooks) {
hooks.beforeEach(function(this: TestContext) {
this.server = new Pretender();
});
hooks.afterEach(function(this: TestContext) {
this.server.shutdown();
});
}
declare module 'ember-test-helpers' {
interface TestContext {
server: Pretender;
}
}
| import { TestContext } from '@ember/test-helpers';
import Pretender from 'pretender';
export default function setupPretender(hooks: NestedHooks) {
hooks.beforeEach(function(this: TestContext) {
this.server = new Pretender();
});
hooks.afterEach(function(this: TestContext) {
this.server.shutdown();
});
}
declare module 'ember-test-helpers' {
interface TestContext {
server: Pretender;
}
}
|
Fix sort language switch items alphabethical. | import { Component } from '@angular/core';
import { Language, LanguageService } from '@picturepark/sdk-v1-angular';
@Component({
selector: 'pp-language-switch',
templateUrl: './language-switch.component.html',
styleUrls: ['./language-switch.component.scss'],
})
export class LanguageSwitchComponent {
get languages(): Language[] {
return this.languageService.languages;
}
get selectedLanguageCode(): string {
return this.languageService.currentLanguage.ietf;
}
constructor(private languageService: LanguageService) {}
public changeLanguage(languageCode: string) {
this.languageService.changeCurrentLanguage(languageCode);
window.location.reload();
}
}
| import { Component } from '@angular/core';
import { Language, LanguageService } from '@picturepark/sdk-v1-angular';
import { TranslatePipe } from '../../shared-module/pipes/translate.pipe';
@Component({
selector: 'pp-language-switch',
templateUrl: './language-switch.component.html',
styleUrls: ['./language-switch.component.scss'],
})
export class LanguageSwitchComponent {
languages: Language[];
get selectedLanguageCode(): string {
return this.languageService.currentLanguage.ietf;
}
constructor(private languageService: LanguageService, translatePipe: TranslatePipe) {
this.languages = this.languageService.languages.sort((a, b) =>
translatePipe.transform(a.name) < translatePipe.transform(b.name) ? -1 : 1
);
}
public changeLanguage(languageCode: string) {
this.languageService.changeCurrentLanguage(languageCode);
window.location.reload();
}
}
|
Add AuthInfo and AuthGuard into the AuthModule | import { NgModule, ModuleWithProviders } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './interceptors/token.interceptor';
import { JwtHelper } from './helpers/jwt.helper';
import { TokenService } from './services/token.service';
import { AuthService } from './services/auth.service';
import { RefreshInterceptor } from './interceptors/refresh.interceptor';
@NgModule({
imports: [],
declarations: [],
exports: [],
providers: [
JwtHelper,
AuthService,
TokenService,
{
provide: HTTP_INTERCEPTORS,
useClass: RefreshInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
],
})
export class AuthModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: AuthModule,
providers: [TokenService]
};
}
} | import { NgModule, ModuleWithProviders } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './interceptors/token.interceptor';
import { JwtHelper } from './helpers/jwt.helper';
import { TokenService } from './services/token.service';
import { AuthService } from './services/auth.service';
import { RefreshInterceptor } from './interceptors/refresh.interceptor';
import { AuthInfoService } from './services/auth-info.service';
import { AuthGuard } from './guards/auth.guard';
@NgModule({
imports: [],
declarations: [],
exports: [],
providers: [
JwtHelper,
AuthService,
AuthInfoService,
TokenService,
{
provide: HTTP_INTERCEPTORS,
useClass: RefreshInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
AuthGuard
],
})
export class AuthModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: AuthModule,
providers: [TokenService]
};
}
} |
Update canLoad to access full route (w/parameters) | import { Injectable } from '@angular/core';
import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, Route } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanLoad {
constructor(private authService: AuthService,
private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.checkLoggedIn(state.url);
}
canLoad(route: Route): boolean {
return this.checkLoggedIn(route.path);
}
checkLoggedIn(url: string): boolean {
if (this.authService.isLoggedIn) {
return true;
}
// Retain the attempted URL for redirection
this.authService.redirectUrl = url;
this.router.navigate(['/login']);
return false;
}
}
| import { Injectable } from '@angular/core';
import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router, Route, UrlSegment } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanLoad {
constructor(private authService: AuthService,
private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.checkLoggedIn(state.url);
}
// Use the segments to build the full route
// when using canLoad
canLoad(route: Route, segments: UrlSegment[]): boolean {
return this.checkLoggedIn(segments.join('/'));
}
checkLoggedIn(url: string): boolean {
if (this.authService.isLoggedIn) {
return true;
}
// Retain the attempted URL for redirection
this.authService.redirectUrl = url;
this.router.navigate(['/login']);
return false;
}
}
|
Enable use of Row custom component | import * as React from 'react';
import { Head, Row } from '../../components';
import { useDayPicker } from '../../hooks';
import { UIElement } from '../../types';
import { getWeeks } from './utils/getWeeks';
/**
* The props for the [[Table]] component.
*/
export interface TableProps {
/** The month used to render the table */
displayMonth: Date;
}
/**
* Render the table with the calendar.
*/
export function Table(props: TableProps): JSX.Element {
const { locale, fixedWeeks, classNames, styles, hideHead } = useDayPicker();
const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks });
return (
<table
className={classNames?.[UIElement.Table]}
style={styles?.[UIElement.Table]}
>
{!hideHead && <Head />}
<tbody
className={classNames?.[UIElement.TBody]}
style={styles?.[UIElement.TBody]}
>
{Object.keys(weeks).map((weekNumber) => (
<Row
displayMonth={props.displayMonth}
key={weekNumber}
dates={weeks[weekNumber]}
weekNumber={Number(weekNumber)}
/>
))}
</tbody>
</table>
);
}
| import * as React from 'react';
import { Head } from '../../components';
import { useDayPicker } from '../../hooks';
import { UIElement } from '../../types';
import { getWeeks } from './utils/getWeeks';
/**
* The props for the [[Table]] component.
*/
export interface TableProps {
/** The month used to render the table */
displayMonth: Date;
}
/**
* Render the table with the calendar.
*/
export function Table(props: TableProps): JSX.Element {
const {
locale,
fixedWeeks,
classNames,
styles,
hideHead,
components: { Row }
} = useDayPicker();
const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks });
return (
<table
className={classNames?.[UIElement.Table]}
style={styles?.[UIElement.Table]}
>
{!hideHead && <Head />}
<tbody
className={classNames?.[UIElement.TBody]}
style={styles?.[UIElement.TBody]}
>
{Object.keys(weeks).map((weekNumber) => (
<Row
displayMonth={props.displayMonth}
key={weekNumber}
dates={weeks[weekNumber]}
weekNumber={Number(weekNumber)}
/>
))}
</tbody>
</table>
);
}
|
Fix instance of content not converted to value | /*
R Markdown Editor Actions
*/
import { Actions } from "../markdown-editor/actions";
import { convert } from "./rmd2md";
import { FrameTree } from "../frame-tree/types";
export class RmdActions extends Actions {
_init2(): void {
if (!this.is_public) {
// one extra thing after markdown.
this._init_rmd2md();
}
}
_init_rmd2md(): void {
this._syncstring.on("save-to-disk", () => this._run_rmd2md());
this._run_rmd2md();
}
async _run_rmd2md(time?: number): Promise<void> {
// TODO: should only run knitr if at least one frame is visible showing preview?
// maybe not, since might want to show error.
this.set_status("Running knitr...");
let markdown: string;
try {
markdown = await convert(this.project_id, this.path, time);
} catch (err) {
this.set_error(err);
return;
} finally {
this.set_status("");
}
this.setState({ content: markdown });
}
_raw_default_frame_tree(): FrameTree {
if (this.is_public) {
return { type: "cm" };
} else {
return {
direction: "col",
type: "node",
first: {
type: "cm"
},
second: {
type: "markdown"
}
};
}
}
}
| /*
R Markdown Editor Actions
*/
import { Actions } from "../markdown-editor/actions";
import { convert } from "./rmd2md";
import { FrameTree } from "../frame-tree/types";
export class RmdActions extends Actions {
_init2(): void {
if (!this.is_public) {
// one extra thing after markdown.
this._init_rmd2md();
}
}
_init_rmd2md(): void {
this._syncstring.on("save-to-disk", () => this._run_rmd2md());
this._run_rmd2md();
}
async _run_rmd2md(time?: number): Promise<void> {
// TODO: should only run knitr if at least one frame is visible showing preview?
// maybe not, since might want to show error.
this.set_status("Running knitr...");
let markdown: string;
try {
markdown = await convert(this.project_id, this.path, time);
} catch (err) {
this.set_error(err);
return;
} finally {
this.set_status("");
}
this.setState({ value: markdown });
}
_raw_default_frame_tree(): FrameTree {
if (this.is_public) {
return { type: "cm" };
} else {
return {
direction: "col",
type: "node",
first: {
type: "cm"
},
second: {
type: "markdown"
}
};
}
}
}
|
Remove console.log after verifying the correct files are ignored | import {PluginObj} from '@babel/core'
import {NodePath} from '@babel/traverse'
import {Program} from '@babel/types'
import commonjsPlugin from '@babel/plugin-transform-modules-commonjs'
// Rewrite imports using next/<something> to next-server/<something>
export default function NextToNextServer (...args: any): PluginObj {
const commonjs = commonjsPlugin(...args)
return {
visitor: {
Program: {
exit (path: NodePath<Program>, state) {
let foundModuleExports = false
path.traverse({
MemberExpression (
path: any
) {
if (path.node.object.name !== 'module') return
if (path.node.property.name !== 'exports') return
foundModuleExports = true
console.log('FOUND', state.file.opts.filename)
}
})
if (!foundModuleExports) {
console.log('NOT FOUND', state.file.opts.filename)
return
}
commonjs.visitor.Program.exit.call(this, path, state)
}
}
}
}
}
| import {PluginObj} from '@babel/core'
import {NodePath} from '@babel/traverse'
import {Program} from '@babel/types'
import commonjsPlugin from '@babel/plugin-transform-modules-commonjs'
// Rewrite imports using next/<something> to next-server/<something>
export default function NextToNextServer (...args: any): PluginObj {
const commonjs = commonjsPlugin(...args)
return {
visitor: {
Program: {
exit (path: NodePath<Program>, state) {
let foundModuleExports = false
path.traverse({
MemberExpression (
path: any
) {
if (path.node.object.name !== 'module') return
if (path.node.property.name !== 'exports') return
foundModuleExports = true
}
})
if (!foundModuleExports) {
return
}
commonjs.visitor.Program.exit.call(this, path, state)
}
}
}
}
}
|
Add comments for exported interface types | import { Observable } from 'rxjs';
import { FilterOptions } from './collection';
export { Database } from './database';
export { Collection } from './collection';
export { Query } from './query';
/**
* IDatabase
* ...
*/
export interface IDatabase {
collection( name ): ICollection;
}
/**
* ICollection
* ...
*/
export interface ICollection {
find( filter: any, options: FilterOptions ): IQuery;
insert( doc: any ): Observable<any>;
update( filter: any, changes: any ): Observable<any[]>;
remove( filter: any ): Observable<any[]>;
}
/**
* IQuery
* ...
*/
export interface IQuery {
value(): Observable<any[]>;
}
/**
* Persistor
* ...
*/
export interface IPersistorFactory {
create( collectionName: string ): IPersistor;
}
/**
* Persistor
* ...
*/
export interface IPersistor {
load(): Promise<any[]>;
store( docs: any[]): Promise<any>;
remove( docs: any[]): Promise<any>;
}
| import { Observable } from 'rxjs';
import { FilterOptions } from './collection';
export { Database } from './database';
export { Collection } from './collection';
export { Query } from './query';
/**
* IDatabase
* IDatabase contains a set of collections which stores documents.
*/
export interface IDatabase {
collection( name ): ICollection;
}
/**
* ICollection
* ICollection contains a set of documents which can be manipulated
* using collection methods. It uses a IPersistor to store data.
*/
export interface ICollection {
find( filter: any, options: FilterOptions ): IQuery;
insert( doc: any ): Observable<any>;
update( filter: any, changes: any ): Observable<any[]>;
remove( filter: any ): Observable<any[]>;
}
/**
* IQuery
* IQuery wraps the result of a collection find query.
*/
export interface IQuery {
value(): Observable<any[]>;
}
/**
* IPersistorFactory
* IPersistorFactory creates a Persistors for collections to store data.
*/
export interface IPersistorFactory {
create( collectionName: string ): IPersistor;
}
/**
* IPersistor
* IPersistor stores data in a permanent storage location. With default
* options, data may get stored in IndexedDB, WebSQL or LocalStorage.
* Each collection has it's own IPersistor instance to store data.
*/
export interface IPersistor {
load(): Promise<any[]>;
store( docs: any[]): Promise<any>;
remove( docs: any[]): Promise<any>;
}
|
Correct visibility of StoryList custom element | import {
bindable,
customElement
} from 'aurelia-framework';
@customElement('hn-story-list')
export class StoryList {
@bindable() private readonly stories: any[];
@bindable() private readonly offset: number;
}
| import {
bindable,
customElement
} from 'aurelia-framework';
@customElement('hn-story-list')
export class StoryList {
@bindable() readonly stories: any[];
@bindable() readonly offset: number;
}
|
Add default parameters of calculator method | import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: "/app/app.component.tpl.html"
})
export class AppComponent {
operation:string;
firstvalue:number = 0;
scdvalue:number = 0;
result:number = 0;
listOperation: Array<{firstvalue:number,scdvalue:number,operation:string}>;
process(operation:string, firstvalue:number, scdvalue:number):void{
}
addition():void{
}
multiplication(): void{
}
substration(): void{
}
}
| import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: "/app/app.component.tpl.html"
})
export class AppComponent {
operation: string = 'x';
fstvalue: number = 0;
scdvalue: number = 0;
result: number = 0;
listOperation: Array<{ firstvalue: number, scdvalue: number, operation: string }>;
constructor() {
this.result = this.multiplication(this.fstvalue,this.scdvalue);
}
process(operation: string, firstvalue: number, scdvalue: number): void {
}
addition(firstvalue: number, scdvalue: number): number {
let result:number;
return result;
}
multiplication(firstvalue: number, scdvalue: number): number {
let result:number;
return result;
}
substration(firstvalue: number, scdvalue: number): number {
let result:number;
return result;
}
}
|
Add ability to blissfully ignore certain nodes | import { Node, SyntaxKind, SourceFile } from 'typescript';
import { emitImportDeclaration } from './imports';
import { emitFunctionLikeDeclaration } from './functions';
import { emitExpressionStatement, emitCallExpressionStatement } from './expressions';
import { emitIdentifier, emitType } from './identifiers';
import { emitSourceFile } from './source';
import { Context } from '../contexts';
export interface EmitResult {
context: Context;
emitted_string: string;
}
export const emit = (node: Node, context: Context): EmitResult => {
switch (node.kind) {
case SyntaxKind.SourceFile: return emitSourceFile(<any>node, context);
case SyntaxKind.ImportDeclaration: return emitImportDeclaration(<any>node, context);
case SyntaxKind.FunctionDeclaration: return emitFunctionLikeDeclaration(<any>node, context);
case SyntaxKind.ExpressionStatement: return emitExpressionStatement(<any>node, context);
case SyntaxKind.CallExpression: return emitCallExpressionStatement(<any>node, context);
case SyntaxKind.Identifier: return emitIdentifier(<any>node, context);
case SyntaxKind.TypeReference: return emitType(<any>node, context);
case SyntaxKind.EndOfFileToken: return { context, emitted_string: 'end' };
default: throw new Error(`unknown syntax kind ${SyntaxKind[node.kind]}`);
}
};
| import { Node, SyntaxKind, SourceFile } from 'typescript';
import { emitImportDeclaration } from './imports';
import { emitFunctionLikeDeclaration } from './functions';
import { emitExpressionStatement, emitCallExpressionStatement } from './expressions';
import { emitIdentifier, emitType } from './identifiers';
import { emitBlock } from './blocks';
import { emitSourceFile } from './source';
import { emitReturnStatement } from './statements';
import { Context } from '../contexts';
export interface EmitResult {
context: Context;
emitted_string: string;
}
const ignore = (node: Node, context: Context): EmitResult => ({
context,
emitted_string: `ignored ${SyntaxKind[node.kind]}`
})
export const emit = (node: Node, context: Context): EmitResult => {
switch (node.kind) {
case SyntaxKind.SourceFile: return emitSourceFile(<any>node, context);
case SyntaxKind.ImportDeclaration: return emitImportDeclaration(<any>node, context);
case SyntaxKind.FunctionDeclaration: return emitFunctionLikeDeclaration(<any>node, context);
case SyntaxKind.ExpressionStatement: return emitExpressionStatement(<any>node, context);
case SyntaxKind.CallExpression: return emitCallExpressionStatement(<any>node, context);
case SyntaxKind.Identifier: return emitIdentifier(<any>node, context);
case SyntaxKind.TypeReference: return emitType(<any>node, context);
case SyntaxKind.Block: return emitBlock(<any>node, context);
case SyntaxKind.ReturnStatement: return emitReturnStatement(<any>node, context);
case SyntaxKind.EndOfFileToken: return { context, emitted_string: 'end' };
case SyntaxKind.ConditionalExpression: return ignore(node, context);
case SyntaxKind.VariableStatement: return ignore(node, context);
case SyntaxKind.BinaryExpression: return ignore(node, context);
default: throw new Error(`unknown syntax kind ${SyntaxKind[node.kind]}`);
}
};
|
Fix top page component test | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TopPageComponent } from './top-page.component';
describe('TopPageComponent', () => {
let component: TopPageComponent;
let fixture: ComponentFixture<TopPageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ TopPageComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TopPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ImageService } from '../../gallery/image.service';
import { MockImageService } from '../../gallery/mocks/mock-image.service';
import { GalleryFormatPipe } from '../../gallery/gallery-format.pipe';
import { ThumbnailComponent } from '../../gallery/thumbnail/thumbnail.component';
import { ImageContainerComponent } from '../../gallery/image-container/image-container.component';
import { TopPageComponent } from './top-page.component';
describe('TopPageComponent', () => {
const mockImageService = new MockImageService();
let component: TopPageComponent;
let fixture: ComponentFixture<TopPageComponent>;
let compiled: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [
GalleryFormatPipe,
ThumbnailComponent,
ImageContainerComponent,
TopPageComponent
],
providers: [
{ provide: ImageService, useValue: mockImageService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TopPageComponent);
component = fixture.componentInstance;
compiled = fixture.debugElement.nativeElement;
fixture.detectChanges();
});
it('should create and load images', () => {
expect(component).toBeTruthy();
const thumbnails = compiled.querySelectorAll('jblog-thumbnail');
expect(thumbnails.length).toBe(1);
});
});
|
Add new public addCommand functions | import { Injectable } from '@angular/core';
import artyomjs = require('artyom.js');
@Injectable()
export class VoiceService {
private voiceProvider: IVoiceProvider = new ArtyomProvider();
constructor() { }
public say(text: string) {
console.log("Saying: ", text);
this.voiceProvider.say(text);
}
public sayGeocodeResult(result : /*google.maps.GeocoderResult*/any) {
const address = result.address_components[0].long_name + ' '+
result.address_components[1].long_name;
this.say(address);
}
}
interface IVoiceProvider {
say(text: string): void;
}
class ArtyomProvider implements IVoiceProvider {
readonly artyom = artyomjs.ArtyomBuilder.getInstance();
constructor() {
this.artyom.initialize({
lang: "fr-FR", // GreatBritain english
continuous: false, // Listen forever
soundex: true,// Use the soundex algorithm to increase accuracy
debug: true, // Show messages in the console
listen: false // Start to listen commands !
});
}
public say(text: string): void {
this.artyom.say(text);
}
} | import { Injectable } from '@angular/core';
import artyomjs = require('artyom.js');
import ArtyomCommand = Artyom.ArtyomCommand;
import * as _ from "lodash";
@Injectable()
export class VoiceService {
private voiceProvider: IVoiceProvider = new ArtyomProvider();
constructor() { }
public say(text: string) {
console.log("Saying: ", text);
this.voiceProvider.say(text);
}
public sayGeocodeResult(result : /*google.maps.GeocoderResult*/any) {
const address = result.address_components[0].long_name + ' '+
result.address_components[1].long_name;
this.say(address);
}
}
interface IVoiceProvider {
say(text: string): void;
}
class ArtyomProvider implements IVoiceProvider {
readonly artyom = artyomjs.ArtyomBuilder.getInstance();
constructor() {
this.artyom.initialize({
lang: "fr-FR", // GreatBritain english
continuous: false, // Listen forever
soundex: true,// Use the soundex algorithm to increase accuracy
debug: true, // Show messages in the console
listen: false // Start to listen commands !
});
}
public say(text: string): void {
this.artyom.say(text);
}
public addCommand(indexes: string[], description: string, action: (i: number, wildcard?: string) => void ): void {
const isSmart = _.some(indexes, str => _.includes(str, "*"));
const command: ArtyomCommand = <ArtyomCommand> { indexes: indexes, action: action, description: description, smart: isSmart};
this.artyom.addCommands(command);
}
} |
Fix logical error in `computeBestTime` | import { ConnectionStatus } from "./interfaces";
import * as m from "moment";
import { isString, max } from "lodash";
export function maxDate(l: m.Moment, r: m.Moment): string {
const dates = [l, r].map(y => y.toDate());
return (max(dates) || dates[0]).toJSON();
}
export function getStatus(cs: ConnectionStatus | undefined): "up" | "down" {
return (cs && cs.state) || "down";
}
/** USE CASE: We have numerous, possibly duplicate sources of information
* that represent `last_saw_mq`. One came from the API and another (possibly)
* came from the MQ directly to the browser. This function determines which of
* the two is most relevant. It is a heuristic process that gives up when
* unable to make a determination. */
export function computeBestTime(cs: ConnectionStatus | undefined,
lastSawMq: string | undefined,
now = m()): ConnectionStatus | undefined {
// Only use the `last_saw_mq` time if it is more recent than the local
// timestamp.
// don't bother guessing if info is unavailable
return isString(lastSawMq) ?
{ at: maxDate(now, m(lastSawMq)), state: getStatus(cs) } : cs;
}
| import { ConnectionStatus } from "./interfaces";
import * as m from "moment";
import { isString, max } from "lodash";
export function maxDate(l: m.Moment, r: m.Moment): string {
const dates = [l, r].map(y => y.toDate());
return (max(dates) || dates[0]).toJSON();
}
export function getStatus(cs: ConnectionStatus | undefined): "up" | "down" {
return (cs && cs.state) || "down";
}
/** USE CASE: We have numerous, possibly duplicate sources of information
* that represent `last_saw_mq`. One came from the API and another (possibly)
* came from the MQ directly to the browser. This function determines which of
* the two is most relevant. It is a heuristic process that gives up when
* unable to make a determination. */
export function computeBestTime(cs: ConnectionStatus | undefined,
lastSawMq: string | undefined): ConnectionStatus | undefined {
// Only use the `last_saw_mq` time if it is more recent than the local
// timestamp.
// don't bother guessing if info is unavailable
return isString(lastSawMq) ?
{ at: maxDate(m(cs && cs.at ? cs.at : lastSawMq), m(lastSawMq)), state: getStatus(cs) } : cs;
}
|
Use namespace prefix for style tag | import { isBrowser } from './browser'
/**
* Injects a string of CSS styles to a style node in <head>
*/
export function injectCSS(css: string): void {
if (isBrowser) {
const style = document.createElement('style')
style.type = 'text/css'
style.textContent = css
style.setAttribute('data-tippy-stylesheet', '')
const head = document.head
const { firstChild } = head
if (firstChild) {
head.insertBefore(style, firstChild)
} else {
head.appendChild(style)
}
}
}
| import { isBrowser } from './browser'
/**
* Injects a string of CSS styles to a style node in <head>
*/
export function injectCSS(css: string): void {
if (isBrowser) {
const style = document.createElement('style')
style.type = 'text/css'
style.textContent = css
style.setAttribute('data-__NAMESPACE_PREFIX__-stylesheet', '')
const head = document.head
const { firstChild } = head
if (firstChild) {
head.insertBefore(style, firstChild)
} else {
head.appendChild(style)
}
}
}
|
Update dependency checking for ImageMagick | import Logger from './logger';
import { execSync } from 'child_process';
export default class {
private logger: Logger;
constructor() {
this.logger = new Logger('Deps');
}
public showAll(): void {
this.show('MongoDB', 'mongo --version', x => x.match(/^MongoDB shell version:? (.*)\r?\n/));
this.show('Redis', 'redis-server --version', x => x.match(/v=([0-9\.]*)/));
this.show('ImageMagick', 'magick -version', x => x.match(/^Version: ImageMagick (.+?)\r?\n/));
}
public show(serviceName: string, command: string, transform: (x: string) => RegExpMatchArray): void {
try {
// ステータス0以外のときにexecSyncはstderrをコンソール上に出力してしまうので
// プロセスからのstderrをすべて無視するように stdio オプションをセット
const x = execSync(command, { stdio: ['pipe', 'pipe', 'ignore'] });
const ver = transform(x.toString());
if (ver != null) {
this.logger.succ(`${serviceName} ${ver[1]} found`);
} else {
this.logger.warn(`${serviceName} not found`);
this.logger.warn(`Regexp used for version check of ${serviceName} is probably messed up`);
}
} catch (e) {
this.logger.warn(`${serviceName} not found`);
}
}
}
| import Logger from './logger';
import { execSync } from 'child_process';
export default class {
private logger: Logger;
constructor() {
this.logger = new Logger('Deps');
}
public showAll(): void {
this.show('MongoDB', 'mongo --version', x => x.match(/^MongoDB shell version:? (.*)\r?\n/));
this.show('Redis', 'redis-server --version', x => x.match(/v=([0-9\.]*)/));
this.show('ImageMagick', 'magick -version', x => x.match(/^Version: ImageMagick ([^ ]*)/));
}
public show(serviceName: string, command: string, transform: (x: string) => RegExpMatchArray): void {
try {
// ステータス0以外のときにexecSyncはstderrをコンソール上に出力してしまうので
// プロセスからのstderrをすべて無視するように stdio オプションをセット
const x = execSync(command, { stdio: ['pipe', 'pipe', 'ignore'] });
const ver = transform(x.toString());
if (ver != null) {
this.logger.succ(`${serviceName} ${ver[1]} found`);
} else {
this.logger.warn(`${serviceName} not found`);
this.logger.warn(`Regexp used for version check of ${serviceName} is probably messed up`);
}
} catch (e) {
this.logger.warn(`${serviceName} not found`);
}
}
}
|
Add todo for fixing auth | import React from 'react';
import { Redirect } from 'react-router';
export const Authenticated = ({ location }) =>
location.referrer !== location.url ? (
<Redirect
to={{
pathname: location.referrer
}}
/>
) : (
<div>You have been successfully logged in</div>
);
| import React from 'react';
import { Redirect } from 'react-router';
//TODO: Redirect back to correct path
export const Authenticated = ({ location }) =>
location.referrer !== location.url ? (
<Redirect
to={{
pathname: location.referrer
}}
/>
) : (
<div>You have been successfully logged in</div>
);
|
Check render() API arguments at runtime. | /*
This is the main module, it exports the 'render' API.
The compiled modules are bundled by Webpack into 'var' (script tag) and 'commonjs' (npm)
formatted libraries.
*/
/* tslint:disable */
import {renderSource} from './render'
import * as options from './options'
import * as quotes from './quotes'
/* tslint:enable */
/**
*
* This is the single public API which translates Rimu Markup to HTML.
*
* @param source
* Input text containing Rimu Markup.
*
* @param opts
* Markup translation options.
*
* @returns Returns HTML output text.
*
* Example:
*
* Rimu.render('Hello *Rimu*!', {safeMode: 1})
*
*/
export function render(source: string, opts: options.RenderOptions = {}): string {
options.update(opts)
return renderSource(source)
}
// Load-time initializations.
quotes.initialize()
| /*
This is the main module, it exports the 'render' API.
The compiled modules are bundled by Webpack into 'var' (script tag) and 'commonjs' (npm)
formatted libraries.
*/
/* tslint:disable */
import {renderSource} from './render'
import * as options from './options'
import * as quotes from './quotes'
/* tslint:enable */
/**
*
* This is the single public API which translates Rimu Markup to HTML.
*
* @param source
* Input text containing Rimu Markup.
*
* @param opts
* Markup translation options.
*
* @returns Returns HTML output text.
*
* Example:
*
* Rimu.render('Hello *Rimu*!', {safeMode: 1})
*
*/
export function render(source: string, opts: options.RenderOptions = {}): string {
if (typeof source !== 'string') {
throw new TypeError('render(): source argument is not a string')
}
if (opts !== undefined && typeof opts !== 'object') {
throw new TypeError('render(): options argument is not an object')
}
options.update(opts)
return renderSource(source)
}
// Load-time initializations.
quotes.initialize()
|
Add blank line after copyright |
// Copyright 2018 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export type AccessKeyId = string;
export interface ProxyParams {
hostname: string;
portNumber: number;
encryptionMethod: string;
password: string;
}
export interface AccessKey {
// The unique identifier for this access key.
id: AccessKeyId;
// Admin-controlled, editable name for this access key.
name: string;
// Used in metrics reporting to decouple from the real id. Can change.
metricsId: AccessKeyId;
// Parameters to access the proxy
proxyParams: ProxyParams;
}
export interface AccessKeyRepository {
// Creates a new access key. Parameters are chosen automatically.
createNewAccessKey(): Promise<AccessKey>;
// Removes the access key given its id. Returns true if successful.
removeAccessKey(id: AccessKeyId): boolean;
// Lists all existing access keys
listAccessKeys(): IterableIterator<AccessKey>;
// Apply the specified update to the specified access key.
// Returns true if successful.
renameAccessKey(id: AccessKeyId, name: string): boolean;
} |
// Copyright 2018 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export type AccessKeyId = string;
export interface ProxyParams {
hostname: string;
portNumber: number;
encryptionMethod: string;
password: string;
}
export interface AccessKey {
// The unique identifier for this access key.
id: AccessKeyId;
// Admin-controlled, editable name for this access key.
name: string;
// Used in metrics reporting to decouple from the real id. Can change.
metricsId: AccessKeyId;
// Parameters to access the proxy
proxyParams: ProxyParams;
}
export interface AccessKeyRepository {
// Creates a new access key. Parameters are chosen automatically.
createNewAccessKey(): Promise<AccessKey>;
// Removes the access key given its id. Returns true if successful.
removeAccessKey(id: AccessKeyId): boolean;
// Lists all existing access keys
listAccessKeys(): IterableIterator<AccessKey>;
// Apply the specified update to the specified access key.
// Returns true if successful.
renameAccessKey(id: AccessKeyId, name: string): boolean;
} |
Fix undefined error in PlayComponent.stopNote | import { Component } from '@angular/core';
/**
* This class represents the lazy loaded PlayComponent.
*/
@Component({
moduleId: module.id,
selector: 'sd-play',
templateUrl: 'play.component.html',
styleUrls: ['play.component.css']
})
export class PlayComponent {
audioContext: AudioContext;
currentOscillator: OscillatorNode;
constructor() {
this.audioContext = new AudioContext();
}
startNote(frequency: number) {
console.log("startNote()");
var oscillator = this.audioContext.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = frequency;
oscillator.connect(this.audioContext.destination);
oscillator.start(0);
this.currentOscillator = oscillator;
}
stopNote() {
console.log("stopNote()");
this.currentOscillator.stop(0);
}
}
| import { Component } from '@angular/core';
/**
* This class represents the lazy loaded PlayComponent.
*/
@Component({
moduleId: module.id,
selector: 'sd-play',
templateUrl: 'play.component.html',
styleUrls: ['play.component.css']
})
export class PlayComponent {
audioContext: AudioContext;
currentOscillator: OscillatorNode;
constructor() {
this.audioContext = new AudioContext();
}
startNote(frequency: number) {
console.log("startNote()");
var oscillator = this.audioContext.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = frequency;
oscillator.connect(this.audioContext.destination);
oscillator.start(0);
this.currentOscillator = oscillator;
}
stopNote() {
console.log("stopNote()");
if (this.currentOscillator !== undefined)
{
this.currentOscillator.stop(0);
}
}
}
|
Revert "Apparently null is a-ok for array/record of things" | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import { forEach } from 'lodash';
export function classWithModifiers(className: string, modifiers?: string[] | Record<string, boolean>) {
let ret = className;
if (modifiers != null) {
if (Array.isArray(modifiers)) {
modifiers.forEach((modifier) => {
if (modifier != null) {
ret += ` ${className}--${modifier}`;
}
});
} else {
forEach(modifiers, (isActive, modifier) => {
if (isActive) {
ret += ` ${className}--${modifier}`;
}
});
}
}
return ret;
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import { forEach } from 'lodash';
type Modifiers = (string | null | undefined)[] | Record<string, boolean | null | undefined>;
export function classWithModifiers(className: string, modifiers?: Modifiers) {
let ret = className;
if (modifiers != null) {
if (Array.isArray(modifiers)) {
modifiers.forEach((modifier) => {
if (modifier != null) {
ret += ` ${className}--${modifier}`;
}
});
} else {
forEach(modifiers, (isActive, modifier) => {
if (isActive) {
ret += ` ${className}--${modifier}`;
}
});
}
}
return ret;
}
|
Remove needless substitutions to a temporary variable x | /**
* Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Koya Sakuma
* Adapted from MolQL implemtation of atom-set.ts
*
* Copyright (c) 2017 MolQL contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { StructureQuery } from '../query';
import { StructureSelection } from '../selection';
import { getCurrentStructureProperties } from './filters';
import { QueryContext, QueryFn } from '../context';
export function atomCount(ctx: QueryContext) {
return ctx.currentStructure.elementCount;
}
export function countQuery(query: StructureQuery) {
return (ctx: QueryContext) => {
const sel = query(ctx);
const x: number = StructureSelection.structureCount(sel);
return x;
};
}
export function propertySet(prop: QueryFn<any>) {
return (ctx: QueryContext) => {
const set = new Set();
const x = getCurrentStructureProperties(ctx, prop, set);
return x;
};
}
| /**
* Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Koya Sakuma
* Adapted from MolQL implemtation of atom-set.ts
*
* Copyright (c) 2017 MolQL contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { StructureQuery } from '../query';
import { StructureSelection } from '../selection';
import { getCurrentStructureProperties } from './filters';
import { QueryContext, QueryFn } from '../context';
export function atomCount(ctx: QueryContext) {
return ctx.currentStructure.elementCount;
}
export function countQuery(query: StructureQuery) {
return (ctx: QueryContext) => {
const sel = query(ctx);
return StructureSelection.structureCount(sel);
};
}
export function propertySet(prop: QueryFn<any>) {
return (ctx: QueryContext) => {
const set = new Set();
return getCurrentStructureProperties(ctx, prop, set);
};
}
|
Use the export function-style rather than export const | import { Repository } from '../../../models/repository'
import { IAPIRepository } from '../../api'
import { GitStore } from '../git-store'
export const updateRemoteUrl = async (
gitStore: GitStore,
repository: Repository,
apiRepo: IAPIRepository
): Promise<void> => {
// I'm not sure when these early exit conditions would be met. But when they are
// we don't have enough information to continue so exit early!
if (!gitStore.currentRemote) {
return
}
if (!repository.gitHubRepository) {
return
}
const remoteUrl = gitStore.currentRemote.url
const updatedRemoteUrl = apiRepo.clone_url
const isProtocolHttps = remoteUrl && remoteUrl.startsWith('https://')
const usingDefaultRemote =
gitStore.defaultRemote &&
gitStore.defaultRemote.url === repository.gitHubRepository.cloneURL
if (isProtocolHttps && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) {
await gitStore.setRemoteURL(gitStore.currentRemote.name, updatedRemoteUrl)
}
}
| import { Repository } from '../../../models/repository'
import { IAPIRepository } from '../../api'
import { GitStore } from '../git-store'
export async function updateRemoteUrl(
gitStore: GitStore,
repository: Repository,
apiRepo: IAPIRepository
): Promise<void> {
// I'm not sure when these early exit conditions would be met. But when they are
// we don't have enough information to continue so exit early!
if (!gitStore.currentRemote) {
return
}
if (!repository.gitHubRepository) {
return
}
const remoteUrl = gitStore.currentRemote.url
const updatedRemoteUrl = apiRepo.clone_url
const isProtocolHttps = remoteUrl && remoteUrl.startsWith('https://')
const usingDefaultRemote =
gitStore.defaultRemote &&
gitStore.defaultRemote.url === repository.gitHubRepository.cloneURL
if (isProtocolHttps && usingDefaultRemote && remoteUrl !== updatedRemoteUrl) {
await gitStore.setRemoteURL(gitStore.currentRemote.name, updatedRemoteUrl)
}
}
|
Add titlePage to first page header | // Page numbers
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
import { AlignmentType, Document, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build";
const doc = new Document();
doc.addSection({
headers: {
default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("My Title "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("First Page Header "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
},
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
| // Page numbers
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build";
const doc = new Document();
doc.addSection({
properties: {
titlePage: true,
},
headers: {
default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("My Title "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("First Page Header "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
},
footers: {
default: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("My Title "),
new TextRun({
children: ["Footer - Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
first: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [
new TextRun("First Page Footer "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}),
],
}),
},
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
|
Add proxy prefix to HsConfig | export class HsConfig {
cesiumTime: any;
componentsEnabled: any;
mapInteractionsEnabled: boolean;
allowAddExternalDatasets: boolean;
sidebarClosed: boolean;
layer_order: string;
box_layers: Array<any>;
senslog: any;
cesiumdDebugShowFramesPerSecond: boolean;
cesiumShadows: number;
cesiumBase: string;
createWorldTerrainOptions: any;
terrain_provider: any;
cesiumTimeline: boolean;
cesiumAnimation: boolean;
creditContainer: any;
cesiumInfoBox: any;
imageryProvider: any;
terrainExaggeration: number;
cesiumBingKey: string;
newTerrainProviderOptions: any;
terrain_providers: any;
cesiumAccessToken: string;
constructor() {}
}
| export class HsConfig {
cesiumTime: any;
componentsEnabled: any;
mapInteractionsEnabled: boolean;
allowAddExternalDatasets: boolean;
sidebarClosed: boolean;
layer_order: string;
box_layers: Array<any>;
senslog: any;
cesiumdDebugShowFramesPerSecond: boolean;
cesiumShadows: number;
cesiumBase: string;
createWorldTerrainOptions: any;
terrain_provider: any;
cesiumTimeline: boolean;
cesiumAnimation: boolean;
creditContainer: any;
cesiumInfoBox: any;
imageryProvider: any;
terrainExaggeration: number;
cesiumBingKey: string;
newTerrainProviderOptions: any;
terrain_providers: any;
cesiumAccessToken: string;
proxyPrefix: string;
constructor() {}
}
|
Add interface for settings provider | import { Injectable } from '@angular/core';
@Injectable()
export class TubularSettingsService {
constructor() {
}
public put(id: string, value: string) {
localStorage.setItem(id, JSON.stringify(value));
}
public get(key: string): any {
return JSON.parse(localStorage.getItem(key)) || false;
}
public delete(key: string): any {
localStorage.removeItem(key);
}
}
| import { Injectable } from '@angular/core';
export interface ITubularSettingsProvider {
put(id: string, value: string): void;
get(key: string): any;
delete(key: string): void;
}
@Injectable()
export class TubularSettingsService {
constructor() {
}
public put(id: string, value: string) {
localStorage.setItem(id, JSON.stringify(value));
}
public get(key: string): any {
return JSON.parse(localStorage.getItem(key)) || false;
}
public delete(key: string) {
localStorage.removeItem(key);
}
}
|
Fix some useMulti parameters accidentally being passed as view terms | import React from 'react';
import { useMulti } from '../../lib/crud/withMulti';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useCurrentUser } from '../common/withUser';
export const GardenCodesList = ({classes, terms}:{classes:ClassesType, terms: GardenCodesViewTerms}) => {
const { GardenCodesItem } = Components
const currentUser = useCurrentUser()
const { results } = useMulti({
terms: {
userId: currentUser?._id,
enableTotal: false,
fetchPolicy: 'cache-and-network',
...terms
},
collectionName: "GardenCodes",
fragmentName: 'GardenCodeFragment'
});
return <div>
{results?.map(code=><GardenCodesItem key={code._id} gardenCode={code}/>)}
</div>
}
const GardenCodesListComponent = registerComponent('GardenCodesList', GardenCodesList);
declare global {
interface ComponentTypes {
GardenCodesList: typeof GardenCodesListComponent
}
}
| import React from 'react';
import { useMulti } from '../../lib/crud/withMulti';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useCurrentUser } from '../common/withUser';
export const GardenCodesList = ({classes, terms}:{classes:ClassesType, terms: GardenCodesViewTerms}) => {
const { GardenCodesItem } = Components
const currentUser = useCurrentUser()
const { results } = useMulti({
terms: {
userId: currentUser?._id,
...terms
},
enableTotal: false,
fetchPolicy: 'cache-and-network',
collectionName: "GardenCodes",
fragmentName: 'GardenCodeFragment'
});
return <div>
{results?.map(code=><GardenCodesItem key={code._id} gardenCode={code}/>)}
</div>
}
const GardenCodesListComponent = registerComponent('GardenCodesList', GardenCodesList);
declare global {
interface ComponentTypes {
GardenCodesList: typeof GardenCodesListComponent
}
}
|
Fix crashing using moment utils on datepicker page | import dayjs, { Dayjs } from 'dayjs';
import moment, { Moment } from 'moment';
import { DateTime } from 'luxon';
export function cloneCrossUtils(date: Date | Moment | DateTime | Dayjs) {
if (date instanceof dayjs) {
return (date as Dayjs).clone().toDate();
}
if (date instanceof moment) {
return (date as Moment).clone().toDate();
}
if (date instanceof DateTime) {
return date.toJSDate();
}
if (date instanceof Date) {
return new Date(date.getTime());
}
throw new Error('Cannot properly parse argument passed to cloneCrossUtils');
}
export function copy(text: string) {
return window.navigator.permissions.query({ name: 'clipboard-write' }).then(result => {
if (result.state == 'granted' || result.state == 'prompt') {
return navigator.clipboard.writeText(text);
}
return Promise.reject();
});
}
export function loadScript(src: string, position: Element) {
const script = document.createElement('script');
script.setAttribute('async', '');
script.src = src;
position.appendChild(script);
return script;
}
| import dayjs, { Dayjs } from 'dayjs';
import moment, { Moment } from 'moment';
import { DateTime } from 'luxon';
export function cloneCrossUtils(date: Date | Moment | DateTime | Dayjs) {
if (date instanceof dayjs) {
return (date as Dayjs).clone().toDate();
}
if (moment.isMoment(date)) {
return (date as Moment).clone().toDate();
}
if (date instanceof DateTime) {
return date.toJSDate();
}
if (date instanceof Date) {
return new Date(date.getTime());
}
throw new Error('Cannot properly parse argument passed to cloneCrossUtils');
}
export function copy(text: string) {
return window.navigator.permissions.query({ name: 'clipboard-write' }).then(result => {
if (result.state == 'granted' || result.state == 'prompt') {
return navigator.clipboard.writeText(text);
}
return Promise.reject();
});
}
export function loadScript(src: string, position: Element) {
const script = document.createElement('script');
script.setAttribute('async', '');
script.src = src;
position.appendChild(script);
return script;
}
|
Throw an error if no steps are provided | import { parse, IGitProgress } from './parser'
export interface IProgressStep {
title: string
weight: number
}
export interface ICombinedProgress {
percent: number
details: IGitProgress
}
export class StepProgressParser {
private readonly steps: ReadonlyArray<IProgressStep>
private stepIndex = 0
public constructor(steps: ReadonlyArray<IProgressStep>) {
// Scale the step weight so that they're all a percentage
// adjusted to the total weight of all steps.
const totalStepWeight = steps.reduce((sum, step) => sum + step.weight, 0)
this.steps = steps.map(step => ({
title: step.title,
weight: step.weight / totalStepWeight,
}))
}
public parse(line: string): ICombinedProgress | null {
const progress = parse(line)
if (!progress) {
return null
}
let percent = 0
for (let i = this.stepIndex; i < this.steps.length; i++) {
const step = this.steps[i]
if (progress.title === step.title) {
if (progress.total) {
percent += step.weight * (progress.value / progress.total)
}
this.stepIndex = i
return { percent, details: progress }
} else {
percent += step.weight
}
}
return null
}
}
| import { parse, IGitProgress } from './parser'
export interface IProgressStep {
title: string
weight: number
}
export interface ICombinedProgress {
percent: number
details: IGitProgress
}
export class StepProgressParser {
private readonly steps: ReadonlyArray<IProgressStep>
private stepIndex = 0
public constructor(steps: ReadonlyArray<IProgressStep>) {
if (!steps.length) {
throw new Error('must specify at least one step')
}
// Scale the step weight so that they're all a percentage
// adjusted to the total weight of all steps.
const totalStepWeight = steps.reduce((sum, step) => sum + step.weight, 0)
this.steps = steps.map(step => ({
title: step.title,
weight: step.weight / totalStepWeight,
}))
}
public parse(line: string): ICombinedProgress | null {
const progress = parse(line)
if (!progress) {
return null
}
let percent = 0
for (let i = this.stepIndex; i < this.steps.length; i++) {
const step = this.steps[i]
if (progress.title === step.title) {
if (progress.total) {
percent += step.weight * (progress.value / progress.total)
}
this.stepIndex = i
return { percent, details: progress }
} else {
percent += step.weight
}
}
return null
}
}
|
Change in default test delay | export function delay (timeout) {
return new Promise<void>(resolve => {
setTimeout(resolve, timeout)
})
}
// for some reason editor.action.triggerSuggest needs more delay at the beginning when the process is not yet warmed up
// let's start from high delays and then slowly go to lower delays
let delaySteps = [2000, 1200, 700, 400, 300, 200]
export const getCurrentDelay = () => (delaySteps.length > 1) ? delaySteps.shift() : delaySteps[0]
| export function delay (timeout) {
return new Promise<void>(resolve => {
setTimeout(resolve, timeout)
})
}
// for some reason editor.action.triggerSuggest needs more delay at the beginning when the process is not yet warmed up
// let's start from high delays and then slowly go to lower delays
let delaySteps = [2000, 1200, 700, 400, 300, 250]
export const getCurrentDelay = () => (delaySteps.length > 1) ? delaySteps.shift() : delaySteps[0]
|
Fix uievent to fix typedoc | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import TelemetryEvent from "./TelemetryEvent";
import { prependEventNamePrefix } from "./TelemetryUtils";
export const EVENT_KEYS = {
USER_CANCELLED: prependEventNamePrefix("user_cancelled"),
ACCESS_DENIED: prependEventNamePrefix("access_denied")
};
export default class UiEvent extends TelemetryEvent {
constructor(correlationId: string) {
super(prependEventNamePrefix("ui_event"), correlationId);
}
public set userCancelled(userCancelled: boolean) {
this.event[EVENT_KEYS.USER_CANCELLED] = userCancelled;
}
public set accessDenied(accessDenied: boolean) {
this.event[EVENT_KEYS.ACCESS_DENIED] = accessDenied;
}
}
| /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import TelemetryEvent from "./TelemetryEvent";
import { prependEventNamePrefix } from "./TelemetryUtils";
export const EVENT_KEYS = {
USER_CANCELLED: prependEventNamePrefix("user_cancelled"),
ACCESS_DENIED: prependEventNamePrefix("access_denied")
};
export default class UiEvent extends TelemetryEvent {
constructor(correlationId: string) {
super(prependEventNamePrefix("ui_event"), correlationId, "UiEvent");
}
public set userCancelled(userCancelled: boolean) {
this.event[EVENT_KEYS.USER_CANCELLED] = userCancelled;
}
public set accessDenied(accessDenied: boolean) {
this.event[EVENT_KEYS.ACCESS_DENIED] = accessDenied;
}
}
|
Make source code accessible from outside | export { ColorPalette, ColorItem, IconGallery, IconItem, Typeset } from '@storybook/components';
export * from './Anchor';
export * from './ArgsTable';
export * from './Canvas';
export * from './Description';
export * from './DocsContext';
export * from './DocsPage';
export * from './DocsContainer';
export * from './DocsStory';
export * from './Heading';
export * from './Meta';
export * from './Preview';
export * from './Primary';
export * from './Props';
export * from './Source';
export * from './Stories';
export * from './Story';
export * from './Subheading';
export * from './Subtitle';
export * from './Title';
export * from './Wrapper';
export * from './types';
export * from './mdx';
| export { ColorPalette, ColorItem, IconGallery, IconItem, Typeset } from '@storybook/components';
export * from './Anchor';
export * from './ArgsTable';
export * from './Canvas';
export * from './Description';
export * from './DocsContext';
export * from './DocsPage';
export * from './DocsContainer';
export * from './DocsStory';
export * from './Heading';
export * from './Meta';
export * from './Preview';
export * from './Primary';
export * from './Props';
export * from './Source';
export * from './SourceContainer';
export * from './Stories';
export * from './Story';
export * from './Subheading';
export * from './Subtitle';
export * from './Title';
export * from './Wrapper';
export * from './types';
export * from './mdx';
|
Patch for wrong Firefox add-ons CSS MIME type | async function getOKResponse(url: string, mimeType?: string) {
const response = await fetch(
url,
{
cache: 'force-cache',
credentials: 'omit',
},
);
if (mimeType && !response.headers.get('Content-Type').startsWith(mimeType)) {
throw new Error(`Mime type mismatch when loading ${url}`);
}
if (!response.ok) {
throw new Error(`Unable to load ${url} ${response.status} ${response.statusText}`);
}
return response;
}
export async function loadAsDataURL(url: string, mimeType?: string) {
const response = await getOKResponse(url, mimeType);
return await readResponseAsDataURL(response);
}
export async function readResponseAsDataURL(response: Response) {
const blob = await response.blob();
const dataURL = await (new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
}));
return dataURL;
}
export async function loadAsText(url: string, mimeType?: string) {
const response = await getOKResponse(url, mimeType);
return await response.text();
}
| import {isFirefox} from './platform';
async function getOKResponse(url: string, mimeType?: string) {
const response = await fetch(
url,
{
cache: 'force-cache',
credentials: 'omit',
},
);
// Firefox bug, content type is "application/x-unknown-content-type"
if (isFirefox() && mimeType === 'text/css' && url.startsWith('moz-extension://') && url.endsWith('.css')) {
return response;
}
if (mimeType && !response.headers.get('Content-Type').startsWith(mimeType)) {
throw new Error(`Mime type mismatch when loading ${url}`);
}
if (!response.ok) {
throw new Error(`Unable to load ${url} ${response.status} ${response.statusText}`);
}
return response;
}
export async function loadAsDataURL(url: string, mimeType?: string) {
const response = await getOKResponse(url, mimeType);
return await readResponseAsDataURL(response);
}
export async function readResponseAsDataURL(response: Response) {
const blob = await response.blob();
const dataURL = await (new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
}));
return dataURL;
}
export async function loadAsText(url: string, mimeType?: string) {
const response = await getOKResponse(url, mimeType);
return await response.text();
}
|
Build is stable so debug log removed | import * as fs from "fs";
import * as child from "child_process";
import * as path from "path";
export function getWasmInstance(sourcePath: string, outputFile?:string): WebAssembly.Instance {
outputFile = outputFile || sourcePath.replace(".tbs", ".wasm");
let result = child.spawnSync(path.join(__dirname, '../../bin/tc'), [sourcePath, '--out', outputFile]);
console.log(result);
const data = fs.readFileSync(outputFile);
const mod = new WebAssembly.Module(data);
return new WebAssembly.Instance(mod);
}
| import * as fs from "fs";
import * as child from "child_process";
import * as path from "path";
export function getWasmInstance(sourcePath: string, outputFile?:string): WebAssembly.Instance {
outputFile = outputFile || sourcePath.replace(".tbs", ".wasm");
let result = child.spawnSync(path.join(__dirname, '../../bin/tc'), [sourcePath, '--out', outputFile]);
const data = fs.readFileSync(outputFile);
const mod = new WebAssembly.Module(data);
return new WebAssembly.Instance(mod);
}
|
Set return type of onAuthStateChanged function | import * as firebase from "firebase";
const projectId = process.env.REACT_APP_FIREBASE_PROJECT_ID;
export function initialize(): void {
firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: `${projectId}.firebaseapp.com`,
databaseURL: `https://${projectId}.firebaseio.com`,
storageBucket: `${projectId}.appspot.com`,
});
}
export async function signIn(): Promise<void> {
await firebase.auth().signInWithRedirect(new firebase.auth.GithubAuthProvider());
await firebase.auth().getRedirectResult();
}
export function onAuthStateChanged(callback: (user: firebase.User) => void) {
firebase.auth().onAuthStateChanged(callback);
}
| import * as firebase from "firebase";
const projectId = process.env.REACT_APP_FIREBASE_PROJECT_ID;
export function initialize(): void {
firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: `${projectId}.firebaseapp.com`,
databaseURL: `https://${projectId}.firebaseio.com`,
storageBucket: `${projectId}.appspot.com`,
});
}
export async function signIn(): Promise<void> {
await firebase.auth().signInWithRedirect(new firebase.auth.GithubAuthProvider());
await firebase.auth().getRedirectResult();
}
export function onAuthStateChanged(callback: (user: firebase.User) => void): void {
firebase.auth().onAuthStateChanged(callback);
}
|
Make Read on NotificationFilterSet required |
interface INotificationFilterSet
{
read?: boolean;
subjectType: string[];
reasonType: string[];
repository: number[];
}; |
interface INotificationFilterSet
{
read: boolean;
subjectType: string[];
reasonType: string[];
repository: number[];
}; |
Load DB settings in parallel | import { setPublicSettings, getServerSettingsCache, setServerSettingsCache, registeredSettings } from '../../../lib/settingsCache';
import { getDatabase } from '../lib/mongoCollection';
export async function refreshSettingsCaches() {
const db = getDatabase();
if (db) {
const table = db.collection("databasemetadata");
// TODO: Do these two parallel to save a roundtrip
const serverSettingsObject = await table.findOne({name: "serverSettings"})
const publicSettingsObject = await table.findOne({name: "publicSettings"})
setServerSettingsCache(serverSettingsObject?.value || {__initialized: true});
// We modify the publicSettings object that is made available in lib to allow both the client and the server to access it
setPublicSettings(publicSettingsObject?.value || {__initialized: true});
}
}
| import { setPublicSettings, getServerSettingsCache, setServerSettingsCache, registeredSettings } from '../../../lib/settingsCache';
import { getDatabase } from '../lib/mongoCollection';
export async function refreshSettingsCaches() {
const db = getDatabase();
if (db) {
const table = db.collection("databasemetadata");
const [serverSettingsObject, publicSettingsObject] = await Promise.all([
await table.findOne({name: "serverSettings"}),
await table.findOne({name: "publicSettings"})
]);
setServerSettingsCache(serverSettingsObject?.value || {__initialized: true});
// We modify the publicSettings object that is made available in lib to allow both the client and the server to access it
setPublicSettings(publicSettingsObject?.value || {__initialized: true});
}
}
|
Add unit tests for OvApiService | import { TestBed } from '@angular/core/testing';
import { OvApiService } from './ov-api.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('OvApiService', () => {
let service: OvApiService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
],
});
service = TestBed.inject(OvApiService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
| import { TestBed } from '@angular/core/testing';
import { OvApiService } from './ov-api.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('OvApiService', () => {
let service: OvApiService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
],
});
// Inject the HTTP test controller for each test
httpTestingController = TestBed.inject(HttpTestingController);
// Instantiate service under test
service = TestBed.inject(OvApiService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('#getDepartureTimes() should request and unwrap departure times', () => {
service.getDepartureTimes('zazzoo').subscribe(data => expect(data).toEqual({foo: 'bar'}));
// Mock the HTTP service
const req = httpTestingController.expectOne('http://v0.ovapi.nl/stopareacode/zazzoo');
// Verify request method
expect(req.request.method).toEqual('GET');
// Respond with test data
req.flush({
zazzoo: {
foo: 'bar',
}
});
// Verify there's no outstanding request
httpTestingController.verify();
});
});
|
Remove the update changelog setp | import * as fs from "fs"
// Update the CHANGELOG with the new version
const changelog = fs.readFileSync("CHANGELOG.md", "utf8")
const newCHANGELOG = changelog.replace(
"<!-- Your comment below this -->",
`<!-- Your comment below this -->
# ${process.env.VERSION}
`
)
fs.writeFileSync("CHANGELOG.md", newCHANGELOG, "utf8")
| // import * as fs from "fs"
// // Update the CHANGELOG with the new version
// const changelog = fs.readFileSync("CHANGELOG.md", "utf8")
// const newCHANGELOG = changelog.replace(
// "<!-- Your comment below this -->",
// `<!-- Your comment below this -->
// # ${process.env.VERSION}
// `
// )
// fs.writeFileSync("CHANGELOG.md", newCHANGELOG, "utf8")
|
Remove all Signature child nodes | import { Select, XE, XmlError } from "xml-core";
import { Transform } from "../transform";
/**
* Represents the enveloped signature transform for an XML digital signature as defined by the W3C.
*/
export class XmlDsigEnvelopedSignatureTransform extends Transform {
public Algorithm = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
/**
* Returns the output of the current XmlDsigEnvelopedSignatureTransform object.
* @returns string
*/
public GetOutput(): any {
if (!this.innerXml) {
throw new XmlError(XE.PARAM_REQUIRED, "innerXml");
}
const signature = Select(this.innerXml, ".//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']")[0];
if (signature) {
signature.parentNode!.removeChild(signature);
}
return this.innerXml;
}
}
| import { Select, XE, XmlError } from "xml-core";
import { Transform } from "../transform";
/**
* Represents the enveloped signature transform for an XML digital signature as defined by the W3C.
*/
export class XmlDsigEnvelopedSignatureTransform extends Transform {
public Algorithm = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
/**
* Returns the output of the current XmlDsigEnvelopedSignatureTransform object.
* @returns string
*/
public GetOutput(): any {
if (!this.innerXml) {
throw new XmlError(XE.PARAM_REQUIRED, "innerXml");
}
const signatures = Select(this.innerXml, ".//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']");
for (let i = 0; i < signatures.length; i++) {
const signature = signatures[i];
if (signature.parentNode) {
signature.parentNode.removeChild(signature);
}
}
return this.innerXml;
}
}
|
Expand hero selector view to more height | import { Component, Input, Output, EventEmitter } from '@angular/core';
import { HeroesService, IHero } from '../services/heroes.service';
@Component({
selector: 'hero-selector',
template: `
<div class="modal" [class.is-active]="active">
<div class="modal-background"></div>
<div class="modal-container">
<div class="modal-content">
<div class="hero-selector">
<hero-portrait
*ngFor="let hero of heroes"
(click)="heroClicked(hero)"
class="hero"
[hero]="hero"
[small]="true">
</hero-portrait>
</div>
</div>
</div>
<button class="modal-close" (click)="close()"></button>
</div>
`,
styles: [`
.hero-selector {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.modal-content {
margin: 0;
}
`],
providers: [HeroesService],
})
export class HeroSelectorComponent {
private heroes: IHero[];
@Input() private active: boolean;
@Output() private heroSelected = new EventEmitter<IHero>();
@Output() private closeClicked = new EventEmitter();
constructor(private heroesService: HeroesService) {
this.heroes = heroesService.AllHeroes;
}
private heroClicked(hero: IHero) {
this.heroSelected.emit(hero);
}
private close() {
this.closeClicked.emit();
}
}
| import { Component, Input, Output, EventEmitter } from '@angular/core';
import { HeroesService, IHero } from '../services/heroes.service';
@Component({
selector: 'hero-selector',
template: `
<div class="modal" [class.is-active]="active">
<div class="modal-background"></div>
<div class="modal-container">
<div class="modal-content">
<div class="hero-selector">
<hero-portrait
*ngFor="let hero of heroes"
(click)="heroClicked(hero)"
class="hero"
[hero]="hero"
[small]="true">
</hero-portrait>
</div>
</div>
</div>
<button class="modal-close" (click)="close()"></button>
</div>
`,
styles: [`
.hero-selector {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.modal-content {
max-height: calc(100vh - 100px);
margin: 0;
}
`],
providers: [HeroesService],
})
export class HeroSelectorComponent {
private heroes: IHero[];
@Input() private active: boolean;
@Output() private heroSelected = new EventEmitter<IHero>();
@Output() private closeClicked = new EventEmitter();
constructor(private heroesService: HeroesService) {
this.heroes = heroesService.AllHeroes;
}
private heroClicked(hero: IHero) {
this.heroSelected.emit(hero);
}
private close() {
this.closeClicked.emit();
}
}
|
Fix timing when download is really finished | import axios from 'axios';
import { createWriteStream } from 'fs';
import * as cp from 'child_process';
export async function download(from: string, to: string) {
const { data } = await axios({
method: 'get',
url: from,
responseType:'stream',
});
return new Promise((resolve, reject) => {
data.pipe(createWriteStream(to));
data.on('end', resolve);
data.on('error', reject);
});
}
export function exec(command: string): Promise<string> {
return new Promise((
resolve: (result: string) => void,
reject,
) => {
cp.exec(command, (err, stdout) => {
if (err) {
reject(err);
} else {
resolve(stdout);
}
});
});
}
export function rm(file: string) {
return exec(`rm ${file}`);
}
| import axios from 'axios';
import { createWriteStream } from 'fs';
import * as cp from 'child_process';
export async function download(from: string, to: string) {
const { data } = await axios({
method: 'get',
url: from,
responseType:'stream',
});
return new Promise((resolve, reject) => {
const writable = createWriteStream(to);
data.pipe(writable);
writable.on('close', resolve);
writable.on('error', reject);
});
}
export function exec(command: string): Promise<string> {
return new Promise((
resolve: (result: string) => void,
reject,
) => {
cp.exec(command, (err, stdout) => {
if (err) {
reject(err);
} else {
resolve(stdout);
}
});
});
}
export function rm(file: string) {
return exec(`rm ${file}`);
}
|
Improve display of test RSS data | import m = require("mithril");
import testData = require("./rssFeedExampleFromFSF");
export function initialize() {
console.log("test data:", testData)
console.log("RSS plugin initialized");
}
export function display() {
return m("div.rssPlugin", ["RSS feed reader plugin", m("pre", JSON.stringify(testData, null, 2))]);
} | import m = require("mithril");
import testData = require("./rssFeedExampleFromFSF");
export function initialize() {
console.log("test data:", testData)
console.log("RSS plugin initialized");
}
function displayItem(item) {
var title = item.title;
var link = item.link;
var description = item.desc;
var timestamp = item.date;
return m("div.item", [
m("br")
m("strong", title),
m("br")
description,
" ",
m("a", { href: link }, "More ..."),
m("br"),
]);
}
function displayRSS() {
return m("div.feed", [
testData.items.map(displayItem);
]);
}
export function display() {
return m("div.rssPlugin", [
m("hr"),
m("strong", "RSS feed reader plugin"),
//m("pre", JSON.stringify(testData, null, 2))
displayRSS()
]);
} |
Call refreshInformation on URL change | import { Component, OnInit } from '@angular/core';
import { PlantListService } from "./plant-list.service";
import { Plant } from "./plant";
import {Params, ActivatedRoute} from "@angular/router";
@Component({
selector: 'bed-component',
templateUrl: 'bed.component.html',
})
export class BedComponent implements OnInit {
public bed : string;
public plants: Plant[];
public locations: Plant[];
constructor(private plantListService: PlantListService, private route: ActivatedRoute) {
// this.plants = this.plantListService.getPlants()
//Get the bed from the params of the route
this.bed = this.route.snapshot.params["gardenLocation"];
}
ngOnInit(): void{
this.refreshInformation();
}
refreshInformation() : void
{
this.plantListService.getFlowersByBed(this.bed).subscribe (
plants => this.plants = plants,
err => {
console.log(err);
}
);
this.plantListService.getGardenLocations().subscribe(
locations => this.locations = locations,
err => {
console.log(err);
}
);
}
}
| import { Component, OnInit } from '@angular/core';
import { PlantListService } from "./plant-list.service";
import { Plant } from "./plant";
import {Params, ActivatedRoute, Router} from "@angular/router";
@Component({
selector: 'bed-component',
templateUrl: 'bed.component.html',
})
export class BedComponent implements OnInit {
public bed : string;
public plants: Plant[];
public locations: Plant[];
constructor(private plantListService: PlantListService, private route: ActivatedRoute, private router: Router) {
// this.plants = this.plantListService.getPlants()
//Get the bed from the params of the route
this.router.events.subscribe((val) => {
this.bed = this.route.snapshot.params["gardenLocation"];
this.refreshInformation();
});
}
ngOnInit(): void{
}
refreshInformation() : void
{
this.plantListService.getFlowersByBed(this.bed).subscribe (
plants => this.plants = plants,
err => {
console.log(err);
}
);
this.plantListService.getGardenLocations().subscribe(
locations => this.locations = locations,
err => {
console.log(err);
}
);
}
}
|
Update message to state changes will only be stored on the current branch | import * as React from 'react'
import { DialogContent } from '../dialog'
import { TextArea } from '../lib/text-area'
import { LinkButton } from '../lib/link-button'
interface IGitIgnoreProps {
readonly text: string | null
readonly isDefaultBranch: boolean
readonly onIgnoreTextChanged: (text: string) => void
readonly onShowExamples: () => void
}
/** A view for creating or modifying the repository's gitignore file */
export class GitIgnore extends React.Component<IGitIgnoreProps, {}> {
private renderBranchWarning(): JSX.Element | null {
if (this.props.isDefaultBranch) {
return null
}
return (
<p>
You are not on the default branch, so changes here may not be applied to
the repository when you switch branches.
</p>
)
}
public render() {
return (
<DialogContent>
<p>
The .gitignore file controls which files are tracked by Git and which
are ignored. Check out{' '}
<LinkButton onClick={this.props.onShowExamples}>
git-scm.com
</LinkButton>{' '}
for more information about the file format, or simply ignore a file by
right clicking on it in the uncommitted changes view.
</p>
{this.renderBranchWarning()}
<TextArea
placeholder="Ignored files"
value={this.props.text || ''}
onValueChanged={this.props.onIgnoreTextChanged}
rows={6}
/>
</DialogContent>
)
}
}
| import * as React from 'react'
import { DialogContent } from '../dialog'
import { TextArea } from '../lib/text-area'
import { LinkButton } from '../lib/link-button'
interface IGitIgnoreProps {
readonly text: string | null
readonly isDefaultBranch: boolean
readonly onIgnoreTextChanged: (text: string) => void
readonly onShowExamples: () => void
}
/** A view for creating or modifying the repository's gitignore file */
export class GitIgnore extends React.Component<IGitIgnoreProps, {}> {
private renderBranchWarning(): JSX.Element | null {
if (this.props.isDefaultBranch) {
return null
}
return (
<p>
You are not on the default branch, changes here will only be stored
locally on this branch.
</p>
)
}
public render() {
return (
<DialogContent>
<p>
The .gitignore file controls which files are tracked by Git and which
are ignored. Check out{' '}
<LinkButton onClick={this.props.onShowExamples}>
git-scm.com
</LinkButton>{' '}
for more information about the file format, or simply ignore a file by
right clicking on it in the uncommitted changes view.
</p>
{this.renderBranchWarning()}
<TextArea
placeholder="Ignored files"
value={this.props.text || ''}
onValueChanged={this.props.onIgnoreTextChanged}
rows={6}
/>
</DialogContent>
)
}
}
|
Call the create client edge function |
import express = require('express');
import path = require('path');
import fs = require('fs');
import edge = require('edge');
const app = require('../application');
const createClientEdge = edge.func(function () {/*
async (input) => {
return ".NET Welcomes " + input.ToString();
}
*/});
export function createNewClient(req: express.Request, res: express.Response): void {
console.log('res body-->', req.body);//roberto
res.status(200).send('New client added');
return;
}
|
import express = require('express');
import path = require('path');
import fs = require('fs');
import edge = require('edge');
const app = require('../application');
const createClientEdge = edge.func(function () {/*
async (input) => {
return ".NET Welcomes " + input.ToString();
}
*/});
export function createNewClient(req: express.Request, res: express.Response): void {
createClientEdge(null, function (error, result) {
if (error) {
res.status(500).send('Error executing the createClientEdge function');
return;
};
console.log('result-->', result);//roberto
res.status(200).send('New client added');
return;
});
}
|
Make it possible to convert an entire directory at once | import * as fs from 'fs';
import build from './build';
import * as parseArgs from 'minimist';
for (let arg of parseArgs(process.argv.slice(2))._) {
console.log(build(fs.readFileSync(arg, {encoding:'utf8'})));
}
| import * as fs from 'fs';
import build from './build';
import * as parseArgs from 'minimist';
for (let inFile of parseArgs(process.argv.slice(2))._) {
let outFile = inFile.substring(0, inFile.length - ".in.hledger".length) + ".want";
let converted = build(fs.readFileSync(inFile, {encoding:'utf8'}));
fs.writeFileSync(outFile, converted, {encoding: 'utf8'});
}
|
Fix setIcon warning on Android | export default class IndicatorPresenter {
indicate(enabled: boolean): Promise<void> {
let path = enabled
? 'resources/enabled_32x32.png'
: 'resources/disabled_32x32.png';
return browser.browserAction.setIcon({ path });
}
onClick(listener: (arg: browser.tabs.Tab) => void): void {
browser.browserAction.onClicked.addListener(listener);
}
}
| export default class IndicatorPresenter {
indicate(enabled: boolean): Promise<void> {
let path = enabled
? 'resources/enabled_32x32.png'
: 'resources/disabled_32x32.png';
if (typeof browser.browserAction.setIcon === "function") {
return browser.browserAction.setIcon({ path });
}
else {
// setIcon not supported on Android
return Promise.resolve();
}
}
onClick(listener: (arg: browser.tabs.Tab) => void): void {
browser.browserAction.onClicked.addListener(listener);
}
}
|
Remove no longer needed declare. | // tslint:disable:interface-name
// tslint:disable:no-empty-interface
interface IWebpackRequire { context: any; }
interface NodeRequire extends IWebpackRequire {}
declare var require: NodeRequire;
const srcContext = require.context("../src/app/", true, /\.ts$/);
srcContext.keys().map(srcContext);
const testContext = require.context("./", true, /spec\.ts$/);
testContext.keys().map(testContext);
| // tslint:disable:interface-name
// tslint:disable:no-empty-interface
interface IWebpackRequire { context: any; }
interface NodeRequire extends IWebpackRequire {}
const srcContext = require.context("../src/app/", true, /\.ts$/);
srcContext.keys().map(srcContext);
const testContext = require.context("./", true, /spec\.ts$/);
testContext.keys().map(testContext);
|
Make func list item active class into a getter | import React, {PureComponent} from 'react'
interface Props {
name: string
onAddNode: (name: string) => void
selectedFunc: string
onSetSelectedFunc: (name: string) => void
}
export default class FuncListItem extends PureComponent<Props> {
public render() {
const {name} = this.props
return (
<li
onClick={this.handleClick}
onMouseEnter={this.handleMouseEnter}
className={`ifql-func--item ${this.getActiveClass()}`}
>
{name}
</li>
)
}
private getActiveClass(): string {
const {name, selectedFunc} = this.props
return name === selectedFunc ? 'active' : ''
}
private handleMouseEnter = () => {
this.props.onSetSelectedFunc(this.props.name)
}
private handleClick = () => {
this.props.onAddNode(this.props.name)
}
}
| import React, {PureComponent} from 'react'
interface Props {
name: string
onAddNode: (name: string) => void
selectedFunc: string
onSetSelectedFunc: (name: string) => void
}
export default class FuncListItem extends PureComponent<Props> {
public render() {
const {name} = this.props
return (
<li
onClick={this.handleClick}
onMouseEnter={this.handleMouseEnter}
className={`ifql-func--item ${this.activeClass}`}
>
{name}
</li>
)
}
private get activeClass(): string {
const {name, selectedFunc} = this.props
return name === selectedFunc ? 'active' : ''
}
private handleMouseEnter = () => {
this.props.onSetSelectedFunc(this.props.name)
}
private handleClick = () => {
this.props.onAddNode(this.props.name)
}
}
|
Set exact options on routes | import * as React from "react";
import { BrowserRouter, Redirect, Route } from "react-router-dom";
import SignIn from "./SignIn";
import Tasks from "./Tasks";
export default class extends React.Component {
public render() {
return (
<BrowserRouter>
<div>
<Route path="/" render={() => <Redirect to="/tasks" />} />
<Route path="/tasks" render={() => <Redirect to="/tasks/todo" />} />
<Route path="/tasks/todo" render={() => <Tasks />} />
<Route path="/tasks/done" render={() => <Tasks {...{ done: true }} />} />
<Route path="/sign-in" component={SignIn} />
</div>
</BrowserRouter>
);
}
}
| import * as React from "react";
import { BrowserRouter, Redirect, Route } from "react-router-dom";
import SignIn from "./SignIn";
import Tasks from "./Tasks";
export default class extends React.Component {
public render() {
return (
<BrowserRouter>
<div>
<Route exact={true} path="/" render={() => <Redirect to="/tasks" />} />
<Route exact={true} path="/tasks" render={() => <Redirect to="/tasks/todo" />} />
<Route exact={true} path="/tasks/todo" render={() => <Tasks />} />
<Route exact={true} path="/tasks/done" render={() => <Tasks {...{ done: true }} />} />
<Route exact={true} path="/sign-in" component={SignIn} />
</div>
</BrowserRouter>
);
}
}
|
Improve naming of test members | interface BaseInterface {
required: number;
optional?: number;
}
declare class BaseClass {
baseMethod();
x2: number;
}
interface Child extends BaseInterface {
x3: number;
}
declare class Child extends BaseClass {
x4: number;
method();
}
// checks if properties actually were merged
var child : Child;
child.required;
child.optional;
child.x3;
child.x4;
child.baseMethod();
child.method();
| interface BaseInterface {
required: number;
optional?: number;
}
declare class BaseClass {
baseMethod();
baseNumber: number;
}
interface Child extends BaseInterface {
additional: number;
}
declare class Child extends BaseClass {
classNumber: number;
method();
}
// checks if properties actually were merged
var child : Child;
child.required;
child.optional;
child.additional;
child.baseNumber;
child.classNumber;
child.baseMethod();
child.method();
|
Change an import statement from double quotes to single quotes. | import * as express from "express"
const app = express()
app.get('/', (req, res) => {
res.send('Hello Typescript!');
})
app.get('/:name', (req, res) => {
const name: string = req.params.name;
res.send('Hello ' + name + '!');
})
app.listen('8080')
console.log('\nApp is running. To view it, open a web browser to http://localhost:8080.\nTo be greeted by the app, visit http://localhost:8080/YourName.\n\nQuit app with ctrl+c.')
| import * as express from 'express'
const app = express()
app.get('/', (req, res) => {
res.send('Hello Typescript!');
})
app.get('/:name', (req, res) => {
const name: string = req.params.name;
res.send('Hello ' + name + '!');
})
app.listen('8080')
console.log('\nApp is running. To view it, open a web browser to http://localhost:8080.\nTo be greeted by the app, visit http://localhost:8080/YourName.\n\nQuit app with ctrl+c.')
|
Add a test for the join game form component | import { GameJoinFormComponent } from './game-join-form.component';
import {TestComponentBuilder,
addProviders,
inject,
async,
ComponentFixture} from '@angular/core/testing';
import { Router } from '@angular/router';
class MockRouter {}
describe('join-form game component', () => {
let builder;
beforeEach(() => {
addProviders([
{ provide: Router, useClass: MockRouter }
]);
});
beforeEach(inject([TestComponentBuilder], (tcb) => {
builder = tcb;
}));
// @TODO: come back to this once async tests work better
/*it('should render join-form game form', async(() => {
builder.createAsync(GameJoinFormComponent)
.then((fixture: ComponentFixture<GameJoinFormComponent>) => {
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('input[name="gameCode"]').length).toBeGreaterThan(0);
});
}));*/
});
| /* tslint:disable:no-unused-variable */
import { addProviders, async, inject } from '@angular/core/testing';
import { GameJoinFormComponent } from './game-join-form.component';
import { Router } from '@angular/router';
class MockRouter {}
describe('GameJoinFormComponent: Testing', () => {
beforeEach(() => {
addProviders(
[
{ provide: Router, useClass: MockRouter },
GameJoinFormComponent
]
);
});
it('should create the join game form component',
inject([GameJoinFormComponent], (component: GameJoinFormComponent) => {
expect(component).toBeTruthy();
}));
});
|
Use ES import to see if it works | import BigCalendar, { BigCalendarProps, Event, stringOrDate } from '../../index';
import React = require('react');
interface withDragAndDropProps<TEvent> {
onEventDrop?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void;
onEventResize?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void;
resizable?: boolean;
}
declare class DragAndDropCalendar<TEvent extends Event = Event, TResource extends object = object>
extends React.Component<BigCalendarProps<TEvent, TResource> & withDragAndDropProps<TEvent>> {}
declare function withDragAndDrop(calendar: typeof BigCalendar): typeof DragAndDropCalendar;
export = withDragAndDrop;
| import BigCalendar, { BigCalendarProps, Event, stringOrDate } from '../../index';
import React from 'react';
interface withDragAndDropProps<TEvent> {
onEventDrop?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void;
onEventResize?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void;
resizable?: boolean;
}
declare class DragAndDropCalendar<TEvent extends Event = Event, TResource extends object = object>
extends React.Component<BigCalendarProps<TEvent, TResource> & withDragAndDropProps<TEvent>> {}
declare function withDragAndDrop(calendar: typeof BigCalendar): typeof DragAndDropCalendar;
export = withDragAndDrop;
|
Fix how we calculate the position of trackes dropped into the playlist | import React from "react";
interface Coord {
x: number;
y: number;
}
interface Props extends React.HTMLAttributes<HTMLDivElement> {
handleDrop(e: React.DragEvent<HTMLDivElement>, coord: Coord): void;
}
export default class DropTarget extends React.Component<Props> {
supress(e: React.DragEvent<HTMLDivElement>) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = "link";
e.dataTransfer.effectAllowed = "link";
}
handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
this.supress(e);
const { target } = e;
if (!(target instanceof Element)) {
return;
}
const { left: x, top: y } = target.getBoundingClientRect();
this.props.handleDrop(e, { x, y });
};
render() {
const {
// eslint-disable-next-line no-shadow, no-unused-vars
handleDrop,
...passThroughProps
} = this.props;
return (
<div
{...passThroughProps}
onDragStart={this.supress}
onDragEnter={this.supress}
onDragOver={this.supress}
onDrop={this.handleDrop}
/>
);
}
}
| import React from "react";
interface Coord {
x: number;
y: number;
}
interface Props extends React.HTMLAttributes<HTMLDivElement> {
handleDrop(e: React.DragEvent<HTMLDivElement>, coord: Coord): void;
}
export default class DropTarget extends React.Component<Props> {
supress(e: React.DragEvent<HTMLDivElement>) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = "link";
e.dataTransfer.effectAllowed = "link";
}
handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
this.supress(e);
// TODO: We could probably move this coordinate logic into the playlist.
// I think that's the only place it gets used.
const { currentTarget } = e;
if (!(currentTarget instanceof Element)) {
return;
}
const { left: x, top: y } = currentTarget.getBoundingClientRect();
this.props.handleDrop(e, { x, y });
};
render() {
const {
// eslint-disable-next-line no-shadow, no-unused-vars
handleDrop,
...passThroughProps
} = this.props;
return (
<div
{...passThroughProps}
onDragStart={this.supress}
onDragEnter={this.supress}
onDragOver={this.supress}
onDrop={this.handleDrop}
/>
);
}
}
|
Add early error message if MAXMIND_LICENSE_KEY is missing for DB download | import path from 'path';
import { downloadFolder } from './constants';
import { setDbLocation } from './db/maxmind/db-helper';
import { downloadDB } from './file-fetch-extract';
const main = async (): Promise<void> => {
const downloadFileLocation = path.join(__dirname, downloadFolder);
await setDbLocation(downloadFileLocation);
await downloadDB(downloadFileLocation);
};
main();
| import path from 'path';
import { downloadFolder } from './constants';
import { setDbLocation } from './db/maxmind/db-helper';
import { downloadDB } from './file-fetch-extract';
const main = async (): Promise<void> => {
const { MAXMIND_LICENSE_KEY } = process.env;
if (!MAXMIND_LICENSE_KEY) {
console.error('You need to export MAXMIND_LICENSE_KEY');
process.exit();
}
const downloadFileLocation = path.join(__dirname, downloadFolder);
await setDbLocation(downloadFileLocation);
await downloadDB(downloadFileLocation);
};
main();
|
Remove response time bottleneck fix | 'use strict';
export function formatPath(contractPath: string) {
return contractPath.replace(/\\/g, '/');
}
| 'use strict';
export function formatPath(contractPath: string) {
return contractPath.replace(/\\/g, '/');
}
|
Add experiment ID for new image diff UI | /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface FlagsService {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
// Note that this flag is not supposed to be used by Gerrit itself, but can
// be used by plugins. The new Checks UI will show up, if a plugin registers
// with the new Checks plugin API.
CI_REBOOT_CHECKS = 'UiFeature__ci_reboot_checks',
NEW_CHANGE_SUMMARY_UI = 'UiFeature__new_change_summary_ui',
PORTING_COMMENTS = 'UiFeature__porting_comments',
}
| /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface FlagsService {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
// Note that this flag is not supposed to be used by Gerrit itself, but can
// be used by plugins. The new Checks UI will show up, if a plugin registers
// with the new Checks plugin API.
CI_REBOOT_CHECKS = 'UiFeature__ci_reboot_checks',
NEW_CHANGE_SUMMARY_UI = 'UiFeature__new_change_summary_ui',
PORTING_COMMENTS = 'UiFeature__porting_comments',
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
}
|
Add names for data displayed | import * as React from 'react';
import { WeatherLocationData } from '../../model/WeatherLocationData';
interface MonitoringItemProps {
weatherData: WeatherLocationData;
}
class MonitoringItem extends React.Component<MonitoringItemProps, void> {
public render(): JSX.Element {
let temperatureDataToRender: string = 'N/A';
if (this.props.weatherData.temperatureData) {
// Don't render ℃ with N/A.
if (this.props.weatherData.temperatureData.temperature !== 'N/A') {
temperatureDataToRender = this.props.weatherData.temperatureData.temperature + ' ℃';
}
}
let rainfallDataToRender: string = 'N/A';
if (this.props.weatherData.rainfallData) {
if (this.props.weatherData.rainfallData.rainfall !== 'N/A') {
rainfallDataToRender = this.props.weatherData.rainfallData.rainfall + ' mm';
}
}
return (
<section className="pad-item-list">
<h1 className="txt-body-2">{this.props.weatherData.location}</h1>
{
this.props.weatherData.rainfallData ?
<h2 className="txt-body-1">{rainfallDataToRender}</h2> :
null
}
{
this.props.weatherData.temperatureData ?
<h2 className="txt-body-1">{temperatureDataToRender}</h2> :
null
}
</section>
);
}
}
export {MonitoringItem};
export default MonitoringItem;
| import * as React from 'react';
import { WeatherLocationData } from '../../model/WeatherLocationData';
interface MonitoringItemProps {
weatherData: WeatherLocationData;
}
class MonitoringItem extends React.Component<MonitoringItemProps, void> {
public render(): JSX.Element {
let temperatureDataToRender: string = 'N/A';
if (this.props.weatherData.temperatureData) {
// Don't render ℃ with N/A.
if (this.props.weatherData.temperatureData.temperature !== 'N/A') {
temperatureDataToRender = this.props.weatherData.temperatureData.temperature + ' ℃';
}
}
let rainfallDataToRender: string = 'N/A';
if (this.props.weatherData.rainfallData) {
if (this.props.weatherData.rainfallData.rainfall !== 'N/A') {
rainfallDataToRender = this.props.weatherData.rainfallData.rainfall + ' mm';
}
}
return (
<section className="pad-item-list">
<h1 className="txt-body-2">{this.props.weatherData.location}</h1>
{
this.props.weatherData.rainfallData ?
<h2 className="txt-body-1">Rainfall: {rainfallDataToRender}</h2> :
null
}
{
this.props.weatherData.temperatureData ?
<h2 className="txt-body-1">Temperature: {temperatureDataToRender}</h2> :
null
}
</section>
);
}
}
export {MonitoringItem};
export default MonitoringItem;
|
Fix the theme prop typings | import { Grommet } from 'grommet';
import merge from 'lodash/merge';
import * as React from 'react';
import styled from 'styled-components';
import { DefaultProps, Theme } from '../../common-types';
import defaultTheme from '../../theme';
import { px } from '../../utils';
import { BreakpointProvider } from './BreakpointProvider';
const Base = styled(Grommet)`
font-family: ${props => props.theme.font};
font-size: ${props => px(props.theme.fontSizes[1])};
h1,
h2,
h3,
h4,
h5,
h6,
button {
font-family: ${props => props.theme.titleFont};
}
`;
const Provider = ({ theme, ...props }: ThemedProvider) => {
const providerTheme = merge(defaultTheme, theme);
return (
<BreakpointProvider breakpoints={providerTheme.breakpoints}>
<Base theme={providerTheme} {...props} />
</BreakpointProvider>
);
};
export interface ThemedProvider extends DefaultProps {
theme?: Theme;
}
export default Provider;
| import { Grommet } from 'grommet';
import merge from 'lodash/merge';
import * as React from 'react';
import styled from 'styled-components';
import { DefaultProps, Theme } from '../../common-types';
import defaultTheme from '../../theme';
import { px } from '../../utils';
import { BreakpointProvider } from './BreakpointProvider';
const Base = styled(Grommet)`
font-family: ${props => props.theme.font};
font-size: ${props => px(props.theme.fontSizes[1])};
h1,
h2,
h3,
h4,
h5,
h6,
button {
font-family: ${props => props.theme.titleFont};
}
`;
const Provider = ({ theme, ...props }: ThemedProvider) => {
const providerTheme = merge(defaultTheme, theme);
return (
<BreakpointProvider breakpoints={providerTheme.breakpoints}>
<Base theme={providerTheme} {...props} />
</BreakpointProvider>
);
};
export interface ThemedProvider extends DefaultProps {
theme?: Partial<Theme>;
}
export default Provider;
|
Update wording of http code errors to point at rawResponse | import { Response } from "request";
import { ApiResponse } from "./types";
export function resolveHttpError(response, message): Error | undefined {
if (response.statusCode < 400) {
return;
}
message = message ? message + " " : "";
message +=
"Status code " +
response.statusCode +
" (" +
response.statusMessage +
"). See the response property for details.";
var error: Error & { rawResponse?: Response } = new Error(message);
error.rawResponse = response;
return error;
}
export function createCallback(action, cb): (err, response) => void {
return function(err, response): void {
err = err || resolveHttpError(response, "Error " + action + ".");
if (err) {
return cb(err);
}
cb(null, {
data: response.body,
response: response
});
};
}
export function createPromiseCallback<P>(
action: string,
resolve: (response: ApiResponse<P>) => void,
reject: (err: {}) => void,
transformPayload: (response: Response, payload: any) => P = (_, p) => p
): (err: Error, response: Response) => void {
return function(err, response): void {
err = err || resolveHttpError(response, "Error " + action + ".");
if (err) {
return reject(err);
}
resolve({
payload: transformPayload(response, response.body),
rawResponse: response
});
};
}
| import { Response } from "request";
import { ApiResponse } from "./types";
export function resolveHttpError(response, message): Error | undefined {
if (response.statusCode < 400) {
return;
}
message = message ? message + " " : "";
message +=
"Status code " +
response.statusCode +
" (" +
response.statusMessage +
"). See the rawResponse property for details.";
var error: Error & { rawResponse?: Response } = new Error(message);
error.rawResponse = response;
return error;
}
export function createCallback(action, cb): (err, response) => void {
return function(err, response): void {
err = err || resolveHttpError(response, "Error " + action + ".");
if (err) {
return cb(err);
}
cb(null, {
data: response.body,
response: response
});
};
}
export function createPromiseCallback<P>(
action: string,
resolve: (response: ApiResponse<P>) => void,
reject: (err: {}) => void,
transformPayload: (response: Response, payload: any) => P = (_, p) => p
): (err: Error, response: Response) => void {
return function(err, response): void {
err = err || resolveHttpError(response, "Error " + action + ".");
if (err) {
return reject(err);
}
resolve({
payload: transformPayload(response, response.body),
rawResponse: response
});
};
}
|
Add inversion between sma and period. | /// <reference path="_references.ts" />
module Calculator.Orbital {
'use strict';
export function period(sma: number, stdGravParam: number): number {
return 2 * Math.PI * Math.sqrt(Math.pow(sma, 3) / stdGravParam);
}
export function nightTime(radius: number, sma: number, stdGravParam: number): number {
return Orbital.period(sma, stdGravParam) * Math.asin(radius / sma) / Math.PI;
}
export function hohmannStartDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma1) * (Math.sqrt((2 * sma2) / (sma1 + sma2)) - 1);
}
export function hohmannFinishDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma2) * (1 - Math.sqrt((2 * sma1) / (sma1 + sma2)));
}
export function slidePhaseAngle(slideDeg: number, periodLow: number, periodHigh: number): number {
return slideDeg / (1 - periodLow / periodHigh);
}
}
| /// <reference path="_references.ts" />
module Calculator.Orbital {
'use strict';
export function period(sma: number, stdGravParam: number): number {
return 2 * Math.PI * Math.sqrt(Math.pow(sma, 3) / stdGravParam);
}
export function sma(stdGravParam: number, period: number): number {
return Math.pow(Math.pow(period, 2) * stdGravParam / (4 * Math.pow(Math.PI, 2)), 1 / 3);
}
export function nightTime(radius: number, sma: number, stdGravParam: number): number {
return Orbital.period(sma, stdGravParam) * Math.asin(radius / sma) / Math.PI;
}
export function hohmannStartDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma1) * (Math.sqrt((2 * sma2) / (sma1 + sma2)) - 1);
}
export function hohmannFinishDV(sma1: number, sma2: number, stdGravParam: number): number {
return Math.sqrt(stdGravParam / sma2) * (1 - Math.sqrt((2 * sma1) / (sma1 + sma2)));
}
export function slidePhaseAngle(slideDeg: number, periodLow: number, periodHigh: number): number {
return slideDeg / (1 - periodLow / periodHigh);
}
}
|
Make mnemonic unavailable for non private users | import { getHasMigratedAddressKeys } from '@proton/shared/lib/keys';
import { FeatureCode } from '../containers/features';
import { useAddresses } from './useAddresses';
import useFeature from './useFeature';
const useIsMnemonicAvailable = (): boolean => {
const mnemonicFeature = useFeature(FeatureCode.Mnemonic);
const [addresses = []] = useAddresses();
const hasMigratedKeys = getHasMigratedAddressKeys(addresses);
return mnemonicFeature.feature?.Value && hasMigratedKeys;
};
export default useIsMnemonicAvailable;
| import { getHasMigratedAddressKeys } from '@proton/shared/lib/keys';
import { FeatureCode } from '../containers/features';
import { useAddresses } from './useAddresses';
import useFeature from './useFeature';
import useUser from './useUser';
const useIsMnemonicAvailable = (): boolean => {
const [user] = useUser();
const mnemonicFeature = useFeature(FeatureCode.Mnemonic);
const [addresses = []] = useAddresses();
const hasMigratedKeys = getHasMigratedAddressKeys(addresses);
const isNonPrivateUser = !user?.isPrivate;
return mnemonicFeature.feature?.Value && hasMigratedKeys && !isNonPrivateUser;
};
export default useIsMnemonicAvailable;
|
Hide the menu when loading a room | import { ActionShowMenu, ActionHideMenu } from './actions';
import { ActionTypes, Action } from '../actions';
export interface UIState {
isMenuShown: boolean;
isFullscreen: boolean;
}
const initialState: UIState = {
isMenuShown: false,
isFullscreen: false,
};
function handleShowMenu(state: UIState, action: ActionShowMenu): UIState {
return {
...state,
isMenuShown: true,
};
}
function handleHideMenu(state: UIState, action: ActionHideMenu): UIState {
return {
...state,
isMenuShown: false,
};
}
export const ui = (state: UIState = initialState, action: Action): UIState => {
switch (action.type) {
case ActionTypes.UI_SHOW_MENU:
return handleShowMenu(state, action as ActionShowMenu);
case ActionTypes.UI_HIDE_MENU:
return handleHideMenu(state, action as ActionHideMenu);
case ActionTypes.UI_ENTER_FULLSCREEN:
case ActionTypes.UI_EXIT_FULLSCREEN:
return { ...state, isMenuShown: false };
case ActionTypes.UI_SET_IS_FULLSCREEN:
return { ...state, isFullscreen: action.payload.isFullscreen };
default:
return state;
}
};
| import { ActionShowMenu, ActionHideMenu } from './actions';
import { ActionTypes, Action } from '../actions';
export interface UIState {
isMenuShown: boolean;
isFullscreen: boolean;
}
const initialState: UIState = {
isMenuShown: false,
isFullscreen: false,
};
function handleShowMenu(state: UIState, action: ActionShowMenu): UIState {
return {
...state,
isMenuShown: true,
};
}
function handleHideMenu(state: UIState, action: ActionHideMenu): UIState {
return {
...state,
isMenuShown: false,
};
}
export const ui = (state: UIState = initialState, action: Action): UIState => {
switch (action.type) {
case ActionTypes.UI_SHOW_MENU:
return handleShowMenu(state, action as ActionShowMenu);
case ActionTypes.UI_HIDE_MENU:
return handleHideMenu(state, action as ActionHideMenu);
case ActionTypes.UI_ENTER_FULLSCREEN:
case ActionTypes.UI_EXIT_FULLSCREEN:
return { ...state, isMenuShown: false };
case ActionTypes.UI_SET_IS_FULLSCREEN:
return { ...state, isFullscreen: action.payload.isFullscreen };
case ActionTypes.ROOM_LOAD:
return { ...state, isMenuShown: false };
default:
return state;
}
};
|
Change expected type of value in registerEditable | const schema = new Map()
export interface Field {
field: string,
label: string,
component: React.ReactElement<any>,
props?: Object
}
export interface Meta {
type: string,
editorSchema?: Array<Field>,
name?: string,
}
export function registerEditable(type: string,
value: Array<Object> | ((editorSchema: Map<string, Field>) => Map<string, Field>)) {
schema.set(type, value)
}
export function getEditorSchema(meta: Meta): Array<Field> {
const adapterSchema = meta.editorSchema
const userDefinedSchema = schema.get(meta.type)
if (adapterSchema && !userDefinedSchema) {
return adapterSchema
} else if (!adapterSchema && userDefinedSchema) {
if (userDefinedSchema instanceof Array) {
return userDefinedSchema
}
// else, if the userDefinedSchema is a function to operate on current schema
// we do not have any schema to operate on, so return an empty array
} else if (adapterSchema && userDefinedSchema) {
if (userDefinedSchema instanceof Array) {
// overwrite adapter schema
return userDefinedSchema
} else if (userDefinedSchema instanceof Function) {
// operate on adapter schema with user provided function
const schemaAsMap = new Map(adapterSchema.map(field => [field.field, field]))
const editedSchema = userDefinedSchema(schemaAsMap)
const result = []
for (const field of editedSchema) {
result.push(field)
}
return result
}
}
return []
}
| const schema = new Map()
export interface Field {
field: string,
label: string,
component: React.ReactElement<any>,
props?: Object
}
export interface Meta {
type: string,
editorSchema?: Array<Field>,
name?: string,
}
export function registerEditable(
type: string,
value: Array<Field> | ((editorSchema: Map<string, Field>) => Map<string, Field>)
) {
schema.set(type, value)
}
export function getEditorSchema(meta: Meta): Array<Field> {
const adapterSchema = meta.editorSchema
const userDefinedSchema = schema.get(meta.type)
if (adapterSchema && !userDefinedSchema) {
return adapterSchema
} else if (!adapterSchema && userDefinedSchema) {
if (userDefinedSchema instanceof Array) {
return userDefinedSchema
}
// else, if the userDefinedSchema is a function to operate on current schema
// we do not have any schema to operate on, so return an empty array
} else if (adapterSchema && userDefinedSchema) {
if (userDefinedSchema instanceof Array) {
// overwrite adapter schema
return userDefinedSchema
} else if (userDefinedSchema instanceof Function) {
// operate on adapter schema with user provided function
const schemaAsMap = new Map(adapterSchema.map(field => [field.field, field]))
const editedSchema = userDefinedSchema(schemaAsMap)
const result = []
for (const field of editedSchema) {
result.push(field)
}
return result
}
}
return []
}
|
Fix type in test description | import { StorageMock } from '../mocks/mocks';
import { Storage } from '@ionic/storage';
import { TestBed, inject, async } from '@angular/core/testing';
import { SettingService } from './setting-service';
describe('Provider: SettingService', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
providers: [SettingService, { provide: Storage, useClass: StorageMock }],
imports: []
}).compileComponents();
}));
it('Should initialize with default values', inject([SettingService], (settingService: SettingService) => {
settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBe(settingService.isShowRestUrlFieldDefault));
}));
it('Settings should bebe written and read from store', async(inject([SettingService, Storage], (settingService: SettingService, storage: Storage) => {
storage.set(settingService.restUrlKey, 'abc');
storage.set(settingService.usernameKey, 'def');
storage.set(settingService.isShowRestUrlFieldKey, false);
settingService.getRestUrl().subscribe(restUrl => expect(restUrl).toBe('abc'));
settingService.getUsername().subscribe(username => expect(username).toBe('def'));
settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBeFalsy());
})));
});
| import { StorageMock } from '../mocks/mocks';
import { Storage } from '@ionic/storage';
import { TestBed, inject, async } from '@angular/core/testing';
import { SettingService } from './setting-service';
describe('Provider: SettingService', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
providers: [SettingService, { provide: Storage, useClass: StorageMock }],
imports: []
}).compileComponents();
}));
it('Should initialize with default values', inject([SettingService], (settingService: SettingService) => {
settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBe(settingService.isShowRestUrlFieldDefault));
}));
it('Settings should be written and read from store', async(inject([SettingService, Storage], (settingService: SettingService, storage: Storage) => {
storage.set(settingService.restUrlKey, 'abc');
storage.set(settingService.usernameKey, 'def');
storage.set(settingService.isShowRestUrlFieldKey, false);
settingService.getRestUrl().subscribe(restUrl => expect(restUrl).toBe('abc'));
settingService.getUsername().subscribe(username => expect(username).toBe('def'));
settingService.isShowRestUrlField().subscribe(isShowRestUrlField => expect(isShowRestUrlField).toBeFalsy());
})));
});
|
Fix implicit any for `WebComponents` global. | /**
* @externs
* @license
* Copyright (c) 2021 The Polymer Project Authors. All rights reserved. This
* code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be found
* at http://polymer.github.io/AUTHORS.txt The complete set of contributors may
* be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by
* Google as part of the polymer project is also subject to an additional IP
* rights grant found at http://polymer.github.io/PATENTS.txt
*/
// eslint-disable-next-line no-var
declare var WebComponents;
interface HTMLTemplateElement {
bootstrap(): void;
}
| /**
* @externs
* @license
* Copyright (c) 2021 The Polymer Project Authors. All rights reserved. This
* code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be found
* at http://polymer.github.io/AUTHORS.txt The complete set of contributors may
* be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by
* Google as part of the polymer project is also subject to an additional IP
* rights grant found at http://polymer.github.io/PATENTS.txt
*/
// eslint-disable-next-line no-var
declare var WebComponents: {};
interface HTMLTemplateElement {
bootstrap(): void;
}
|
Update redux-typed to match latest third-party .d.ts files for React and Redux | import * as React from 'react';
import { connect as nativeConnect, ElementClass } from 'react-redux';
interface ClassDecoratorWithProps<TProps> extends Function {
<T extends (typeof ElementClass)>(component: T): T;
props: TProps;
}
export type ReactComponentClass<T, S> = new(props: T) => React.Component<T, S>;
export class ComponentBuilder<TOwnProps, TActions, TExternalProps> {
constructor(private stateToProps: (appState: any) => TOwnProps, private actionCreators: TActions) {
}
public withExternalProps<TAddExternalProps>() {
return this as any as ComponentBuilder<TOwnProps, TActions, TAddExternalProps>;
}
public get allProps(): TOwnProps & TActions & TExternalProps { return null; }
public connect<TState>(componentClass: ReactComponentClass<TOwnProps & TActions & TExternalProps, TState>): ReactComponentClass<TExternalProps, TState> {
return nativeConnect(this.stateToProps, this.actionCreators as any)(componentClass);
}
}
export function provide<TOwnProps, TActions>(stateToProps: (appState: any) => TOwnProps, actionCreators: TActions) {
return new ComponentBuilder<TOwnProps, TActions, {}>(stateToProps, actionCreators);
}
| import * as React from 'react';
import { connect as nativeConnect } from 'react-redux';
export type ReactComponentClass<T, S> = new(props: T) => React.Component<T, S>;
export class ComponentBuilder<TOwnProps, TActions, TExternalProps> {
constructor(private stateToProps: (appState: any) => TOwnProps, private actionCreators: TActions) {
}
public withExternalProps<TAddExternalProps>() {
return this as any as ComponentBuilder<TOwnProps, TActions, TAddExternalProps>;
}
public get allProps(): TOwnProps & TActions & TExternalProps { return null; }
public connect<TState>(componentClass: ReactComponentClass<TOwnProps & TActions & TExternalProps, TState>): ReactComponentClass<TExternalProps, TState> {
return nativeConnect(this.stateToProps, this.actionCreators as any)(componentClass) as any;
}
}
export function provide<TOwnProps, TActions>(stateToProps: (appState: any) => TOwnProps, actionCreators: TActions) {
return new ComponentBuilder<TOwnProps, TActions, {}>(stateToProps, actionCreators);
}
|
Add cache directory to debug logger | import * as vscode from 'vscode';
import * as os from 'os';
import * as path from 'path';
import { Position } from '../common/motion/position';
import { Range } from '../common/motion/range';
import { logger } from './logger';
const AppDirectory = require('appdirectory');
/**
* This is certainly quite janky! The problem we're trying to solve
* is that writing editor.selection = new Position() won't immediately
* update the position of the cursor. So we have to wait!
*/
export async function waitForCursorSync(
timeout: number = 0,
rejectOnTimeout = false
): Promise<void> {
await new Promise((resolve, reject) => {
let timer = setTimeout(rejectOnTimeout ? reject : resolve, timeout);
const disposable = vscode.window.onDidChangeTextEditorSelection(x => {
disposable.dispose();
clearTimeout(timer);
resolve();
});
});
}
export async function getCursorsAfterSync(timeout: number = 0): Promise<Range[]> {
try {
await waitForCursorSync(timeout, true);
} catch (e) {
logger.warn(`getCursorsAfterSync: selection not updated within ${timeout}ms. error=${e}.`);
}
return vscode.window.activeTextEditor!.selections.map(
x => new Range(Position.FromVSCodePosition(x.start), Position.FromVSCodePosition(x.end))
);
}
export function getExtensionDirPath(): string {
const dirs = new AppDirectory('VSCodeVim');
return dirs.userCache();
}
| import * as vscode from 'vscode';
import * as os from 'os';
import * as path from 'path';
import { Position } from '../common/motion/position';
import { Range } from '../common/motion/range';
import { logger } from './logger';
const AppDirectory = require('appdirectory');
/**
* This is certainly quite janky! The problem we're trying to solve
* is that writing editor.selection = new Position() won't immediately
* update the position of the cursor. So we have to wait!
*/
export async function waitForCursorSync(
timeout: number = 0,
rejectOnTimeout = false
): Promise<void> {
await new Promise((resolve, reject) => {
let timer = setTimeout(rejectOnTimeout ? reject : resolve, timeout);
const disposable = vscode.window.onDidChangeTextEditorSelection(x => {
disposable.dispose();
clearTimeout(timer);
resolve();
});
});
}
export async function getCursorsAfterSync(timeout: number = 0): Promise<Range[]> {
try {
await waitForCursorSync(timeout, true);
} catch (e) {
logger.warn(`getCursorsAfterSync: selection not updated within ${timeout}ms. error=${e}.`);
}
return vscode.window.activeTextEditor!.selections.map(
x => new Range(Position.FromVSCodePosition(x.start), Position.FromVSCodePosition(x.end))
);
}
export function getExtensionDirPath(): string {
const dirs = new AppDirectory('VSCodeVim');
logger.debug("VSCodeVim Cache Directory: " + dirs.userCache());
return dirs.userCache();
}
|
Set & declare var on same line |
import NoStringParameterToFunctionCallWalker = require('./utils/NoStringParameterToFunctionCallWalker');
/**
* Implementation of the no-string-parameter-to-function-call rule.
*/
export class Rule extends Lint.Rules.AbstractRule {
public apply(sourceFile : ts.SourceFile): Lint.RuleFailure[] {
var languageServiceHost;
var documentRegistry = ts.createDocumentRegistry();
languageServiceHost = Lint.createLanguageServiceHost('file.ts', sourceFile.getFullText());
var languageService = ts.createLanguageService(languageServiceHost, documentRegistry);
var walker : Lint.RuleWalker = new NoStringParameterToFunctionCallWalker(
sourceFile , 'setImmediate', this.getOptions(), languageService
);
return this.applyWithWalker(walker);
}
}
|
import NoStringParameterToFunctionCallWalker = require('./utils/NoStringParameterToFunctionCallWalker');
/**
* Implementation of the no-string-parameter-to-function-call rule.
*/
export class Rule extends Lint.Rules.AbstractRule {
public apply(sourceFile : ts.SourceFile): Lint.RuleFailure[] {
var documentRegistry = ts.createDocumentRegistry();
var languageServiceHost = Lint.createLanguageServiceHost('file.ts', sourceFile.getFullText());
var languageService = ts.createLanguageService(languageServiceHost, documentRegistry);
var walker : Lint.RuleWalker = new NoStringParameterToFunctionCallWalker(
sourceFile , 'setImmediate', this.getOptions(), languageService
);
return this.applyWithWalker(walker);
}
}
|
Fix return Promises to match type. | interface PackageMetadata {
name: String;
version: String;
}
interface ApiOptions {
regions: String[];
}
interface ContentOptions {
bucket: String;
contentDirectory: String;
}
interface PublishLambdaOptions {
bucket: String;
}
interface StackConfiguration {
}
interface StackParameters {
}
interface StageDeploymentOptions {
stage: String;
functionName: String;
deploymentBucketName: String;
deploymentKeyName: String;
}
interface WebsiteDeploymentOptions {
cacheControlRegexMap: Object;
contentTypeMappingOverride: Object;
}
declare class AwsArchitect {
constructor(packageMetadata: PackageMetadata, apiOptions: ApiOptions, contentOptions: ContentOptions);
publishLambdaArtifactPromise(options: PublishLambdaOptions): Promise<Boolean>;
validateTemplate(stackTemplate: Object): Promise<Boolean>;
deployTemplate(stackTemplate: Object, stackConfiguration: StackConfiguration, parameters: StackParameters): Promise<Boolean>;
deployStagePromise(stage: String, lambdaVersion: String): Promise<Boolean>;
removeStagePromise(stage: String): Promise<Boolean>;
publishAndDeployStagePromise(options: StageDeploymentOptions): Promise<Boolean>;
publishWebsite(version: String, options: WebsiteDeploymentOptions): Promise<Boolean>;
run(port: Short; logger: Function): Promise<Boolean>;
}
| interface PackageMetadata {
name: String;
version: String;
}
interface ApiOptions {
regions: String[];
}
interface ContentOptions {
bucket: String;
contentDirectory: String;
}
interface PublishLambdaOptions {
bucket: String;
}
interface StackConfiguration {
changeSetName: String;
stackName: String;
}
interface StageDeploymentOptions {
stage: String;
functionName: String;
deploymentBucketName: String;
deploymentKeyName: String;
}
interface WebsiteDeploymentOptions {
cacheControlRegexMap: Object;
contentTypeMappingOverride: Object;
}
declare class AwsArchitect {
constructor(packageMetadata: PackageMetadata, apiOptions: ApiOptions, contentOptions: ContentOptions);
publishLambdaArtifactPromise(options: PublishLambdaOptions): Promise<Object>;
validateTemplate(stackTemplate: Object): Promise<Object>;
deployTemplate(stackTemplate: Object, stackConfiguration: StackConfiguration, parameters: Object): Promise<Object>;
deployStagePromise(stage: String, lambdaVersion: String): Promise<Object>;
removeStagePromise(stage: String): Promise<Object>;
publishAndDeployStagePromise(options: StageDeploymentOptions): Promise<Object>;
publishWebsite(version: String, options: WebsiteDeploymentOptions): Promise<Object>;
run(port: Number, logger: Function): Promise<Object>;
}
|
Fix for cases where esm version of rtl-css-js is hit | import * as rtl from 'rtl-css-js';
export interface JssRTLOptions {
enabled?: boolean;
opt?: 'in' | 'out';
}
export default function jssRTL({ enabled = true, opt = 'out' }: JssRTLOptions = {}) {
return {
onProcessStyle(style: any, _: any, sheet: any) {
if (!enabled) {
if (typeof style.flip === 'boolean') {
delete style.flip;
}
return style;
}
let flip = opt === 'out'; // If it's set to opt-out, then it should flip by default
if (typeof sheet.options.flip === 'boolean') {
flip = sheet.options.flip;
}
if (typeof style.flip === 'boolean') {
flip = style.flip;
delete style.flip;
}
if (!flip) {
return style;
}
return rtl(style);
},
};
}
| import * as rtl from 'rtl-css-js';
const convert = rtl['default'] || rtl;
export interface JssRTLOptions {
enabled?: boolean;
opt?: 'in' | 'out';
}
export default function jssRTL({ enabled = true, opt = 'out' }: JssRTLOptions = {}) {
return {
onProcessStyle(style: any, _: any, sheet: any) {
if (!enabled) {
if (typeof style.flip === 'boolean') {
delete style.flip;
}
return style;
}
let flip = opt === 'out'; // If it's set to opt-out, then it should flip by default
if (typeof sheet.options.flip === 'boolean') {
flip = sheet.options.flip;
}
if (typeof style.flip === 'boolean') {
flip = style.flip;
delete style.flip;
}
if (!flip) {
return style;
}
return convert(style);
},
};
}
|
Add EOL symbol at the end of the file. |
import { saveAs } from 'file-saver';
import { FileFormat } from './FileFormat';
export class FileOperations {
readonly UNKNOWN_FORMAT: string = "UNKNOWN";
readonly NON_SET_DELIMITER: string = "";
// Note: File types
readonly TEXT_FILE_TYPE: string = "text/plain;charset=utf-8";
readonly JSON_FILE_TYPE: string = "application/json;charset=utf-8";
// Defining empty constructor
constructor() {}
public saveFile(fileName: String, fileType: FileFormat, data: String, lineDelimiter: string = this.NON_SET_DELIMITER) {
data = data.toString();
var textFromFileInLines: string[] = data.split(lineDelimiter);
let fileTypeTag: string = this.getFileTypeTag(fileType);
let binaryFileData = new Blob(textFromFileInLines, { type: fileTypeTag});
saveAs(binaryFileData, `${fileName}.yml`);
}
private getFileTypeTag(fileType: FileFormat): string {
switch (fileType) {
case FileFormat.TEXT:
return this.TEXT_FILE_TYPE;
case FileFormat.JSON:
return this.TEXT_FILE_TYPE;
}
return this.TEXT_FILE_TYPE;
}
} |
import { saveAs } from 'file-saver';
import { FileFormat } from './FileFormat';
export class FileOperations {
readonly UNKNOWN_FORMAT: string = "UNKNOWN";
readonly NON_SET_DELIMITER: string = "";
// Note: File types
readonly TEXT_FILE_TYPE: string = "text/plain;charset=utf-8";
readonly JSON_FILE_TYPE: string = "application/json;charset=utf-8";
// Defining empty constructor
constructor() {}
public saveFile(fileName: String, fileType: FileFormat, data: String, lineDelimiter: string = this.NON_SET_DELIMITER) {
data = data.toString();
var textFromFileInLines: string[] = data.split(lineDelimiter);
let fileTypeTag: string = this.getFileTypeTag(fileType);
let binaryFileData = new Blob(textFromFileInLines, { type: fileTypeTag});
saveAs(binaryFileData, `${fileName}.yml`);
}
private getFileTypeTag(fileType: FileFormat): string {
switch (fileType) {
case FileFormat.TEXT:
return this.TEXT_FILE_TYPE;
case FileFormat.JSON:
return this.TEXT_FILE_TYPE;
}
return this.TEXT_FILE_TYPE;
}
}
|
Refactor question generating to use request.js | import Rails from '@rails/ujs';
import I18n from 'retrospring/i18n';
import { updateDeleteButton } from './delete';
import { showErrorNotification } from 'utilities/notifications';
export function generateQuestionHandler(): void {
Rails.ajax({
url: '/ajax/generate_question',
type: 'POST',
dataType: 'json',
success: (data) => {
if (!data.success) return false;
document.querySelector('#entries').insertAdjacentHTML('afterbegin', data.render);
updateDeleteButton();
},
error: (data, status, xhr) => {
console.log(data, status, xhr);
showErrorNotification(I18n.translate('frontend.error.message'));
}
});
} | import { post } from '@rails/request.js';
import I18n from 'retrospring/i18n';
import { updateDeleteButton } from './delete';
import { showErrorNotification } from 'utilities/notifications';
export function generateQuestionHandler(): void {
post('/ajax/generate_question')
.then(async response => {
const data = await response.json;
if (!data.success) return false;
document.querySelector('#entries').insertAdjacentHTML('afterbegin', data.render);
updateDeleteButton();
})
.catch(err => {
console.log(err);
showErrorNotification(I18n.translate('frontend.error.message'));
});
} |
Remove trailing whitespace for Travis | // Type definitions for connect-history-api-fallback-exclusions 1.5
// Project: https://github.com/Wirewheel/connect-history-api-fallback#readme
// Definitions by: Tony Stone <https://github.com/tonystonee>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
import { Url } from 'url';
import * as core from "express-serve-static-core";
declare function historyApiFallback(options?: historyApiFallback.Options): core.RequestHandler;
declare namespace historyApiFallback {
interface Options {
exclusions?: string[];
disableDotRule?: true;
htmlAcceptHeaders?: string[];
index?: string;
logger?: typeof console.log;
rewrites?: Rewrite[];
verbose?: boolean;
}
interface Context {
match: RegExpMatchArray;
parsedUrl: Url;
}
type RewriteTo = (context: Context) => string;
interface Rewrite {
from: RegExp;
to: string | RegExp | RewriteTo;
}
}
export = historyApiFallback;
| // Type definitions for connect-history-api-fallback-exclusions 1.5
// Project: https://github.com/Wirewheel/connect-history-api-fallback#readme
// Definitions by: Tony Stone <https://github.com/tonystonee>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
import { Url } from 'url';
import * as core from "express-serve-static-core";
declare function historyApiFallback(options?: historyApiFallback.Options): core.RequestHandler;
declare namespace historyApiFallback {
interface Options {
exclusions?: string[];
disableDotRule?: true;
htmlAcceptHeaders?: string[];
index?: string;
logger?: typeof console.log;
rewrites?: Rewrite[];
verbose?: boolean;
}
interface Context {
match: RegExpMatchArray;
parsedUrl: Url;
}
type RewriteTo = (context: Context) => string;
interface Rewrite {
from: RegExp;
to: string | RegExp | RewriteTo;
}
}
export = historyApiFallback;
|
Fix group initializer for displaying label | import {
GroupLayout,
JsonFormsState,
RankedTester,
rankWith,
uiTypeIs
} from '@jsonforms/core';
import { Component } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { JsonFormsIonicLayout } from '../JsonFormsIonicLayout';
@Component({
selector: 'jsonforms-group-layout',
template: `
<ion-card>
<ion-card-header>
{{label}}
</ion-card-header>
<ion-card-content>
<div *ngFor="let element of uischema?.elements">
<jsonforms-outlet
[uischema]="element"
[path]="path"
[schema]="schema"
></jsonforms-outlet>
</div>
</ion-card-content>
</ion-card>
`
})
export class GroupLayoutRenderer extends JsonFormsIonicLayout {
label: string;
constructor(ngRedux: NgRedux<JsonFormsState>) {
super(ngRedux);
}
mapAdditionalProps() {
this.label = (this.uischema as GroupLayout).label;
}
}
export const groupTester: RankedTester = rankWith(1, uiTypeIs('Group'));
| import {
GroupLayout, JsonFormsProps,
JsonFormsState,
RankedTester,
rankWith,
uiTypeIs
} from '@jsonforms/core';
import { Component } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { JsonFormsIonicLayout } from '../JsonFormsIonicLayout';
@Component({
selector: 'jsonforms-group-layout',
template: `
<ion-card>
<ion-card-header>
{{label}}
</ion-card-header>
<ion-card-content>
<div *ngFor="let element of uischema?.elements">
<jsonforms-outlet
[uischema]="element"
[path]="path"
[schema]="schema"
></jsonforms-outlet>
</div>
</ion-card-content>
</ion-card>
`
})
export class GroupLayoutRenderer extends JsonFormsIonicLayout {
label: string;
constructor(ngRedux: NgRedux<JsonFormsState>) {
super(ngRedux);
this.initializers.push((props: JsonFormsProps) => {
this.label = (props.uischema as GroupLayout).label;
});
}
}
export const groupTester: RankedTester = rankWith(1, uiTypeIs('Group'));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.