commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
---|---|---|---|---|---|---|---|---|---|---|
f99b9ab56e7fb5cc0f678b5c34b33957055750da | components/radio/radioButton.tsx | components/radio/radioButton.tsx | import * as React from 'react';
import * as PropTypes from 'prop-types';
import { AbstractCheckboxProps } from '../checkbox/Checkbox';
import Radio from './radio';
import { RadioChangeEvent } from './interface';
import Wave from '../_util/wave';
export type RadioButtonProps = AbstractCheckboxProps<RadioChangeEvent>;
export default class RadioButton extends React.Component<RadioButtonProps, any> {
static defaultProps = {
prefixCls: 'ant-radio-button',
};
static contextTypes = {
radioGroup: PropTypes.any,
};
render() {
const radioProps: RadioButtonProps = { ...this.props };
if (this.context.radioGroup) {
radioProps.onChange = this.context.radioGroup.onChange;
radioProps.checked = this.props.value === this.context.radioGroup.value;
radioProps.disabled = this.props.disabled || this.context.radioGroup.disabled;
}
return (
<Wave>
<Radio {...radioProps} />
</Wave>
);
}
}
| import * as React from 'react';
import * as PropTypes from 'prop-types';
import { AbstractCheckboxProps } from '../checkbox/Checkbox';
import Radio from './radio';
import { RadioChangeEvent } from './interface';
export type RadioButtonProps = AbstractCheckboxProps<RadioChangeEvent>;
export default class RadioButton extends React.Component<RadioButtonProps, any> {
static defaultProps = {
prefixCls: 'ant-radio-button',
};
static contextTypes = {
radioGroup: PropTypes.any,
};
render() {
const radioProps: RadioButtonProps = { ...this.props };
if (this.context.radioGroup) {
radioProps.onChange = this.context.radioGroup.onChange;
radioProps.checked = this.props.value === this.context.radioGroup.value;
radioProps.disabled = this.props.disabled || this.context.radioGroup.disabled;
}
return <Radio {...radioProps} />;
}
}
| Remove wave effect of Radio.Button | Remove wave effect of Radio.Button
| TypeScript | mit | ant-design/ant-design,zheeeng/ant-design,zheeeng/ant-design,icaife/ant-design,elevensky/ant-design,elevensky/ant-design,icaife/ant-design,icaife/ant-design,ant-design/ant-design,icaife/ant-design,ant-design/ant-design,zheeeng/ant-design,elevensky/ant-design,zheeeng/ant-design,ant-design/ant-design,elevensky/ant-design | ---
+++
@@ -3,7 +3,6 @@
import { AbstractCheckboxProps } from '../checkbox/Checkbox';
import Radio from './radio';
import { RadioChangeEvent } from './interface';
-import Wave from '../_util/wave';
export type RadioButtonProps = AbstractCheckboxProps<RadioChangeEvent>;
@@ -24,10 +23,6 @@
radioProps.disabled = this.props.disabled || this.context.radioGroup.disabled;
}
- return (
- <Wave>
- <Radio {...radioProps} />
- </Wave>
- );
+ return <Radio {...radioProps} />;
}
} |
7d6f79fea30816cfa073227f2567b93fddb4f010 | client/src/components/form.tsx | client/src/components/form.tsx | import * as React from 'react';
interface IProps {
onSubmit?: React.EventHandler<React.FormEvent<HTMLFormElement>>;
}
export class Form extends React.Component<
IProps & React.HTMLAttributes<HTMLFormElement>,
any
> {
render() {
const { props: p } = this;
const { onSubmit, children, ...rest } = p;
return (
<form onSubmit={this.onSubmit} {...rest}>
{children}
</form>
);
}
onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const { onSubmit } = this.props;
if (onSubmit) {
onSubmit(event);
}
};
}
| import * as React from 'react';
interface IProps {
onSubmit?: React.EventHandler<React.FormEvent<HTMLFormElement>>;
}
export class Form extends React.PureComponent<
IProps & React.HTMLAttributes<HTMLFormElement>,
{}
> {
render() {
const { props: p } = this;
const { onSubmit, children, ...rest } = p;
return (
<form onSubmit={this.onSubmit} {...rest}>
{children}
</form>
);
}
onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const { onSubmit } = this.props;
if (onSubmit) {
onSubmit(event);
}
};
}
| Fix TypeScript issues with Form component | Fix TypeScript issues with Form component
| TypeScript | unlicense | forabi/hollowverse,forabi/hollowverse,forabi/hollowverse,forabi/hollowverse | ---
+++
@@ -4,9 +4,9 @@
onSubmit?: React.EventHandler<React.FormEvent<HTMLFormElement>>;
}
-export class Form extends React.Component<
+export class Form extends React.PureComponent<
IProps & React.HTMLAttributes<HTMLFormElement>,
- any
+ {}
> {
render() {
const { props: p } = this; |
971a34831310af957aa38d2eb78d4f3ecc6b5225 | packages/@sanity/form-builder/src/hooks/useScrollIntoViewOnFocusWithin.ts | packages/@sanity/form-builder/src/hooks/useScrollIntoViewOnFocusWithin.ts | import {useCallback} from 'react'
import scrollIntoView from 'scroll-into-view-if-needed'
import {useDidUpdate} from './useDidUpdate'
const SCROLL_OPTIONS = {scrollMode: 'if-needed'} as const
/**
* A hook to help make sure the parent element of a value edited in a dialog (or "out of band") stays
visible in the background
* @param elementRef The element to scroll into view when the proivided focusWithin changes from true to false
* @param hasFocusWithin A boolean indicating whether we have has focus within the currently edited value
*/
export function useScrollIntoViewOnFocusWithin(
elementRef: {current?: HTMLElement},
hasFocusWithin: boolean
): void {
return useDidUpdate(
hasFocusWithin,
useCallback(
(hadFocus) => {
if (!hadFocus) {
scrollIntoView(elementRef.current, SCROLL_OPTIONS)
}
},
[elementRef]
)
)
}
| import {useCallback} from 'react'
import scrollIntoView from 'scroll-into-view-if-needed'
import {useDidUpdate} from './useDidUpdate'
const SCROLL_OPTIONS = {scrollMode: 'if-needed'} as const
/**
* A hook to help make sure the parent element of a value edited in a dialog (or "out of band") stays
visible in the background
* @param elementRef The element to scroll into view when the proivided focusWithin changes from true to false
* @param hasFocusWithin A boolean indicating whether we have has focus within the currently edited value
*/
export function useScrollIntoViewOnFocusWithin(
elementRef: {current?: HTMLElement},
hasFocusWithin: boolean
): void {
return useDidUpdate(
hasFocusWithin,
useCallback(
(hadFocus, hasFocus) => {
if (!hadFocus && hasFocus) {
scrollIntoView(elementRef.current, SCROLL_OPTIONS)
}
},
[elementRef]
)
)
}
| Make sure to only scroll into view when focused | fix(form-builder): Make sure to only scroll into view when focused
This fixes a small regression introduced in v2.4.1 that made scrollIntoView trigger for root level fields on inital render, effectively making the page scroll to the bottom.
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -17,8 +17,8 @@
return useDidUpdate(
hasFocusWithin,
useCallback(
- (hadFocus) => {
- if (!hadFocus) {
+ (hadFocus, hasFocus) => {
+ if (!hadFocus && hasFocus) {
scrollIntoView(elementRef.current, SCROLL_OPTIONS)
}
}, |
2f69736cd55d32f53f669df2860dd89d0554f3d1 | src/web-editor/ClientApp/boot-server.ts | src/web-editor/ClientApp/boot-server.ts | import 'angular2-universal-polyfills';
import 'angular2-universal-patch';
import 'zone.js';
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import { enableProdMode } from '@angular/core';
import { platformNodeDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
enableProdMode();
const platform = platformNodeDynamic();
export default createServerRenderer(params => {
return new Promise<RenderResult>((resolve, reject) => {
const requestZone = Zone.current.fork({
name: 'angular-universal request',
properties: {
baseUrl: '/',
requestUrl: params.url,
originUrl: params.origin,
preboot: false,
document: '<app></app>'
},
onHandleError: (parentZone, currentZone, targetZone, error) => {
// If any error occurs while rendering the module, reject the whole operation
reject(error);
return true;
}
});
return requestZone.run<Promise<string>>(() => platform.serializeModule(AppModule)).then(html => {
resolve({ html: html });
}, reject);
});
});
| import 'angular2-universal-polyfills';
import 'angular2-universal-patch';
import 'zone.js';
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import { enableProdMode } from '@angular/core';
import { platformNodeDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';
enableProdMode();
const platform = platformNodeDynamic();
export default createServerRenderer(params => {
return new Promise<RenderResult>((resolve, reject) => {
const requestZone = Zone.current.fork({
name: 'angular-universal request',
properties: {
baseUrl: '/',
// Workarround to avoid reference errors when url address a complex view with window.* objects access
requestUrl: '/',//params.url,
originUrl: params.origin,
preboot: false,
document: '<app></app>'
},
onHandleError: (parentZone, currentZone, targetZone, error) => {
// If any error occurs while rendering the module, reject the whole operation
reject(error);
return true;
}
});
return requestZone.run<Promise<string>>(() => platform.serializeModule(AppModule)).then(html => {
resolve({ html: html });
}, reject);
});
});
| Fix prerendering to force request to the appRoot. | Fix prerendering to force request to the appRoot.
| TypeScript | mit | vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit | ---
+++
@@ -15,7 +15,8 @@
name: 'angular-universal request',
properties: {
baseUrl: '/',
- requestUrl: params.url,
+ // Workarround to avoid reference errors when url address a complex view with window.* objects access
+ requestUrl: '/',//params.url,
originUrl: params.origin,
preboot: false,
document: '<app></app>' |
27bdb5b6fd61b6f115cd0441e469b13d57e8d087 | src/common/IUploadConfig.ts | src/common/IUploadConfig.ts | /**
* An object that contains settings necessary for uploading files using a
* POST request.
*/
export interface IUploadConfig {
/**
* Upload URL to send POST request to.
*/
url: string;
/**
* Fields to include in the POST request for it to succeed.
*/
fields: { [key:string]: string };
}
| /**
* An object that contains settings necessary for uploading files using a
* POST request.
*/
export interface IUploadConfig {
/**
* Upload URL to send POST request to.
*/
url: string;
/**
* Fields to include in the POST request for it to succeed.
*/
fields: { [key: string]: string };
}
| Add a missing whitespace to satisfy tslint. | Add a missing whitespace to satisfy tslint.
| TypeScript | bsd-3-clause | nimbis/s3commander,nimbis/s3commander,nimbis/s3commander,nimbis/s3commander | ---
+++
@@ -11,5 +11,5 @@
/**
* Fields to include in the POST request for it to succeed.
*/
- fields: { [key:string]: string };
+ fields: { [key: string]: string };
} |
3d5dcdf1155453c1552cc572972b79e0039ccc0a | src/tests/languageTests/expression/objectTypeTests.ts | src/tests/languageTests/expression/objectTypeTests.ts | import {getInfoFromString} from "./../../../main";
import {runFileDefinitionTests} from "./../../testHelpers";
describe("object type tests", () => {
const code = `
let obj: { myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; };
class Note {
prop: string;
}`;
const def = getInfoFromString(code);
runFileDefinitionTests(def, {
variables: [{
name: "obj",
type: {
text: "{ myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; }",
properties: [{
name: "myString",
type: { text: "string" }
}, {
name: "myOtherType",
isOptional: true,
type: {
text: "Note",
properties: [] // shouldn't have any properties
}
}, {
name: "myNext",
type: { text: "string" }
}, {
name: "myNext2",
type: { text: "string" }
}, {
name: "myReallyReallyReallyReallyReallyLongName",
type: { text: "string" }
}]
}
}],
classes: [{
name: "Note",
properties: [{
name: "prop",
type: { text: "string" }
}]
}]
});
});
| import {getInfoFromString} from "./../../../main";
import {runFileDefinitionTests} from "./../../testHelpers";
describe("object type tests", () => {
const code = `
let obj: { readonly myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; };
class Note {
prop: string;
}`;
const def = getInfoFromString(code);
runFileDefinitionTests(def, {
variables: [{
name: "obj",
type: {
text: "{ readonly myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; }",
properties: [{
name: "myString",
type: { text: "string" },
isReadonly: true
}, {
name: "myOtherType",
isOptional: true,
type: {
text: "Note",
properties: [] // shouldn't have any properties
}
}, {
name: "myNext",
type: { text: "string" }
}, {
name: "myNext2",
type: { text: "string" }
}, {
name: "myReallyReallyReallyReallyReallyLongName",
type: { text: "string" }
}]
}
}],
classes: [{
name: "Note",
properties: [{
name: "prop",
type: { text: "string" }
}]
}]
});
});
| Test for readonly in object type. | Test for readonly in object type.
| TypeScript | mit | dsherret/ts-type-info,dsherret/type-info-ts,dsherret/ts-type-info,dsherret/type-info-ts | ---
+++
@@ -3,7 +3,7 @@
describe("object type tests", () => {
const code = `
-let obj: { myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; };
+let obj: { readonly myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; };
class Note {
prop: string;
@@ -15,10 +15,11 @@
variables: [{
name: "obj",
type: {
- text: "{ myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; }",
+ text: "{ readonly myString: string; myOtherType?: Note; myNext: string; myNext2: string; myReallyReallyReallyReallyReallyLongName: string; }",
properties: [{
name: "myString",
- type: { text: "string" }
+ type: { text: "string" },
+ isReadonly: true
}, {
name: "myOtherType",
isOptional: true, |
957a016317fa6aa5ca38b4eb8270fb63f8f30581 | src/app/components/app/app.component.ts | src/app/components/app/app.component.ts | import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Routes } from "@angular/router";
import { AppRoutingModule } from '../../modules/app/app-routing.module';
import { LoginRoutingModule } from '../../modules/login/login-routing.module';
import { FeaturesRoutingModule } from '../../modules/features/features-routing.module';
import * as config from '../../../../config/config.json';
@Component({
selector: 'at-app',
templateUrl: './app.component.html',
// require('./app.component.css').toString() to avoid Error: Expected 'styles' to be an array of strings.
styles: [require('./app.component.css').toString()],
})
export class AppComponent {
public appName = (<any>config).appname;
public routes: Routes;
public constructor(private titleService: Title) {
this.routes = AppRoutingModule.ROUTES;
if ((<any>config).routes.showLogin) {
this.routes = this.routes.concat(LoginRoutingModule.ROUTES);
}
if ((<any>config).routes.showFeatures) {
this.routes = this.routes.concat(FeaturesRoutingModule.ROUTES);
}
this.titleService.setTitle(this.appName);
}
}
| import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Routes } from "@angular/router";
import { AppRoutingModule } from '../../modules/app/app-routing.module';
import { LoginRoutingModule } from '../../modules/login/login-routing.module';
import { FeaturesRoutingModule } from '../../modules/features/features-routing.module';
import * as config from '../../../../config/config.json';
@Component({
selector: 'at-app',
templateUrl: './app.component.html',
// require('./app.component.css').toString() to avoid Error: Expected 'styles' to be an array of strings.
styles: [require('./app.component.css').toString()],
})
export class AppComponent {
public appName = (<any>config).appname;
public routes: Routes;
public constructor(private titleService: Title) {
this.routes = AppRoutingModule.ROUTES;
if ((<any>config).routes.showFeatures) {
this.routes = this.routes.concat(FeaturesRoutingModule.ROUTES);
}
if ((<any>config).routes.showLogin) {
this.routes = this.routes.concat(LoginRoutingModule.ROUTES);
}
this.titleService.setTitle(this.appName);
}
}
| Change Order, first show features then login | Change Order, first show features then login | TypeScript | mit | inpercima/publicmedia,inpercima/publicmedia,inpercima/publicmedia,inpercima/publicmedia | ---
+++
@@ -22,11 +22,11 @@
public constructor(private titleService: Title) {
this.routes = AppRoutingModule.ROUTES;
+ if ((<any>config).routes.showFeatures) {
+ this.routes = this.routes.concat(FeaturesRoutingModule.ROUTES);
+ }
if ((<any>config).routes.showLogin) {
this.routes = this.routes.concat(LoginRoutingModule.ROUTES);
- }
- if ((<any>config).routes.showFeatures) {
- this.routes = this.routes.concat(FeaturesRoutingModule.ROUTES);
}
this.titleService.setTitle(this.appName);
} |
2d60e37de2ce1d449614b093aa80f6f99c7a093e | packages/formdata-event/ts_src/environment/event.ts | packages/formdata-event/ts_src/environment/event.ts | /**
* @license
* Copyright (c) 2020 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
*/
export const constructor: typeof Event = window.Event;
export const prototype = constructor.prototype;
export const methods = {
initEvent: prototype.initEvent,
stopImmediatePropagation: prototype?.stopImmediatePropagation,
stopPropagation: prototype?.stopPropagation,
};
export const descriptors = {
defaultPrevented: Object.getOwnPropertyDescriptor(
prototype,
'defaultPrevented'
)!,
target: Object.getOwnPropertyDescriptor(prototype, 'target')!,
type: Object.getOwnPropertyDescriptor(prototype, 'type')!,
};
| /**
* @license
* Copyright (c) 2020 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
*/
// Without this explicit type, TS seems to think that `window.Event` is the
// wrapper from `wrappers/event.ts` at this point, which is typed in terms of
// this binding, causing a cycle in its type.
export const constructor: typeof Event = window.Event;
export const prototype = constructor.prototype;
export const methods = {
initEvent: prototype.initEvent,
stopImmediatePropagation: prototype?.stopImmediatePropagation,
stopPropagation: prototype?.stopPropagation,
};
export const descriptors = {
defaultPrevented: Object.getOwnPropertyDescriptor(
prototype,
'defaultPrevented'
)!,
target: Object.getOwnPropertyDescriptor(prototype, 'target')!,
type: Object.getOwnPropertyDescriptor(prototype, 'type')!,
};
| Add a comment explaining why a binding set to `window.Event` needs an explicit type. | Add a comment explaining why a binding set to `window.Event` needs an explicit type.
| TypeScript | bsd-3-clause | webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills | ---
+++
@@ -9,6 +9,9 @@
* additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
+// Without this explicit type, TS seems to think that `window.Event` is the
+// wrapper from `wrappers/event.ts` at this point, which is typed in terms of
+// this binding, causing a cycle in its type.
export const constructor: typeof Event = window.Event;
export const prototype = constructor.prototype; |
f225680d5bcaffbbf7f6311f3a5ac0f1db485281 | app/tests/src/renderer/reporter/index.ts | app/tests/src/renderer/reporter/index.ts | // Copyright (c) 2016 Vadim Macagon
// MIT License, see LICENSE file for full terms.
import * as ReactDOM from 'react-dom';
import * as React from 'react';
import MobxDevToolsComponent from 'mobx-react-devtools';
import * as ReactFreeStyle from 'react-free-style';
import { ReportGenerator } from './report-generator';
import { ReportView } from './report-view';
const reportGenerator = new ReportGenerator();
const styleRegistry = ReactFreeStyle.create();
const rootContainer = document.createElement('div');
rootContainer.className = 'root-container';
const rootComponent = styleRegistry.component(React.createClass({
render: () => React.createElement(
'div', null,
React.createElement(ReportView, { report: reportGenerator.report }),
React.createElement(styleRegistry.Element),
React.createElement(MobxDevToolsComponent)
)
}));
ReactDOM.render(React.createElement(rootComponent), rootContainer);
document.body.appendChild(rootContainer);
| // Copyright (c) 2016 Vadim Macagon
// MIT License, see LICENSE file for full terms.
import * as ReactDOM from 'react-dom';
import * as React from 'react';
import MobxDevToolsComponent from 'mobx-react-devtools';
import * as ReactFreeStyle from 'react-free-style';
import installDevToolsExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer';
import { ReportGenerator } from './report-generator';
import { ReportView } from './report-view';
installDevToolsExtension(REACT_DEVELOPER_TOOLS);
const reportGenerator = new ReportGenerator();
const styleRegistry = ReactFreeStyle.create();
const rootContainer = document.createElement('div');
rootContainer.className = 'root-container';
const rootComponent = styleRegistry.component(React.createClass({
render: () => React.createElement(
'div', null,
React.createElement(ReportView, { report: reportGenerator.report }),
React.createElement(styleRegistry.Element),
React.createElement(MobxDevToolsComponent)
)
}));
ReactDOM.render(React.createElement(rootComponent), rootContainer);
document.body.appendChild(rootContainer);
| Install React DevTools in the test harness | Install React DevTools in the test harness
| TypeScript | mit | debugworkbench/hydragon,debugworkbench/hydragon,debugworkbench/hydragon | ---
+++
@@ -5,8 +5,11 @@
import * as React from 'react';
import MobxDevToolsComponent from 'mobx-react-devtools';
import * as ReactFreeStyle from 'react-free-style';
+import installDevToolsExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer';
import { ReportGenerator } from './report-generator';
import { ReportView } from './report-view';
+
+installDevToolsExtension(REACT_DEVELOPER_TOOLS);
const reportGenerator = new ReportGenerator();
|
a97711be44b2c13af2cf728aa173774f6070f3c5 | bin/pipeline.ts | bin/pipeline.ts | import 'source-map-support/register';
import * as cdk from '@aws-cdk/core';
import { AppStack } from '../lib/app-stack';
import { SetupStack } from '../lib/setup-stack'
const app = new cdk.App();
const region = "us-west-1";
const account = '084374970894';
new SetupStack(app, "ApiTestToolSetupStack", {
env: {
account: account,
region: region
}
});
const appStack = new AppStack(app, "ApiTestToolAppStack", {
env: {
account: account,
region: region
}
});
console.log("LoadBalancer" + appStack.urlOutput);
app.synth(); | import * as cdk from '@aws-cdk/core';
import { AppStack } from '../lib/app-stack';
import { SetupStack } from '../lib/setup-stack'
const app = new cdk.App();
new SetupStack(app, "ApiTestToolSetupStack", {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION
}
});
const appStack = new AppStack(app, "ApiTestToolAppStack", {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION
}
});
console.log("LoadBalancer" + appStack.urlOutput);
app.synth(); | Remove region and account information. | Remove region and account information.
| TypeScript | apache-2.0 | Brightspace/util-api-test-tool,Brightspace/util-api-test-tool,Brightspace/util-api-test-tool | ---
+++
@@ -1,23 +1,20 @@
-import 'source-map-support/register';
import * as cdk from '@aws-cdk/core';
import { AppStack } from '../lib/app-stack';
import { SetupStack } from '../lib/setup-stack'
const app = new cdk.App();
-const region = "us-west-1";
-const account = '084374970894';
new SetupStack(app, "ApiTestToolSetupStack", {
env: {
- account: account,
- region: region
+ account: process.env.CDK_DEFAULT_ACCOUNT,
+ region: process.env.CDK_DEFAULT_REGION
}
});
const appStack = new AppStack(app, "ApiTestToolAppStack", {
env: {
- account: account,
- region: region
+ account: process.env.CDK_DEFAULT_ACCOUNT,
+ region: process.env.CDK_DEFAULT_REGION
}
});
|
f526ad370efc7168e0fcaf5443178079f02f0a65 | lib/client-logger/src/index.ts | lib/client-logger/src/index.ts | const { console } = global;
export const logger = {
info: (message: any): void => console.log(message),
warn: (message: any): void => console.warn(message),
error: (message: any): void => console.error(message),
};
| const { console } = global;
export const logger = {
info: (message: any, ...rest: any[]): void => console.log(message, ...rest),
warn: (message: any, ...rest: any[]): void => console.warn(message, ...rest),
error: (message: any, ...rest: any[]): void => console.error(message, ...rest),
};
| FIX client-logger only accepting a single argument | FIX client-logger only accepting a single argument
| TypeScript | mit | storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -1,7 +1,7 @@
const { console } = global;
export const logger = {
- info: (message: any): void => console.log(message),
- warn: (message: any): void => console.warn(message),
- error: (message: any): void => console.error(message),
+ info: (message: any, ...rest: any[]): void => console.log(message, ...rest),
+ warn: (message: any, ...rest: any[]): void => console.warn(message, ...rest),
+ error: (message: any, ...rest: any[]): void => console.error(message, ...rest),
}; |
968c624ca6be461fcec0d54114e498a7c742f91d | src/Apps/Components/AppShell.tsx | src/Apps/Components/AppShell.tsx | import { Box } from "@artsy/palette"
import { findCurrentRoute } from "Artsy/Router/Utils/findCurrentRoute"
import { NavBar } from "Components/NavBar"
import { isFunction } from "lodash"
import React, { useEffect } from "react"
import createLogger from "Utils/logger"
const logger = createLogger("Apps/Components/AppShell")
export const AppShell = props => {
const { children, match } = props
const routeConfig = findCurrentRoute(match)
/**
* Check to see if a route has a prepare key; if so call it. Used typically to
* preload bundle-split components (import()) while the route is fetching data
* in the background.
*/
useEffect(() => {
if (isFunction(routeConfig.prepare)) {
try {
routeConfig.prepare()
} catch (error) {
logger.error(error)
}
}
}, [routeConfig])
return (
<Box width="100%">
<Box pb={6}>
<Box left={0} position="fixed" width="100%" zIndex={100}>
<NavBar />
</Box>
</Box>
<Box>
<Box>{children}</Box>
</Box>
</Box>
)
}
| import { Box } from "@artsy/palette"
import { findCurrentRoute } from "Artsy/Router/Utils/findCurrentRoute"
import { NavBar } from "Components/NavBar"
import { isFunction } from "lodash"
import React, { useEffect } from "react"
import createLogger from "Utils/logger"
const logger = createLogger("Apps/Components/AppShell")
export const AppShell = props => {
const { children, match } = props
const routeConfig = findCurrentRoute(match)
/**
* Check to see if a route has a prepare key; if so call it. Used typically to
* preload bundle-split components (import()) while the route is fetching data
* in the background.
*/
useEffect(() => {
if (isFunction(routeConfig.prepare)) {
try {
routeConfig.prepare()
} catch (error) {
logger.error(error)
}
}
}, [routeConfig])
/**
* Let our end-to-end tests know that the app is hydrated and ready to go
*/
useEffect(() => {
if (typeof window !== "undefined") {
document.body.setAttribute("data-test-ready", "")
}
}, [])
return (
<Box width="100%">
<Box pb={6}>
<Box left={0} position="fixed" width="100%" zIndex={100}>
<NavBar />
</Box>
</Box>
<Box>
<Box>{children}</Box>
</Box>
</Box>
)
}
| Add hook to know when app is ready to interact with | Add hook to know when app is ready to interact with
| TypeScript | mit | artsy/reaction,artsy/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction-force | ---
+++
@@ -26,6 +26,15 @@
}
}, [routeConfig])
+ /**
+ * Let our end-to-end tests know that the app is hydrated and ready to go
+ */
+ useEffect(() => {
+ if (typeof window !== "undefined") {
+ document.body.setAttribute("data-test-ready", "")
+ }
+ }, [])
+
return (
<Box width="100%">
<Box pb={6}> |
71ec2062e9da6be08a8ca0bd95237a35884811f5 | src/components/AccordionItem.tsx | src/components/AccordionItem.tsx | import * as React from 'react';
import DisplayName from '../helpers/DisplayName';
import { DivAttributes } from '../helpers/types';
import { assertValidHtmlId, nextUuid } from '../helpers/uuid';
import {
Consumer as ItemConsumer,
ItemContext,
Provider as ItemProvider,
UUID,
} from './ItemContext';
type Props = DivAttributes & {
uuid?: UUID;
activeClassName?: string;
dangerouslySetExpanded?: boolean;
};
const AccordionItem = ({
uuid = nextUuid(),
dangerouslySetExpanded,
className = 'accordion__item',
activeClassName,
...rest
}: Props): JSX.Element => {
const renderChildren = (itemContext: ItemContext): JSX.Element => {
const { expanded } = itemContext;
const cx = expanded && activeClassName ? activeClassName : className;
return (
<div
data-accordion-component="AccordionItem"
className={cx}
{...rest}
/>
);
};
assertValidHtmlId(uuid);
if (rest.id) {
assertValidHtmlId(rest.id);
}
return (
<ItemProvider
uuid={uuid}
dangerouslySetExpanded={dangerouslySetExpanded}
>
<ItemConsumer>{renderChildren}</ItemConsumer>
</ItemProvider>
);
};
AccordionItem.displayName = DisplayName.AccordionItem;
export default AccordionItem;
| import * as React from 'react';
import { useState } from 'react';
import DisplayName from '../helpers/DisplayName';
import { DivAttributes } from '../helpers/types';
import { assertValidHtmlId, nextUuid } from '../helpers/uuid';
import {
Consumer as ItemConsumer,
ItemContext,
Provider as ItemProvider,
UUID,
} from './ItemContext';
type Props = DivAttributes & {
uuid?: UUID;
activeClassName?: string;
dangerouslySetExpanded?: boolean;
};
const AccordionItem = ({
uuid: customUuid,
dangerouslySetExpanded,
className = 'accordion__item',
activeClassName,
...rest
}: Props): JSX.Element => {
const [instanceUuid] = useState(nextUuid());
const uuid = customUuid || instanceUuid;
const renderChildren = (itemContext: ItemContext): JSX.Element => {
const { expanded } = itemContext;
const cx = expanded && activeClassName ? activeClassName : className;
return (
<div
data-accordion-component="AccordionItem"
className={cx}
{...rest}
/>
);
};
assertValidHtmlId(uuid);
if (rest.id) {
assertValidHtmlId(rest.id);
}
return (
<ItemProvider
uuid={uuid}
dangerouslySetExpanded={dangerouslySetExpanded}
>
<ItemConsumer>{renderChildren}</ItemConsumer>
</ItemProvider>
);
};
AccordionItem.displayName = DisplayName.AccordionItem;
export default AccordionItem;
| Move instance uuid to useState hook | Move instance uuid to useState hook
| TypeScript | mit | springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion | ---
+++
@@ -1,4 +1,5 @@
import * as React from 'react';
+import { useState } from 'react';
import DisplayName from '../helpers/DisplayName';
import { DivAttributes } from '../helpers/types';
import { assertValidHtmlId, nextUuid } from '../helpers/uuid';
@@ -16,12 +17,15 @@
};
const AccordionItem = ({
- uuid = nextUuid(),
+ uuid: customUuid,
dangerouslySetExpanded,
className = 'accordion__item',
activeClassName,
...rest
}: Props): JSX.Element => {
+ const [instanceUuid] = useState(nextUuid());
+ const uuid = customUuid || instanceUuid;
+
const renderChildren = (itemContext: ItemContext): JSX.Element => {
const { expanded } = itemContext;
const cx = expanded && activeClassName ? activeClassName : className; |
4cb85a0f3664202c3fff8b48758e2d3709f6eef0 | src/util/source-maps.spec.ts | src/util/source-maps.spec.ts | import { join } from 'path';
import * as Constants from './constants';
import * as sourceMaps from './source-maps';
import * as helpers from './helpers';
describe('source maps', () => {
describe('purgeSourceMapsIfNeeded', () => {
it('should return a resolved promise when purging source maps isnt needed', () => {
// arrange
let env: any = {};
env[Constants.ENV_VAR_GENERATE_SOURCE_MAP] = 'true';
process.env = env;
// act
const resultPromise = sourceMaps.purgeSourceMapsIfNeeded(null);
// assert
return resultPromise;
});
it('should return a promise call unlink on all files with a .map extensin', () => {
// arrange
let env: any = {};
env[Constants.ENV_VAR_GENERATE_SOURCE_MAP] = null;
process.env = env;
const buildDir = '/some/fake/build/dir';
const context = { buildDir: buildDir };
spyOn(helpers, helpers.readDirAsync.name).and.returnValue(Promise.resolve(['test.js', 'test.js.map', 'test2.js', 'test2.js.map']));
const unlinkSpy = spyOn(helpers, helpers.unlinkAsync.name).and.returnValue(Promise.resolve());
// act
const resultPromise = sourceMaps.purgeSourceMapsIfNeeded(context);
// assert
return resultPromise.then(() => {
expect(unlinkSpy.calls.argsFor(0)[0]).toEqual(join(buildDir, 'test.js.map'));
expect(unlinkSpy.calls.argsFor(1)[0]).toEqual(join(buildDir, 'test2.js.map'));
});
});
});
});
| import { join } from 'path';
import * as Constants from './constants';
import * as sourceMaps from './source-maps';
import * as helpers from './helpers';
describe('source maps', () => {
describe('purgeSourceMapsIfNeeded', () => {
it('should return a promise call unlink on all files with a .map extensin', () => {
// arrange
let env: any = {};
env[Constants.ENV_VAR_GENERATE_SOURCE_MAP] = null;
process.env = env;
const buildDir = '/some/fake/build/dir';
const context = { buildDir: buildDir };
spyOn(helpers, helpers.readDirAsync.name).and.returnValue(Promise.resolve(['test.js', 'test.js.map', 'test2.js', 'test2.js.map']));
const unlinkSpy = spyOn(helpers, helpers.unlinkAsync.name).and.returnValue(Promise.resolve());
// act
const resultPromise = sourceMaps.purgeSourceMapsIfNeeded(context);
// assert
return resultPromise.then(() => {
expect(unlinkSpy.calls.argsFor(0)[0]).toEqual(join(buildDir, 'test.js.map'));
expect(unlinkSpy.calls.argsFor(1)[0]).toEqual(join(buildDir, 'test2.js.map'));
});
});
});
});
| Remove obsolete unit test for sourcemaps | Remove obsolete unit test for sourcemaps
| TypeScript | mit | driftyco/ionic-app-scripts,driftyco/ionic-app-scripts,driftyco/ionic-app-scripts | ---
+++
@@ -5,17 +5,6 @@
describe('source maps', () => {
describe('purgeSourceMapsIfNeeded', () => {
- it('should return a resolved promise when purging source maps isnt needed', () => {
- // arrange
- let env: any = {};
- env[Constants.ENV_VAR_GENERATE_SOURCE_MAP] = 'true';
- process.env = env;
- // act
- const resultPromise = sourceMaps.purgeSourceMapsIfNeeded(null);
- // assert
- return resultPromise;
- });
-
it('should return a promise call unlink on all files with a .map extensin', () => {
// arrange
let env: any = {}; |
c0a9df7f76d3d90ecf8cac71225936462356d4d5 | src/languageConfiguration.ts | src/languageConfiguration.ts | const languageConfiguration = {
indentationRules: {
increaseIndentPattern: /^(\s*(module|class|((private|protected)\s+)?def|unless|if|else|elsif|case|when|begin|rescue|ensure|for|while|until|(?=.*?\b(do|begin|case|if|unless)\b)("(\\.|[^\\"])*"|'(\\.|[^\\'])*'|[^#"'])*(\s(do|begin|case)|[-+=&|*/~%^<>~]\s*(if|unless)))\b(?![^;]*;.*?\bend\b)|("(\\.|[^\\"])*"|'(\\.|[^\\'])*'|[^#"'])*(\((?![^\)]*\))|\{(?![^\}]*\})|\[(?![^\]]*\]))).*$/,
decreaseIndentPattern: /^\s*([}\]]([,)]?\s*(#|$)|\.[a-zA-Z_]\w*\b)|(end|rescue|ensure|else|elsif|when)\b)/,
},
wordPattern: /(-?\d+(?:\.\d+))|([A-Za-z][^-`~@#%^&()=+[{}|;:'",<>/.*\]\s\\!?]*[!?]?)/,
};
export default languageConfiguration;
| const languageConfiguration = {
indentationRules: {
increaseIndentPattern: /^(\s*(module|class|((private|protected)\s+)?def|unless|if|else|elsif|case|when|begin|rescue|ensure|for|while|until|(?=.*?\b(do|begin|case|if|unless)\b)("(\\.|[^\\"])*"|'(\\.|[^\\'])*'|[^#"'])*(\s(do|begin|case)|[-+=&|*/~%^<>~]\s*(if|unless)))\b(?![^;]*;.*?\bend\b)|("(\\.|[^\\"])*"|'(\\.|[^\\'])*'|[^#"'])*(\((?![^\)]*\))|\{(?![^\}]*\})|\[(?![^\]]*\]))).*$/,
decreaseIndentPattern: /^\s*([}\])](,?\s*(#|$)|\.[a-zA-Z_]\w*\b)|(end|rescue|ensure|else|elsif|when)\b)/,
},
wordPattern: /(-?\d+(?:\.\d+))|([A-Za-z][^-`~@#%^&()=+[{}|;:'",<>/.*\]\s\\!?]*[!?]?)/,
};
export default languageConfiguration;
| Update `decreaseIndentPattern` to match Atom | Update `decreaseIndentPattern` to match Atom
Atom's [decrease regexp](https://github.com/atom/language-ruby/blob/d88a4cfb32876295ec5b090a2994957e62130f4a/settings/language-ruby.cson) handles cases like this:
```
@date = Date.today()
@name = "Test Name"
@data = {
id: 8,
foo: Foo.new(
id: 1,
phone_number: "412-555-7640"
),
bar: Bar.new(
id: 1,
name: "Valentine",
vin: "DF5S6HFG365HGDCVG",
status: :AVAILABLE
),
start_time: start_time.to_s,
end_time: end_time.to_s,
cost: 23.45,
rating: 3,
}
``` | TypeScript | mit | rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby | ---
+++
@@ -1,7 +1,7 @@
const languageConfiguration = {
indentationRules: {
increaseIndentPattern: /^(\s*(module|class|((private|protected)\s+)?def|unless|if|else|elsif|case|when|begin|rescue|ensure|for|while|until|(?=.*?\b(do|begin|case|if|unless)\b)("(\\.|[^\\"])*"|'(\\.|[^\\'])*'|[^#"'])*(\s(do|begin|case)|[-+=&|*/~%^<>~]\s*(if|unless)))\b(?![^;]*;.*?\bend\b)|("(\\.|[^\\"])*"|'(\\.|[^\\'])*'|[^#"'])*(\((?![^\)]*\))|\{(?![^\}]*\})|\[(?![^\]]*\]))).*$/,
- decreaseIndentPattern: /^\s*([}\]]([,)]?\s*(#|$)|\.[a-zA-Z_]\w*\b)|(end|rescue|ensure|else|elsif|when)\b)/,
+ decreaseIndentPattern: /^\s*([}\])](,?\s*(#|$)|\.[a-zA-Z_]\w*\b)|(end|rescue|ensure|else|elsif|when)\b)/,
},
wordPattern: /(-?\d+(?:\.\d+))|([A-Za-z][^-`~@#%^&()=+[{}|;:'",<>/.*\]\s\\!?]*[!?]?)/,
}; |
dbbbd47ca320d398465185d583dc2af22cfe4ce2 | packages/slack/src/api/chat.ts | packages/slack/src/api/chat.ts | import { APIModule } from './base'
import { camel, snake } from './converters'
import { Message, MessageOptions } from '../types'
import * as messageFormat from '../helpers/formatters/message'
export class Chat extends APIModule {
delete(channel: string, ts: string, options: { asUser?: boolean } = {}): Promise<{ channel: string, ts: string }> {
return this.request('delete', snake({ channel, ts, ...options }))
}
meMessage(channel: string, text: string): Promise<{ channel: string, ts: string }> {
return this.request('meMessage', { channel, text })
}
postEphemeral(channel: string, message: Message, options: MessageOptions = {}): Promise<{ messageTs: string }> {
return this.request('postEphemeral',
snake({
channel, asUser: true, ...options,
...messageFormat.toSlack(message)
}))
.then(camel)
}
postMessage(channel: string, message: Message, options: MessageOptions = {})
: Promise<{ channel: string, ts: string, message: Message }> {
return this.request('postMessage',
snake({
channel, asUser: true, ...options,
...messageFormat.toSlack(message)
}))
.then(messageFormat.fromSlack)
.then(camel)
}
update(channel: string, ts: string, message: Message) {
return this.request('update', snake({
channel, ts, asUser: true, parse: 'none',
...messageFormat.toSlack(message)
})).then(camel)
}
}
| import { APIModule } from './base'
import { camel, snake } from './converters'
import { Message, MessageOptions } from '../types'
import * as messageFormat from '../helpers/formatters/message'
export class Chat extends APIModule {
delete(channel: string, ts: string, options: { asUser?: boolean } = {}): Promise<{ channel: string, ts: string }> {
return this.request('delete', snake({ channel, ts, ...options }))
}
meMessage(channel: string, text: string): Promise<{ channel: string, ts: string }> {
return this.request('meMessage', { channel, text })
}
postEphemeral(channel: string, message: Message, options: MessageOptions = {}): Promise<{ messageTs: string }> {
return this.request('postEphemeral',
snake({
channel, asUser: true, ...options,
...messageFormat.toSlack(message)
}))
.then(camel)
}
postMessage(channel: string, message: Message, options: MessageOptions = {})
: Promise<{ channel: string, ts: string, message: Message }> {
return this.request('postMessage',
snake({
channel, asUser: true, ...options,
...messageFormat.toSlack(message)
}))
.then(camel)
.then(({message, ...rest}) => ({
message: messageFormat.fromSlack(message),
...rest
}))
}
update(channel: string, ts: string, message: Message) {
return this.request('update', snake({
channel, ts, asUser: true, parse: 'none',
...messageFormat.toSlack(message)
})).then(camel)
}
}
| Fix issue with formatting of api response | Fix issue with formatting of api response
| TypeScript | apache-2.0 | dempfi/xene | ---
+++
@@ -28,8 +28,11 @@
channel, asUser: true, ...options,
...messageFormat.toSlack(message)
}))
- .then(messageFormat.fromSlack)
.then(camel)
+ .then(({message, ...rest}) => ({
+ message: messageFormat.fromSlack(message),
+ ...rest
+ }))
}
update(channel: string, ts: string, message: Message) { |
109fde296dc1a6ad777b984f391525845ae73302 | src/middlewear/matchTestFiles.ts | src/middlewear/matchTestFiles.ts | import glob from "glob";
import path from "path";
import Setup from "../types/Setup";
export default (...patterns: Array<string>) => (setup: Setup) => {
setup.testFilePaths = patterns
.reduce(
(paths, pattern) => [
...paths,
...glob.sync(pattern, { cwd: process.cwd(), absolute: true })
],
[]
)
.map(p => path.relative(process.cwd(), p));
};
| import glob from "glob";
import path from "path";
import Setup from "../types/Setup";
export default (...patterns: Array<string>) => (setup: Setup) => {
setup.testFilePaths = patterns
.reduce(
(paths, pattern) => [
...paths,
...glob.sync(pattern, {
cwd: process.cwd(),
absolute: true,
ignore: ["./node_modules"]
})
],
[]
)
.map(p => path.relative(process.cwd(), p));
};
| Add node_modules to glob ignore | Add node_modules to glob ignore
| TypeScript | mit | testingrequired/tf,testingrequired/tf | ---
+++
@@ -8,7 +8,11 @@
.reduce(
(paths, pattern) => [
...paths,
- ...glob.sync(pattern, { cwd: process.cwd(), absolute: true })
+ ...glob.sync(pattern, {
+ cwd: process.cwd(),
+ absolute: true,
+ ignore: ["./node_modules"]
+ })
],
[]
) |
a79c2f38459be420cd7c73733cc57579f062ce5f | src/scripts/extensions/appendIsInstalledMarker.ts | src/scripts/extensions/appendIsInstalledMarker.ts | let oneNoteWebClipperInstallMarker = "oneNoteWebClipperIsInstalledOnThisBrowser";
let marker = document.createElement("DIV");
marker.id = oneNoteWebClipperInstallMarker;
marker.style.display = "none";
if (document.body) {
appendMarker();
} else {
document.addEventListener("DOMContentLoaded", appendMarker, false);
}
function appendMarker() {
if (!document.getElementById(oneNoteWebClipperInstallMarker)) {
document.body.appendChild(marker);
}
}
| let oneNoteWebClipperInstallMarkerClassName = "oneNoteWebClipperIsInstalledOnThisBrowser";
let marker = document.createElement("DIV");
marker.className = oneNoteWebClipperInstallMarkerClassName;
marker.style.display = "none";
// We need to do this asap so we append it to the documentElement instead of the body
if (document.documentElement.getElementsByClassName(oneNoteWebClipperInstallMarkerClassName).length === 0) {
document.documentElement.appendChild(marker);
}
| Append marker to html element, not body element | Append marker to html element, not body element
| TypeScript | mit | larsendaniel/WebClipper,OneNoteDev/WebClipper,larsendaniel/WebClipper,OneNoteDev/WebClipper,larsendaniel/WebClipper,OneNoteDev/WebClipper | ---
+++
@@ -1,16 +1,9 @@
-let oneNoteWebClipperInstallMarker = "oneNoteWebClipperIsInstalledOnThisBrowser";
+let oneNoteWebClipperInstallMarkerClassName = "oneNoteWebClipperIsInstalledOnThisBrowser";
let marker = document.createElement("DIV");
-marker.id = oneNoteWebClipperInstallMarker;
+marker.className = oneNoteWebClipperInstallMarkerClassName;
marker.style.display = "none";
-if (document.body) {
- appendMarker();
-} else {
- document.addEventListener("DOMContentLoaded", appendMarker, false);
+// We need to do this asap so we append it to the documentElement instead of the body
+if (document.documentElement.getElementsByClassName(oneNoteWebClipperInstallMarkerClassName).length === 0) {
+ document.documentElement.appendChild(marker);
}
-
-function appendMarker() {
- if (!document.getElementById(oneNoteWebClipperInstallMarker)) {
- document.body.appendChild(marker);
- }
-} |
3680f688ca556bce7ab0b1dcbb0f0c9fecd8be3c | applications/jupyter-extension/nteract_on_jupyter/app/store.ts | applications/jupyter-extension/nteract_on_jupyter/app/store.ts | import {
combineReducers,
createStore,
applyMiddleware,
compose,
Action
} from "redux";
import { createEpicMiddleware, combineEpics } from "redux-observable";
import { AppState } from "@nteract/core";
import {
reducers,
epics as coreEpics,
middlewares as coreMiddlewares
} from "@nteract/core";
const composeEnhancers =
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer = combineReducers({
app: reducers.app,
comms: reducers.comms,
config: reducers.config,
core: reducers.core
});
export default function configureStore(initialState: Partial<AppState>) {
const rootEpic = combineEpics<Action, AppState>(...coreEpics.allEpics);
const epicMiddleware = createEpicMiddleware();
const middlewares = [epicMiddleware, coreMiddlewares.errorMiddleware];
const store = createStore(
rootReducer,
initialState,
composeEnhancers(applyMiddleware(...middlewares))
);
epicMiddleware.run(rootEpic);
return store;
}
| import {
combineReducers,
createStore,
applyMiddleware,
compose,
Action
} from "redux";
import { createEpicMiddleware, combineEpics, Epic } from "redux-observable";
import { AppState } from "@nteract/core";
import {
reducers,
epics as coreEpics,
middlewares as coreMiddlewares
} from "@nteract/core";
const composeEnhancers =
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer = combineReducers({
app: reducers.app,
comms: reducers.comms,
config: reducers.config,
core: reducers.core
});
export default function configureStore(initialState: Partial<AppState>) {
const rootEpic = combineEpics<Epic>(...coreEpics.allEpics);
const epicMiddleware = createEpicMiddleware();
const middlewares = [epicMiddleware, coreMiddlewares.errorMiddleware];
const store = createStore(
rootReducer,
initialState,
composeEnhancers(applyMiddleware(...middlewares))
);
epicMiddleware.run(rootEpic);
return store;
}
| Fix type for combineEpics invocation | Fix type for combineEpics invocation
| TypeScript | bsd-3-clause | nteract/composition,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/composition | ---
+++
@@ -5,7 +5,7 @@
compose,
Action
} from "redux";
-import { createEpicMiddleware, combineEpics } from "redux-observable";
+import { createEpicMiddleware, combineEpics, Epic } from "redux-observable";
import { AppState } from "@nteract/core";
import {
reducers,
@@ -24,7 +24,7 @@
});
export default function configureStore(initialState: Partial<AppState>) {
- const rootEpic = combineEpics<Action, AppState>(...coreEpics.allEpics);
+ const rootEpic = combineEpics<Epic>(...coreEpics.allEpics);
const epicMiddleware = createEpicMiddleware();
const middlewares = [epicMiddleware, coreMiddlewares.errorMiddleware];
|
3387f8f656c8212bdd82f7599af46c38532313d9 | lib/actions/help_ts.ts | lib/actions/help_ts.ts | /**
* @license
* Copyright 2019 Balena Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Command } from '@oclif/command';
import * as _ from 'lodash';
import EnvAddCmd from '../actions-oclif/env/add';
export function getOclifHelpLinePairs(): [[string, string]] {
return [getCmdUsageDescriptionLinePair(EnvAddCmd)];
}
function getCmdUsageDescriptionLinePair(cmd: typeof Command): [string, string] {
const usage = (cmd.usage || '').toString().toLowerCase();
let description = '';
const matches = /\s*(.+?)\n.*/s.exec(cmd.description || '');
if (matches && matches.length > 1) {
description = _.lowerFirst(_.trimEnd(matches[1], '.'));
}
return [usage, description];
}
| /**
* @license
* Copyright 2019 Balena Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Command } from '@oclif/command';
import * as _ from 'lodash';
import EnvAddCmd from '../actions-oclif/env/add';
export function getOclifHelpLinePairs(): [[string, string]] {
return [getCmdUsageDescriptionLinePair(EnvAddCmd)];
}
function getCmdUsageDescriptionLinePair(cmd: typeof Command): [string, string] {
const usage = (cmd.usage || '').toString().toLowerCase();
let description = '';
// note: [^] matches any characters (including line breaks), achieving the
// same effect as the 's' regex flag which is only supported by Node 9+
const matches = /\s*([^]+?)\n[^]*/.exec(cmd.description || '');
if (matches && matches.length > 1) {
description = _.lowerFirst(_.trimEnd(matches[1], '.'));
}
return [usage, description];
}
| Fix 'npm help' SyntaxError on Node 8 (invalid 's' regex flag) | Fix 'npm help' SyntaxError on Node 8 (invalid 's' regex flag)
Change-type: patch
Signed-off-by: Paulo Castro <[email protected]>
| TypeScript | apache-2.0 | resin-io/resin-cli,resin-io/resin-cli,resin-io/resin-cli,resin-io/resin-cli | ---
+++
@@ -27,7 +27,9 @@
function getCmdUsageDescriptionLinePair(cmd: typeof Command): [string, string] {
const usage = (cmd.usage || '').toString().toLowerCase();
let description = '';
- const matches = /\s*(.+?)\n.*/s.exec(cmd.description || '');
+ // note: [^] matches any characters (including line breaks), achieving the
+ // same effect as the 's' regex flag which is only supported by Node 9+
+ const matches = /\s*([^]+?)\n[^]*/.exec(cmd.description || '');
if (matches && matches.length > 1) {
description = _.lowerFirst(_.trimEnd(matches[1], '.'));
} |
6a2cd92ca25805200c50fa229a550dbf8035d240 | src/lib/nameOldEigenQueries.ts | src/lib/nameOldEigenQueries.ts | import { error } from "./loggers"
import { RequestHandler } from "express"
export const nameOldEigenQueries: RequestHandler = (req, _res, next) => {
const agent = req.headers["user-agent"]
if (agent && agent.includes("Eigen") && req.body.query) {
const { query } = req.body as { query: string }
if (!query.startsWith("query ")) {
if (query.includes("saved_artworks")) {
// https://github.com/artsy/eigen/blob/master/Artsy/Networking/favorites.graphql
req.body.query = `query FavoritesQuery ${query}`
} else if (query.includes("sale_artworks")) {
// https://github.com/artsy/eigen/blob/master/Artsy/Networking/artworks_in_sale.graphql
req.body.query = `query ArtworksInSaleQuery ${query}`
} else if (query.includes("totalUnreadCount")) {
// https://github.com/artsy/eigen/blob/master/Artsy/Networking/conversations.graphql
req.body.query = `query TotalUnreadCountQuery ${query}`
} else {
error(`Unexpected Eigen query: ${query}`)
}
}
}
next()
}
| import { error } from "./loggers"
import { RequestHandler } from "express"
export const nameOldEigenQueries: RequestHandler = (req, _res, next) => {
const agent = req.headers["user-agent"]
if (req.body.query && agent && agent.includes("Eigen")) {
const { query } = req.body as { query: string }
if (!query.startsWith("query ")) {
if (query.includes("saved_artworks")) {
// https://github.com/artsy/eigen/blob/master/Artsy/Networking/favorites.graphql
req.body.query = `query FavoritesQuery ${query}`
} else if (query.includes("sale_artworks")) {
// https://github.com/artsy/eigen/blob/master/Artsy/Networking/artworks_in_sale.graphql
req.body.query = `query ArtworksInSaleQuery ${query}`
} else if (query.includes("totalUnreadCount")) {
// https://github.com/artsy/eigen/blob/master/Artsy/Networking/conversations.graphql
req.body.query = `query TotalUnreadCountQuery ${query}`
} else {
error(`Unexpected Eigen query: ${query}`)
}
}
}
next()
}
| Refactor the query check in the eigen queries | Refactor the query check in the eigen queries
| TypeScript | mit | mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1 | ---
+++
@@ -3,7 +3,7 @@
export const nameOldEigenQueries: RequestHandler = (req, _res, next) => {
const agent = req.headers["user-agent"]
- if (agent && agent.includes("Eigen") && req.body.query) {
+ if (req.body.query && agent && agent.includes("Eigen")) {
const { query } = req.body as { query: string }
if (!query.startsWith("query ")) {
if (query.includes("saved_artworks")) { |
a7d2fddd0773c4eedf8f94e315fe0e393a950f50 | src/app/applications/components/application-conditions/application-conditions.tsx | src/app/applications/components/application-conditions/application-conditions.tsx | import * as React from 'react';
import * as models from '../../../shared/models';
export const ApplicationConditions = ({conditions}: { conditions: models.ApplicationCondition[]}) => {
return (
<div>
<h4>Application conditions</h4>
{conditions.length == 0 && (
<p>No conditions to report!</p>
)}
{conditions.length > 0 && (
<div className='white-box'>
<div className='white-box__details'>
{conditions.map((condition, index) => (
<div className='row white-box__details-row' key={index}>
<div className='columns small-12'>
{condition.message} ({condition.type})
</div>
</div>
))}
</div>
</div>)}
</div>
);
};
| import * as React from 'react';
import * as models from '../../../shared/models';
export const ApplicationConditions = ({conditions}: { conditions: models.ApplicationCondition[]}) => {
return (
<div>
<h4>Application conditions</h4>
{conditions.length == 0 && (
<p>No conditions to report!</p>
)}
{conditions.length > 0 && (
<div className='white-box'>
<div className='white-box__details'>
{conditions.map((condition, index) => (
<div className='row white-box__details-row' key={index}>
<div className='columns small-2'>
{condition.type}
</div>
<div className='columns small-10'>
{condition.message}
</div>
</div>
))}
</div>
</div>)}
</div>
);
};
| Break out condition table into columns | Break out condition table into columns
| TypeScript | apache-2.0 | argoproj/argo-cd,argoproj/argo-cd,argoproj/argo-cd,argoproj/argo-cd,argoproj/argo-cd | ---
+++
@@ -14,8 +14,11 @@
<div className='white-box__details'>
{conditions.map((condition, index) => (
<div className='row white-box__details-row' key={index}>
- <div className='columns small-12'>
- {condition.message} ({condition.type})
+ <div className='columns small-2'>
+ {condition.type}
+ </div>
+ <div className='columns small-10'>
+ {condition.message}
</div>
</div>
))} |
de8defe0520cb38f29f41a732eaee1ecc4a924b4 | e2e/connect-page.e2e-spec.ts | e2e/connect-page.e2e-spec.ts | import {ConnectPage} from "./connect-page.po";
describe("Connect page", () => {
let page: ConnectPage;
beforeEach(() => {
page = new ConnectPage();
});
it("should display message saying 'ZooNavigator. An awesome Zookeeper web admin.'", () => {
page.navigateTo();
expect(page.getHeaderText()).toEqual("ZooNavigator. An awesome Zookeeper web admin.");
});
});
| import {ConnectPage} from "./connect-page.po";
describe("Connect page", () => {
let page: ConnectPage;
beforeEach(() => {
page = new ConnectPage();
});
it("should display message saying 'ZooNavigator. An awesome Zookeeper web admin.'", () => {
page.navigateTo();
expect<any>(page.getHeaderText()).toEqual("ZooNavigator. An awesome Zookeeper web admin.");
});
});
| Fix e2e spec compilation error | Fix e2e spec compilation error
| TypeScript | agpl-3.0 | elkozmon/zoonavigator-web,elkozmon/zoonavigator-web,elkozmon/zoonavigator-web | ---
+++
@@ -9,6 +9,6 @@
it("should display message saying 'ZooNavigator. An awesome Zookeeper web admin.'", () => {
page.navigateTo();
- expect(page.getHeaderText()).toEqual("ZooNavigator. An awesome Zookeeper web admin.");
+ expect<any>(page.getHeaderText()).toEqual("ZooNavigator. An awesome Zookeeper web admin.");
});
}); |
af6b0209034ec3328a5c771a8e83d0476875f687 | src/TwitterShareButton.ts | src/TwitterShareButton.ts | import assert from 'assert';
import objectToGetParams from './utils/objectToGetParams';
import createShareButton from './hocs/createShareButton';
function twitterLink(
url: string,
{ title, via, hashtags = [] }: { title?: string; via?: string; hashtags?: string[] },
) {
assert(url, 'twitter.url');
assert(Array.isArray(hashtags), 'twitter.hashtags is not an array');
return (
'https://twitter.com/share' +
objectToGetParams({
url,
text: title,
via,
hashtags: hashtags.join(','),
})
);
}
const TwitterShareButton = createShareButton<{ title?: string; via?: string; hashtags?: string[] }>(
'twitter',
twitterLink,
props => ({
hashtags: props.hashtags,
title: props.title,
via: props.via,
}),
{
windowWidth: 550,
windowHeight: 400,
},
);
export default TwitterShareButton;
| import assert from 'assert';
import objectToGetParams from './utils/objectToGetParams';
import createShareButton from './hocs/createShareButton';
function twitterLink(
url: string,
{ title, via, hashtags = [] }: { title?: string; via?: string; hashtags?: string[] },
) {
assert(url, 'twitter.url');
assert(Array.isArray(hashtags), 'twitter.hashtags is not an array');
return (
'https://twitter.com/share' +
objectToGetParams({
url,
text: title,
via,
hashtags: hashtags.length > 0 ? hashtags.join(',') : undefined,
})
);
}
const TwitterShareButton = createShareButton<{ title?: string; via?: string; hashtags?: string[] }>(
'twitter',
twitterLink,
props => ({
hashtags: props.hashtags,
title: props.title,
via: props.via,
}),
{
windowWidth: 550,
windowHeight: 400,
},
);
export default TwitterShareButton;
| Handle no hashtag for Twitter | Handle no hashtag for Twitter
If you pass Twitter an empty string (which is what happens when you call Array.join on an empty array), Twitter adds an empty hashtag to the post when sharing with the native app on iOS. I haven't checked Android. Web seems fine.
| TypeScript | mit | nygardk/react-share,nygardk/react-share | ---
+++
@@ -16,7 +16,7 @@
url,
text: title,
via,
- hashtags: hashtags.join(','),
+ hashtags: hashtags.length > 0 ? hashtags.join(',') : undefined,
})
);
} |
85c128d8f4cbc4f092a52f2c847dcd03139a315a | src/server.ts | src/server.ts | import puppeteer from 'puppeteer';
import * as xmlrpc from 'xmlrpc';
import { Bot } from './bot';
import { Doku } from './doku';
import { onExit } from './on_exit';
import { Renderer } from './render';
// Used by our .service initfile to find the bot process.
process.title = 'comicsbot';
interface Config {
discordToken: string
doku: {
user: string,
password: string,
baseUrl: string,
},
}
(async () => {
let config: Config = require('../config/config.json');
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
handleSIGINT: false,
handleSIGTERM: false,
handleSIGHUP: false,
});
onExit(browser.close);
// TODO(dotdoom): createClient vs createSecureClient based on protocol in URL.
const doku = new Doku(xmlrpc.createSecureClient({
url: config.doku.baseUrl + 'lib/exe/xmlrpc.php',
cookies: true,
// headers: {
// 'User-Agent': await browser.userAgent(),
// },
}));
await doku.login(config.doku.user, config.doku.password);
const render = new Renderer('../config/render.js', doku, browser,
config.doku.baseUrl);
const bot = new Bot(render);
bot.connect(config.discordToken);
onExit(bot.destroy);
})();
| import puppeteer from 'puppeteer';
import * as url from 'url';
import * as xmlrpc from 'xmlrpc';
import { Bot } from './bot';
import { Doku } from './doku';
import { onExit } from './on_exit';
import { Renderer } from './render';
// Used by our .service initfile to find the bot process.
process.title = 'comicsbot';
interface Config {
discordToken: string
doku: {
user: string,
password: string,
baseUrl: string,
},
}
(async () => {
let config: Config = require('../config/config.json');
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
handleSIGINT: false,
handleSIGTERM: false,
handleSIGHUP: false,
});
onExit(browser.close);
let baseUrl = url.parse(config.doku.baseUrl);
let xmlrpcConstructor = baseUrl.protocol == 'http'
? xmlrpc.createClient
: xmlrpc.createSecureClient;
const doku = new Doku(xmlrpcConstructor({
url: config.doku.baseUrl + 'lib/exe/xmlrpc.php',
cookies: true,
// headers: {
// 'User-Agent': await browser.userAgent(),
// },
}));
await doku.login(config.doku.user, config.doku.password);
const render = new Renderer('../config/render.js', doku, browser,
config.doku.baseUrl);
const bot = new Bot(render);
bot.connect(config.discordToken);
onExit(bot.destroy);
})();
| Allow http in XMLRPC client | Allow http in XMLRPC client
| TypeScript | mit | dotdoom/comicsbot,dotdoom/comicsbot | ---
+++
@@ -1,4 +1,5 @@
import puppeteer from 'puppeteer';
+import * as url from 'url';
import * as xmlrpc from 'xmlrpc';
import { Bot } from './bot';
import { Doku } from './doku';
@@ -28,8 +29,12 @@
});
onExit(browser.close);
- // TODO(dotdoom): createClient vs createSecureClient based on protocol in URL.
- const doku = new Doku(xmlrpc.createSecureClient({
+ let baseUrl = url.parse(config.doku.baseUrl);
+ let xmlrpcConstructor = baseUrl.protocol == 'http'
+ ? xmlrpc.createClient
+ : xmlrpc.createSecureClient;
+
+ const doku = new Doku(xmlrpcConstructor({
url: config.doku.baseUrl + 'lib/exe/xmlrpc.php',
cookies: true,
// headers: { |
cc97f3cbdfdf6ce90d1860c830bb5fccb06c4e7d | packages/lesswrong/components/posts/PostsItemTooltipWrapper.tsx | packages/lesswrong/components/posts/PostsItemTooltipWrapper.tsx | import React from 'react';
import { registerComponent, Components } from '../../lib/vulcan-lib';
import { useHover } from "../common/withHover";
const PostsItemTooltipWrapper = ({children, post, className}: {
children?: React.ReactNode,
post: PostsList,
className?: string,
}) => {
const { LWPopper, PostsPreviewTooltip } = Components
const {eventHandlers, hover, anchorEl} = useHover({
pageElementContext: "postItemTooltip",
postId: post?._id
});
return <div {...eventHandlers} className={className}>
<LWPopper
open={hover}
anchorEl={anchorEl}
clickable={false}
placement="bottom-end"
modifiers={{
flip: {
enabled: false
}
}}
>
<PostsPreviewTooltip post={post} postsList />
</LWPopper>
{ children }
</div>
}
const PostsItemTooltipWrapperComponent = registerComponent('PostsItemTooltipWrapper', PostsItemTooltipWrapper
)
declare global {
interface ComponentTypes {
PostsItemTooltipWrapper: typeof PostsItemTooltipWrapperComponent
}
}
| import React from 'react';
import { registerComponent, Components } from '../../lib/vulcan-lib';
import { useHover } from "../common/withHover";
const PostsItemTooltipWrapper = ({children, post, className}: {
children?: React.ReactNode,
post: PostsList,
className?: string,
}) => {
const { LWPopper, PostsPreviewTooltip } = Components
const {eventHandlers, hover, anchorEl} = useHover({
pageElementContext: "postItemTooltip",
postId: post?._id
});
return <div {...eventHandlers} className={className}>
<LWPopper
open={hover}
anchorEl={anchorEl}
clickable={false}
placement="bottom-end"
>
<PostsPreviewTooltip post={post} postsList />
</LWPopper>
{ children }
</div>
}
const PostsItemTooltipWrapperComponent = registerComponent('PostsItemTooltipWrapper', PostsItemTooltipWrapper
)
declare global {
interface ComponentTypes {
PostsItemTooltipWrapper: typeof PostsItemTooltipWrapperComponent
}
}
| Remove flip disabled modifier to fix UI bug | Remove flip disabled modifier to fix UI bug
| TypeScript | mit | Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2 | ---
+++
@@ -18,11 +18,6 @@
anchorEl={anchorEl}
clickable={false}
placement="bottom-end"
- modifiers={{
- flip: {
- enabled: false
- }
- }}
>
<PostsPreviewTooltip post={post} postsList />
</LWPopper> |
2acd66de86a604aeaabd86a5dc08998709a32d52 | packages/util/src/index.ts | packages/util/src/index.ts | import { Application, Router } from 'express'
import proxy from 'express-http-proxy'
export const BASE_PATH = '/api/v1'
const BOT_REQUEST_HEADERS = 'x-api-bot-id'
export class HttpProxy {
constructor(private app: Application | Router, private targetHost: string) {}
proxy(originPath: string, targetPathOrOptions: string | {}) {
const options =
typeof targetPathOrOptions === 'string'
? {
proxyReqPathResolver: req => setApiBasePath(req) + targetPathOrOptions
}
: targetPathOrOptions
this.app.use(originPath, proxy(this.targetHost, options))
return this
}
}
export function setApiBasePath(req) {
// TODO: Get actual headers once the UI has been modified
const botId = req.get(BOT_REQUEST_HEADERS) || 'bot123'
return `${BASE_PATH}/bots/${botId}`
}
| import { Application, Router } from 'express'
import proxy from 'express-http-proxy'
export const BASE_PATH = '/api/v1'
const BOT_REQUEST_HEADERS = 'X-API-Bot-Id'
export class HttpProxy {
constructor(private app: Application | Router, private targetHost: string) {}
proxy(originPath: string, targetPathOrOptions: string | {}) {
const options =
typeof targetPathOrOptions === 'string'
? {
proxyReqPathResolver: req => setApiBasePath(req) + targetPathOrOptions
}
: targetPathOrOptions
this.app.use(originPath, proxy(this.targetHost, options))
return this
}
}
export function setApiBasePath(req) {
const botId = req.get(BOT_REQUEST_HEADERS)
return `${BASE_PATH}/bots/${botId}`
}
| Fix bot id api headers key | Fix bot id api headers key
| TypeScript | agpl-3.0 | botpress/botpress,botpress/botpress,botpress/botpress,botpress/botpress | ---
+++
@@ -2,7 +2,7 @@
import proxy from 'express-http-proxy'
export const BASE_PATH = '/api/v1'
-const BOT_REQUEST_HEADERS = 'x-api-bot-id'
+const BOT_REQUEST_HEADERS = 'X-API-Bot-Id'
export class HttpProxy {
constructor(private app: Application | Router, private targetHost: string) {}
@@ -21,7 +21,6 @@
}
export function setApiBasePath(req) {
- // TODO: Get actual headers once the UI has been modified
- const botId = req.get(BOT_REQUEST_HEADERS) || 'bot123'
+ const botId = req.get(BOT_REQUEST_HEADERS)
return `${BASE_PATH}/bots/${botId}`
} |
75e65863c61a2bd4d4e7f7a9a3485e5740288cca | packages/renderer-preact/src/index.ts | packages/renderer-preact/src/index.ts | import { options, render } from 'preact';
const mapDom = new WeakMap();
const mapNodeName = new WeakMap();
let oldVnode;
function generateUniqueName(prefix) {
let suffix = 0;
while (customElements.get(prefix + suffix)) ++suffix;
return `${prefix}-${suffix}`;
}
function newVnode(vnode) {
let fn = vnode.nodeName;
if (fn && fn.prototype instanceof HTMLElement) {
let nodeName = mapNodeName.get(fn);
if (!nodeName) {
nodeName = generateUniqueName(fn.name.toLowerCase());
mapNodeName.set(fn, nodeName);
customElements.define(nodeName, class extends fn {});
}
vnode.nodeName = nodeName;
}
return vnode;
}
function setupPreact() {
oldVnode = options.vnode;
options.vnode = newVnode;
}
function teardownPreact() {
options.vnode = oldVnode;
}
export default function(root, func) {
const dom = mapDom.get(root);
setupPreact();
mapDom.set(root, render(func(), root, dom || root.childNodes[0]));
teardownPreact();
}
export { h } from 'preact';
| import { options, render } from 'preact';
const mapDom = new WeakMap();
const mapNodeName = new WeakMap();
let oldVnode;
function generateUniqueName(prefix) {
let suffix = 0;
while (customElements.get(`${prefix}-${suffix}`)) ++suffix;
return `${prefix}-${suffix}`;
}
function newVnode(vnode) {
let fn = vnode.nodeName;
if (fn && fn.prototype instanceof HTMLElement) {
let nodeName = mapNodeName.get(fn);
if (!nodeName) {
nodeName = generateUniqueName(fn.name.toLowerCase());
mapNodeName.set(fn, nodeName);
customElements.define(nodeName, class extends fn {});
}
vnode.nodeName = nodeName;
}
return vnode;
}
function setupPreact() {
oldVnode = options.vnode;
options.vnode = newVnode;
}
function teardownPreact() {
options.vnode = oldVnode;
}
export default function(root, func) {
const dom = mapDom.get(root);
setupPreact();
mapDom.set(root, render(func(), root, dom || root.childNodes[0]));
teardownPreact();
}
export { h } from 'preact';
| Fix issue causing preact renderer to invoke an infinite loop. | Fix issue causing preact renderer to invoke an infinite loop.
| TypeScript | mit | skatejs/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -6,7 +6,7 @@
function generateUniqueName(prefix) {
let suffix = 0;
- while (customElements.get(prefix + suffix)) ++suffix;
+ while (customElements.get(`${prefix}-${suffix}`)) ++suffix;
return `${prefix}-${suffix}`;
}
|
fc01f90a2f0fad8f947c581c4472b46a41f4f517 | src/Parsing/Outline/GetHeadingParser.ts | src/Parsing/Outline/GetHeadingParser.ts | import { TextConsumer } from '../../TextConsumption/TextConsumer'
import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
import { ParseArgs, OnParse, Parser } from '../Parser'
import { streakOf, dottedStreakOf, either, NON_BLANK_LINE } from './Patterns'
import { parseInline } from '../Inline/ParseInline'
// Underlined text is considered a heading. Headings can have an optional overline, too.
export function getHeadingParser(underlinePattern: string, level: number): Parser {
let underlineOrOverline = new RegExp(underlinePattern)
return function parseHeading(text: string, parseArgs: ParseArgs, onParse: OnParse): boolean {
const consumer = new TextConsumer(text)
// Parse optional overline
consumer.consumeLineIf(underlineOrOverline)
const headingNode = new HeadingNode(parseArgs.parentNode, level)
let content: string
const hasContentAndOverline =
consumer.consumeLineIf(NON_BLANK_LINE,
(line) => {
content = line
})
&& consumer.consumeLineIf(underlineOrOverline)
return hasContentAndOverline
&& parseInline(content, { parentNode: headingNode }, (inlineNodes) => {
headingNode.addChildren(inlineNodes)
})
}
}
| import { TextConsumer } from '../../TextConsumption/TextConsumer'
import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
import { ParseArgs, OnParse, Parser } from '../Parser'
import { streakOf, dottedStreakOf, either, NON_BLANK_LINE } from './Patterns'
import { parseInline } from '../Inline/ParseInline'
// Underlined text is considered a heading. Headings can have an optional overline, too.
export function getHeadingParser(underlinePattern: string, level: number): Parser {
let underlineOrOverline = new RegExp(underlinePattern)
return function parseHeading(text: string, parseArgs: ParseArgs, onParse: OnParse): boolean {
const consumer = new TextConsumer(text)
// Parse optional overline
consumer.consumeLineIf(underlineOrOverline)
const headingNode = new HeadingNode(parseArgs.parentNode, level)
let content: string
const hasContentAndOverline =
consumer.consumeLineIf(NON_BLANK_LINE,
(line) => {
content = line
})
&& consumer.consumeLineIf(underlineOrOverline)
return hasContentAndOverline
&& parseInline(content, { parentNode: headingNode }, (inlineNodes) => {
headingNode.addChildren(inlineNodes)
onParse([headingNode], consumer.countCharsAdvanced(), parseArgs.parentNode)
})
}
}
| Make heading parser call onParse callback | Make heading parser call onParse callback
| TypeScript | mit | start/up,start/up | ---
+++
@@ -27,6 +27,7 @@
return hasContentAndOverline
&& parseInline(content, { parentNode: headingNode }, (inlineNodes) => {
headingNode.addChildren(inlineNodes)
+ onParse([headingNode], consumer.countCharsAdvanced(), parseArgs.parentNode)
})
}
} |
92d9519ebb8aa11e5f71e5f965ddc371512e922f | src/components/sources/osm.component.ts | src/components/sources/osm.component.ts | import { Component, Host, OnInit, forwardRef, Input } from '@angular/core';
import { source, AttributionLike, TileLoadFunctionType } from 'openlayers';
import { LayerTileComponent } from '../layers';
import { SourceComponent } from './source.component';
@Component({
selector: 'aol-source-osm',
template: `<div class="aol-source-osm"></div>`,
providers: [
{ provide: SourceComponent, useExisting: forwardRef(() => SourceOsmComponent) }
]
})
export class SourceOsmComponent extends SourceComponent implements OnInit {
instance: source.OSM;
@Input() attributions: AttributionLike;
@Input() cacheSize: number;
@Input() crossOrigin: string;
@Input() maxZoom: number;
@Input() opaque: boolean;
@Input() reprojectionErrorThreshold: number;
@Input() tileLoadFunction: TileLoadFunctionType;
@Input() url: string;
@Input() wrapX: boolean;
constructor(@Host() layer: LayerTileComponent) {
super(layer);
}
ngOnInit() {
this.instance = new source.OSM(this);
this.host.instance.setSource(this.instance);
}
}
| import { Component, Host, OnInit, forwardRef, Input } from '@angular/core';
import { source, AttributionLike, TileLoadFunctionType } from 'openlayers';
import { LayerTileComponent } from '../layers';
import { SourceComponent } from './source.component';
import { SourceXYZComponent } from './xyz.component';
@Component({
selector: 'aol-source-osm',
template: `<div class="aol-source-osm"></div>`,
providers: [
{ provide: SourceComponent, useExisting: forwardRef(() => SourceOsmComponent) }
]
})
export class SourceOsmComponent extends SourceXYZComponent implements OnInit {
instance: source.OSM;
@Input() attributions: AttributionLike;
@Input() cacheSize: number;
@Input() crossOrigin: string;
@Input() maxZoom: number;
@Input() opaque: boolean;
@Input() reprojectionErrorThreshold: number;
@Input() tileLoadFunction: TileLoadFunctionType;
@Input() url: string;
@Input() wrapX: boolean;
constructor(@Host() layer: LayerTileComponent) {
super(layer);
}
ngOnInit() {
this.instance = new source.OSM(this);
this.host.instance.setSource(this.instance);
}
}
| Use SourceXYZComponent as parent class instead of SourceComponent | feat(Source:OSM): Use SourceXYZComponent as parent class instead of SourceComponent
| TypeScript | mpl-2.0 | quentin-ol/ngx-openlayers,karomamczi/ngx-openlayers,karomamczi/ngx-openlayers,quentin-ol/ngx-openlayers,karomamczi/ngx-openlayers,quentin-ol/ngx-openlayers | ---
+++
@@ -2,6 +2,7 @@
import { source, AttributionLike, TileLoadFunctionType } from 'openlayers';
import { LayerTileComponent } from '../layers';
import { SourceComponent } from './source.component';
+import { SourceXYZComponent } from './xyz.component';
@Component({
selector: 'aol-source-osm',
@@ -10,7 +11,7 @@
{ provide: SourceComponent, useExisting: forwardRef(() => SourceOsmComponent) }
]
})
-export class SourceOsmComponent extends SourceComponent implements OnInit {
+export class SourceOsmComponent extends SourceXYZComponent implements OnInit {
instance: source.OSM;
@Input() attributions: AttributionLike; |
d25dbb4e6637cf057bb3e34fb053eb43cc98f45c | src/util/util.ts | src/util/util.ts |
export function uniqueFilterFnGenerator<T>(): (v: T) => boolean;
export function uniqueFilterFnGenerator<T, U>(extractFn: (v: T) => U): (v: T) => boolean;
export function uniqueFilterFnGenerator<T>(extractFn?: (v: T) => T): (v: T) => boolean {
const values = new Set<T>();
const extractor = extractFn || (a => a);
return (v: T) => {
const vv = extractor(v);
const ret = !values.has(vv);
values.add(vv);
return ret;
};
}
export function unique<T>(src: T[]): T[] {
return [...(new Set(src))];
}
export function clean<T extends Object>(src: T): T {
const r = src;
type keyOfT = keyof T;
type keysOfT = keyOfT[];
for (const key of Object.keys(r) as keysOfT) {
if (r[key] === undefined) {
delete r[key];
}
}
return r;
}
|
// alias for uniqueFilterFnGenerator
export const uniqueFn = uniqueFilterFnGenerator;
export function uniqueFilterFnGenerator<T>(): (v: T) => boolean;
export function uniqueFilterFnGenerator<T, U>(extractFn: (v: T) => U): (v: T) => boolean;
export function uniqueFilterFnGenerator<T>(extractFn?: (v: T) => T): (v: T) => boolean {
const values = new Set<T>();
const extractor = extractFn || (a => a);
return (v: T) => {
const vv = extractor(v);
const ret = !values.has(vv);
values.add(vv);
return ret;
};
}
export function unique<T>(src: T[]): T[] {
return [...(new Set(src))];
}
export function clean<T extends Object>(src: T): T {
const r = src;
type keyOfT = keyof T;
type keysOfT = keyOfT[];
for (const key of Object.keys(r) as keysOfT) {
if (r[key] === undefined) {
delete r[key];
}
}
return r;
}
| Add alias for unique files function | Add alias for unique files function
| TypeScript | mit | Jason3S/cspell,Jason3S/cspell,Jason3S/cspell,Jason3S/cspell,Jason3S/cspell | ---
+++
@@ -1,3 +1,6 @@
+
+// alias for uniqueFilterFnGenerator
+export const uniqueFn = uniqueFilterFnGenerator;
export function uniqueFilterFnGenerator<T>(): (v: T) => boolean;
export function uniqueFilterFnGenerator<T, U>(extractFn: (v: T) => U): (v: T) => boolean; |
c807aa00dda3b61ad536db12f156b54a6a53388d | packages/interactjs/index.ts | packages/interactjs/index.ts | // eslint-disable-next-line import/no-extraneous-dependencies
export { default } from '@interactjs/interactjs/index'
| // eslint-disable-next-line import/no-extraneous-dependencies
import interact from '@interactjs/interactjs/index'
export default interact
if (typeof module === 'object' && !!module) {
try {
module.exports = interact
} catch {}
}
;(interact as any).default = interact
| Revert "chore: remove redundant module.exports assignment" | Revert "chore: remove redundant module.exports assignment"
Close #895
| TypeScript | mit | taye/interact.js,taye/interact.js,taye/interact.js | ---
+++
@@ -1,2 +1,12 @@
// eslint-disable-next-line import/no-extraneous-dependencies
-export { default } from '@interactjs/interactjs/index'
+import interact from '@interactjs/interactjs/index'
+
+export default interact
+
+if (typeof module === 'object' && !!module) {
+ try {
+ module.exports = interact
+ } catch {}
+}
+
+;(interact as any).default = interact |
bfd0b037bbbd0a8d41b6360b21f6fb8462f31201 | app/components/backup/backup.ts | app/components/backup/backup.ts | import * as fs from 'fs';
const PouchDB = require('pouchdb');
const replicationStream = require('pouchdb-replication-stream');
const MemoryStream = require('memorystream');
/**
* @author Daniel de Oliveira
**/
export module Backup {
export const FILE_NOT_EXIST = 'filenotexist';
export async function dump(filePath: string, project: string) {
PouchDB.plugin(replicationStream.plugin);
PouchDB.adapter('writableStream', replicationStream.adapters.writableStream);
let dumpedString = '';
const stream = new MemoryStream();
stream.on('data', (chunk: any) => {
dumpedString +=
chunk.toString()
.replace(/"data"[\s\S]+?,/g,'\"data\":\"\",')
}); // TODO note that this regex is a too general. we want to get rid of this asap anyway, as soon as the thumbnail thing is fixed in pouchdb-replication stream.
const db = new PouchDB(project);
await db.dump(stream, {attachments:false});
fs.writeFileSync(filePath, dumpedString);
}
export async function readDump(filePath: string, project: string) {
if (!fs.existsSync(filePath)) throw FILE_NOT_EXIST;
if (!fs.lstatSync(filePath).isFile()) throw FILE_NOT_EXIST;
const db2 = new PouchDB(project); // TODO destroy before load and unit test it
PouchDB.plugin(require('pouchdb-load'));
await db2.load(filePath);
}
} | import * as fs from 'fs';
const PouchDB = require('pouchdb');
const replicationStream = require('pouchdb-replication-stream');
const MemoryStream = require('memorystream');
/**
* @author Daniel de Oliveira
**/
export module Backup {
export const FILE_NOT_EXIST = 'filenotexist';
export async function dump(filePath: string, project: string) {
PouchDB.plugin(replicationStream.plugin);
PouchDB.adapter('writableStream', replicationStream.adapters.writableStream);
let dumpedString = '';
const stream = new MemoryStream();
stream.on('data', (chunk: any) => {
dumpedString +=
chunk.toString()
.replace(/"data"[\s\S]+?,/g,'\"data\":\"\",')
}); // TODO note that this regex is a too general. we want to get rid of this asap anyway, as soon as the thumbnail thing is fixed in pouchdb-replication stream.
const db = new PouchDB(project);
await db.dump(stream, {attachments:false});
fs.writeFileSync(filePath, dumpedString);
}
export async function readDump(filePath: string, project: string) {
if (!fs.existsSync(filePath)) throw FILE_NOT_EXIST;
if (!fs.lstatSync(filePath).isFile()) throw FILE_NOT_EXIST;
const db = new PouchDB(project);
await db.destroy(); // to prevent pouchdb-load's incremental loading and force a true overwrite of the old db
const db2 = new PouchDB(project);
PouchDB.plugin(require('pouchdb-load'));
await db2.load(filePath);
}
} | Make sure db gets overwritten on read dump | Make sure db gets overwritten on read dump
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -38,7 +38,10 @@
if (!fs.existsSync(filePath)) throw FILE_NOT_EXIST;
if (!fs.lstatSync(filePath).isFile()) throw FILE_NOT_EXIST;
- const db2 = new PouchDB(project); // TODO destroy before load and unit test it
+ const db = new PouchDB(project);
+ await db.destroy(); // to prevent pouchdb-load's incremental loading and force a true overwrite of the old db
+
+ const db2 = new PouchDB(project);
PouchDB.plugin(require('pouchdb-load'));
await db2.load(filePath); |
9dd2619ffd6628164e8b32752f63f85457b08645 | src/components/auth/auth.component.ts | src/components/auth/auth.component.ts | import {Request} from 'express';
import {HookableComponent, HookableModels} from '../hookable';
import {DependencyInjectorComponent} from '../dependency-injector';
import {User} from './models/user';
/**
* Connect to a database and perform operation in that
*/
@DependencyInjectorComponent.createWith(HookableComponent)
export class AuthComponent {
/**
* Get the user performing a request
*/
public getUser: HookableModels.ReturnableAll<Request, User>;
/**
* Create a new user based upon the information in the request
*/
public createUser: HookableModels.ReturnableAll<Request, User>;
/**
* Update information about the user
*/
public updateUser: HookableModels.ReturnableAll<Request, User>;
/**
* Delete the user performing the request
*/
public deleteUser: HookableModels.ReturnableAll<Request, User>;
/**
* Create new instance of DBManager and bind middleware to it
*/
constructor(hc: HookableComponent) {
// init hookable
this.getUser = hc.returnableAll();
this.createUser = hc.returnableAll();
this.updateUser = hc.returnableAll();
this.deleteUser = hc.returnableAll();
}
}
| import {Request} from 'express';
import {HookableComponent, HookableModels} from '../hookable';
import {DependencyInjectorComponent} from '../dependency-injector';
import {User} from './models/user';
/**
* Connect to a database and perform operation in that
*/
@DependencyInjectorComponent.createWith(HookableComponent)
export class AuthComponent {
/**
* Get the user performing a request
*/
public getUser: HookableModels.Returnable<Request, User>;
/**
* Create a new user based upon the information in the request
*/
public createUser: HookableModels.Returnable<Request, User>;
/**
* Update information about the user
*/
public updateUser: HookableModels.Returnable<Request, User>;
/**
* Delete the user performing the request
*/
public deleteUser: HookableModels.Returnable<Request, User>;
/**
* Create new instance of DBManager and bind middleware to it
*/
constructor(hc: HookableComponent) {
// init hookable
this.getUser = hc.returnable();
this.createUser = hc.returnable();
this.updateUser = hc.returnable();
this.deleteUser = hc.returnable();
}
}
| Set auth to only returnable | Set auth to only returnable
| TypeScript | mit | MedSolve/ords-fhir | ---
+++
@@ -11,29 +11,29 @@
/**
* Get the user performing a request
*/
- public getUser: HookableModels.ReturnableAll<Request, User>;
+ public getUser: HookableModels.Returnable<Request, User>;
/**
* Create a new user based upon the information in the request
*/
- public createUser: HookableModels.ReturnableAll<Request, User>;
+ public createUser: HookableModels.Returnable<Request, User>;
/**
* Update information about the user
*/
- public updateUser: HookableModels.ReturnableAll<Request, User>;
+ public updateUser: HookableModels.Returnable<Request, User>;
/**
* Delete the user performing the request
*/
- public deleteUser: HookableModels.ReturnableAll<Request, User>;
+ public deleteUser: HookableModels.Returnable<Request, User>;
/**
* Create new instance of DBManager and bind middleware to it
*/
constructor(hc: HookableComponent) {
// init hookable
- this.getUser = hc.returnableAll();
- this.createUser = hc.returnableAll();
- this.updateUser = hc.returnableAll();
- this.deleteUser = hc.returnableAll();
+ this.getUser = hc.returnable();
+ this.createUser = hc.returnable();
+ this.updateUser = hc.returnable();
+ this.deleteUser = hc.returnable();
}
} |
a404c32864f378d238314308685017c92400a6eb | src/validate.ts | src/validate.ts | import * as glob from 'glob';
export default function validate() {
let files = glob.sync('src/**/*.ts');
files.forEach(file => {
console.log(file);
});
}
| import * as fs from 'fs';
import * as glob from 'glob';
import * as ts from 'typescript';
import getCompilerOptions from './getCompilerOptions';
export default function validate() {
let files = glob.sync('src/**/*.ts');
const compilerOptions = getCompilerOptions();
let compilerHost = ts.createCompilerHost(compilerOptions);
files.forEach(file => {
let fileInfo = ts.preProcessFile(fs.readFileSync(file).toString(), true, true);
console.log('Validating file:', file);
fileInfo.importedFiles.forEach(importInfo => {
let resolvedFile = ts.resolveModuleName(
importInfo.fileName,
file,
compilerOptions,
compilerHost,
null // TODO
);
console.log(
'resolvedModule:',
resolvedFile.resolvedModule && resolvedFile.resolvedModule.resolvedFileName
);
});
console.log();
});
}
| Resolve each import in each file | Resolve each import in each file
| TypeScript | mit | smikula/good-fences,smikula/good-fences | ---
+++
@@ -1,8 +1,33 @@
+import * as fs from 'fs';
import * as glob from 'glob';
+import * as ts from 'typescript';
+import getCompilerOptions from './getCompilerOptions';
export default function validate() {
let files = glob.sync('src/**/*.ts');
+
+ const compilerOptions = getCompilerOptions();
+ let compilerHost = ts.createCompilerHost(compilerOptions);
+
files.forEach(file => {
- console.log(file);
+ let fileInfo = ts.preProcessFile(fs.readFileSync(file).toString(), true, true);
+ console.log('Validating file:', file);
+
+ fileInfo.importedFiles.forEach(importInfo => {
+ let resolvedFile = ts.resolveModuleName(
+ importInfo.fileName,
+ file,
+ compilerOptions,
+ compilerHost,
+ null // TODO
+ );
+
+ console.log(
+ 'resolvedModule:',
+ resolvedFile.resolvedModule && resolvedFile.resolvedModule.resolvedFileName
+ );
+ });
+
+ console.log();
});
} |
273e020c2876af3dfeb7e7382edc54508fccdab3 | packages/components/components/alertModal/AlertModal.tsx | packages/components/components/alertModal/AlertModal.tsx | import { ReactNode, useContext } from 'react';
import { classnames } from '../../helpers';
import { ModalTwo, ModalProps, ModalTwoContent, ModalTwoFooter, ModalContext } from '../modalTwo';
import './AlertModal.scss';
const AlertModalTitle = ({ children }: { children: ReactNode }) => (
<h3 id={useContext(ModalContext).id} className="text-lg text-bold">
{children}
</h3>
);
interface AlertModalProps extends Omit<ModalProps, 'children'> {
title: string;
subline?: string;
buttons: JSX.Element | [JSX.Element] | [JSX.Element, JSX.Element];
children: ReactNode;
}
const AlertModal = ({ title, subline, buttons, className, children, ...rest }: AlertModalProps) => {
const [firstButton, secondButton] = Array.isArray(buttons) ? buttons : [buttons];
return (
<ModalTwo size="small" {...rest} className={classnames([className, 'alert-modal'])}>
<div className="alert-modal-header">
<AlertModalTitle>{title}</AlertModalTitle>
{subline && <div className="color-weak">{subline}</div>}
</div>
<ModalTwoContent>{children}</ModalTwoContent>
<ModalTwoFooter className="flex-column flex-align-items-stretch">
{firstButton}
{secondButton}
</ModalTwoFooter>
</ModalTwo>
);
};
export default AlertModal;
| import { ReactNode, useContext } from 'react';
import { classnames } from '../../helpers';
import { ModalTwo, ModalProps, ModalTwoContent, ModalTwoFooter, ModalContext } from '../modalTwo';
import './AlertModal.scss';
const AlertModalTitle = ({ children }: { children: ReactNode }) => (
<h3 id={useContext(ModalContext).id} className="text-lg text-bold">
{children}
</h3>
);
interface AlertModalProps extends Omit<ModalProps, 'children'> {
title: string;
subline?: string;
buttons: JSX.Element | [JSX.Element] | [JSX.Element, JSX.Element] | [JSX.Element, JSX.Element, JSX.Element];
children: ReactNode;
}
const AlertModal = ({ title, subline, buttons, className, children, ...rest }: AlertModalProps) => {
const [firstButton, secondButton, thirdButton] = Array.isArray(buttons) ? buttons : [buttons];
return (
<ModalTwo size="small" {...rest} className={classnames([className, 'alert-modal'])}>
<div className="alert-modal-header">
<AlertModalTitle>{title}</AlertModalTitle>
{subline && <div className="color-weak">{subline}</div>}
</div>
<ModalTwoContent>{children}</ModalTwoContent>
<ModalTwoFooter className="flex-column flex-align-items-stretch">
{firstButton}
{secondButton}
{thirdButton}
</ModalTwoFooter>
</ModalTwo>
);
};
export default AlertModal;
| Add support for a third button in alert modal | Add support for a third button in alert modal
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -13,12 +13,12 @@
interface AlertModalProps extends Omit<ModalProps, 'children'> {
title: string;
subline?: string;
- buttons: JSX.Element | [JSX.Element] | [JSX.Element, JSX.Element];
+ buttons: JSX.Element | [JSX.Element] | [JSX.Element, JSX.Element] | [JSX.Element, JSX.Element, JSX.Element];
children: ReactNode;
}
const AlertModal = ({ title, subline, buttons, className, children, ...rest }: AlertModalProps) => {
- const [firstButton, secondButton] = Array.isArray(buttons) ? buttons : [buttons];
+ const [firstButton, secondButton, thirdButton] = Array.isArray(buttons) ? buttons : [buttons];
return (
<ModalTwo size="small" {...rest} className={classnames([className, 'alert-modal'])}>
@@ -30,6 +30,7 @@
<ModalTwoFooter className="flex-column flex-align-items-stretch">
{firstButton}
{secondButton}
+ {thirdButton}
</ModalTwoFooter>
</ModalTwo>
); |
67febf8145ea00c9a71938979d1bfa67c0377fe4 | packages/components/containers/addresses/PmMeSection.tsx | packages/components/containers/addresses/PmMeSection.tsx | import React from 'react';
import { UserModel } from 'proton-shared/lib/interfaces';
import PmMePanel from './PmMePanel';
interface Props {
user: UserModel;
}
const PmMeSection = ({ user }: Props) => {
if (!user.canPay) {
return null;
}
return <PmMePanel />;
};
export default PmMeSection;
| import React from 'react';
import { UserModel } from 'proton-shared/lib/interfaces';
import PmMePanel from './PmMePanel';
interface Props {
user: UserModel;
}
const PmMeSection = ({ user }: Props) => {
if (!user.canPay || user.isSubUser) {
return null;
}
return <PmMePanel />;
};
export default PmMeSection;
| Hide pm.me section for sub user | [MAILWEB-1290] Hide pm.me section for sub user
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -8,7 +8,7 @@
}
const PmMeSection = ({ user }: Props) => {
- if (!user.canPay) {
+ if (!user.canPay || user.isSubUser) {
return null;
}
|
6c8e0850a4b1aeab54fd582e6619a390386f6ff9 | src/externals.ts | src/externals.ts | /**
* Re-exports commonly used modules:
* * Exports [`BN`](https://github.com/indutny/bn.js), [`rlp`](https://github.com/ethereumjs/rlp).
* @packageDocumentation
*/
import * as BN from 'bn.js'
import * as rlp from 'rlp'
/**
* [`BN`](https://github.com/indutny/bn.js)
*/
export { BN }
/**
* [`rlp`](https://github.com/ethereumjs/rlp)
*/
export { rlp }
| /**
* Re-exports commonly used modules:
* * Exports [`BN`](https://github.com/indutny/bn.js), [`rlp`](https://github.com/ethereumjs/rlp).
* @packageDocumentation
*/
// TODO: This can be replaced with a normal ESM import once
// the new major version of the typescript config package
// is released and adopted here.
import BN = require('bn.js');
import rlp = require('rlp');
/**
* [`BN`](https://github.com/indutny/bn.js)
*/
export { BN }
/**
* [`rlp`](https://github.com/ethereumjs/rlp)
*/
export { rlp }
| Fix BN and rlp re-exports' types | Fix BN and rlp re-exports' types
| TypeScript | mpl-2.0 | ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereum/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-util,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-util | ---
+++
@@ -4,8 +4,11 @@
* @packageDocumentation
*/
-import * as BN from 'bn.js'
-import * as rlp from 'rlp'
+// TODO: This can be replaced with a normal ESM import once
+// the new major version of the typescript config package
+// is released and adopted here.
+import BN = require('bn.js');
+import rlp = require('rlp');
/**
* [`BN`](https://github.com/indutny/bn.js) |
54ebfd364a012e72f48897fa699070848bacabb2 | src/index.ts | src/index.ts | import {h, VNode} from '@cycle/dom';
const hyperx = require(`hyperx`);
/**
* Returns a {@code VNode} tree representing the given HTML string.
*
* This is but a wrapper around hyperx to adjust its attrs for snabbdom, where snabbdom uses
* various modules (`class`, `props`, `attrs`, and `style`) instead of a single attrs object.
*/
const html: (s: TemplateStringsArray, ...vals: any[]) => VNode = hyperx((tag: string, attrs: any, children: any[]) => {
const attributes: {[k: string]: {}} = { attrs };
if (attrs.className && typeof attrs.className == `string`) {
const klass: { [k: string]: boolean } = {};
attrs.className.split(' ').map((className: string) => klass[className] = true);
attributes['class'] = klass;
}
if (children) {
return h(tag, attributes, children.reduce((acc, val) => acc.concat(Array.isArray(val) ? val : [val]), []));
}
return h(tag, attributes);
});
export { html };
| import {h, VNode} from '@cycle/dom';
const hyperx = require(`hyperx`);
/**
* Returns a {@code VNode} tree representing the given HTML string.
*
* This is but a wrapper around hyperx to adjust its attrs for snabbdom, where snabbdom uses
* various modules (`class`, `props`, `attrs`, and `style`) instead of a single attrs object.
*/
const html: (s: TemplateStringsArray, ...vals: any[]) => VNode = hyperx((tag: string, attrs: any, children: any[]) => {
const attributes: {[k: string]: {}} = Object.assign({}, { attrs });
if (attrs.className && typeof attrs.className == `string`) {
const klass: { [k: string]: boolean } = {};
attrs.className.split(' ').map((className: string) => klass[className] = true);
attributes['class'] = klass;
delete (<{[k: string]: {}}>attributes['attrs'])['className'];
}
if (children) {
return h(tag, attributes, children.reduce((acc, val) => acc.concat(Array.isArray(val) ? val : [val]), []));
}
return h(tag, attributes);
});
export { html };
| Delete attrs.className after transforming it | Delete attrs.className after transforming it
| TypeScript | isc | whymarrh/hypercycle | ---
+++
@@ -9,11 +9,12 @@
* various modules (`class`, `props`, `attrs`, and `style`) instead of a single attrs object.
*/
const html: (s: TemplateStringsArray, ...vals: any[]) => VNode = hyperx((tag: string, attrs: any, children: any[]) => {
- const attributes: {[k: string]: {}} = { attrs };
+ const attributes: {[k: string]: {}} = Object.assign({}, { attrs });
if (attrs.className && typeof attrs.className == `string`) {
const klass: { [k: string]: boolean } = {};
attrs.className.split(' ').map((className: string) => klass[className] = true);
attributes['class'] = klass;
+ delete (<{[k: string]: {}}>attributes['attrs'])['className'];
}
if (children) { |
c26f113b52108351f40ffd2caef63bbcc6118ea5 | src/Accordion/Accordion.tsx | src/Accordion/Accordion.tsx | import * as React from 'react';
type AccordionProps = React.HTMLAttributes<HTMLDivElement> & {
accordion: boolean;
};
const Accordion = ({ accordion, ...rest }: AccordionProps): JSX.Element => {
const role = accordion ? 'tablist' : undefined;
return <div role={role} {...rest} />;
};
export default Accordion;
| import * as React from 'react';
type AccordionProps = React.HTMLAttributes<HTMLDivElement> & {
accordion: boolean;
};
const Accordion = ({ accordion, ...rest }: AccordionProps): JSX.Element => {
return <div {...rest} />;
};
export default Accordion;
| Remove unnecessary tablist role from accordion parent | Remove unnecessary tablist role from accordion parent
| TypeScript | mit | springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion | ---
+++
@@ -5,9 +5,7 @@
};
const Accordion = ({ accordion, ...rest }: AccordionProps): JSX.Element => {
- const role = accordion ? 'tablist' : undefined;
-
- return <div role={role} {...rest} />;
+ return <div {...rest} />;
};
export default Accordion; |
9d54e5312484b270b245adcb992e84a462976d3c | src/main/stores/reactions.ts | src/main/stores/reactions.ts | import { observe } from "mobx"
import { isNotNull } from "../../common/helpers/array"
import { resetSelection } from "../actions"
import MIDIOutput from "../services/MIDIOutput"
import RootStore from "./RootStore"
export const registerReactions = (rootStore: RootStore) => {
// reset selection when tool changed
observe(rootStore.pianoRollStore, "mouseMode", resetSelection(rootStore))
// sync synthGroup.output to enabledOutputIds/isFactorySoundEnabled
const updateOutputDevices = () => {
const { midiDeviceStore } = rootStore
rootStore.services.player.allSoundsOff()
const getMIDIDeviceEntries = () =>
Array.from(midiDeviceStore.enabledOutputIds.values())
.map((deviceId) => {
const device = midiDeviceStore.outputs.find((d) => d.id === deviceId)
if (device === undefined) {
console.error(`device not found: ${deviceId}`)
return null
}
return { synth: new MIDIOutput(device), isEnabled: true }
})
.filter(isNotNull)
rootStore.services.synthGroup.outputs = [
{
synth: rootStore.services.synth,
isEnabled: midiDeviceStore.isFactorySoundEnabled,
},
...getMIDIDeviceEntries(),
]
}
observe(rootStore.midiDeviceStore, "enabledOutputIds", updateOutputDevices)
observe(
rootStore.midiDeviceStore,
"isFactorySoundEnabled",
updateOutputDevices
)
}
| import { autorun, observe } from "mobx"
import { isNotNull } from "../../common/helpers/array"
import { emptySelection } from "../../common/selection/Selection"
import { resetSelection } from "../actions"
import MIDIOutput from "../services/MIDIOutput"
import RootStore from "./RootStore"
export const registerReactions = (rootStore: RootStore) => {
// reset selection when tool changed
observe(rootStore.pianoRollStore, "mouseMode", resetSelection(rootStore))
// sync synthGroup.output to enabledOutputIds/isFactorySoundEnabled
const updateOutputDevices = () => {
const { midiDeviceStore } = rootStore
rootStore.services.player.allSoundsOff()
const getMIDIDeviceEntries = () =>
Array.from(midiDeviceStore.enabledOutputIds.values())
.map((deviceId) => {
const device = midiDeviceStore.outputs.find((d) => d.id === deviceId)
if (device === undefined) {
console.error(`device not found: ${deviceId}`)
return null
}
return { synth: new MIDIOutput(device), isEnabled: true }
})
.filter(isNotNull)
rootStore.services.synthGroup.outputs = [
{
synth: rootStore.services.synth,
isEnabled: midiDeviceStore.isFactorySoundEnabled,
},
...getMIDIDeviceEntries(),
]
}
observe(rootStore.midiDeviceStore, "enabledOutputIds", updateOutputDevices)
observe(
rootStore.midiDeviceStore,
"isFactorySoundEnabled",
updateOutputDevices
)
// reset selection when change track
autorun(() => {
// deep observe
const _ = rootStore.song.selectedTrackId
rootStore.pianoRollStore.selection = emptySelection
})
}
| Remove selection when track changed | Remove selection when track changed
| TypeScript | mit | ryohey/signal,ryohey/signal,ryohey/signal | ---
+++
@@ -1,5 +1,6 @@
-import { observe } from "mobx"
+import { autorun, observe } from "mobx"
import { isNotNull } from "../../common/helpers/array"
+import { emptySelection } from "../../common/selection/Selection"
import { resetSelection } from "../actions"
import MIDIOutput from "../services/MIDIOutput"
import RootStore from "./RootStore"
@@ -41,4 +42,11 @@
"isFactorySoundEnabled",
updateOutputDevices
)
+
+ // reset selection when change track
+ autorun(() => {
+ // deep observe
+ const _ = rootStore.song.selectedTrackId
+ rootStore.pianoRollStore.selection = emptySelection
+ })
} |
eee321516ee05678ec4c57b2515d05a7a7b6a508 | src/app/views/accessibility/accessibility.component.ts | src/app/views/accessibility/accessibility.component.ts | import { Component, OnInit } from "@angular/core";
import log from "loglevel";
import { ErrorService } from "../../core/errorhandler/error.service";
import { ConfigService } from "../../shared/services/config.service";
import { RouteService } from "../../shared/services/route.service";
@Component({
selector: "ch-accessibility",
templateUrl: "./accessibility.component.html",
styleUrls: ["./accessibility.component.less"]
})
export class AccessibilityComponent implements OnInit {
public accessibilityPath: string;
public accessibilityFile: string;
public accessibilityRouterPath = "accessibility";
constructor(
private configService: ConfigService,
private errorService: ErrorService,
private routeService: RouteService
) {}
ngOnInit() {
this.configService.get(ConfigService.KEY_ACCESSIBILITY_PATH).subscribe(
path => {
if (path) {
this.accessibilityFile = this.routeService.basename(path);
this.accessibilityPath = this.routeService.dirname(path) + "/";
log.info(
"loading custom accessibility page",
this.accessibilityPath,
this.accessibilityFile
);
}
},
err =>
this.errorService.showError(
"failed to get the path of the accessibility page",
err
)
);
}
}
| import { Component, OnInit } from "@angular/core";
import log from "loglevel";
import { ErrorService } from "../../core/errorhandler/error.service";
import { ConfigService } from "../../shared/services/config.service";
import { RouteService } from "../../shared/services/route.service";
@Component({
selector: "ch-accessibility",
templateUrl: "./accessibility.component.html",
styleUrls: ["./accessibility.component.less"]
})
export class AccessibilityComponent implements OnInit {
public accessibilityPath: string;
public accessibilityFile: string;
public accessibilityRouterPath = "accessibility";
constructor(
private configService: ConfigService,
private errorService: ErrorService,
private routeService: RouteService
) {}
ngOnInit() {
this.configService.get(ConfigService.KEY_ACCESSIBILITY_PATH).subscribe(
path => {
if (path || false) {
this.accessibilityFile = this.routeService.basename(path);
this.accessibilityPath = this.routeService.dirname(path) + "/";
log.info(
"loading custom accessibility page",
this.accessibilityPath,
this.accessibilityFile
);
} else {
this.accessibilityFile = "accessibility.html";
this.accessibilityPath = "assets/manual/";
}
},
err =>
this.errorService.showError(
"failed to get the path of the accessibility page",
err
)
);
}
}
| Add defaults to accessibility paths | Add defaults to accessibility paths
| TypeScript | mit | chipster/chipster-web,chipster/chipster-web,chipster/chipster-web | ---
+++
@@ -23,7 +23,7 @@
ngOnInit() {
this.configService.get(ConfigService.KEY_ACCESSIBILITY_PATH).subscribe(
path => {
- if (path) {
+ if (path || false) {
this.accessibilityFile = this.routeService.basename(path);
this.accessibilityPath = this.routeService.dirname(path) + "/";
log.info(
@@ -31,6 +31,9 @@
this.accessibilityPath,
this.accessibilityFile
);
+ } else {
+ this.accessibilityFile = "accessibility.html";
+ this.accessibilityPath = "assets/manual/";
}
},
err => |
5772cfdb7f1d68987dbde03eca8ec6ba2df8f830 | src/app/shared/app-details-install-instructions/app-details-install-instructions.component.ts | src/app/shared/app-details-install-instructions/app-details-install-instructions.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { App } from '../../shared/app.model';
@Component({
selector: 'store-app-details-install-instructions',
templateUrl: './app-details-install-instructions.component.html',
styleUrls: ['./app-details-install-instructions.component.scss']
})
export class AppDetailsInstallInstructionsComponent implements OnInit {
@Input() app: App;
constructor() { }
ngOnInit() {
}
public getDownloadFlatpakRefUrl() {
return window.location.href + this.app.downloadFlatpakRefUrl;
}
}
| import { Component, OnInit, Input } from '@angular/core';
import { App } from '../../shared/app.model';
@Component({
selector: 'store-app-details-install-instructions',
templateUrl: './app-details-install-instructions.component.html',
styleUrls: ['./app-details-install-instructions.component.scss']
})
export class AppDetailsInstallInstructionsComponent implements OnInit {
@Input() app: App;
constructor() { }
ngOnInit() {
}
public getDownloadFlatpakRefUrl() {
return window.location.origin + this.app.downloadFlatpakRefUrl;
}
}
| Fix app.flatpakref url in command line instructions | Fix app.flatpakref url in command line instructions
| TypeScript | apache-2.0 | jgarciao/linux-store-frontend,jgarciao/linux-store-frontend,jgarciao/linux-store-frontend | ---
+++
@@ -16,7 +16,7 @@
}
public getDownloadFlatpakRefUrl() {
- return window.location.href + this.app.downloadFlatpakRefUrl;
+ return window.location.origin + this.app.downloadFlatpakRefUrl;
}
} |
cea1d5f8c536f02c2d7b4100838fd20df85dca38 | integration/tests/login.spec.ts | integration/tests/login.spec.ts | import { expect, test } from '@playwright/test'
test('logging in with an existing account', async ({ page }) => {
await page.goto('/login')
await page.fill('input[name="username"]', 'admin')
await page.fill('input[name="password"]', 'admin1234')
await page.check('input[name="remember"]')
await page.click('[data-test=submit-button]')
const channelName = await page.innerText('[data-test=left-nav] a[href="/chat/ShieldBattery"]')
expect(channelName).toBe('#ShieldBattery')
})
test('logging in with a non-existent account', async ({ page }) => {
await page.goto('/login')
await page.fill('input[name="username"]', 'DoesNotExist')
await page.fill('input[name="password"]', 'password123')
await page.click('[data-test=submit-button]')
const errorMessage = await page.innerText('[data-test=errors-container]')
expect(errorMessage).toBe('Incorrect username or password')
})
| import { expect, test } from '@playwright/test'
test('logging in with an existing account', async ({ page }) => {
await page.goto('/login')
await page.fill('input[name="username"]', 'admin')
await page.fill('input[name="password"]', 'admin1234')
await page.check('input[name="remember"]')
await page.click('[data-test=submit-button]')
const channelName = await page.innerText('[data-test=left-nav] a[href="/chat/ShieldBattery"]')
expect(channelName).toBe('#ShieldBattery')
})
test('logging in with a non-existent account', async ({ page }) => {
await page.goto('/login')
await page.fill('input[name="username"]', 'DoesNotExist')
await page.fill('input[name="password"]', 'password123')
await page.click('[data-test=submit-button]')
const errorMessage = await page.innerText('[data-test=errors-container]')
expect(errorMessage).toBe('Incorrect username or password')
})
test('logging in with the wrong password', async ({ page }) => {
await page.goto('/login')
await page.fill('input[name="username"]', 'admin')
await page.fill('input[name="password"]', 'NotMyPassword')
await page.click('[data-test=submit-button]')
const errorMessage = await page.innerText('[data-test=errors-container]')
expect(errorMessage).toBe('Incorrect username or password')
})
| Add a test for logging in with the wrong on an existing account. | Add a test for logging in with the wrong on an existing account.
| TypeScript | mit | ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery | ---
+++
@@ -20,3 +20,13 @@
const errorMessage = await page.innerText('[data-test=errors-container]')
expect(errorMessage).toBe('Incorrect username or password')
})
+
+test('logging in with the wrong password', async ({ page }) => {
+ await page.goto('/login')
+ await page.fill('input[name="username"]', 'admin')
+ await page.fill('input[name="password"]', 'NotMyPassword')
+ await page.click('[data-test=submit-button]')
+
+ const errorMessage = await page.innerText('[data-test=errors-container]')
+ expect(errorMessage).toBe('Incorrect username or password')
+}) |
20696ad508d97efe1e85add6704ad05154ebf359 | packages/vue-styleguidist/src/scripts/create-server.ts | packages/vue-styleguidist/src/scripts/create-server.ts | import webpack, { Configuration } from 'webpack'
import WebpackDevServer from 'webpack-dev-server'
import merge from 'webpack-merge'
import { StyleguidistConfig } from '../types/StyleGuide'
import makeWebpackConfig from './make-webpack-config'
import { ServerInfo } from './binutils'
export default function createServer(
config: StyleguidistConfig,
env: 'development' | 'production' | 'none'
): ServerInfo {
const webpackConfig: Configuration = makeWebpackConfig(config, env)
const { devServer: webpackDevServerConfig } = merge(
{
devServer: {
noInfo: true,
compress: true,
clientLogLevel: 'none',
hot: true,
injectClient: false,
quiet: true,
watchOptions: {
ignored: /node_modules/
},
watchContentBase: config.assetsDir !== undefined,
stats: webpackConfig.stats || {},
headers: {
'Access-Control-Allow-Origin': '*'
}
}
},
{
devServer: webpackConfig.devServer
},
{
devServer: {
contentBase: config.assetsDir
}
}
)
const compiler = webpack(webpackConfig)
const devServer = new WebpackDevServer(compiler, webpackDevServerConfig)
// User defined customizations
if (config.configureServer) {
config.configureServer(devServer, env)
}
return { app: devServer, compiler }
}
| import webpack, { Configuration } from 'webpack'
import WebpackDevServer from 'webpack-dev-server'
import merge from 'webpack-merge'
import { StyleguidistConfig } from '../types/StyleGuide'
import makeWebpackConfig from './make-webpack-config'
import { ServerInfo } from './binutils'
export default function createServer(
config: StyleguidistConfig,
env: 'development' | 'production' | 'none'
): ServerInfo {
const webpackConfig: Configuration = makeWebpackConfig(config, env)
const { devServer: webpackDevServerConfig } = merge(
{
devServer: {
noInfo: true,
compress: true,
clientLogLevel: 'none',
hot: true,
injectClient: false,
quiet: true,
watchOptions: {
ignored: /node_modules/
},
watchContentBase: config.assetsDir !== undefined,
stats: webpackConfig.stats || {}
}
},
{
devServer: webpackConfig.devServer
},
{
devServer: {
contentBase: config.assetsDir
}
}
)
const compiler = webpack(webpackConfig)
const devServer = new WebpackDevServer(compiler, webpackDevServerConfig)
// User defined customizations
if (config.configureServer) {
config.configureServer(devServer, env)
}
return { app: devServer, compiler }
}
| Revert "fix: avoid cors issue on codesandbox" | fix: Revert "fix: avoid cors issue on codesandbox"
This reverts commit 26450b28535eeb032385a99799a05f6ccf1f7951.
| TypeScript | mit | vue-styleguidist/vue-styleguidist,vue-styleguidist/vue-styleguidist,vue-styleguidist/vue-styleguidist,vue-styleguidist/vue-styleguidist | ---
+++
@@ -23,10 +23,7 @@
ignored: /node_modules/
},
watchContentBase: config.assetsDir !== undefined,
- stats: webpackConfig.stats || {},
- headers: {
- 'Access-Control-Allow-Origin': '*'
- }
+ stats: webpackConfig.stats || {}
}
},
{ |
69c894c8bf7d1772086a89e9fb45ca5055382137 | step-release-vis/src/app/models/Candidate.ts | step-release-vis/src/app/models/Candidate.ts | import {Polygon} from './Polygon';
export class Candidate {
candName: string;
color: number;
polygons: Polygon[];
constructor(candName: string, color: number) {
this.candName = candName;
this.color = color;
}
polygonHovered(): void {}
polygonUnhovered(): void {}
}
| import {Polygon} from './Polygon';
export class Candidate {
candName: string;
color: number;
polygons: Polygon[];
constructor(candName: string, color: number) {
this.candName = candName;
this.color = color;
}
polygonHovered(): void {
this.polygons.map(polygon => (polygon.highlight = true));
}
polygonUnhovered(): void {
this.polygons.map(polygon => (polygon.highlight = true));
}
}
| Add methods for hovering/unvovering over candidate. | Add methods for hovering/unvovering over candidate.
| TypeScript | apache-2.0 | googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020 | ---
+++
@@ -10,7 +10,11 @@
this.color = color;
}
- polygonHovered(): void {}
+ polygonHovered(): void {
+ this.polygons.map(polygon => (polygon.highlight = true));
+ }
- polygonUnhovered(): void {}
+ polygonUnhovered(): void {
+ this.polygons.map(polygon => (polygon.highlight = true));
+ }
} |
aa6a655de7e18e7d5987728510a66c7c32290f3e | lib/mappers/AttributesMapper.ts | lib/mappers/AttributesMapper.ts | import {AttributesMetadata} from "../metadata/AttributesMetadata";
import {Type} from "../utils/types";
import {isPresent} from "../utils/core";
import {GraphEntity} from "../model";
import {ExtensionsRowMapper} from "./ExtensionsRowMapper";
import {TransformContext} from "../extensions/IRowTransformer";
export class AttributesMapper<T extends GraphEntity> {
constructor(private klass:Type<T>,
private extensionsRowMapper:ExtensionsRowMapper) {}
private get attributesMetadata():AttributesMetadata {
return AttributesMetadata.getForClass(this.klass);
}
mapToInstance(record):T {
if (!isPresent(record)) {
return record;
}
let instance = new this.klass();
let propertiesNames = this.attributesMetadata.getAttributesNames();
propertiesNames.forEach(prop => {
let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
if (isPresent(record.properties[prop])) {
instance[prop] = attributeMetadata.fromRowMapper(record.properties[prop]);
}
});
return instance as T;
}
mapToRow(nodeInstance, type:TransformContext) {
let row:any = {};
let propertiesNames = this.attributesMetadata.getAttributesNames();
propertiesNames.forEach(prop => {
let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
if (isPresent(nodeInstance[prop])) {
row[prop] = attributeMetadata.toRowMapper(nodeInstance[prop]);
}
});
row = this.extensionsRowMapper.mapToRow(row,type);
return row;
}
} | import {AttributesMetadata} from "../metadata/AttributesMetadata";
import {Type} from "../utils/types";
import {isPresent} from "../utils/core";
import {GraphEntity} from "../model";
import {ExtensionsRowMapper} from "./ExtensionsRowMapper";
import {TransformContext} from "../extensions/IRowTransformer";
export class AttributesMapper<T extends GraphEntity> {
constructor(private klass:Type<T>,
private extensionsRowMapper:ExtensionsRowMapper) {}
private get attributesMetadata():AttributesMetadata {
return AttributesMetadata.getForClass(this.klass);
}
private get hasAnyAttributes():boolean {
return !!this.attributesMetadata;
}
mapToInstance(record):T {
if (!isPresent(record)) {
return record;
}
let instance = new this.klass();
if (this.hasAnyAttributes) {
let propertiesNames = this.attributesMetadata.getAttributesNames();
propertiesNames.forEach(prop => {
let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
if (isPresent(record.properties[prop])) {
instance[prop] = attributeMetadata.fromRowMapper(record.properties[prop]);
}
});
}
return instance as T;
}
mapToRow(nodeInstance, type:TransformContext) {
let row:any = {};
if (this.hasAnyAttributes) {
let propertiesNames = this.attributesMetadata.getAttributesNames();
propertiesNames.forEach(prop => {
let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
if (isPresent(nodeInstance[prop])) {
row[prop] = attributeMetadata.toRowMapper(nodeInstance[prop]);
}
});
}
row = this.extensionsRowMapper.mapToRow(row, type);
return row;
}
} | Fix bug related to mapping relation without any defined attribute | Fix bug related to mapping relation without any defined attribute
| TypeScript | mit | robak86/neography | ---
+++
@@ -15,20 +15,26 @@
return AttributesMetadata.getForClass(this.klass);
}
+ private get hasAnyAttributes():boolean {
+ return !!this.attributesMetadata;
+ }
+
mapToInstance(record):T {
if (!isPresent(record)) {
return record;
}
let instance = new this.klass();
- let propertiesNames = this.attributesMetadata.getAttributesNames();
- propertiesNames.forEach(prop => {
- let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
- if (isPresent(record.properties[prop])) {
- instance[prop] = attributeMetadata.fromRowMapper(record.properties[prop]);
- }
- });
+ if (this.hasAnyAttributes) {
+ let propertiesNames = this.attributesMetadata.getAttributesNames();
+ propertiesNames.forEach(prop => {
+ let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
+ if (isPresent(record.properties[prop])) {
+ instance[prop] = attributeMetadata.fromRowMapper(record.properties[prop]);
+ }
+ });
+ }
return instance as T;
}
@@ -36,15 +42,17 @@
mapToRow(nodeInstance, type:TransformContext) {
let row:any = {};
- let propertiesNames = this.attributesMetadata.getAttributesNames();
- propertiesNames.forEach(prop => {
- let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
- if (isPresent(nodeInstance[prop])) {
- row[prop] = attributeMetadata.toRowMapper(nodeInstance[prop]);
- }
- });
+ if (this.hasAnyAttributes) {
+ let propertiesNames = this.attributesMetadata.getAttributesNames();
+ propertiesNames.forEach(prop => {
+ let attributeMetadata = this.attributesMetadata.getAttributeMetadata(prop);
+ if (isPresent(nodeInstance[prop])) {
+ row[prop] = attributeMetadata.toRowMapper(nodeInstance[prop]);
+ }
+ });
+ }
- row = this.extensionsRowMapper.mapToRow(row,type);
+ row = this.extensionsRowMapper.mapToRow(row, type);
return row;
} |
5f6c1d8c5f43cfe930246d1c6645dd8f0bf7366c | src/main/ts/ephox/bridge/components/dialog/Collection.ts | src/main/ts/ephox/bridge/components/dialog/Collection.ts | import { FieldProcessorAdt, FieldSchema, ValueSchema } from '@ephox/boulder';
import { Result } from '@ephox/katamari';
import { FormComponent, FormComponentApi, formComponentFields } from './FormComponent';
export interface CollectionApi extends FormComponentApi {
type: 'collection';
columns?: number | 'auto';
}
export interface Collection extends FormComponent {
type: 'collection';
columns: number | 'auto';
}
export const collectionFields: FieldProcessorAdt[] = formComponentFields.concat([
FieldSchema.defaulted('columns', 1)
]);
export const collectionSchema = ValueSchema.objOf(collectionFields);
// TODO: Make type for CollectionItem
export const collectionDataProcessor = ValueSchema.arrOfObj([
FieldSchema.strictString('value'),
FieldSchema.optionString('text'),
FieldSchema.optionString('icon')
]);
export const createCollection = (spec: CollectionApi): Result<Collection, ValueSchema.SchemaError<any>> => {
return ValueSchema.asRaw<Collection>('collection', collectionSchema, spec);
}; | import { FieldProcessorAdt, FieldSchema, ValueSchema } from '@ephox/boulder';
import { Result } from '@ephox/katamari';
import { FormComponent, FormComponentApi, formComponentFields } from './FormComponent';
export interface CollectionApi extends FormComponentApi {
type: 'collection';
// TODO TINY-3229 implement collection columns properly
// columns?: number | 'auto';
}
export interface Collection extends FormComponent {
type: 'collection';
columns: number | 'auto';
}
export const collectionFields: FieldProcessorAdt[] = formComponentFields.concat([
FieldSchema.defaulted('columns', 'auto')
]);
export const collectionSchema = ValueSchema.objOf(collectionFields);
// TODO: Make type for CollectionItem
export const collectionDataProcessor = ValueSchema.arrOfObj([
FieldSchema.strictString('value'),
FieldSchema.optionString('text'),
FieldSchema.optionString('icon')
]);
export const createCollection = (spec: CollectionApi): Result<Collection, ValueSchema.SchemaError<any>> => {
return ValueSchema.asRaw<Collection>('collection', collectionSchema, spec);
}; | Disable the columns property in the collection component for release, it will return later | TINY-3229: Disable the columns property in the collection component for release, it will return later
| TypeScript | mit | tinymce/tinymce,TeamupCom/tinymce,FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,tinymce/tinymce,FernCreek/tinymce,TeamupCom/tinymce | ---
+++
@@ -5,7 +5,8 @@
export interface CollectionApi extends FormComponentApi {
type: 'collection';
- columns?: number | 'auto';
+ // TODO TINY-3229 implement collection columns properly
+ // columns?: number | 'auto';
}
export interface Collection extends FormComponent {
@@ -14,7 +15,7 @@
}
export const collectionFields: FieldProcessorAdt[] = formComponentFields.concat([
- FieldSchema.defaulted('columns', 1)
+ FieldSchema.defaulted('columns', 'auto')
]);
export const collectionSchema = ValueSchema.objOf(collectionFields); |
b07797cc97b81652027b7e2606886090ab085c3f | tests/cases/fourslash/importNameCodeFixDefaultExport2.ts | tests/cases/fourslash/importNameCodeFixDefaultExport2.ts | /// <reference path="fourslash.ts" />
// @allowJs: true
// @checkJs: true
// @Filename: /lib.js
////class Base { }
////export default Base;
// @Filename: /test.js
////[|class Derived extends Base { }|]
goTo.file("/test.js");
verify.importFixAtPosition([
`// @ts-ignore
class Derived extends Base { }`,
`// @ts-nocheck
class Derived extends Base { }`,
`import Base from "./lib";
class Derived extends Base { }`,]);
| /// <reference path="fourslash.ts" />
// @Filename: /lib.ts
////class Base { }
////export default Base;
// @Filename: /test.ts
////[|class Derived extends Base { }|]
goTo.file("/test.ts");
verify.importFixAtPosition([
`import Base from "./lib";
class Derived extends Base { }`,]);
| Convert test from JS to TS | Convert test from JS to TS
| TypeScript | apache-2.0 | microsoft/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,Microsoft/TypeScript,SaschaNaz/TypeScript,kitsonk/TypeScript,kitsonk/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,kpreisser/TypeScript,alexeagle/TypeScript,Microsoft/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,microsoft/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,basarat/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,weswigham/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,SaschaNaz/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,basarat/TypeScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,kpreisser/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript | ---
+++
@@ -1,21 +1,14 @@
/// <reference path="fourslash.ts" />
-// @allowJs: true
-// @checkJs: true
-
-// @Filename: /lib.js
+// @Filename: /lib.ts
////class Base { }
////export default Base;
-// @Filename: /test.js
+// @Filename: /test.ts
////[|class Derived extends Base { }|]
-goTo.file("/test.js");
+goTo.file("/test.ts");
verify.importFixAtPosition([
-`// @ts-ignore
-class Derived extends Base { }`,
-`// @ts-nocheck
-class Derived extends Base { }`,
`import Base from "./lib";
class Derived extends Base { }`,]); |
28a95f882e6da0758945e4cfc5554adf067dd651 | src/js/components/Search.tsx | src/js/components/Search.tsx | import React, { MutableRefObject } from 'react'
import { observer } from 'mobx-react'
import { useStore } from './StoreContext'
import { Input, InputAdornment } from '@material-ui/core'
import CloseButton from './CloseButton'
export type InputRefProps = { inputRef: MutableRefObject<HTMLInputElement> }
export default observer(({ inputRef }: InputRefProps) => {
const { userStore, searchStore } = useStore()
const { search, query, startType, stopType, clear } = searchStore
const endAdornment = query && (
<InputAdornment position='end'>
<CloseButton
onClick={() => {
inputRef.current.focus()
clear()
}}
/>
</InputAdornment>
)
return (
<Input
fullWidth
autoFocus={userStore.autoFocusSearch}
inputProps={{ ref: inputRef }}
placeholder='Search your tab title...'
onChange={e => search(e.target.value)}
onFocus={() => {
search(query)
startType()
}}
onBlur={() => stopType()}
value={query}
endAdornment={endAdornment}
/>
)
})
| import React, { MutableRefObject } from 'react'
import { observer } from 'mobx-react'
import { useStore } from './StoreContext'
import { Input, InputAdornment } from '@material-ui/core'
import CloseButton from './CloseButton'
export type InputRefProps = { inputRef: MutableRefObject<HTMLInputElement> }
export default observer(({ inputRef }: InputRefProps) => {
const { userStore, searchStore } = useStore()
const { search, query, startType, stopType, clear } = searchStore
const endAdornment = query && (
<InputAdornment position='end'>
<CloseButton
onClick={() => {
inputRef.current.focus()
clear()
}}
/>
</InputAdornment>
)
return (
<Input
fullWidth
autoFocus={userStore.autoFocusSearch}
inputProps={{ ref: inputRef }}
placeholder='Search your tab title... (Press "/" to focus)'
onChange={e => search(e.target.value)}
onFocus={() => {
search(query)
startType()
}}
onBlur={() => stopType()}
value={query}
endAdornment={endAdornment}
/>
)
})
| Append (Press "/" to focus) for search input hint | feat: Append (Press "/" to focus) for search input hint
| TypeScript | mit | xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2 | ---
+++
@@ -24,7 +24,7 @@
fullWidth
autoFocus={userStore.autoFocusSearch}
inputProps={{ ref: inputRef }}
- placeholder='Search your tab title...'
+ placeholder='Search your tab title... (Press "/" to focus)'
onChange={e => search(e.target.value)}
onFocus={() => {
search(query) |
037ba167a5b9b12233df14efecb31e66798b4caf | app/src/ui/repository-settings/git-ignore.tsx | app/src/ui/repository-settings/git-ignore.tsx | import * as React from 'react'
import { DialogContent } from '../dialog'
import { TextArea } from '../lib/text-area'
import { LinkButton } from '../lib/link-button'
import { Ref } from '../lib/ref'
interface IGitIgnoreProps {
readonly text: string | null
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, {}> {
public render() {
return (
<DialogContent>
<p>
Editing <Ref>.gitignore</Ref>. This file specifies intentionally
untracked files that Git should ignore. Files already tracked by Git
are not affected.
<LinkButton onClick={this.props.onShowExamples}>
Learn more
</LinkButton>
</p>
<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'
import { Ref } from '../lib/ref'
interface IGitIgnoreProps {
readonly text: string | null
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, {}> {
public render() {
return (
<DialogContent>
<p>
Editing <Ref>.gitignore</Ref>. This per-branch file specifies
intentionally untracked files that Git should ignore. Files already
tracked by Git are not affected.
<LinkButton onClick={this.props.onShowExamples}>
Learn more
</LinkButton>
</p>
<TextArea
placeholder="Ignored files"
value={this.props.text || ''}
onValueChanged={this.props.onIgnoreTextChanged}
rows={6}
/>
</DialogContent>
)
}
}
| Add 'per-branch' to make it a tiny bit more clear | Add 'per-branch' to make it a tiny bit more clear
| TypeScript | mit | j-f1/forked-desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,desktop/desktop,say25/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,say25/desktop | ---
+++
@@ -16,9 +16,9 @@
return (
<DialogContent>
<p>
- Editing <Ref>.gitignore</Ref>. This file specifies intentionally
- untracked files that Git should ignore. Files already tracked by Git
- are not affected.
+ Editing <Ref>.gitignore</Ref>. This per-branch file specifies
+ intentionally untracked files that Git should ignore. Files already
+ tracked by Git are not affected.
<LinkButton onClick={this.props.onShowExamples}>
Learn more
</LinkButton> |
3fd6edb593445334d46d851e1ed8a1c5adfbdab1 | packages/truffle-db/src/db.ts | packages/truffle-db/src/db.ts | import { graphql, GraphQLSchema } from "graphql";
import { schema } from "truffle-db/data";
import { Workspace } from "truffle-db/workspace";
interface IConfig {
contracts_build_directory: string,
working_directory?: string
}
interface IContext {
artifactsDirectory: string,
workingDirectory: string,
workspace: Workspace
}
export class TruffleDB {
schema: GraphQLSchema;
context: IContext;
constructor (config: IConfig) {
this.context = TruffleDB.createContext(config);
this.schema = schema;
}
async query (query: string, variables: any): Promise<any> {
return await graphql(this.schema, query, null, this.context, variables);
}
static createContext(config: IConfig): IContext {
return {
workspace: new Workspace(),
artifactsDirectory: config.contracts_build_directory,
workingDirectory: config.working_directory || process.cwd()
}
}
}
| import {
GraphQLSchema,
DocumentNode,
parse,
execute
} from "graphql";
import { schema } from "truffle-db/data";
import { Workspace } from "truffle-db/workspace";
interface IConfig {
contracts_build_directory: string,
working_directory?: string
}
interface IContext {
artifactsDirectory: string,
workingDirectory: string,
workspace: Workspace
}
export class TruffleDB {
schema: GraphQLSchema;
context: IContext;
constructor (config: IConfig) {
this.context = TruffleDB.createContext(config);
this.schema = schema;
}
async query (
query: DocumentNode | string,
variables: any = {}
):
Promise<any>
{
const document: DocumentNode =
(typeof query !== "string")
? query
: parse(query);
return await execute(
this.schema, document, null, this.context, variables
);
}
static createContext(config: IConfig): IContext {
return {
workspace: new Workspace(),
artifactsDirectory: config.contracts_build_directory,
workingDirectory: config.working_directory || process.cwd()
}
}
}
| Allow DB to query strings or DocumentNodes | Allow DB to query strings or DocumentNodes
- Detect document to be string or pre-parsed value
- Use graphql.execute instead of graphql.graphql, parsing if necessary
- Also, allow `variables` argument to be omitted
| TypeScript | mit | ConsenSys/truffle | ---
+++
@@ -1,4 +1,10 @@
-import { graphql, GraphQLSchema } from "graphql";
+import {
+ GraphQLSchema,
+ DocumentNode,
+ parse,
+ execute
+} from "graphql";
+
import { schema } from "truffle-db/data";
import { Workspace } from "truffle-db/workspace";
@@ -23,8 +29,20 @@
this.schema = schema;
}
- async query (query: string, variables: any): Promise<any> {
- return await graphql(this.schema, query, null, this.context, variables);
+ async query (
+ query: DocumentNode | string,
+ variables: any = {}
+ ):
+ Promise<any>
+ {
+ const document: DocumentNode =
+ (typeof query !== "string")
+ ? query
+ : parse(query);
+
+ return await execute(
+ this.schema, document, null, this.context, variables
+ );
}
static createContext(config: IConfig): IContext { |
5dda9601f72d99b05438aa3ea11ddddb2ff64e15 | app/components/searchBox.tsx | app/components/searchBox.tsx | export default function SearchBox({
text,
onChange,
}: {
text: string;
onChange: (text: string) => void;
}) {
return (
<div>
<style jsx={true}>{`
.search_input {
width: 100%;
outline: none;
padding: 22px 10px 16px 52px;
color: #ffffff;
transition: ease-in-out, 0.35s ease-in-out;
border: none;
box-shadow: 2px 1px 3px gray;
font-size: 12pt;
font-weight: none;
background: #ee6e73 url(/search_icon_color_feature.svg) no-repeat
scroll 20px 22px;
}
.search_input:focus {
color: #000000;
background: #ffffff url(/search_icon_color_black.svg) no-repeat scroll
20px 22px;
}
.search_input:focus ::placeholder {
color: #999999;
}
.search_input ::placeholder {
color: #eebdbf;
}
`}</style>
<div>
<input
className="search_input"
placeholder="Search gifs"
value={text}
onChange={(e) => onChange(e.target.value)}
/>
</div>
</div>
);
}
| export default function SearchBox({
text,
onChange,
}: {
text: string;
onChange: (text: string) => void;
}) {
return (
<div>
<style jsx={true}>{`
.search_input {
width: 100%;
outline: none;
padding: 22px 10px 16px 52px;
color: #ffffff;
transition: ease-in-out, 0.35s ease-in-out;
border: none;
box-shadow: 2px 1px 3px gray;
font-size: 12pt;
font-weight: none;
background: #ee6e73 url(/search_icon_color_feature.svg) no-repeat
scroll 20px 22px;
}
.search_input:focus {
color: #000000;
background: #ffffff url(/search_icon_color_black.svg) no-repeat scroll
20px 22px;
}
.search_input:focus ::placeholder {
color: #999999;
}
.search_input ::placeholder {
color: #eebdbf;
}
.search_input::-webkit-search-cancel-button {
-webkit-appearance: none;
}
`}</style>
<div>
<input
className="search_input"
placeholder="Search gifs"
type="search"
value={text}
onChange={(e) => onChange(e.target.value)}
/>
</div>
</div>
);
}
| Make search input=search but force webkit to not show x | Make search input=search but force webkit to not show x
| TypeScript | apache-2.0 | thenickreynolds/popcorngif,thenickreynolds/popcorngif | ---
+++
@@ -35,11 +35,16 @@
.search_input ::placeholder {
color: #eebdbf;
}
+
+ .search_input::-webkit-search-cancel-button {
+ -webkit-appearance: none;
+ }
`}</style>
<div>
<input
className="search_input"
placeholder="Search gifs"
+ type="search"
value={text}
onChange={(e) => onChange(e.target.value)}
/> |
fb0cf55456c142671a8f4603e5ed4e3cc534f1e5 | app/src/component/Button.tsx | app/src/component/Button.tsx | import * as React from "react";
import "./style/Button.css";
interface IProps {
className?: string;
onClick?: () => void;
onMouseOver?: () => void;
onMouseOut?: () => void;
style?: object;
type?: string;
}
export default class extends React.Component<IProps> {
public render() {
const { children, className, onClick, onMouseOver, onMouseOut, style, type }
= this.props;
return (
<button
className={"Button-container " + className}
onClick={(event) => {
onClick();
event.stopPropagation();
}}
onMouseOver={onMouseOver}
onMouseOut={onMouseOut}
style={style}
type={type}
>
{children}
</button>
);
}
}
| import * as React from "react";
import "./style/Button.css";
interface IProps {
className?: string;
onClick?: () => void;
onMouseOver?: () => void;
onMouseOut?: () => void;
style?: object;
type?: string;
}
export default class extends React.Component<IProps> {
public render() {
const { children, className, onClick, onMouseOver, onMouseOut, style, type }
= this.props;
return (
<button
className={"Button-container " + className}
onClick={onClick && ((event) => {
onClick();
event.stopPropagation();
})}
onMouseOver={onMouseOver}
onMouseOut={onMouseOut}
style={style}
type={type}
>
{children}
</button>
);
}
}
| Set undefined to onClick prop when nothing is provided by parent | Set undefined to onClick prop when nothing is provided by parent
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -19,10 +19,10 @@
return (
<button
className={"Button-container " + className}
- onClick={(event) => {
+ onClick={onClick && ((event) => {
onClick();
event.stopPropagation();
- }}
+ })}
onMouseOver={onMouseOver}
onMouseOut={onMouseOut}
style={style} |
b4e0304f2fbd5c0c63d201b5f8976cd198140773 | app/utils/permalink/index.ts | app/utils/permalink/index.ts | // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Keyboard} from 'react-native';
import {OptionsModalPresentationStyle} from 'react-native-navigation';
import {dismissAllModals, showModalOverCurrentContext} from '@screens/navigation';
import {changeOpacity} from '@utils/theme';
let showingPermalink = false;
export const displayPermalink = async (teamName: string, postId: string, openAsPermalink = true) => {
Keyboard.dismiss();
if (showingPermalink) {
await dismissAllModals();
}
const screen = 'Permalink';
const passProps = {
isPermalink: openAsPermalink,
teamName,
postId,
};
const options = {
modalPresentationStyle: OptionsModalPresentationStyle.fullScreen,
layout: {
componentBackgroundColor: changeOpacity('#000', 0.2),
},
};
showingPermalink = true;
showModalOverCurrentContext(screen, passProps, options);
};
export const closePermalink = () => {
showingPermalink = false;
};
| // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Keyboard} from 'react-native';
import {OptionsModalPresentationStyle} from 'react-native-navigation';
import {dismissAllModals, showModalOverCurrentContext} from '@screens/navigation';
import {changeOpacity} from '@utils/theme';
let showingPermalink = false;
export const displayPermalink = async (teamName: string, postId: string, openAsPermalink = true) => {
Keyboard.dismiss();
if (showingPermalink) {
await dismissAllModals();
}
const screen = 'Permalink';
const passProps = {
isPermalink: openAsPermalink,
teamName,
postId,
};
const options = {
modalPresentationStyle: OptionsModalPresentationStyle.overFullScreen,
layout: {
componentBackgroundColor: changeOpacity('#000', 0.2),
},
};
showingPermalink = true;
showModalOverCurrentContext(screen, passProps, options);
};
export const closePermalink = () => {
showingPermalink = false;
};
| Change permalink modal to overFullScreen | Change permalink modal to overFullScreen
| TypeScript | apache-2.0 | mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile,mattermost/mattermost-mobile | ---
+++
@@ -23,7 +23,7 @@
};
const options = {
- modalPresentationStyle: OptionsModalPresentationStyle.fullScreen,
+ modalPresentationStyle: OptionsModalPresentationStyle.overFullScreen,
layout: {
componentBackgroundColor: changeOpacity('#000', 0.2),
}, |
b36f994d0110df0db09c2a66a932a0c6b155c131 | src/ts/config/db.ts | src/ts/config/db.ts | /// <reference path="../core/migraterList" />
namespace YJMCNT.Config.DB {
export const name = 'counter';
export const version = 0;
export const READONLY = "readonry";
export const READWRITE = "readwrite";
var Migrater = YJMCNT.Core.Migrater;
export const migraters = new YJMCNT.Core.MigraterList([
new Migrater((db: IDBDatabase) => {
}),
new Migrater((db: IDBDatabase) => {
}),
]);
}
| /// <reference path="../core/migraterList" />
namespace YJMCNT.Config.DB {
export const name = 'counter';
export const version = 1;
export const READONLY = "readonry";
export const READWRITE = "readwrite";
var Migrater = YJMCNT.Core.Migrater;
export const migraters = new YJMCNT.Core.MigraterList([
new Migrater((db: IDBDatabase) => {
}),
new Migrater((db: IDBDatabase) => {
db.createObjectStore('counters', { keyPath: "id" });
}),
]);
}
| Edit migration: add object store | Edit migration: add object store
counters
| TypeScript | mit | yajamon/chrome-ext-counter,yajamon/chrome-ext-counter,yajamon/chrome-ext-counter | ---
+++
@@ -2,7 +2,7 @@
namespace YJMCNT.Config.DB {
export const name = 'counter';
- export const version = 0;
+ export const version = 1;
export const READONLY = "readonry";
export const READWRITE = "readwrite";
@@ -11,6 +11,7 @@
new Migrater((db: IDBDatabase) => {
}),
new Migrater((db: IDBDatabase) => {
+ db.createObjectStore('counters', { keyPath: "id" });
}),
]);
} |
bcbdd12ce1b2ddf7a54ce57e38dc9a3f35353d65 | components/locale-provider/LocaleReceiver.tsx | components/locale-provider/LocaleReceiver.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
export interface LocaleReceiverProps {
componentName: string;
defaultLocale: object | Function;
children: (locale, localeCode?) => React.ReactElement<any>;
}
export interface LocaleReceiverContext {
antLocale?: { [key: string]: any };
}
export default class LocaleReceiver extends React.Component<LocaleReceiverProps> {
static contextTypes = {
antLocale: PropTypes.object,
};
context: LocaleReceiverContext;
getLocale() {
const { componentName, defaultLocale } = this.props;
const { antLocale } = this.context;
const localeFromContext = antLocale && antLocale[componentName];
return {
...(typeof defaultLocale === 'function' ? defaultLocale() : defaultLocale),
...(localeFromContext || {}),
};
}
getLocaleCode() {
const { antLocale } = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return 'en-us';
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode());
}
}
| import * as React from 'react';
import PropTypes from 'prop-types';
export interface LocaleReceiverProps {
componentName: string;
defaultLocale: object | Function;
children: (locale: object, localeCode?: string) => React.ReactElement<any>;
}
export interface LocaleReceiverContext {
antLocale?: { [key: string]: any };
}
export default class LocaleReceiver extends React.Component<LocaleReceiverProps> {
static contextTypes = {
antLocale: PropTypes.object,
};
context: LocaleReceiverContext;
getLocale() {
const { componentName, defaultLocale } = this.props;
const { antLocale } = this.context;
const localeFromContext = antLocale && antLocale[componentName];
return {
...(typeof defaultLocale === 'function' ? defaultLocale() : defaultLocale),
...(localeFromContext || {}),
};
}
getLocaleCode() {
const { antLocale } = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return 'en-us';
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode());
}
}
| Fix implicit any error for LocalProvider | Fix implicit any error for LocalProvider
| TypeScript | mit | icaife/ant-design,RaoHai/ant-design,RaoHai/ant-design,elevensky/ant-design,RaoHai/ant-design,ant-design/ant-design,elevensky/ant-design,havefive/ant-design,zheeeng/ant-design,icaife/ant-design,zheeeng/ant-design,havefive/ant-design,icaife/ant-design,zheeeng/ant-design,ant-design/ant-design,elevensky/ant-design,icaife/ant-design,havefive/ant-design,ant-design/ant-design,RaoHai/ant-design,havefive/ant-design,zheeeng/ant-design,elevensky/ant-design,ant-design/ant-design | ---
+++
@@ -4,7 +4,7 @@
export interface LocaleReceiverProps {
componentName: string;
defaultLocale: object | Function;
- children: (locale, localeCode?) => React.ReactElement<any>;
+ children: (locale: object, localeCode?: string) => React.ReactElement<any>;
}
export interface LocaleReceiverContext { |
3023d8a2bfb99795cf2acbe0689ac20f7f840321 | examples/query/src/main.ts | examples/query/src/main.ts | import * as query from 'dojo/query';
/* An example of working with query and NodeLists */
/* Querying all the nodes of the current document. The will default to the node
list being an array of Nodes */
const results = query('*');
/* Now we are going to assert that we will be only returning HTML elements,
this now means resulting functions will be typed approriatly */
results
.filter<HTMLElement>((node) => node.parentElement === document.body)
.forEach((item) => {
/* item is typed as HTMLElement */
console.log(item.tagName);
});
/* If we want to assert what types of nodes our query will return, we can do that
upfront */
const myDiv = document.createElement('div');
const myP = document.createElement('p');
query<HTMLDivElement>('div')
.concat(myDiv)
.forEach((div) => {
console.log(div.noWrap);
});
/* it will also type guard us, for example, if you uncomment the below, you will
throw a type error */
// divs = divs.concat(myP);
| import * as query from 'dojo/query';
/* An example of working with query and NodeLists */
/* Querying all the nodes of the current document. The will default to the node
list being an array of Nodes */
const results = query('*');
/* Now we are going to assert that we will be only returning HTML elements,
this now means resulting functions will be typed appropriately */
results
.filter<HTMLElement>((node) => node.parentElement === document.body)
.forEach((item) => {
/* item is typed as HTMLElement */
console.log(item.tagName);
});
/* If we want to assert what types of nodes our query will return, we can do that
upfront */
const myDiv = document.createElement('div');
const myP = document.createElement('p');
query<HTMLDivElement>('div')
.concat(myDiv)
.forEach((div) => {
console.log(div.noWrap);
});
/* it will also type guard us, for example, if you uncomment the below, you will
throw a type error */
// divs = divs.concat(myP);
| Fix typo in example comment | Fix typo in example comment
| TypeScript | bsd-3-clause | ca0v/typings,ca0v/typings | ---
+++
@@ -7,7 +7,7 @@
const results = query('*');
/* Now we are going to assert that we will be only returning HTML elements,
- this now means resulting functions will be typed approriatly */
+ this now means resulting functions will be typed appropriately */
results
.filter<HTMLElement>((node) => node.parentElement === document.body)
.forEach((item) => { |
214686203cb6ae3db94c624d09b0c2fc810b611c | src/actors/player.ts | src/actors/player.ts | import { Actor, Color, Engine, Input, Vector } from "excalibur";
export class Player extends Actor {
static readonly speed: Vector = new Vector(5, 5);
constructor(x: number, y: number) {
super(x, y);
this.setWidth(40);
this.setHeight(40);
this.color = Color.Chartreuse;
}
public update(engine: Engine, delta: number) {
this.vel.setTo(0, 0);
if (engine.input.keyboard.isHeld(Input.Keys.Up)) {
this.vel.y = -Player.speed.y;
}
if (engine.input.keyboard.isHeld(Input.Keys.Down)) {
this.vel.y = Player.speed.y;
}
if (engine.input.keyboard.isHeld(Input.Keys.Left)) {
this.vel.x = -Player.speed.x;
}
if (engine.input.keyboard.isHeld(Input.Keys.Right)) {
this.vel.x = Player.speed.x;
}
this.pos.addEqual(this.vel);
}
}
| import { Actor, Color, Engine, Input, Vector } from "excalibur";
export class Player extends Actor {
static readonly speed: Vector = new Vector(250, 250);
constructor(x: number, y: number) {
super(x, y);
this.setWidth(40);
this.setHeight(40);
this.color = Color.Chartreuse;
}
public update(engine: Engine, delta: number) {
this.vel.setTo(0, 0);
if (engine.input.keyboard.isHeld(Input.Keys.Up)) {
this.vel.y = -Player.speed.y;
}
if (engine.input.keyboard.isHeld(Input.Keys.Down)) {
this.vel.y = Player.speed.y;
}
if (engine.input.keyboard.isHeld(Input.Keys.Left)) {
this.vel.x = -Player.speed.x;
}
if (engine.input.keyboard.isHeld(Input.Keys.Right)) {
this.vel.x = Player.speed.x;
}
super.update(engine, delta);
}
}
| Use super.update in order to smooth out movement based on delta | Use super.update in order to smooth out movement based on delta
| TypeScript | agpl-3.0 | Towerism/binary-fusion,Towerism/binary-fusion | ---
+++
@@ -1,7 +1,7 @@
import { Actor, Color, Engine, Input, Vector } from "excalibur";
export class Player extends Actor {
- static readonly speed: Vector = new Vector(5, 5);
+ static readonly speed: Vector = new Vector(250, 250);
constructor(x: number, y: number) {
super(x, y);
@@ -24,6 +24,6 @@
if (engine.input.keyboard.isHeld(Input.Keys.Right)) {
this.vel.x = Player.speed.x;
}
- this.pos.addEqual(this.vel);
+ super.update(engine, delta);
}
} |
3316539f75be2251a95afc0a6c5b9d4df470f8ce | src/index.ts | src/index.ts | import * as angular from 'angular';
import {FileComponent} from './file/FileComponent';
import {FolderComponent} from './folder/FolderComponent';
import {BucketComponent} from './bucket/BucketComponent';
import './index.css';
angular
.module('s3commander', [])
.component('file', FileComponent)
.component('folder', FolderComponent)
.component('bucket', BucketComponent);
| import * as angular from 'angular';
import {FileComponent} from './file/FileComponent';
import {FolderComponent} from './folder/FolderComponent';
import {BucketComponent} from './bucket/BucketComponent';
import './index.css';
// register components and configure the module.
angular
.module('s3commander', [])
.config(function ($sceDelegateProvider: any) {
// https://docs.angularjs.org/api/ng/provider/$sceDelegateProvider
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://s3.amazonaws.com/*',
'https://*.s3.amazonaws.com/'
]);
})
.component('file', FileComponent)
.component('folder', FolderComponent)
.component('bucket', BucketComponent);
| Configure the s3commander module to whitelist form URLs. | Configure the s3commander module to whitelist form URLs.
By default AngularJS doesn't allow you to interpolate form URLs unless
they are whitelisted in the module's security policy. I added two URLs
for the AWS S3 API to the whitelist.
| TypeScript | bsd-3-clause | nimbis/s3commander,nimbis/s3commander,nimbis/s3commander,nimbis/s3commander | ---
+++
@@ -6,8 +6,17 @@
import './index.css';
+// register components and configure the module.
angular
.module('s3commander', [])
+ .config(function ($sceDelegateProvider: any) {
+ // https://docs.angularjs.org/api/ng/provider/$sceDelegateProvider
+ $sceDelegateProvider.resourceUrlWhitelist([
+ 'self',
+ 'https://s3.amazonaws.com/*',
+ 'https://*.s3.amazonaws.com/'
+ ]);
+ })
.component('file', FileComponent)
.component('folder', FolderComponent)
.component('bucket', BucketComponent); |
36518e0a8b4c9bfca10ccda758c525c36c743aed | src/decorators/prop.decorator.ts | src/decorators/prop.decorator.ts | import { PropMetadata, PropMetadataSym, ModelPropertiesSym } from '../core/metadata';
import * as sequelize from 'sequelize';
import 'reflect-metadata';
export function Prop(propMeta?: PropMetadata) {
let meta = propMeta || {};
return function(model: any, propertyName: string) {
var props: string[] = Reflect.getOwnMetadata(ModelPropertiesSym, model) || [];
props.push(propertyName);
Reflect.defineMetadata(ModelPropertiesSym, props, model);
if (!meta.type) {
var reflectType = Reflect.getMetadata('design:type', model, propertyName);
var sequelizeType: any = null;
if (reflectType === String) sequelizeType = sequelize.STRING;
else if (reflectType === Number) sequelizeType = sequelize.FLOAT;
else if (reflectType === Date) sequelizeType = sequelize.DATE;
else if (reflectType === Boolean) sequelizeType = sequelize.BOOLEAN;
else throw new Error(`Could not infer column type for model property: ${propertyName}`);
meta.type = sequelizeType;
}
Reflect.defineMetadata(PropMetadataSym, meta, model, propertyName);
}
}
| import { PropMetadata, PropMetadataSym, ModelPropertiesSym } from '../core/metadata';
import * as sequelize from 'sequelize';
import 'reflect-metadata';
export function Prop(propMeta?: PropMetadata) {
let meta = propMeta || {};
return function(model: any, propertyName: string) {
var props: string[] = Reflect.getOwnMetadata(ModelPropertiesSym, model) || [];
props.push(propertyName);
Reflect.defineMetadata(ModelPropertiesSym, props, model);
if (!meta.type) {
var reflectType = Reflect.getMetadata('design:type', model, propertyName);
var sequelizeType: any = null;
if (reflectType === String) sequelizeType = sequelize.STRING;
else if (reflectType === Number) {
if (meta.primaryKey || meta.autoIncrement) sequelizeType = sequelize.INTEGER;
else sequelizeType = sequelize.FLOAT;
}
else if (reflectType === Date) sequelizeType = sequelize.DATE;
else if (reflectType === Boolean) sequelizeType = sequelize.BOOLEAN;
else throw new Error(`Could not infer column type for model property: ${propertyName}`);
meta.type = sequelizeType;
}
Reflect.defineMetadata(PropMetadataSym, meta, model, propertyName);
}
}
| Change default type for number if property is primary key or auto-incrementing | Change default type for number if property is primary key or auto-incrementing
| TypeScript | mit | miter-framework/miter,miter-framework/miter | ---
+++
@@ -13,7 +13,10 @@
var reflectType = Reflect.getMetadata('design:type', model, propertyName);
var sequelizeType: any = null;
if (reflectType === String) sequelizeType = sequelize.STRING;
- else if (reflectType === Number) sequelizeType = sequelize.FLOAT;
+ else if (reflectType === Number) {
+ if (meta.primaryKey || meta.autoIncrement) sequelizeType = sequelize.INTEGER;
+ else sequelizeType = sequelize.FLOAT;
+ }
else if (reflectType === Date) sequelizeType = sequelize.DATE;
else if (reflectType === Boolean) sequelizeType = sequelize.BOOLEAN;
else throw new Error(`Could not infer column type for model property: ${propertyName}`); |
daeae314faed84b03f0d9f4ddb6ab8aeed410593 | src/types.ts | src/types.ts | /**
* @license
* Copyright 2018 The Incremental DOM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// tslint:disable-next-line:no-any
export type AttrMutator = (a: HTMLElement, b: string, c: any) => void;
export type AttrMutatorConfig = {[x: string]: AttrMutator};
export type ElementConstructor = new () => Element;
export type NameOrCtorDef = string|ElementConstructor;
export type Key = string|number|null|undefined;
export type Statics = Array<{}>|null|undefined;
| /**
* @license
* Copyright 2018 The Incremental DOM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface ElementConstructor {new(): Element};
// tslint:disable-next-line:no-any
export type AttrMutator = (a: HTMLElement, b: string, c: any) => void;
export type AttrMutatorConfig = {[x: string]: AttrMutator};
export type NameOrCtorDef = string|ElementConstructor;
export type Key = string|number|null|undefined;
export type Statics = Array<{}>|null|undefined;
| Change type to play nicer with tsickle. | Change type to play nicer with tsickle.
| TypeScript | apache-2.0 | PolymerLabs/incremental-dom,google/incremental-dom,PolymerLabs/incremental-dom,google/incremental-dom,google/incremental-dom,jridgewell/incremental-dom,sparhami/incremental-dom,jridgewell/incremental-dom,sparhami/incremental-dom,sparhami/incremental-dom,jridgewell/incremental-dom,sparhami/incremental-dom,PolymerLabs/incremental-dom | ---
+++
@@ -15,12 +15,12 @@
* limitations under the License.
*/
+export interface ElementConstructor {new(): Element};
+
// tslint:disable-next-line:no-any
export type AttrMutator = (a: HTMLElement, b: string, c: any) => void;
export type AttrMutatorConfig = {[x: string]: AttrMutator};
-
-export type ElementConstructor = new () => Element;
export type NameOrCtorDef = string|ElementConstructor;
|
7bb6efec162f81422076428b3972d83a418a5929 | src/app/app.component.spec.ts | src/app/app.component.spec.ts | import { AppComponent } from './app.component';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
describe('AppComponent', function () {
let de: DebugElement;
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('h1'));
});
it('should create component', () => expect(comp).toBeDefined() );
it('should have expected <h1> text', () => {
fixture.detectChanges();
const h1 = de.nativeElement;
expect(h1.innerText).toMatch(/angular/i,
'<h1> should say something about "Angular"');
});
});
| import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { HspApiService } from './hsp-api.service';
import { ResourceService } from './national_rail/resource.service';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common'
describe('AppComponent', function () {
let de: DebugElement;
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
// Configure the test bed
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ],
imports: [ AppModule ],
providers: [
{provide: APP_BASE_HREF, useValue: '/'}
]
})
.compileComponents();
}));
// Create the component under test
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('h1'));
});
// Test component created
it('should create component', () => expect(comp).toBeDefined() );
// Test title
it('should have expected <h1> text', () => {
fixture.detectChanges();
const h1 = de.nativeElement;
expect(h1.innerText).toMatch(/Late Mate/i,
'<h1> should say something about "Late Mate"');
});
});
| Fix up simple app test | Fix up simple app test
| TypeScript | mit | briggySmalls/late-train-mate,briggySmalls/late-train-mate,briggySmalls/late-train-mate | ---
+++
@@ -1,33 +1,45 @@
import { AppComponent } from './app.component';
+import { AppModule } from './app.module';
+import { HspApiService } from './hsp-api.service';
+import { ResourceService } from './national_rail/resource.service';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
+import { APP_BASE_HREF } from '@angular/common'
describe('AppComponent', function () {
let de: DebugElement;
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
+ // Configure the test bed
beforeEach(async(() => {
TestBed.configureTestingModule({
- declarations: [ AppComponent ]
+ declarations: [ ],
+ imports: [ AppModule ],
+ providers: [
+ {provide: APP_BASE_HREF, useValue: '/'}
+ ]
})
.compileComponents();
}));
+ // Create the component under test
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('h1'));
});
+ // Test component created
it('should create component', () => expect(comp).toBeDefined() );
+ // Test title
it('should have expected <h1> text', () => {
fixture.detectChanges();
const h1 = de.nativeElement;
- expect(h1.innerText).toMatch(/angular/i,
- '<h1> should say something about "Angular"');
+ expect(h1.innerText).toMatch(/Late Mate/i,
+ '<h1> should say something about "Late Mate"');
});
}); |
3f2d9f176a30cf3c0e475355b00a4b43648fb7b7 | src/components/preference-item/preference-item.component.ts | src/components/preference-item/preference-item.component.ts | import { Component, Host, Input, OnInit, Optional } from '@angular/core';
import { Preference } from '../../services/preference/types';
import { PreferenceGroupComponent } from '../preference-group/preference-group.component';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-preference-item',
templateUrl: './preference-item.component.html',
styleUrls: ['./preference-item.component.scss'],
})
export class PreferenceItemComponent<T extends Preference, U extends keyof T> implements OnInit {
@Input() name: string;
// the component should either be nested under PreferenceGroupComponent, or have the preference$ property provided
@Input() preference$: BehaviorSubject<T>;
@Input() property: U;
constructor(
@Optional() @Host() private host: PreferenceGroupComponent<T> | null,
) {
}
get type(): string {
return typeof this.value;
}
get value(): T[U] {
return this.preference$.value[this.property];
}
set value(value: T[U]) {
this.preference$.next({
...this.preference$.value,
[this.property]: value,
});
}
ngOnInit() {
if (this.host && !this.preference$) {
this.preference$ = this.host.preference$;
}
}
}
| import { Component, Host, Input, OnInit, Optional } from '@angular/core';
import { Preference } from '../../services/preference/types';
import { PreferenceGroupComponent } from '../preference-group/preference-group.component';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-preference-item',
templateUrl: './preference-item.component.html',
styleUrls: ['./preference-item.component.scss'],
})
export class PreferenceItemComponent<T extends Preference, U extends keyof T> implements OnInit {
@Input() name: string;
// the component should either be nested under PreferenceGroupComponent, or have the preference$ property provided
@Input() preference$: BehaviorSubject<T>;
@Input() property: U;
constructor(
@Optional() @Host() private host: PreferenceGroupComponent<T> | null,
) {
}
get type(): string {
return typeof this.value;
}
get value(): T[U] {
return this.preference$.value[this.property];
}
set value(value: T[U]) {
if (value !== undefined && value !== null) {
this.preference$.next({
...this.preference$.value,
[this.property]: value,
});
}
}
ngOnInit() {
if (this.host && !this.preference$) {
this.preference$ = this.host.preference$;
}
}
}
| Fix preference-item input element disappearing issue | Fix preference-item input element disappearing issue
| TypeScript | apache-2.0 | googleinterns/guide-doge,googleinterns/guide-doge,googleinterns/guide-doge | ---
+++
@@ -29,10 +29,12 @@
}
set value(value: T[U]) {
- this.preference$.next({
- ...this.preference$.value,
- [this.property]: value,
- });
+ if (value !== undefined && value !== null) {
+ this.preference$.next({
+ ...this.preference$.value,
+ [this.property]: value,
+ });
+ }
}
ngOnInit() { |
3d2ee519360a78e425fbd7b4c8fa098878b94843 | problems/complementary-colours/solution.ts | problems/complementary-colours/solution.ts | import {ISolution} from '../solution.interface';
export class Solution implements ISolution<string, string> {
static CHARS = "0123456789abcdef";
solve(input: string) {
var pairs = {};
for (var c = 0; c < Solution.CHARS.length; c++) {
pairs[Solution.CHARS[c]] = Solution.CHARS[Solution.CHARS.length - 1 - c];
}
return "#" + pairs[input[1]] + pairs[input[2]]
+ pairs[input[3]] + pairs[input[4]]
+ pairs[input[5]] + pairs[input[6]];
}
}
| import {ISolution} from '../solution.interface';
export class Solution implements ISolution<string, string> {
solve(x: string) {
for (var i = 0, c = "0123456789abcdef", p = {}; i < 16; i++) {
p[c[i]] = c[15 - i];
}
return "#" + p[x[1]] + p[x[2]]
+ p[x[3]] + p[x[4]]
+ p[x[5]] + p[x[6]];
}
}
| Make complementary-colours a bit more code-golfy | Make complementary-colours a bit more code-golfy
| TypeScript | unlicense | Jameskmonger/challenges | ---
+++
@@ -1,16 +1,13 @@
import {ISolution} from '../solution.interface';
export class Solution implements ISolution<string, string> {
- static CHARS = "0123456789abcdef";
-
- solve(input: string) {
- var pairs = {};
- for (var c = 0; c < Solution.CHARS.length; c++) {
- pairs[Solution.CHARS[c]] = Solution.CHARS[Solution.CHARS.length - 1 - c];
+ solve(x: string) {
+ for (var i = 0, c = "0123456789abcdef", p = {}; i < 16; i++) {
+ p[c[i]] = c[15 - i];
}
- return "#" + pairs[input[1]] + pairs[input[2]]
- + pairs[input[3]] + pairs[input[4]]
- + pairs[input[5]] + pairs[input[6]];
+ return "#" + p[x[1]] + p[x[2]]
+ + p[x[3]] + p[x[4]]
+ + p[x[5]] + p[x[6]];
}
} |
276c2466b24b24a57433febee7edc7dc1ac07a10 | dev-kits/addon-roundtrip/src/register.tsx | dev-kits/addon-roundtrip/src/register.tsx | import React from 'react';
import { addons, types } from '@storybook/addons';
import { ADDON_ID, PANEL_ID } from './constants';
import { Panel } from './panel';
addons.register(ADDON_ID, () => {
addons.add('placeholder', {
title: 'empty placeholder',
type: types.PANEL,
render: ({ active, key }) => (
<div hidden={!active} key={key}>
{active}Empty indeed
</div>
),
});
addons.add(PANEL_ID, {
title: 'roundtrip',
type: types.PANEL,
render: ({ active, key }) => <Panel key={key} active={active} />,
});
});
| import React from 'react';
import { addons, types } from '@storybook/addons';
import { ADDON_ID, PANEL_ID } from './constants';
import { Panel } from './panel';
addons.register(ADDON_ID, () => {
addons.add(PANEL_ID, {
title: 'roundtrip',
type: types.PANEL,
render: ({ active, key }) => <Panel key={key} active={active} />,
});
});
| DELETE the placeholder addon panel | DELETE the placeholder addon panel
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook | ---
+++
@@ -5,15 +5,6 @@
import { Panel } from './panel';
addons.register(ADDON_ID, () => {
- addons.add('placeholder', {
- title: 'empty placeholder',
- type: types.PANEL,
- render: ({ active, key }) => (
- <div hidden={!active} key={key}>
- {active}Empty indeed
- </div>
- ),
- });
addons.add(PANEL_ID, {
title: 'roundtrip',
type: types.PANEL, |
7999b286227ec4561bdb1e3a24546275d81e5c99 | src/Components/Publishing/ToolTip/Components/Description.tsx | src/Components/Publishing/ToolTip/Components/Description.tsx | import { garamond } from "Assets/Fonts"
import { Truncator } from "Components/Truncator"
import React from "react"
import Markdown from "react-markdown"
import styled from "styled-components"
interface Props {
text: string
}
export const ToolTipDescription: React.SFC<Props> = props => {
const { text } = props
return (
<Description>
<Truncator maxLineCount={3}>
<Markdown
source={text}
containerTagName="span"
disallowedTypes={["Link", "Paragraph"]}
unwrapDisallowed
/>
</Truncator>
</Description>
)
}
const Description = styled.div`
${garamond("s15")};
p,
p:first-child::first-letter {
margin: 0;
${garamond("s15")};
}
padding-bottom: 10px;
`
| import { garamond } from "Assets/Fonts"
import { Truncator } from "Components/Truncator"
import React from "react"
import Markdown from "react-markdown"
import styled from "styled-components"
interface Props {
text: string
}
export const ToolTipDescription: React.SFC<Props> = props => {
const { text } = props
return (
<Description>
<Truncator maxLineCount={3}>
<Markdown
source={text}
containerTagName="span"
disallowedTypes={["Link", "Paragraph"]}
unwrapDisallowed
/>
</Truncator>
</Description>
)
}
const Description = styled.div`
${garamond("s15")};
p,
p:first-child::first-letter {
margin: 0;
${garamond("s15")};
}
padding-bottom: 10px;
white-space: initial;
`
| Add white-space CSS property to fix overflowing descriptions | Add white-space CSS property to fix overflowing descriptions
| TypeScript | mit | artsy/reaction,artsy/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction | ---
+++
@@ -34,4 +34,5 @@
${garamond("s15")};
}
padding-bottom: 10px;
+ white-space: initial;
` |
e0b1354f5cdb4a74a8ef1d4c2497802a3b45f5d0 | app/dashboard/component.ts | app/dashboard/component.ts | import { Component, OnInit } from '@angular/core';
declare var electron: any;
@Component({
selector:'<dashboard>',
templateUrl: 'app/dashboard/template.html',
styleUrls: ['app/dashboard/style.css']
})
export class Dashboard implements OnInit {
ngOnInit():void {
}
} | import { Component, OnInit } from '@angular/core';
import { Task } from '../models/task';
import { Tasks } from '../tasks/service';
declare var electron: any;
@Component({
selector:'<dashboard>',
templateUrl: 'app/dashboard/template.html',
styleUrls: ['app/dashboard/style.css']
})
export class Dashboard implements OnInit {
taskList: Task[] = [];
expandedList: string[] = [];
constructor(private tasks: Tasks) {}
ngOnInit():void {
this.tasks.getUncomplete().then(taskList => {
this.taskList = taskList;
})
}
toggle(_id: string) {
if (this.expandedList.includes(_id)) {
this.expandedList = this.expandedList.filter(id => {
return id != _id;
})
} else {
this.expandedList.push(_id);
}
}
} | Add basic function (list, expandable) | Add basic function (list, expandable)
| TypeScript | mit | FreeMasen/time.manager,FreeMasen/time.manager,FreeMasen/time.manager | ---
+++
@@ -1,4 +1,7 @@
import { Component, OnInit } from '@angular/core';
+
+import { Task } from '../models/task';
+import { Tasks } from '../tasks/service';
declare var electron: any;
@Component({
@@ -7,7 +10,24 @@
styleUrls: ['app/dashboard/style.css']
})
export class Dashboard implements OnInit {
+ taskList: Task[] = [];
+ expandedList: string[] = [];
+
+ constructor(private tasks: Tasks) {}
ngOnInit():void {
+ this.tasks.getUncomplete().then(taskList => {
+ this.taskList = taskList;
+ })
+ }
+
+ toggle(_id: string) {
+ if (this.expandedList.includes(_id)) {
+ this.expandedList = this.expandedList.filter(id => {
+ return id != _id;
+ })
+ } else {
+ this.expandedList.push(_id);
+ }
}
} |
cfc4b9d955a26606a554e210f4914829181b5267 | src/server/controllers/settings/priority-issues.ts | src/server/controllers/settings/priority-issues.ts | import {GithubRepo} from '../../models/githubAppModel';
import {AppPlugin, settings} from '../github-app-settings';
import {addLabels, deleteLabels} from './manage-github-labels';
// TODO: Conditional types might allow us to define this from config()
export interface PluginSetting {
'issues.priorityIssues': boolean;
}
class PriorityIssuePlugin implements AppPlugin {
config() {
return {
'issues.priorityIssues': {
default: false,
description: 'Adds P0 - P3 labels in all repo\'s',
type: 'boolean',
},
};
}
async settingsChanged(
settingConfig: PluginSetting,
token: string,
repos: GithubRepo[]) {
const priorityLabels = [
{name: 'P0', description: 'Critical', color: 'd0021b'},
{name: 'P1', description: 'Need', color: 'd0021b'},
{name: 'P2', description: 'Want', color: '0071eb'},
{name: 'P3', description: 'Not Critical', color: '0071eb'},
];
if (!settingConfig['issues.priorityIssues']) {
for (const repo of repos) {
deleteLabels(token, repo, priorityLabels);
}
} else {
for (const repo of repos) {
addLabels(token, repo, priorityLabels);
}
}
}
}
settings.registerPlugin(new PriorityIssuePlugin());
| import {GithubRepo} from '../../models/githubAppModel';
import {AppPlugin, settings} from '../github-app-settings';
import {addLabels, deleteLabels} from './manage-github-labels';
// TODO: Conditional types might allow us to define this from config()
export interface PluginSetting {
'issues.priorityIssues': boolean;
}
class PriorityIssuePlugin implements AppPlugin {
config() {
return {
'issues.priorityIssues': {
default: false,
description: 'Adds P0 - P3 labels in all repo\'s',
type: 'boolean',
},
};
}
async settingsChanged(
settingConfig: PluginSetting,
token: string,
repos: GithubRepo[]) {
const priorityLabels = [
{name: 'P0', description: 'Critical', color: 'FF0000'},
{name: 'P1', description: 'Need', color: 'FF6100'},
{name: 'P2', description: 'Want', color: 'FFC500'},
{name: 'P3', description: 'Not Critical', color: 'FEF2C0'},
];
if (!settingConfig['issues.priorityIssues']) {
for (const repo of repos) {
deleteLabels(token, repo, priorityLabels);
}
} else {
for (const repo of repos) {
addLabels(token, repo, priorityLabels);
}
}
}
}
settings.registerPlugin(new PriorityIssuePlugin());
| Fix priority issue label colors | Fix priority issue label colors
Fixes #499 | TypeScript | apache-2.0 | PolymerLabs/project-health,PolymerLabs/project-health,PolymerLabs/project-health | ---
+++
@@ -24,10 +24,10 @@
token: string,
repos: GithubRepo[]) {
const priorityLabels = [
- {name: 'P0', description: 'Critical', color: 'd0021b'},
- {name: 'P1', description: 'Need', color: 'd0021b'},
- {name: 'P2', description: 'Want', color: '0071eb'},
- {name: 'P3', description: 'Not Critical', color: '0071eb'},
+ {name: 'P0', description: 'Critical', color: 'FF0000'},
+ {name: 'P1', description: 'Need', color: 'FF6100'},
+ {name: 'P2', description: 'Want', color: 'FFC500'},
+ {name: 'P3', description: 'Not Critical', color: 'FEF2C0'},
];
if (!settingConfig['issues.priorityIssues']) { |
804508809970220a26da9164321f03701bb164e7 | packages/components/components/sidebar/MobileNavServices.tsx | packages/components/components/sidebar/MobileNavServices.tsx | import React from 'react';
import { useActiveBreakpoint } from '../../index';
interface Props {
children: React.ReactNode;
}
const MobileNavServices = ({ children }: Props) => {
const { isNarrow } = useActiveBreakpoint();
if (!isNarrow) {
return null;
}
return <nav className="p1 flex flex-row flex-spacearound flex-item-noshrink bg-global-grey">{children}</nav>;
};
export default MobileNavServices;
| import React from 'react';
import { APPS } from 'proton-shared/lib/constants';
import { useActiveBreakpoint, useConfig } from '../../index';
interface Props {
children: React.ReactNode;
}
const MobileNavServices = ({ children }: Props) => {
const { isNarrow } = useActiveBreakpoint();
const { APP_NAME } = useConfig();
if (!isNarrow || APP_NAME === APPS.PROTONVPN_SETTINGS) {
return null;
}
return <nav className="p1 flex flex-row flex-spacearound flex-item-noshrink bg-global-grey">{children}</nav>;
};
export default MobileNavServices;
| Remove mobile app menu for VPN settings | [VPNFE-73] Remove mobile app menu for VPN settings
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,13 +1,16 @@
import React from 'react';
-import { useActiveBreakpoint } from '../../index';
+import { APPS } from 'proton-shared/lib/constants';
+
+import { useActiveBreakpoint, useConfig } from '../../index';
interface Props {
children: React.ReactNode;
}
const MobileNavServices = ({ children }: Props) => {
const { isNarrow } = useActiveBreakpoint();
+ const { APP_NAME } = useConfig();
- if (!isNarrow) {
+ if (!isNarrow || APP_NAME === APPS.PROTONVPN_SETTINGS) {
return null;
}
|
f9ad4fa11618ee94a22ad4c2c136071b2f18a1ca | www/src/app/components/product-new/product-new.component.ts | www/src/app/components/product-new/product-new.component.ts | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ProductService } from 'app/services/product.service';
@Component({
selector: 'app-product-new',
templateUrl: './product-new.component.html',
styleUrls: ['./product-new.component.scss'],
providers : [ProductService]
})
export class ProductNewComponent implements OnInit {
productid = null;
categoryid = null;
err = null;
product = {
image : null,
price : 0,
in_stock : 0,
name : null,
description : null,
hidden : false
}
constructor(private route: ActivatedRoute,
private router : Router,
private productService : ProductService) { }
ngOnInit() {
this.route.params.subscribe(params => {
//this.productid = +params['productid'];
this.categoryid = +params['categoryid']
});
}
save() {
this.product["categories"] = [{"id" : this.categoryid}];
console.log(this.product);
this.productService.add(this.product).subscribe(
data => {
this.router.navigate(['/', 'products', data["id"]]);
},
err => {
console.log(err);
this.err = err;
})
}
null(event) {
return;
}
}
| import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ProductService } from 'app/services/product.service';
@Component({
selector: 'app-product-new',
templateUrl: './product-new.component.html',
styleUrls: ['./product-new.component.scss'],
providers : [ProductService]
})
export class ProductNewComponent implements OnInit {
productid = null;
categoryid = null;
err = null;
product = {
image : null,
price : 0,
in_stock : 0,
name : null,
description : null,
hidden : false
}
constructor(private route: ActivatedRoute,
private router : Router,
private productService : ProductService) { }
ngOnInit() {
this.route.params.subscribe(params => {
//this.productid = +params['productid'];
this.categoryid = +params['categoryid']
});
}
save() {
this.product["categories"] = [{"id" : this.categoryid}];
console.log(this.product);
this.productService.add(this.product).subscribe(
data => {
this.router.navigate(['/', 'product', data["id"]]);
},
err => {
console.log(err);
this.err = err;
})
}
null(event) {
return;
}
}
| Fix redirect a to product | Fix redirect a to product
| TypeScript | mit | petrstehlik/pyngShop,petrstehlik/pyngShop,petrstehlik/pyngShop,petrstehlik/pyngShop | ---
+++
@@ -41,7 +41,7 @@
this.productService.add(this.product).subscribe(
data => {
- this.router.navigate(['/', 'products', data["id"]]);
+ this.router.navigate(['/', 'product', data["id"]]);
},
err => {
console.log(err); |
713b29eb1094c3c09ac210c2abbbfc70a3f37f3d | app/app.component.ts | app/app.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<div class="form-group">' +
'<h1>To-Do <small>List</small></h1>' +
'<form role="form">'+
'<input type="text" class="form-control" placeholder="Your Task" name="task" [(ngModel)]="data">'+
'</form>'+
'<button type="button" (click)="add()" class="btn btn btn-primary" >Add</button>'+
'</div>'+
'<div id="list">'+
'<ul>'+
'<li *ngFor="let todo of todoList let i=index"> {{todo}} '+
'<a href="#" class="close" aria-hidden="true" (click)="remove(i)">×</a>'+
' </li>'+
'</ul>'+
'</div>'
})
export class AppComponent {
protected data: any = ''
protected todoList : Array<any> = [];
protected remove = function (i:number) {
this.todoList.splice(i,1);
}
protected add = function () {
debugger;
this.todoList.push(this.data);
this.data = '';
}
}
| import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<div class="form-group">' +
'<h1>To-Do <small>List</small></h1>' +
'<form role="form">'+
'<input type="text" class="form-control" (keyup)="add($event)" placeholder="Your Task" name="task" [(ngModel)]="data">'+
'</form>'+
'<button type="button" (click)="add(true)" class="btn btn btn-primary" >Add</button>'+
'</div>'+
'<div id="list">'+
'<ul>'+
'<li *ngFor="let todo of todoList let i=index"> {{todo}} '+
'<a href="#" class="close" aria-hidden="true" (click)="remove(i)">×</a>'+
' </li>'+
'</ul>'+
'</div>'
})
export class AppComponent {
protected data: any = ''
protected todoList : Array<any> = [];
protected remove = function (i:number) {
this.todoList.splice(i,1);
}
protected add = function (data:any) {
if(data.keyCode == 13 || data === true){
this.todoList.push(this.data);
this.data = '';
}
}
}
| Add todo on enter keypress. | Add todo on enter keypress.
| TypeScript | mit | zainmustafa/angular2-do,zainmustafa/angular2-do,zainmustafa/angular2-do | ---
+++
@@ -5,9 +5,9 @@
template: '<div class="form-group">' +
'<h1>To-Do <small>List</small></h1>' +
'<form role="form">'+
- '<input type="text" class="form-control" placeholder="Your Task" name="task" [(ngModel)]="data">'+
+ '<input type="text" class="form-control" (keyup)="add($event)" placeholder="Your Task" name="task" [(ngModel)]="data">'+
'</form>'+
- '<button type="button" (click)="add()" class="btn btn btn-primary" >Add</button>'+
+ '<button type="button" (click)="add(true)" class="btn btn btn-primary" >Add</button>'+
'</div>'+
'<div id="list">'+
'<ul>'+
@@ -24,9 +24,10 @@
protected remove = function (i:number) {
this.todoList.splice(i,1);
}
- protected add = function () {
- debugger;
- this.todoList.push(this.data);
- this.data = '';
+ protected add = function (data:any) {
+ if(data.keyCode == 13 || data === true){
+ this.todoList.push(this.data);
+ this.data = '';
+ }
}
} |
5efc3b5b8a1c7f3f335d8d412a92ed3efd290b40 | transpiler/src/emitter/declarations.ts | transpiler/src/emitter/declarations.ts | import { FunctionLikeDeclaration, Identifier, TypeReferenceNode } from 'typescript';
import { Context } from '../contexts';
import { EmitResult, emit } from './';
const emitFunctionDeclaration = (node: FunctionLikeDeclaration, context: Context): string => {
const return_type = emit(node.type, context).emitted_string;
const function_name = emit(node.name, context).emitted_string;
const parameters =
node.parameters
.map(p => ({ name: emit(p.name, context).emitted_string, type: emit(p.type, context).emitted_string}))
.map(({ name, type }) => `${type} ${name}`)
.join(', ');
const body = emit(node.body, context).emitted_string;
const declaration = `${return_type} ${function_name}(${parameters}) ${body}`;
return declaration;
};
export const emitFunctionLikeDeclaration = (node: FunctionLikeDeclaration, context: Context): EmitResult => {
return {
context,
emitted_string: emitFunctionDeclaration(node, context)
};
}
| import { FunctionLikeDeclaration, Identifier, TypeReferenceNode, VariableDeclaration } from 'typescript';
import { Context } from '../contexts';
import { EmitResult, emit, emitString } from './';
const emitFunctionDeclaration = (node: FunctionLikeDeclaration, context: Context): string => {
const return_type = emit(node.type, context).emitted_string;
const function_name = emit(node.name, context).emitted_string;
const parameters =
node.parameters
.map(p => ({ name: emit(p.name, context).emitted_string, type: emit(p.type, context).emitted_string}))
.map(({ name, type }) => `${type} ${name}`)
.join(', ');
const body = emit(node.body, context).emitted_string;
const declaration = `${return_type} ${function_name}(${parameters}) ${body}`;
return declaration;
};
export const emitFunctionLikeDeclaration = (node: FunctionLikeDeclaration, context: Context): EmitResult => {
return {
context,
emitted_string: emitFunctionDeclaration(node, context)
};
}
export const emitVariableDeclaration = ({ type, name, initializer }: VariableDeclaration, context: Context): EmitResult => {
return {
context,
emitted_string: `${emitString(type, context)} ${emitString(name, context)} = ${emitString(initializer, context)}`
}
};
| Add emit for variable declaration | Add emit for variable declaration
| TypeScript | mit | artfuldev/RIoT | ---
+++
@@ -1,6 +1,6 @@
-import { FunctionLikeDeclaration, Identifier, TypeReferenceNode } from 'typescript';
+import { FunctionLikeDeclaration, Identifier, TypeReferenceNode, VariableDeclaration } from 'typescript';
import { Context } from '../contexts';
-import { EmitResult, emit } from './';
+import { EmitResult, emit, emitString } from './';
const emitFunctionDeclaration = (node: FunctionLikeDeclaration, context: Context): string => {
const return_type = emit(node.type, context).emitted_string;
@@ -21,3 +21,10 @@
emitted_string: emitFunctionDeclaration(node, context)
};
}
+
+export const emitVariableDeclaration = ({ type, name, initializer }: VariableDeclaration, context: Context): EmitResult => {
+ return {
+ context,
+ emitted_string: `${emitString(type, context)} ${emitString(name, context)} = ${emitString(initializer, context)}`
+ }
+}; |
67e02cd9cb772a6b37e0d0fff3131d8ef4657d45 | src/settings/storage.ts | src/settings/storage.ts | import SettingData, { DefaultSettingData } from '../shared/SettingData';
export const load = async(): Promise<SettingData> => {
let { settings } = await browser.storage.local.get('settings');
if (!settings) {
return DefaultSettingData;
}
return SettingData.valueOf(settings as any);
};
export const save = (data: SettingData) => {
return browser.storage.local.set({
settings: data.toJSON(),
});
};
| import SettingData, { DefaultSettingData } from '../shared/SettingData';
export const load = async(): Promise<SettingData> => {
let { settings } = await browser.storage.local.get('settings');
if (!settings) {
return DefaultSettingData;
}
try {
return SettingData.valueOf(settings as any);
} catch (e) {
console.error('unable to load settings', e);
return DefaultSettingData;
}
};
export const save = (data: SettingData) => {
return browser.storage.local.set({
settings: data.toJSON(),
});
};
| Use default settings on loading failure | Use default settings on loading failure
| TypeScript | mit | ueokande/vim-vixen,ueokande/vim-vixen,ueokande/vim-vixen | ---
+++
@@ -5,7 +5,12 @@
if (!settings) {
return DefaultSettingData;
}
- return SettingData.valueOf(settings as any);
+ try {
+ return SettingData.valueOf(settings as any);
+ } catch (e) {
+ console.error('unable to load settings', e);
+ return DefaultSettingData;
+ }
};
export const save = (data: SettingData) => { |
8b0f10e13406cf8e6406a9f36d676bd3232af55c | src/Apps/Artwork/Components/TrustSignals/SecurePayment.tsx | src/Apps/Artwork/Components/TrustSignals/SecurePayment.tsx | import { Link, LockIcon } from "@artsy/palette"
import { SecurePayment_artwork } from "__generated__/SecurePayment_artwork.graphql"
import React from "react"
import { createFragmentContainer } from "react-relay"
import { graphql } from "react-relay"
import { TrustSignal, TrustSignalProps } from "./TrustSignal"
interface SecurePaymentProps
extends Omit<TrustSignalProps, "Icon" | "label" | "description"> {
artwork: SecurePayment_artwork
}
export const SecurePayment: React.FC<SecurePaymentProps> = ({
artwork,
...other
}) => {
return (
(artwork.is_acquireable || artwork.is_offerable) && (
<TrustSignal
Icon={<LockIcon />}
label="Secure payment"
description={
<>
{"Secure transactions by credit card through Stripe."}
<br />
<Link
href="https://stripe.com/docs/security/stripe"
target="_blank"
>
Learn more
</Link>
{"."}
</>
}
{...other}
/>
)
)
}
export const SecurePaymentFragmentContainer = createFragmentContainer(
SecurePayment,
{
artwork: graphql`
fragment SecurePayment_artwork on Artwork {
is_acquireable
is_offerable
}
`,
}
)
| import { Link, LockIcon } from "@artsy/palette"
import { SecurePayment_artwork } from "__generated__/SecurePayment_artwork.graphql"
import React from "react"
import { createFragmentContainer } from "react-relay"
import { graphql } from "react-relay"
import { TrustSignal, TrustSignalProps } from "./TrustSignal"
interface SecurePaymentProps
extends Omit<TrustSignalProps, "Icon" | "label" | "description"> {
artwork: SecurePayment_artwork
}
export const SecurePayment: React.FC<SecurePaymentProps> = ({
artwork,
...other
}) => {
return (
(artwork.is_acquireable || artwork.is_offerable) && (
<TrustSignal
Icon={<LockIcon />}
label="Secure payment"
description={
<>
{"Secure transactions by credit card through Stripe."}
<br />
<Link
href="https://stripe.com/docs/security/stripe"
target="_blank"
rel="noopener noreferrer"
>
Learn more
</Link>
{"."}
</>
}
{...other}
/>
)
)
}
export const SecurePaymentFragmentContainer = createFragmentContainer(
SecurePayment,
{
artwork: graphql`
fragment SecurePayment_artwork on Artwork {
is_acquireable
is_offerable
}
`,
}
)
| Add `noopener` to `_blank` link | Add `noopener` to `_blank` link
Co-Authored-By: Justin Bennett <[email protected]> | TypeScript | mit | artsy/reaction-force,artsy/reaction,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction | ---
+++
@@ -26,6 +26,7 @@
<Link
href="https://stripe.com/docs/security/stripe"
target="_blank"
+ rel="noopener noreferrer"
>
Learn more
</Link> |
3f0a3521c14d424bc594e93f8a652c61a2fe2d1f | src/index.ts | src/index.ts | 'use strict';
const isBrowser = new Function('try {return this===window;}catch(e){return false;}');
let useES6 = false;
if (!isBrowser()) {
const fs = require('fs');
useES6 = process.env.ES6 === 'true';
if (!useES6) {
const CONFIG_FILE = process.cwd() + '/ioc.config';
if (fs.existsSync(CONFIG_FILE)) {
const config = JSON.parse(fs.readFileSync(CONFIG_FILE));
if (config.es6) {
useES6 = true;
}
}
}
}
module.exports = require(useES6?'./es6':'./es5');
| 'use strict';
const isBrowser = new Function('try {return this===window;}catch(e){return false;}');
let useES6 = false;
if (!isBrowser()) {
useES6 = process.env.ES6 === 'true';
if (!useES6) {
const fs = require('fs');
const path = require('path');
const searchConfigFile = function() {
let configFile = path.join(__dirname, 'ioc.config');
const ROOT = path.join('/', 'ioc.config');
while (!fs.existsSync(configFile)) {
if (configFile === ROOT) {
return null;
}
configFile = path.normalize(path.join(path.dirname(configFile), '..', 'ioc.config'));
}
return configFile;
};
const CONFIG_FILE = searchConfigFile();
if (CONFIG_FILE && fs.existsSync(CONFIG_FILE)) {
const config = JSON.parse(fs.readFileSync(CONFIG_FILE));
if (config.es6) {
useES6 = true;
}
}
}
}
module.exports = require(useES6?'./es6':'./es5');
| Fix the search for ioc.config file | Fix the search for ioc.config file
| TypeScript | mit | thiagobustamante/typescript-ioc,thiagobustamante/typescript-ioc | ---
+++
@@ -4,11 +4,24 @@
let useES6 = false;
if (!isBrowser()) {
- const fs = require('fs');
useES6 = process.env.ES6 === 'true';
if (!useES6) {
- const CONFIG_FILE = process.cwd() + '/ioc.config';
- if (fs.existsSync(CONFIG_FILE)) {
+ const fs = require('fs');
+ const path = require('path');
+ const searchConfigFile = function() {
+ let configFile = path.join(__dirname, 'ioc.config');
+ const ROOT = path.join('/', 'ioc.config');
+ while (!fs.existsSync(configFile)) {
+ if (configFile === ROOT) {
+ return null;
+ }
+ configFile = path.normalize(path.join(path.dirname(configFile), '..', 'ioc.config'));
+ }
+ return configFile;
+ };
+
+ const CONFIG_FILE = searchConfigFile();
+ if (CONFIG_FILE && fs.existsSync(CONFIG_FILE)) {
const config = JSON.parse(fs.readFileSync(CONFIG_FILE));
if (config.es6) {
useES6 = true; |
fd5d03cf3d96354b69adedb6cd9adaf5675adcc9 | src/index.ts | src/index.ts | import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DeviceDetectorService } from './device-detector.service';
@NgModule({
imports: [
CommonModule
]
})
export class DeviceDetectorModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: DeviceDetectorModule,
providers: [DeviceDetectorService]
};
}
}
export { DeviceDetectorService, DeviceInfo } from './device-detector.service';
export { ReTree } from './retree';
export * from './device-detector.constants';
| import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DeviceDetectorService } from './device-detector.service';
@NgModule({
imports: [
CommonModule
]
})
export class DeviceDetectorModule {
static forRoot(): ModuleWithProviders<DeviceDetectorModule> {
return {
ngModule: DeviceDetectorModule,
providers: [DeviceDetectorService]
};
}
}
export { DeviceDetectorService, DeviceInfo } from './device-detector.service';
export { ReTree } from './retree';
export * from './device-detector.constants';
| Use generic version for ModuleWithProviders | Use generic version for ModuleWithProviders
This should add some level of Angular 9 compatibility and fix #144 | TypeScript | mit | KoderLabs/ng2-device-detector,KoderLabs/ng2-device-detector | ---
+++
@@ -8,7 +8,7 @@
]
})
export class DeviceDetectorModule {
- static forRoot(): ModuleWithProviders {
+ static forRoot(): ModuleWithProviders<DeviceDetectorModule> {
return {
ngModule: DeviceDetectorModule,
providers: [DeviceDetectorService] |
1e9287bc4ffefebb04aeb47e43283c15f977fcfb | src/index.ts | src/index.ts | import minecraftData from "minecraft-data";
import { Plugin } from "mineflayer";
import { IndexedData } from "./types";
import { isArmor } from "./lib/isArmor";
import { equipItem } from "./lib/equipItem";
const initializeBot: Plugin = (bot, options) => {
if (!bot) {
throw new Error(
"Bot object is missing, provide mineflayer bot as first argument"
);
}
let versionData: IndexedData;
// Version is only detected after bot logs in
bot.on("login", function onLogin() {
versionData = minecraftData(bot.version);
});
bot.on("playerCollect", function onPlayerCollect(collector, item) {
try {
const itemMetadata = item.metadata[item.metadata.length - 1] as any;
// In older versions blockId is used instead of itemId
var itemId =
"itemId" in itemMetadata
? itemMetadata.itemId
: "blockId" in itemMetadata && itemMetadata.blockId;
if (
itemId &&
collector.username === bot.username &&
isArmor(itemId, versionData)
) {
// Little delay to receive inventory
setTimeout(() => equipItem(bot, itemId), 100);
}
} catch (err) {
if (options.logErrors) {
console.log("Failed to retrieve block id, probably exp bottle");
}
}
});
};
export = initializeBot;
| import minecraftData from "minecraft-data";
import { Plugin } from "mineflayer";
import { IndexedData } from "./types";
import { isArmor } from "./lib/isArmor";
import { equipItem } from "./lib/equipItem";
const initializeBot: Plugin = (bot, options) => {
if (!bot) {
throw new Error(
"Bot object is missing, provide mineflayer bot as first argument"
);
}
let versionData: IndexedData = minecraftData(bot.version);
// Version is only detected after bot logs in
bot.on("login", function onLogin() {
versionData = minecraftData(bot.version);
});
bot.on("playerCollect", function onPlayerCollect(collector, item) {
try {
const itemMetadata = item.metadata[item.metadata.length - 1] as any;
// In older versions blockId is used instead of itemId
var itemId =
"itemId" in itemMetadata
? itemMetadata.itemId
: "blockId" in itemMetadata && itemMetadata.blockId;
if (
itemId &&
collector.username === bot.username &&
isArmor(itemId, versionData)
) {
// Little delay to receive inventory
setTimeout(() => equipItem(bot, itemId), 100);
}
} catch (err) {
if (options.logErrors) {
console.log("Failed to retrieve block id, probably exp bottle");
}
}
});
};
export = initializeBot;
| Load versionData outside login event | Load versionData outside login event
Fixes https://github.com/G07cha/MineflayerArmorManager/issues/7
| TypeScript | mit | G07cha/MineflayerArmorManager | ---
+++
@@ -12,7 +12,7 @@
);
}
- let versionData: IndexedData;
+ let versionData: IndexedData = minecraftData(bot.version);
// Version is only detected after bot logs in
bot.on("login", function onLogin() { |
7920a0fe8af72b859b08292beff808f5debe0dd5 | core/i18n/intl.ts | core/i18n/intl.ts | import areIntlLocalesSupported from 'intl-locales-supported'
export const importIntlPolyfill = async () => {
const IntlPolyfill = await import('intl')
global.Intl = IntlPolyfill.default
}
export const checkForIntlPolyfill = async (storeView) => {
if (!(window || global).Intl || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) {
await importIntlPolyfill()
}
}
| import areIntlLocalesSupported from 'intl-locales-supported'
export const importIntlPolyfill = async () => {
const IntlPolyfill = await import('intl')
global.Intl = IntlPolyfill.default
}
export const checkForIntlPolyfill = async (storeView) => {
if (!(window || global).hasOwnProperty('Intl') || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) {
await importIntlPolyfill()
}
}
| Use `hasOwnProperty` instead of just prop name (caused error during build) | Use `hasOwnProperty` instead of just prop name (caused error during build)
| TypeScript | mit | DivanteLtd/vue-storefront,pkarw/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront | ---
+++
@@ -6,7 +6,7 @@
}
export const checkForIntlPolyfill = async (storeView) => {
- if (!(window || global).Intl || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) {
+ if (!(window || global).hasOwnProperty('Intl') || !areIntlLocalesSupported(storeView.i18n.defaultLocale)) {
await importIntlPolyfill()
}
} |
b507fa6abb3ec91223bd13a2dd98154beb289e7b | src/app/common/user-icon/user-icon.component.ts | src/app/common/user-icon/user-icon.component.ts | import { Component, OnInit, Input, Inject } from '@angular/core';
import { currentUser } from 'src/app/ajs-upgraded-providers';
import { Md5 } from 'node_modules/ts-md5/dist/md5';
@Component({
selector: 'user-icon',
templateUrl: 'user-icon.component.html',
styleUrls: ['user-icon.component.scss']
})
export class UserIconComponent implements OnInit {
@Input() user: any;
@Input() email: string;
@Input() size: number;
constructor(
@Inject(currentUser) private currentUser: any) {
}
get userBackgroundStyle() {
const hash = this.email ? Md5.hashStr(this.email.trim().toLowerCase()) : Md5.hashStr('');
return `https://www.gravatar.com/avatar/${hash}.png?default=blank&size=${this.size}`;
}
get initials() {
const initials = (this.user && this.user.name) ? this.user.name.split(' ') : ' ';
return (initials.length > 1) ? (`${initials[0][0]}${initials[1][0]}`).toUpperCase() : ' ';
}
ngOnInit() {
if (!this.user) { this.user = this.currentUser.profile; }
if (!this.email) { this.email = this.currentUser.profile.email; }
}
}
| import { Component, OnInit, Input, Inject } from '@angular/core';
import { currentUser } from 'src/app/ajs-upgraded-providers';
import { Md5 } from 'node_modules/ts-md5/dist/md5';
@Component({
selector: 'user-icon',
templateUrl: 'user-icon.component.html',
styleUrls: ['user-icon.component.scss']
})
export class UserIconComponent implements OnInit {
@Input() user: any;
@Input() email: string;
@Input() size: number;
constructor(
@Inject(currentUser) private currentUser: any) {
}
get userBackgroundStyle() {
const hash = this.email ? Md5.hashStr(this.email.trim().toLowerCase()) : Md5.hashStr('');
return `https://www.gravatar.com/avatar/${hash}.png?default=blank&size=${this.size}`;
}
get initials() {
const initials = (this.user && this.user.name) ? this.user.name.split(' ') : ' ';
return (initials.length > 1) ? (`${initials[0][0]}${initials[1][0]}`).toUpperCase() : ' ';
}
ngOnInit() {
}
}
| Make sure user icon behaves as expexted for new user | FIX: Make sure user icon behaves as expexted for new user
| TypeScript | agpl-3.0 | doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web,doubtfire-lms/doubtfire-web | ---
+++
@@ -27,7 +27,5 @@
}
ngOnInit() {
- if (!this.user) { this.user = this.currentUser.profile; }
- if (!this.email) { this.email = this.currentUser.profile.email; }
}
} |
51b0a20699657a6c50a6063d503dc493adeb4922 | src/modal/ModalRoot.tsx | src/modal/ModalRoot.tsx | import * as React from 'react';
import { Modal } from 'react-bootstrap';
import { connect } from 'react-redux';
import { angular2react } from '@waldur/shims/angular2react';
import { closeModalDialog } from './actions';
import './ModalRoot.css';
const ModalRoot = ({ modalComponent, modalProps, onHide }) => (
<Modal
show={modalComponent ? true : false}
onHide={onHide}
bsSize={modalProps.size}
>
{modalComponent
? typeof modalComponent === 'string'
? React.createElement(
angular2react(modalComponent, ['resolve', 'close']),
{
...modalProps,
close: onHide,
},
)
: React.createElement(modalComponent, { ...modalProps, close: onHide })
: null}
</Modal>
);
export default connect<
{
modalComponent: React.ComponentType;
modalProps: any;
},
{
onHide(): void;
}
>(
(state: any) => state.modal,
dispatch => ({ onHide: () => dispatch(closeModalDialog()) }),
)(ModalRoot);
| import * as React from 'react';
import { Modal } from 'react-bootstrap';
import { connect } from 'react-redux';
import { angular2react } from '@waldur/shims/angular2react';
import { closeModalDialog } from './actions';
import './ModalRoot.css';
const ModalRoot = ({ modalComponent, modalProps, onHide }) => (
<Modal
show={modalComponent ? true : false}
onHide={onHide}
bsSize={modalProps?.size}
>
{modalComponent
? typeof modalComponent === 'string'
? React.createElement(
angular2react(modalComponent, ['resolve', 'close']),
{
...modalProps,
close: onHide,
},
)
: React.createElement(modalComponent, { ...modalProps, close: onHide })
: null}
</Modal>
);
export default connect<
{
modalComponent: React.ComponentType;
modalProps: any;
},
{
onHide(): void;
}
>(
(state: any) => state.modal,
dispatch => ({ onHide: () => dispatch(closeModalDialog()) }),
)(ModalRoot);
| Fix modal dialog when size is not defined. | Fix modal dialog when size is not defined.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -11,7 +11,7 @@
<Modal
show={modalComponent ? true : false}
onHide={onHide}
- bsSize={modalProps.size}
+ bsSize={modalProps?.size}
>
{modalComponent
? typeof modalComponent === 'string' |
43be48871a57c83cfb8d824ccacc55c719f43121 | app/src/ui/autocompletion/emoji-autocompletion-provider.tsx | app/src/ui/autocompletion/emoji-autocompletion-provider.tsx | import * as React from 'react'
import { IAutocompletionProvider } from './index'
/** Autocompletion provider for emoji. */
export default class EmojiAutocompletionProvider implements IAutocompletionProvider<string> {
private emoji: Map<string, string>
public constructor(emoji: Map<string, string>) {
this.emoji = emoji
}
public getRegExp(): RegExp {
return /(?:^|\n| )(?::)([a-z0-9\\+\\-][a-z0-9_]*)?/g
}
public getAutocompletionItems(text: string): ReadonlyArray<string> {
return Array.from(this.emoji.keys()).filter(e => e.startsWith(`:${text}`))
}
public renderItem(emoji: string) {
return (
<div className='emoji' key={emoji}>
<img className='icon' src={this.emoji.get(emoji)}/>
<div className='title'>{emoji}</div>
</div>
)
}
public getCompletionText(item: IEmojiHit) {
return item.emoji
}
}
| import * as React from 'react'
import { IAutocompletionProvider } from './index'
import { escapeRegExp } from '../lib/escape-regex'
export interface IEmojiHit {
emoji: string,
matchStart: number,
matchLength: number
}
/** Autocompletion provider for emoji. */
export default class EmojiAutocompletionProvider implements IAutocompletionProvider<IEmojiHit> {
private emoji: Map<string, string>
public constructor(emoji: Map<string, string>) {
this.emoji = emoji
}
public getRegExp(): RegExp {
return /(?:^|\n| )(?::)([a-z0-9\\+\\-][a-z0-9_]*)?/g
}
public getAutocompletionItems(text: string): ReadonlyArray<IEmojiHit> {
// empty strings is falsy
if (!text) {
return Array.from(this.emoji.keys())
.map<IEmojiHit>(emoji => { return { emoji: emoji, matchStart: 0, matchLength: 0 } })
}
const expr = new RegExp(escapeRegExp(text), 'i')
const results = new Array<IEmojiHit>()
for (const emoji of this.emoji.keys()) {
const match = expr.exec(emoji)
if (!match) { continue }
results.push({ emoji, matchStart: match.index, matchLength: match[0].length })
}
return results
}
public renderItem(hit: IEmojiHit) {
const emoji = hit.emoji
return (
<div className='emoji' key={emoji}>
<img className='icon' src={this.emoji.get(emoji)}/>
<div className='title'>{emoji}</div>
</div>
)
}
public getCompletionText(item: IEmojiHit) {
return item.emoji
}
}
| Implement naive fuzzy searching for emoji | Implement naive fuzzy searching for emoji
| TypeScript | mit | hjobrien/desktop,j-f1/forked-desktop,BugTesterTest/desktops,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,say25/desktop,gengjiawen/desktop,hjobrien/desktop,say25/desktop,kactus-io/kactus,gengjiawen/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,BugTesterTest/desktops,say25/desktop,j-f1/forked-desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,hjobrien/desktop,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,BugTesterTest/desktops,desktop/desktop,desktop/desktop,shiftkey/desktop,BugTesterTest/desktops,kactus-io/kactus,hjobrien/desktop | ---
+++
@@ -1,8 +1,15 @@
import * as React from 'react'
import { IAutocompletionProvider } from './index'
+import { escapeRegExp } from '../lib/escape-regex'
+
+export interface IEmojiHit {
+ emoji: string,
+ matchStart: number,
+ matchLength: number
+}
/** Autocompletion provider for emoji. */
-export default class EmojiAutocompletionProvider implements IAutocompletionProvider<string> {
+export default class EmojiAutocompletionProvider implements IAutocompletionProvider<IEmojiHit> {
private emoji: Map<string, string>
public constructor(emoji: Map<string, string>) {
@@ -13,11 +20,29 @@
return /(?:^|\n| )(?::)([a-z0-9\\+\\-][a-z0-9_]*)?/g
}
- public getAutocompletionItems(text: string): ReadonlyArray<string> {
- return Array.from(this.emoji.keys()).filter(e => e.startsWith(`:${text}`))
+ public getAutocompletionItems(text: string): ReadonlyArray<IEmojiHit> {
+
+ // empty strings is falsy
+ if (!text) {
+ return Array.from(this.emoji.keys())
+ .map<IEmojiHit>(emoji => { return { emoji: emoji, matchStart: 0, matchLength: 0 } })
+ }
+
+ const expr = new RegExp(escapeRegExp(text), 'i')
+ const results = new Array<IEmojiHit>()
+
+ for (const emoji of this.emoji.keys()) {
+ const match = expr.exec(emoji)
+ if (!match) { continue }
+
+ results.push({ emoji, matchStart: match.index, matchLength: match[0].length })
+ }
+
+ return results
}
- public renderItem(emoji: string) {
+ public renderItem(hit: IEmojiHit) {
+ const emoji = hit.emoji
return (
<div className='emoji' key={emoji}>
<img className='icon' src={this.emoji.get(emoji)}/> |
dba1a0bf176a11bf291ee49debb8e4a0d7169514 | src/util/encode-blob.ts | src/util/encode-blob.ts | export default (blob: Blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = function() {
let result = reader.result as string
// Remove `data:*/*;base64,` prefix:
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
result = result.split(',')[1]
resolve(result)
}
reader.onerror = function() {
reject(reader.error)
}
})
| export default (blob: Blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = function() {
let result = reader.result as string
if (!result) {
return // result.onerror has already been called at this point
}
// Remove `data:*/*;base64,` prefix:
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
result = result.split(',')[1]
resolve(result)
}
reader.onerror = function() {
reject(reader.error)
}
})
| Fix double error reporting in encoe-blob.ts | Fix double error reporting in encoe-blob.ts
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -5,6 +5,9 @@
reader.onloadend = function() {
let result = reader.result as string
+ if (!result) {
+ return // result.onerror has already been called at this point
+ }
// Remove `data:*/*;base64,` prefix:
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL |
e66b260258fa0930ac598d33e03fda2c8dbd8a76 | ui/src/shared/documents/DocumentHierarchyHeader.tsx | ui/src/shared/documents/DocumentHierarchyHeader.tsx | import React, { ReactElement } from 'react';
import { Card } from 'react-bootstrap';
import { ResultDocument } from '../../api/result';
import DocumentTeaser from '../document/DocumentTeaser';
export default function DocumentHierarchyHeader({ documents, searchParams }
: { documents: ResultDocument[], searchParams: string } ): ReactElement {
const firstDoc = documents?.[0];
const project = firstDoc?.project;
return documents.length
? <Card.Header className="hierarchy-parent">
<DocumentTeaser project={ project } searchParams={ searchParams }
document={ getParentDocument(firstDoc) }
hierarchyHeader={ true } />
</Card.Header>
: <></>;
}
const getParentDocument = (doc: ResultDocument): ResultDocument | undefined =>
doc.resource.relations?.isChildOf?.[0];
| import React, { ReactElement } from 'react';
import { Card } from 'react-bootstrap';
import { ResultDocument } from '../../api/result';
import DocumentTeaser from '../document/DocumentTeaser';
export default function DocumentHierarchyHeader({ documents, searchParams }
: { documents: ResultDocument[], searchParams: string } ): ReactElement {
const firstDoc = documents?.[0];
const project = firstDoc?.project;
const parentDoc = getParentDocument(firstDoc);
return documents.length && parentDoc
? <Card.Header className="hierarchy-parent">
<DocumentTeaser project={ project } searchParams={ searchParams }
document={ parentDoc }
hierarchyHeader={ true } />
</Card.Header>
: <></>;
}
const getParentDocument = (doc: ResultDocument): ResultDocument | undefined =>
doc.resource.relations?.isChildOf?.[0];
| Hide hierarchy header in root | Hide hierarchy header in root
| TypeScript | apache-2.0 | dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web | ---
+++
@@ -9,11 +9,12 @@
const firstDoc = documents?.[0];
const project = firstDoc?.project;
+ const parentDoc = getParentDocument(firstDoc);
- return documents.length
+ return documents.length && parentDoc
? <Card.Header className="hierarchy-parent">
<DocumentTeaser project={ project } searchParams={ searchParams }
- document={ getParentDocument(firstDoc) }
+ document={ parentDoc }
hierarchyHeader={ true } />
</Card.Header>
: <></>; |
5931c9fa6cca60c58b9a96a128626148dc343d16 | tests/vdom_jsx.spec.tsx | tests/vdom_jsx.spec.tsx | import { } from 'jasmine';
import app from '../index-jsx';
const model = 'x';
const view = _ => <div>{_}</div>;
const update = {
hi: (_, val) => val
}
describe('vdom-jsx', () => {
let element;
beforeEach(()=>{
element = document.createElement('div');
document.body.appendChild(element);
app.start(element, model, view, update);
});
it('should create first child element', () => {
expect(element.firstChild.nodeName).toEqual('DIV');
expect(element.firstChild.textContent).toEqual('x');
});
it('should re-create child element', () => {
element.removeChild(element.firstChild);
app.run('hi', 'xx');
expect(element.firstChild.nodeName).toEqual('DIV');
expect(element.firstChild.textContent).toEqual('xx');
});
it('should update child element', () => {
app.run('hi', 'xxx');
expect(element.firstChild.nodeName).toEqual('DIV');
expect(element.firstChild.textContent).toEqual('xxx');
});
});
| import { } from 'jasmine';
import app from '../index-jsx';
const model = 'x';
const view = _ => <div>{_}</div>;
const update = {
hi: (_, val) => val
}
describe('vdom-jsx', () => {
let element;
beforeEach(()=>{
element = document.createElement('div');
document.body.appendChild(element);
app.start(element, model, view, update);
});
it('should create first child element', () => {
expect(element.firstChild.nodeName).toEqual('DIV');
expect(element.firstChild.textContent).toEqual('x');
});
it('should re-create child element', () => {
element.removeChild(element.firstChild);
app.run('hi', 'xx');
expect(element.firstChild.nodeName).toEqual('DIV');
expect(element.firstChild.textContent).toEqual('xx');
});
it('should update child element', () => {
app.run('hi', 'xxx');
expect(element.firstChild.nodeName).toEqual('DIV');
expect(element.firstChild.textContent).toEqual('xxx');
});
it('should render custom element', () => {
const CustomElement = ({val}) => <div>{val}</div>;
const view = _ => <CustomElement val= {_} />;
const element = document.createElement('div');
document.body.appendChild(element);
app.start(element, model, view, update);
app.run('hi', 'xxxxx');
expect(element.firstChild.textContent).toEqual('xxxxx');
});
});
| Add unit test for custom element | Add unit test for custom element
| TypeScript | mit | yysun/apprun,yysun/apprun,yysun/apprun | ---
+++
@@ -34,4 +34,17 @@
expect(element.firstChild.textContent).toEqual('xxx');
});
+ it('should render custom element', () => {
+
+ const CustomElement = ({val}) => <div>{val}</div>;
+ const view = _ => <CustomElement val= {_} />;
+ const element = document.createElement('div');
+ document.body.appendChild(element);
+ app.start(element, model, view, update);
+
+ app.run('hi', 'xxxxx');
+ expect(element.firstChild.textContent).toEqual('xxxxx');
+
+ });
+
}); |
a3988f34b21e8c7b4ddf5fb7e12b29495344e874 | typescript/dnd-character/dnd-character.ts | typescript/dnd-character/dnd-character.ts | export class DnDCharacter {
public static generateAbilityScore(): number {
return DnDCharacter.randomInt(3, 18)
}
public static getModifierFor(abilityValue: number): number {
return Math.floor((abilityValue - 10) / 2)
}
public strength: number;
public dexterity: number;
public constitution: number;
public intelligence: number;
public wisdom: number;
public charisma: number;
public hitpoints: number;
public constructor() {
this.strength = DnDCharacter.generateAbilityScore()
this.dexterity = DnDCharacter.generateAbilityScore()
this.constitution = DnDCharacter.generateAbilityScore()
this.intelligence = DnDCharacter.generateAbilityScore()
this.wisdom = DnDCharacter.generateAbilityScore()
this.charisma = DnDCharacter.generateAbilityScore()
this.hitpoints = 10 + DnDCharacter.getModifierFor(this.charisma)
}
/**
* randomNumber returns a random number between min and max (inclusive)
*/
private static randomInt(min: number, max: number) {
return Math.floor((Math.random()) * (max - min + 1)) + min;
}
}
| export class DnDCharacter {
public static generateAbilityScore(): number {
return DnDCharacter.randomInt(3, 18)
}
public static getModifierFor(abilityValue: number): number {
return Math.floor((abilityValue - 10) / 2)
}
public strength: number;
public dexterity: number;
public constitution: number;
public intelligence: number;
public wisdom: number;
public charisma: number;
public hitpoints: number;
public constructor() {
this.strength = DnDCharacter.generateAbilityScore()
this.dexterity = DnDCharacter.generateAbilityScore()
this.constitution = DnDCharacter.generateAbilityScore()
this.intelligence = DnDCharacter.generateAbilityScore()
this.wisdom = DnDCharacter.generateAbilityScore()
this.charisma = DnDCharacter.generateAbilityScore()
this.hitpoints = 10 + DnDCharacter.getModifierFor(this.constitution)
}
/**
* randomNumber returns a random number between min and max (inclusive)
*/
private static randomInt(min: number, max: number) {
return Math.floor((Math.random()) * (max - min + 1)) + min;
}
}
| Fix bug: hitpoints depends on constitution | Fix bug: hitpoints depends on constitution
| TypeScript | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | ---
+++
@@ -22,7 +22,7 @@
this.intelligence = DnDCharacter.generateAbilityScore()
this.wisdom = DnDCharacter.generateAbilityScore()
this.charisma = DnDCharacter.generateAbilityScore()
- this.hitpoints = 10 + DnDCharacter.getModifierFor(this.charisma)
+ this.hitpoints = 10 + DnDCharacter.getModifierFor(this.constitution)
}
|
f9f23f6d8047b9b673ccc6e6d4efd8e83f9049dc | lib/tasks/Test.ts | lib/tasks/Test.ts | import {buildHelper as helper, taskRunner} from "../Container";
const gulp = require("gulp");
const run = require("gulp-run");
import * as path from "path";
export default function Test() {
let settings = helper.getSettings(),
modulesPath = path.resolve(__dirname, "../../node_modules"),
nyc = path.join(modulesPath, '.bin/nyc'),
tsNode = path.join(modulesPath, 'ts-node/register'),
mocha = path.join(modulesPath, '.bin/mocha'),
nycSettings = "";
nycSettings += `--include '${settings.scripts}'`;
nycSettings += ` --exclude node_modules --exclude ${settings.distribution}`;
nycSettings += " --extension .ts --extension .tsx";
nycSettings += " --reporter text-summary --reporter html";
nycSettings += " --sourceMap true --instrument true";
return run(`${nyc} ${nycSettings} --require ${tsNode} ${mocha} '${settings.test}'`)
.exec()
.on("error", (error) => console.error(error));
} | import {buildHelper as helper, taskRunner} from "../Container";
const gulp = require("gulp");
const run = require("gulp-run");
import * as path from "path";
export default function Test() {
let settings = helper.getSettings(),
modulesPath = path.resolve(__dirname, "../../node_modules"),
nyc = path.join(modulesPath, '.bin/nyc'),
tsNode = path.join(modulesPath, 'ts-node/register'),
mocha = path.join(modulesPath, '.bin/mocha'),
nycSettings = "";
nycSettings += `--include '${settings.scripts}'`;
nycSettings += ` --exclude node_modules --exclude ${settings.distribution}`;
nycSettings += " --extension .ts --extension .tsx";
nycSettings += " --reporter text-summary --reporter html";
nycSettings += " --sourceMap true --instrument true";
return run(`${nyc} ${nycSettings} --require ${tsNode} ${mocha} '${settings.test}'`)
.exec()
.on("error", (error) => {
console.error(error);
process.exit(1);
});
} | Exit tests with error if failed | Exit tests with error if failed
| TypeScript | mit | mtfranchetto/smild,mtfranchetto/smild,mtfranchetto/smild | ---
+++
@@ -17,5 +17,8 @@
nycSettings += " --sourceMap true --instrument true";
return run(`${nyc} ${nycSettings} --require ${tsNode} ${mocha} '${settings.test}'`)
.exec()
- .on("error", (error) => console.error(error));
+ .on("error", (error) => {
+ console.error(error);
+ process.exit(1);
+ });
} |
1d9da65138dd2005e5abb7f3808dcab14c51f7a1 | example/js/components/App.tsx | example/js/components/App.tsx | import Component from "inferno-component"
export default class App extends Component<{}, {}> {
render() {
return <div>Hello, Inferno</div>
}
} | import Component from "inferno-component"
import {Box} from "react-polymer-layout"
export default class App extends Component<{}, {}> {
render() {
return (
<Box justified>
<div>Hello, Inferno</div>
<div>{Date.now()}</div>
</Box>
)
}
}
| Add react lib to example | Add react lib to example
| TypeScript | mit | wizawu/1c,wizawu/1c,wizawu/1c,wizawu/1c | ---
+++
@@ -1,7 +1,13 @@
import Component from "inferno-component"
+import {Box} from "react-polymer-layout"
export default class App extends Component<{}, {}> {
render() {
- return <div>Hello, Inferno</div>
+ return (
+ <Box justified>
+ <div>Hello, Inferno</div>
+ <div>{Date.now()}</div>
+ </Box>
+ )
}
} |
b476edaa4513e57cae60e4b25319c82cdb96f2bc | schema/2.0/gooobject.ts | schema/2.0/gooobject.ts | /// <reference path="common.ts"/>
enum LicenseType {
'CC0',
'CC BY',
'CC BY-SA',
'CC BY-NC',
'CC BY-NC-SA',
'PRIVATE'
}
interface GooObject {
id: string;
name: string;
license: LicenseType;
originalLicense?: LicenseType;
created: DateTime;
modified: DateTime;
readOnly?: boolean;
description?: string;
thumbnailRef?: ImageRef;
tags?: {
[tagName: string]: string;
}
originalAsset?: {
id: string;
version: string;
};
deleted: boolean;
/**
* @default 2
*/
dataModelVersion: number;
}
| /// <reference path="common.ts"/>
enum LicenseType {
'CC0',
'CC BY',
'CC BY-SA',
'CC BY-NC',
'CC BY-NC-SA',
'PRIVATE'
}
interface GooObject {
id: string;
name: string;
license: LicenseType;
originalLicense?: LicenseType;
created: DateTime;
modified: DateTime;
readOnly?: boolean;
description?: string;
thumbnailRef?: ImageRef;
tags?: {
[tagName: string]: string;
}
meta?: {
[propName: string]: string;
}
originalAsset?: {
id: string;
version: string;
};
deleted: boolean;
/**
* @default 2
*/
dataModelVersion: number;
}
| Add support for meta properties in every goo object. | Add support for meta properties in every goo object.
| TypeScript | mit | GooTechnologies/datamodel,GooTechnologies/datamodel,GooTechnologies/datamodel | ---
+++
@@ -27,6 +27,10 @@
[tagName: string]: string;
}
+ meta?: {
+ [propName: string]: string;
+ }
+
originalAsset?: {
id: string;
version: string; |
fc04f441d63552afe7ff0a4c9331675b60f4333e | index.d.ts | index.d.ts | import { Handler } from 'express'
declare interface GuardOptions {
requestProperty?: string
permissionsProperty?: string
}
declare class Guard {
public constructor(options: GuardOptions);
public check(required: string | string[]): Handler;
}
declare function guardFactory(options: GuardOptions): Guard;
export = guardFactory;
| import { Handler } from 'express'
declare interface GuardOptions {
requestProperty?: string
permissionsProperty?: string
}
declare class Guard {
public constructor(options: GuardOptions);
public check(required: string | string[] | string[][]): Handler;
}
declare function guardFactory(options: GuardOptions): Guard;
export = guardFactory;
| Support "OR" query in the types | Support "OR" query in the types
Example: `j.check([['role1'], ['role2']])` | TypeScript | mit | MichielDeMey/express-jwt-permissions | ---
+++
@@ -8,7 +8,7 @@
declare class Guard {
public constructor(options: GuardOptions);
- public check(required: string | string[]): Handler;
+ public check(required: string | string[] | string[][]): Handler;
}
declare function guardFactory(options: GuardOptions): Guard; |
e710414fed3b6eb03e386be63ee10d9f294daf20 | plugins/metrics/plugins/metrics/ts/metricsGlobals.ts | plugins/metrics/plugins/metrics/ts/metricsGlobals.ts | /// Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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.
/// <reference path="../../includes.ts"/>
module HawkularMetrics {
export var pluginName = "hawkular-metrics";
export var tenantId = "rest-test";
export var log:Logging.Logger = Logger.get(pluginName);
export var templatePath = "plugins/metrics/html";
}
| /// Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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.
/// <reference path="../../includes.ts"/>
module HawkularMetrics {
export var pluginName = "hawkular-metrics";
export var tenantId = "test";
export var log:Logging.Logger = Logger.get(pluginName);
export var templatePath = "plugins/metrics/html";
}
| Change tenantId from 'rest-test' to 'test'. | Change tenantId from 'rest-test' to 'test'.
| TypeScript | apache-2.0 | hawkular/hawkular-ui-components,ammendonca/hawkular-ui-components,hawkular/hawkular-ui-components,mtho11/hawkular-ui-components,mtho11/hawkular-ui-components,ammendonca/hawkular-ui-components,mtho11/hawkular-ui-components,hawkular/hawkular-ui-components,ammendonca/hawkular-ui-components,mtho11/hawkular-ui-components,ammendonca/hawkular-ui-components,hawkular/hawkular-ui-components | ---
+++
@@ -19,7 +19,7 @@
export var pluginName = "hawkular-metrics";
- export var tenantId = "rest-test";
+ export var tenantId = "test";
export var log:Logging.Logger = Logger.get(pluginName);
|
10125540ce3ee3e1ee8c3d441cbf29e264b80ded | app/index.tsx | app/index.tsx | import 'reflect-metadata';
import React from 'react';
import { Container } from 'libs/typedi';
import { render } from 'react-dom';
import { configure } from 'mobx';
import { enableLogging } from 'mobx-logger';
import { registerServices } from 'core';
import { initializeStats } from 'utils/stats';
import { LoadService, UndoService } from 'core';
import Root from './pages/Root';
import './app.global.css';
// Ensure that all services are registered with the DI provider.
registerServices();
initializeStats();
// Configure mobx logging
enableLogging({
action: true,
reaction: false,
transaction: false,
compute: false,
});
// Configure mobx
configure({
enforceActions: 'observed',
});
const rootEl = document.getElementById('root');
const loadService = Container.get(LoadService);
loadService.loadSession();
const undoService = Container.get(UndoService);
undoService.initialize();
render(<Root />, rootEl);
| import 'reflect-metadata';
import React from 'react';
import { Container } from 'libs/typedi';
import { render } from 'react-dom';
import { configure } from 'mobx';
import { enableLogging } from 'mobx-logger';
import { initializeStats } from 'utils/stats';
import { LoadService, UndoService } from 'core';
import Root from './pages/Root';
import './app.global.css';
initializeStats();
// Configure mobx logging
enableLogging({
action: true,
reaction: false,
transaction: false,
compute: false,
});
// Configure mobx
configure({
enforceActions: 'observed',
});
const rootEl = document.getElementById('root');
const loadService = Container.get(LoadService);
loadService.loadSession();
const undoService = Container.get(UndoService);
undoService.initialize();
render(<Root />, rootEl);
| Remove unnecessary call to registerServices | Remove unnecessary call to registerServices
| TypeScript | mit | cannoneyed/fiddle,cannoneyed/fiddle,cannoneyed/fiddle | ---
+++
@@ -5,7 +5,6 @@
import { configure } from 'mobx';
import { enableLogging } from 'mobx-logger';
-import { registerServices } from 'core';
import { initializeStats } from 'utils/stats';
import { LoadService, UndoService } from 'core';
@@ -14,8 +13,6 @@
import './app.global.css';
-// Ensure that all services are registered with the DI provider.
-registerServices();
initializeStats();
// Configure mobx logging |
f00882f6811a6787cbe46192d4447529975b61b7 | src/api/docker.ts | src/api/docker.ts | import * as DockerClient from 'dockerode'
export default function getDockerClient(host: Concierge.Host, timeout?: number) {
// If no hostname is provided, try and use the local unix socket
if (!host.hostname) {
const dockerClient = new DockerClient({
socketPath: '/var/run/docker.sock',
timeout: timeout || 0
})
return dockerClient
}
const dockerClient = new DockerClient({
host: host.hostname,
port: host.dockerPort || 2375,
protocol: 'http',
timeout: timeout || 0
})
return dockerClient
}
| import * as DockerClient from 'dockerode'
import * as process from 'process'
export default function getDockerClient(host: Concierge.Host, timeout?: number) {
// If no hostname is provided, try and use the local unix socket
if (!host.hostname) {
const socketPath = process.platform === 'win32'
? '//./pipe/docker_engine'
: '/var/run/docker.sock'
const dockerClient = new DockerClient({
socketPath,
timeout: timeout || 0
})
return dockerClient
}
const dockerClient = new DockerClient({
host: host.hostname,
port: host.dockerPort || 2375,
protocol: 'http',
timeout: timeout || 0
})
return dockerClient
}
| Add windows socket support for hostnameless host | Add windows socket support for hostnameless host
| TypeScript | mit | paypac/node-concierge,the-concierge/concierge,paypac/node-concierge,paypac/node-concierge,paypac/node-concierge,the-concierge/concierge,the-concierge/concierge | ---
+++
@@ -1,10 +1,15 @@
import * as DockerClient from 'dockerode'
+import * as process from 'process'
export default function getDockerClient(host: Concierge.Host, timeout?: number) {
// If no hostname is provided, try and use the local unix socket
if (!host.hostname) {
+ const socketPath = process.platform === 'win32'
+ ? '//./pipe/docker_engine'
+ : '/var/run/docker.sock'
+
const dockerClient = new DockerClient({
- socketPath: '/var/run/docker.sock',
+ socketPath,
timeout: timeout || 0
})
return dockerClient |
df950abe97b2b5006ed072b855bfb9eb6e159792 | src/System/Exception.ts | src/System/Exception.ts | /**
* Represents an Exception
*/
export class Exception extends Error
{
/**
* A collection of key/value pairs that provide additional user-defined information about the exception.
*/
private data: any[];
/**
* The Exception instance that caused the current exception.
*/
private innerException: Exception = null;
/**
* Initializes a new instance of the `Exception`.
*
* @param message
* The error message that explains the reason for the exception.
*
* @param innerException
* The exception that is the cause of the current exception, or a `null` reference if no inner exception is specified.
*/
public constructor(message?: string, innerException?: Exception)
{
super(...(message ? [message] : []));
if (innerException)
{
this.innerException = innerException;
}
}
/**
* Gets a collection of key/value pairs that provide additional user-defined information about the exception.
*/
public get Data(): any[]
{
return this.data;
}
/**
* Gets the Exception instance that caused the current exception.
*/
public get InnerException(): Exception
{
return this.innerException;
}
/**
* Gets a message that describes the current exception.
*/
public get Message(): string
{
return this.message;
}
/**
* Gets a string representation of the immediate frames on the call stack.
*/
public get StackTrace(): string
{
return this.stack;
}
}
| /**
* Represents an Exception
*/
export class Exception extends Error
{
/**
* A collection of key/value pairs that provide additional user-defined information about the exception.
*/
private data: any[];
/**
* The message of the exception.
*/
private exceptionMessage: string;
/**
* The Exception instance that caused the current exception.
*/
private innerException: Exception = null;
/**
* Initializes a new instance of the `Exception`.
*
* @param message
* The error message that explains the reason for the exception.
*
* @param innerException
* The exception that is the cause of the current exception, or a `null` reference if no inner exception is specified.
*/
public constructor(message?: string, innerException?: Exception)
{
super();
this.exceptionMessage = message;
if (innerException)
{
this.innerException = innerException;
}
}
/**
* Gets a collection of key/value pairs that provide additional user-defined information about the exception.
*/
public get Data(): any[]
{
return this.data;
}
/**
* Gets the Exception instance that caused the current exception.
*/
public get InnerException(): Exception
{
return this.innerException;
}
/**
* Gets a message that describes the current exception.
*/
public get Message(): string
{
return this.exceptionMessage;
}
/**
* @inheritdoc
*/
public get message(): string
{
return this.Message;
}
/**
* Gets a string representation of the immediate frames on the call stack.
*/
public get StackTrace(): string
{
return this.stack;
}
/**
* Gets a string representing this exception.
*/
public toString()
{
return this.Message;
}
}
| Improve the accessability of exception-info | Improve the accessability of exception-info
| TypeScript | mit | manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter | ---
+++
@@ -7,6 +7,11 @@
* A collection of key/value pairs that provide additional user-defined information about the exception.
*/
private data: any[];
+
+ /**
+ * The message of the exception.
+ */
+ private exceptionMessage: string;
/**
* The Exception instance that caused the current exception.
@@ -24,7 +29,8 @@
*/
public constructor(message?: string, innerException?: Exception)
{
- super(...(message ? [message] : []));
+ super();
+ this.exceptionMessage = message;
if (innerException)
{
@@ -53,7 +59,15 @@
*/
public get Message(): string
{
- return this.message;
+ return this.exceptionMessage;
+ }
+
+ /**
+ * @inheritdoc
+ */
+ public get message(): string
+ {
+ return this.Message;
}
/**
@@ -63,4 +77,12 @@
{
return this.stack;
}
+
+ /**
+ * Gets a string representing this exception.
+ */
+ public toString()
+ {
+ return this.Message;
+ }
} |
f065a26e8120a4c2a4faedec652606478627aafa | src/observers/InformationMessageObserver.ts | src/observers/InformationMessageObserver.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as ObservableEvent from "../omnisharp/loggingEvents";
import { vscode } from '../vscodeAdapter';
import showInformationMessage from "./utils/ShowInformationMessage";
export class InformationMessageObserver {
constructor(private vscode: vscode) {
}
public post = (event: ObservableEvent.BaseEvent) => {
switch (event.constructor.name) {
case ObservableEvent.OmnisharpServerUnresolvedDependencies.name:
this.handleOmnisharpServerUnresolvedDependencies(<ObservableEvent.OmnisharpServerUnresolvedDependencies>event);
break;
}
}
private async handleOmnisharpServerUnresolvedDependencies(event: ObservableEvent.OmnisharpServerUnresolvedDependencies) {
//to do: determine if we need the unresolved dependencies message
let csharpConfig = this.vscode.workspace.getConfiguration('csharp');
if (!csharpConfig.get<boolean>('suppressDotnetRestoreNotification')) {
let message = `There are unresolved dependencies'. Please execute the restore command to continue.`;
return showInformationMessage(this.vscode, message, { title: "Restore", command: "dotnet.restore.all" });
}
}
}
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as ObservableEvent from "../omnisharp/loggingEvents";
import { vscode } from '../vscodeAdapter';
import showInformationMessage from "./utils/ShowInformationMessage";
export class InformationMessageObserver {
constructor(private vscode: vscode) {
}
public post = (event: ObservableEvent.BaseEvent) => {
switch (event.constructor.name) {
case ObservableEvent.OmnisharpServerUnresolvedDependencies.name:
this.handleOmnisharpServerUnresolvedDependencies(<ObservableEvent.OmnisharpServerUnresolvedDependencies>event);
break;
}
}
private async handleOmnisharpServerUnresolvedDependencies(event: ObservableEvent.OmnisharpServerUnresolvedDependencies) {
//to do: determine if we need the unresolved dependencies message
let csharpConfig = this.vscode.workspace.getConfiguration('csharp');
if (!csharpConfig.get<boolean>('suppressDotnetRestoreNotification')) {
let message = `There are unresolved dependencies. Please execute the restore command to continue.`;
return showInformationMessage(this.vscode, message, { title: "Restore", command: "dotnet.restore.all" });
}
}
}
| Remove apostrophe from unresolved dependencies msg | Remove apostrophe from unresolved dependencies msg | TypeScript | mit | OmniSharp/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,OmniSharp/omnisharp-vscode,gregg-miskelly/omnisharp-vscode,OmniSharp/omnisharp-vscode | ---
+++
@@ -23,7 +23,7 @@
//to do: determine if we need the unresolved dependencies message
let csharpConfig = this.vscode.workspace.getConfiguration('csharp');
if (!csharpConfig.get<boolean>('suppressDotnetRestoreNotification')) {
- let message = `There are unresolved dependencies'. Please execute the restore command to continue.`;
+ let message = `There are unresolved dependencies. Please execute the restore command to continue.`;
return showInformationMessage(this.vscode, message, { title: "Restore", command: "dotnet.restore.all" });
}
} |
b15e10713dd8ce9fc687c6f5816b7d1d0a40162a | src/app/journal/journal.module.ts | src/app/journal/journal.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { PostComponent } from './post/post.component';
import { PostListComponent } from './post-list/post-list.component';
import { PostService } from './post.service';
const journalRoutes: Routes = [
{path: 'journal', component: PostListComponent },
{path: 'journal/post/:id', component: PostComponent }
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(journalRoutes)
],
declarations: [PostComponent, PostListComponent],
providers: [PostService]
})
export class JournalModule { }
| import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { PostComponent } from './post/post.component';
import { PostListComponent } from './post-list/post-list.component';
import { PostService } from './post.service';
const journalRoutes: Routes = [
{path: 'journal', component: PostListComponent },
{path: 'journal/post/:id', component: PostListComponent }
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(journalRoutes)
],
declarations: [PostComponent, PostListComponent],
providers: [PostService]
})
export class JournalModule { }
| Make journal post view route point at correct component | Make journal post view route point at correct component
| TypeScript | apache-2.0 | jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog | ---
+++
@@ -8,7 +8,7 @@
const journalRoutes: Routes = [
{path: 'journal', component: PostListComponent },
- {path: 'journal/post/:id', component: PostComponent }
+ {path: 'journal/post/:id', component: PostListComponent }
];
@NgModule({ |
78fb4e244f8d5da57c548900171a3905614748d8 | src/utils/searchOptions.ts | src/utils/searchOptions.ts | import { SearchOptions, SearchSort } from '../types';
import { WorkerSearchParams, WorkerSortParam } from '../worker-mturk-api';
export const generateParams = (options: SearchOptions): WorkerSearchParams => {
const { sortType, minReward, qualifiedOnly, searchTerm } = options;
return {
sort: sortParam(sortType),
filters: {
search_term: searchTerm,
min_reward: parseFloat(minReward),
qualified: qualifiedOnly
},
page_size: 100,
page_number: 1
};
};
const sortParam = (sorting: SearchSort): WorkerSortParam => {
switch (sorting) {
case 'Latest':
return 'updated_desc';
case 'Batch Size':
return 'num_hits_desc';
case 'Reward':
return 'reward_desc';
default:
throw new Error('Problem generating sortType param');
}
};
| import { SearchOptions, SearchSort } from '../types';
import { WorkerSearchParams, WorkerSortParam } from '../worker-mturk-api';
export const generateParams = (options: SearchOptions): WorkerSearchParams => {
const { sortType, minReward, qualifiedOnly, searchTerm } = options;
return {
sort: sortParam(sortType),
filters: {
search_term: searchTerm,
min_reward: parseFloat(minReward) || 0,
qualified: qualifiedOnly
},
page_size: 100,
page_number: 1
};
};
const sortParam = (sorting: SearchSort): WorkerSortParam => {
switch (sorting) {
case 'Latest':
return 'updated_desc';
case 'Batch Size':
return 'num_hits_desc';
case 'Reward':
return 'reward_desc';
default:
throw new Error('Problem generating sortType param');
}
};
| Add 0 as fallback when minReward evaluates to NaN. | Add 0 as fallback when minReward evaluates to NaN.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -8,7 +8,7 @@
sort: sortParam(sortType),
filters: {
search_term: searchTerm,
- min_reward: parseFloat(minReward),
+ min_reward: parseFloat(minReward) || 0,
qualified: qualifiedOnly
},
page_size: 100, |
92f52319dae6539307fd071d27c1d8fa8b9d9212 | libsquoosh/src/emscripten-utils.ts | libsquoosh/src/emscripten-utils.ts | import { fileURLToPath, URL } from 'url';
export function pathify(path: string): string {
if (path.startsWith('file://')) {
path = fileURLToPath(path);
}
return path;
}
export function instantiateEmscriptenWasm<T extends EmscriptenWasm.Module>(
factory: EmscriptenWasm.ModuleFactory<T>,
path: string,
workerJS: string = '',
): Promise<T> {
return factory({
locateFile(requestPath) {
// The glue code generated by emscripten uses the original
// file names of the worker file and the wasm binary.
// These will have changed in the bundling process and
// we need to inject them here.
if (requestPath.endsWith('.wasm')) return pathify(path);
if (requestPath.endsWith('.worker.js')) return new URL(workerJS).pathname;
return requestPath;
},
});
}
| import { fileURLToPath, URL } from 'url';
export function pathify(path: string): string {
if (path.startsWith('file://')) {
path = fileURLToPath(path);
}
return path;
}
export function instantiateEmscriptenWasm<T extends EmscriptenWasm.Module>(
factory: EmscriptenWasm.ModuleFactory<T>,
path: string,
workerJS: string = '',
): Promise<T> {
return factory({
locateFile(requestPath) {
// The glue code generated by emscripten uses the original
// file names of the worker file and the wasm binary.
// These will have changed in the bundling process and
// we need to inject them here.
if (requestPath.endsWith('.wasm')) return pathify(path);
if (requestPath.endsWith('.worker.js')) return pathify(workerJS);
return requestPath;
},
});
}
| Use pathify to calculate absolute paths for cross-platform compatibility | Use pathify to calculate absolute paths for cross-platform compatibility
| TypeScript | apache-2.0 | GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh | ---
+++
@@ -19,7 +19,7 @@
// These will have changed in the bundling process and
// we need to inject them here.
if (requestPath.endsWith('.wasm')) return pathify(path);
- if (requestPath.endsWith('.worker.js')) return new URL(workerJS).pathname;
+ if (requestPath.endsWith('.worker.js')) return pathify(workerJS);
return requestPath;
},
}); |
d8ba97f7e711036d9d90cff76dcabd227fad2bd6 | packages/schematics/schematics/blank/schematic-files/src/__name@dasherize__/index_spec.ts | packages/schematics/schematics/blank/schematic-files/src/__name@dasherize__/index_spec.ts | import { Tree } from '@angular-devkit/schematics';
import { SchematicTestRunner } from '@angular-devkit/schematics/testing';
import * as path from 'path';
const collectionPath = path.join(__dirname, '../collection.json');
describe('<%= dasherize(name) %>', () => {
it('works', () => {
const runner = new SchematicTestRunner('schematics', collectionPath);
const tree = runner.runSchematic('my-schematic', {}, Tree.empty());
expect(tree.files).toEqual([]);
});
});
| import { Tree } from '@angular-devkit/schematics';
import { SchematicTestRunner } from '@angular-devkit/schematics/testing';
import * as path from 'path';
const collectionPath = path.join(__dirname, '../collection.json');
describe('<%= dasherize(name) %>', () => {
it('works', () => {
const runner = new SchematicTestRunner('schematics', collectionPath);
const tree = runner.runSchematic('<%= dasherize(name) %>', {}, Tree.empty());
expect(tree.files).toEqual([]);
});
});
| Fix test in blank schematic project | fix(@schematics/schematics): Fix test in blank schematic project
| TypeScript | mit | hansl/devkit,hansl/devkit,hansl/devkit,hansl/devkit | ---
+++
@@ -9,7 +9,7 @@
describe('<%= dasherize(name) %>', () => {
it('works', () => {
const runner = new SchematicTestRunner('schematics', collectionPath);
- const tree = runner.runSchematic('my-schematic', {}, Tree.empty());
+ const tree = runner.runSchematic('<%= dasherize(name) %>', {}, Tree.empty());
expect(tree.files).toEqual([]);
}); |
72ae2503aeb1af656873f7b379aaa460c0365688 | app/javascript/retrospring/features/settings/index.ts | app/javascript/retrospring/features/settings/index.ts | import {createDeleteEvent, createSubmitEvent} from "retrospring/features/settings/mute";
export default (): void => {
const submit: HTMLButtonElement = document.getElementById('new-rule-submit') as HTMLButtonElement;
if (submit.classList.contains('js-initialized')) return;
const rulesList = document.querySelector<HTMLDivElement>('.js-rules-list');
rulesList.querySelectorAll<HTMLDivElement>('.form-group:not(.js-initalized)').forEach(entry => {
const button = entry.querySelector('button')
button.onclick = createDeleteEvent(entry, button)
});
const textEntry: HTMLButtonElement = document.getElementById('new-rule-text') as HTMLButtonElement;
const template: HTMLTemplateElement = document.getElementById('rule-template') as HTMLTemplateElement;
submit.form.onsubmit = createSubmitEvent(submit, rulesList, textEntry, template)
submit.classList.add('js-initialized')
} | import {createDeleteEvent, createSubmitEvent} from "retrospring/features/settings/mute";
export default (): void => {
const submit: HTMLButtonElement = document.getElementById('new-rule-submit') as HTMLButtonElement;
if (!submit || submit.classList.contains('js-initialized')) return;
const rulesList = document.querySelector<HTMLDivElement>('.js-rules-list');
rulesList.querySelectorAll<HTMLDivElement>('.form-group:not(.js-initalized)').forEach(entry => {
const button = entry.querySelector('button')
button.onclick = createDeleteEvent(entry, button)
});
const textEntry: HTMLButtonElement = document.getElementById('new-rule-text') as HTMLButtonElement;
const template: HTMLTemplateElement = document.getElementById('rule-template') as HTMLTemplateElement;
submit.form.onsubmit = createSubmitEvent(submit, rulesList, textEntry, template)
submit.classList.add('js-initialized')
} | Add null check to mute rule submits to prevent error flood | Add null check to mute rule submits to prevent error flood
| TypeScript | agpl-3.0 | Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring | ---
+++
@@ -2,7 +2,7 @@
export default (): void => {
const submit: HTMLButtonElement = document.getElementById('new-rule-submit') as HTMLButtonElement;
- if (submit.classList.contains('js-initialized')) return;
+ if (!submit || submit.classList.contains('js-initialized')) return;
const rulesList = document.querySelector<HTMLDivElement>('.js-rules-list');
rulesList.querySelectorAll<HTMLDivElement>('.form-group:not(.js-initalized)').forEach(entry => { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.